Skip to content

the ultimate vocal synthesizer - sing, speak, beatbox, and more

Rust

Vector display, phases 1 and 2: the shell and Play mode

Jameson Hodge565b28e9a170
diff --git a/public/fonts/AVHERSHEY-LICENSE.txt b/public/fonts/AVHERSHEY-LICENSE.txt
new file mode 100644
index 0000000..7ba47a3
--- /dev/null
+++ b/public/fonts/AVHERSHEY-LICENSE.txt
@@ -0,0 +1,6 @@
+AVHershey Simplex (AVHersheySimplexLight.otf, AVHersheySimplexMedium.otf)
+by Stewart C. Russell, https://github.com/scruss/AVHershey-OTF
+
+Dual-licensed CC0 1.0 Universal / WTFPL. Derived from character stroke coordinates by
+Allen V. Hershey published in "Calligraphy for Computers" (US Naval Weapons Laboratory,
+1967, NWL Report No. 2101), which were published without copyright.
diff --git a/public/fonts/AVHersheySimplexLight.otf b/public/fonts/AVHersheySimplexLight.otf
new file mode 100644
index 0000000..8a7aa1b
Binary files /dev/null and b/public/fonts/AVHersheySimplexLight.otf differ
diff --git a/public/fonts/AVHersheySimplexMedium.otf b/public/fonts/AVHersheySimplexMedium.otf
new file mode 100644
index 0000000..32d3766
Binary files /dev/null and b/public/fonts/AVHersheySimplexMedium.otf differ
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 13ed3c5..53bced5 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -6,10 +6,10 @@ 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 { VoiceControls, VoiceToggles } from "./components/VoiceControls.tsx";
import { Keys } from "./components/Keys.tsx";
import { Segmented, Toggle } from "./components/Controls.tsx";
+import { Screen } from "./components/Screen.tsx";
import { SpeakPanel } from "./components/SpeakPanel.tsx";
import { BestiaryPanel } from "./components/BestiaryPanel.tsx";
import { CreatureView } from "./components/CreatureView.tsx";
@@ -23,6 +23,8 @@ import { playDemo, DEMO_SONGS } from "./singing.ts";
import type { Mode } from "./store.ts";
import type { BodyName } from "../worklet/protocol.ts";
+const BODY_NAME: Record<BodyName, string> = { male: "Adult male", female: "Adult female", child: "Child" };
+
function TopBar() {
const started = useStore((s) => s.started);
const starting = useStore((s) => s.starting);
@@ -62,8 +64,8 @@ function TopBar() {
value={body}
onChange={setBody}
options={[
- { value: "male", label: "Adult male" },
- { value: "female", label: "Adult female" },
+ { value: "male", label: "Male" },
+ { value: "female", label: "Female" },
{ value: "child", label: "Child" },
]}
/>
@@ -141,103 +143,90 @@ function StartPrompt() {
);
}
-function Deck() {
+/** The tall left screen: the face (or the creature) with its overlays. */
+function LeftScreen() {
const mode = useStore((s) => s.mode);
- if (mode === "speak") return <SpeakPanel />;
- if (mode === "sing") return <SingPanel />;
- if (mode === "bestiary") return <BestiaryPanel />;
- if (mode === "beatbox") return <BeatboxPanel />;
+ const body = useStore((s) => s.body);
+ const bestiary = mode === "bestiary";
return (
- <>
- <section className="deck">
- <div className="panel vowel-panel">
- <h2>Vowels</h2>
- <VowelMap />
- </div>
- <VoicePanel />
- <ArticPanel />
- </section>
- <footer className="keys-bar">
- <Keys />
- </footer>
- </>
+ <Screen
+ className="left"
+ focus
+ title={bestiary ? "Creature" : "Vocal tract"}
+ sub={bestiary ? "Airway / live" : `${BODY_NAME[body]} / midsagittal`}
+ label={bestiary ? "Live creature airway" : "Live vocal tract"}
+ tools={<ViewToggles />}
+ >
+ {bestiary ? <CreatureView /> : <AnatomyView />}
+ {mode === "beatbox" && <BeatOverlay />}
+ <StartPrompt />
+ </Screen>
);
}
-function Instruments() {
- const mode = useStore((s) => s.mode);
- if (mode === "beatbox")
- return (
- <aside className="instruments">
- <figure className="instrument">
- <figcaption>Tube, glottis to lips</figcaption>
- <TubeView />
- </figure>
- <figure className="instrument">
- <figcaption>Spectrogram</figcaption>
- <Spectrogram />
- </figure>
- <figure className="instrument">
- <figcaption>Vocal folds, slowed down</figcaption>
- <Stroboscope />
- </figure>
- </aside>
- );
- if (mode === "bestiary")
- return (
- <aside className="instruments">
- <figure className="instrument">
- <figcaption>Spectrogram</figcaption>
- <Spectrogram />
- </figure>
- <figure className="instrument">
- <figcaption>Waveform, three cycles</figcaption>
- <Scope />
- </figure>
- <figure className="instrument">
- <figcaption>Airway, each tube unrolled</figcaption>
- <CreatureTubes />
- </figure>
- </aside>
- );
+function PlayRight() {
+ const f0 = useStore((s) => s.source.f0);
return (
- <aside className="instruments">
- <figure className="instrument">
- <figcaption>Tube, glottis to lips</figcaption>
+ <div className="right right-play">
+ <Screen className="s-tube" title="Tube" sub="Glottis to lips">
<TubeView />
- </figure>
- <figure className="instrument">
- <figcaption>Vocal folds, slowed down</figcaption>
+ </Screen>
+ <Screen className="s-folds" title="Vocal folds" sub="Slowed 100×">
<Stroboscope />
- </figure>
- <figure className="instrument">
- <figcaption>Spectrum and resonances</figcaption>
+ </Screen>
+ <Screen className="s-spec" title="Spectrum" sub="Resonances">
<SpectrumView />
- </figure>
- </aside>
+ </Screen>
+ <Screen className="s-vowels" title="Vowels" sub="F1 / F2">
+ <VowelMap />
+ </Screen>
+ <Screen className="s-voice" title="Voice" tools={<VoiceToggles />}>
+ <VoiceControls />
+ </Screen>
+ <Screen className="s-keys" title="Keys" sub={`${Math.round(f0)} Hz`}>
+ <Keys />
+ </Screen>
+ </div>
);
}
-function Viewport() {
+/** Modes not yet redrawn in the vector style: their three instruments, as screens. */
+function LegacyRight() {
const mode = useStore((s) => s.mode);
- const bestiary = mode === "bestiary";
+ const screens: [string, React.ReactNode][] =
+ mode === "beatbox"
+ ? [["Tube, glottis to lips", <TubeView key="t" />], ["Spectrogram", <Spectrogram key="s" />], ["Vocal folds, slowed down", <Stroboscope key="f" />]]
+ : mode === "bestiary"
+ ? [["Spectrogram", <Spectrogram key="s" />], ["Waveform, three cycles", <Scope key="w" />], ["Airway, each tube unrolled", <CreatureTubes key="a" />]]
+ : [["Tube, glottis to lips", <TubeView key="t" />], ["Vocal folds, slowed down", <Stroboscope key="f" />], ["Spectrum and resonances", <SpectrumView key="p" ring={mode === "sing"} />]];
return (
- <section className="viewport" aria-label={bestiary ? "Live creature airway" : "Live vocal tract"}>
- {bestiary ? <CreatureView /> : <AnatomyView />}
- {mode === "beatbox" && <BeatOverlay />}
- <StartPrompt />
- <ViewToggles />
- </section>
+ <div className="right right-legacy">
+ {screens.map(([title, node]) => (
+ <Screen key={title} title={title}>
+ {node}
+ </Screen>
+ ))}
+ </div>
);
}
+function Deck() {
+ const mode = useStore((s) => s.mode);
+ if (mode === "speak") return <SpeakPanel />;
+ if (mode === "sing") return <SingPanel />;
+ if (mode === "bestiary") return <BestiaryPanel />;
+ if (mode === "beatbox") return <BeatboxPanel />;
+ return null;
+}
+
export function App() {
+ const mode = useStore((s) => s.mode);
return (
- <div className="app">
+ <div className={`app mode-${mode}`}>
<TopBar />
- <main className="stage">
- <Viewport />
- <Instruments />
+ <main className={`wall wall-${mode}`}>
+ <LeftScreen />
+ {mode === "play" ? <PlayRight /> : <LegacyRight />}
</main>
<Deck />
</div>
diff --git a/src/ui/colors.ts b/src/ui/colors.ts
index 66fb599..013bd48 100644
--- a/src/ui/colors.ts
+++ b/src/ui/colors.ts
@@ -1,13 +1,53 @@
-/** Design tokens shared by canvas renderers (CSS mirrors these as custom properties). */
+/**
+ * The vector-display palette (sampled from the NORAD screens in WarGames; see docs/mockups).
+ * Blue is the body and structure, amber is sound, and green/red/pink/white are the four control
+ * slots: each screen maps its own four controls onto them and draws what they move in the same
+ * colour. CSS mirrors these as custom properties in styles.css.
+ */
+export const V = {
+ blue: "#4fb6f2",
+ blueMid: "#3487c4",
+ blueDim: "#1f5f8c",
+ frame: "#133954",
+ green: "#5be381",
+ red: "#ff5d40",
+ pink: "#ff73cf",
+ white: "#eef6f8",
+ amber: "#ffb340",
+};
+/** the four control slots, in order */
+export const SLOTS = [V.green, V.red, V.pink, V.white] as const;
+
+/** mix two #rrggbb colours */
+export function mix(hex: string, to: string, u: number): string {
+ const a = parseInt(hex.slice(1), 16), b = parseInt(to.slice(1), 16);
+ const ch = (s: number) => Math.round(((a >> s) & 255) * (1 - u) + ((b >> s) & 255) * u);
+ return "#" + [16, 8, 0].map((s) => ch(s).toString(16).padStart(2, "0")).join("");
+}
+/** the whitish core of a bright beam in this colour */
+export const core = (hex: string): string => mix(hex, "#ffffff", 0.55);
+
+const HEAT: [number, string][] = [[0, "#3a2408"], [0.35, "#c9822a"], [0.6, "#ffb340"], [0.82, "#ffe39a"], [1, "#fff8ec"]];
+/** sound level 0..1 → dim amber → amber → pale yellow → white */
+export function heat(level: number): string {
+ const v = Math.max(0, Math.min(1, level));
+ for (let i = 1; i < HEAT.length; i++) if (v <= HEAT[i][0]) return mix(HEAT[i - 1][1], HEAT[i][1], (v - HEAT[i - 1][0]) / (HEAT[i][0] - HEAT[i - 1][0]));
+ return HEAT[HEAT.length - 1][1];
+}
+
+/**
+ * Older tokens, remapped onto the vector palette so screens not yet redrawn in the new style
+ * still sit on black in blue and amber.
+ */
export const C = {
black: "#000000",
- console: "#2a3035",
- inset: "#20262a",
- line: "#3c444a",
- text: "#e8eaeb",
- textDim: "#9aa3a8",
- caliper: "#f2cf5b",
- caliperDim: "rgba(242, 207, 91, 0.45)",
+ console: "#000000",
+ inset: "#000000",
+ line: V.frame,
+ text: V.blue,
+ textDim: V.blueMid,
+ caliper: V.amber,
+ caliperDim: "rgba(255, 179, 64, 0.45)",
// MRI-like tissue intensities (T1-ish)
fat: "#bdbdbd",
skin: "#a8a8a8",
diff --git a/src/ui/components/AnatomyView.tsx b/src/ui/components/AnatomyView.tsx
index c6bd872..24c4465 100644
--- a/src/ui/components/AnatomyView.tsx
+++ b/src/ui/components/AnatomyView.tsx
@@ -1,14 +1,41 @@
import { useEffect, useRef, useState } from "react";
-import { AnatomyRenderer, type HandleId } from "../render/anatomy.ts";
+import { AnatomyRenderer, type HandleId, type Slot } from "../render/anatomy.ts";
+import { Glow } from "../render/vector.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 "../../wasm/types.ts";
+import { V } from "../colors.ts";
+import type { HumanArtic, HumanFrame } from "../../wasm/types.ts";
+import type { TelemetryMessage } from "../../worklet/protocol.ts";
-const BODY_LABEL = { male: "Human, adult male", female: "Human, adult female", child: "Human, child" } as const;
+/** What the four readouts under the chin show; a mode can pass its own. */
+export type SlotsFn = (m: VoiceModel, a: HumanArtic, f: HumanFrame, formants: number[], tele: TelemetryMessage | null) => Slot[];
-export function AnatomyView() {
+/** the calibrated vowel nearest to (F1, F2), same metric as the vowel map */
+export function nearestVowel(m: VoiceModel, F1: number, F2: number): string {
+ let best = "", bd = Infinity;
+ for (const v of m.vowels) {
+ const d = Math.hypot(Math.log(F1 / v.F1) * 2.2, Math.log(F2 / v.F2));
+ if (d < bd) {
+ bd = d;
+ best = v.ipa;
+ }
+ }
+ return best;
+}
+
+/** Play mode: the tongue as its nearest vowel, then jaw, lips and soft palate */
+export const articulatorSlots: SlotsFn = (m, a, f, formants) => [
+ formants.length >= 2 ? { label: "Tongue", value: nearestVowel(m, formants[0], formants[1]), color: V.green, ipa: true } : { label: "Tongue", value: "-", color: V.green },
+ { label: "Jaw", value: a.jaw.toFixed(1), unit: "cm", color: V.red },
+ { label: "Lips", value: a.lipAp.toFixed(1), unit: "cm", color: V.pink },
+ f.velumPort > 0.02 ? { label: "Soft palate", value: f.velumPort.toFixed(2), unit: "cm²", color: V.white } : { label: "Soft palate", value: "Shut", color: V.white },
+];
+
+export function AnatomyView(props: { slots?: SlotsFn }) {
+ const slotsRef = useRef<SlotsFn>(props.slots ?? articulatorSlots);
+ slotsRef.current = props.slots ?? articulatorSlots;
const canvasRef = useRef<HTMLCanvasElement>(null);
const wrapRef = useRef<HTMLDivElement>(null);
const model = useModel();
@@ -20,12 +47,20 @@ export function AnatomyView() {
useEffect(() => {
const canvas = canvasRef.current!;
+ const ctx = canvas.getContext("2d")!;
const wrap = wrapRef.current!;
- const r = new AnatomyRenderer(canvas);
+ const r = new AnatomyRenderer();
+ const glow = new Glow();
rendererRef.current = r;
+ let w = 0, h = 0, dpr = 1;
const ro = new ResizeObserver(() => {
const b = wrap.getBoundingClientRect();
- r.resize(b.width, b.height, Math.min(2, window.devicePixelRatio || 1));
+ dpr = Math.min(2, window.devicePixelRatio || 1);
+ w = b.width;
+ h = b.height;
+ canvas.width = Math.max(1, Math.round(w * dpr));
+ canvas.height = Math.max(1, Math.round(h * dpr));
+ r.resize(w, h);
});
ro.observe(wrap);
let raf = 0;
@@ -39,10 +74,18 @@ export function AnatomyView() {
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) {
+ if (m && w > 0 && h > 0) {
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 });
+ const info = [`Tract ${f.length.toFixed(1)} cm`, `Mouth ${f.lipArea.toFixed(1)} cm²`];
+ if (tele) info.push(`F0 ${tele.t.f0.toFixed(1)} Hz`, `Lungs ${tele.t.pLung.toFixed(1)} cmH₂O`);
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = "source-over";
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ r.draw(ctx, m, f, a, tele, st.view, { hover: hoverRef.current, drag: dragRef.current?.id ?? null, dt, formants, slots: slotsRef.current(m, a, f, formants, tele), info: info.map((s) => s.toUpperCase()) });
+ glow.apply(canvas, ctx, dpr);
}
raf = requestAnimationFrame(loop);
};
diff --git a/src/ui/components/ArticPanel.tsx b/src/ui/components/ArticPanel.tsx
deleted file mode 100644
index 0240aaa..0000000
--- a/src/ui/components/ArticPanel.tsx
+++ /dev/null
@@ -1,25 +0,0 @@
-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.25} max={1.2} onChange={(v) => set({ velum: v })} format={(v) => (v <= 0 ? "Closed" : `${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/Encoder.tsx b/src/ui/components/Encoder.tsx
new file mode 100644
index 0000000..80aae44
--- /dev/null
+++ b/src/ui/components/Encoder.tsx
@@ -0,0 +1,120 @@
+import { useId, useRef, useState, type ReactNode } from "react";
+import { SLOTS } from "../colors.ts";
+
+export interface EncoderSpec {
+ label: string;
+ value: number;
+ min: number;
+ max: number;
+ /** logarithmic mapping (pitch, glide) */
+ log?: boolean;
+ onChange: (v: number) => void;
+ /** big numeral and its unit */
+ format: (v: number) => { value: string; unit: string };
+}
+
+const TICKS = 10;
+const A0 = (225 * Math.PI) / 180;
+const SPAN = (270 * Math.PI) / 180;
+
+/**
+ * OP-1 style encoder: a dial and a big numeral in its slot colour, over a native range input
+ * that does the work (label, keyboard incl. Home/End and Page keys, aria-valuetext). Dragging the
+ * dial is relative: up or right raises the value. touch-action: pan-y keeps vertical swipes
+ * scrolling the page on touch screens, so only horizontal drags edit there.
+ */
+export function Encoder(props: EncoderSpec & { slot: number }) {
+ const { label, value, min, max, log, onChange, format, slot } = props;
+ const id = useId();
+ const color = SLOTS[slot % 4];
+ 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) => {
+ const u = Math.min(1, Math.max(0, p));
+ return log ? Math.exp(Math.log(min) + u * (Math.log(max) - Math.log(min))) : min + u * (max - min);
+ };
+ const pos = Math.min(1, Math.max(0, toPos(value)));
+ const shown = format(value);
+ const drag = useRef<{ x: number; y: number; pos: number; id: number } | null>(null);
+ const at = (u: number, r: number) => [Math.cos(A0 - u * SPAN) * r, -Math.sin(A0 - u * SPAN) * r];
+ const [x0, y0] = at(0, 30), [x1, y1] = at(pos, 30), [px, py] = at(pos, 23);
+ const arc = pos > 0.002 ? `M${x0.toFixed(2)} ${y0.toFixed(2)}A30 30 0 ${pos * 270 > 180 ? 1 : 0} 1 ${x1.toFixed(2)} ${y1.toFixed(2)}` : "";
+ return (
+ <div className="encoder" style={{ "--slot": color } as React.CSSProperties}>
+ <label className="enc-label" htmlFor={id}>
+ {label}
+ </label>
+ <div
+ className="enc-dial"
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ (e.currentTarget as Element).setPointerCapture(e.pointerId);
+ drag.current = { x: e.clientX, y: e.clientY, pos, id: e.pointerId };
+ document.getElementById(id)?.focus({ preventScroll: true });
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d || d.id !== e.pointerId) return;
+ const delta = (e.clientX - d.x - (e.clientY - d.y)) / (e.shiftKey ? 600 : 160);
+ onChange(fromPos(d.pos + delta));
+ }}
+ onPointerUp={() => (drag.current = null)}
+ onPointerCancel={() => (drag.current = null)}
+ onLostPointerCapture={() => (drag.current = null)}
+ >
+ <svg viewBox="-42 -42 84 84" aria-hidden="true">
+ {Array.from({ length: TICKS + 1 }, (_, i) => {
+ const [ax, ay] = at(i / TICKS, 35), [bx, by] = at(i / TICKS, 39);
+ return <line key={i} x1={ax} y1={ay} x2={bx} y2={by} className="enc-tick" />;
+ })}
+ <circle r="30" className="enc-ring" />
+ {arc && <path d={arc} className="enc-arc" />}
+ <line x1="0" y1="0" x2={px} y2={py} className="enc-pointer" />
+ <circle r="2.5" className="enc-hub" />
+ </svg>
+ <input
+ id={id}
+ className="enc-input"
+ type="range"
+ min={0}
+ max={1000}
+ step={1}
+ value={Math.round(pos * 1000)}
+ onChange={(e) => onChange(fromPos(Number(e.target.value) / 1000))}
+ aria-valuetext={`${shown.value} ${shown.unit}`.trim()}
+ />
+ </div>
+ <output className="enc-value" htmlFor={id}>
+ {shown.value}
+ </output>
+ <span className="enc-unit">{shown.unit}</span>
+ </div>
+ );
+}
+
+export interface EncoderPage {
+ name: string;
+ encoders: EncoderSpec[];
+}
+
+/** Four encoders at a time, with page tabs. The page shown is presentation only. */
+export function EncoderPages(props: { pages: EncoderPage[]; footer?: ReactNode; label: string }) {
+ const [page, setPage] = useState(0);
+ const p = props.pages[Math.min(page, props.pages.length - 1)];
+ return (
+ <div className="enc-pages">
+ {props.pages.length > 1 && (
+ <div className="enc-tabs" role="group" aria-label={`${props.label} pages`}>
+ {props.pages.map((pg, i) => (
+ <button key={pg.name} type="button" className={`enc-tab${i === page ? " on" : ""}`} aria-pressed={i === page} onClick={() => setPage(i)}>
+ {pg.name}
+ </button>
+ ))}
+ </div>
+ )}
+ <div className="enc-row" role="group" aria-label={p.name}>
+ {[0, 1, 2, 3].map((i) => (p.encoders[i] ? <Encoder key={`${p.name}-${p.encoders[i].label}`} {...p.encoders[i]} slot={i} /> : <div key={`empty-${i}`} className="encoder empty" aria-hidden="true" />))}
+ </div>
+ {props.footer && <div className="enc-footer">{props.footer}</div>}
+ </div>
+ );
+}
diff --git a/src/ui/components/Screen.tsx b/src/ui/components/Screen.tsx
new file mode 100644
index 0000000..8852c5b
--- /dev/null
+++ b/src/ui/components/Screen.tsx
@@ -0,0 +1,29 @@
+import type { ButtonHTMLAttributes, ReactNode } from "react";
+
+/**
+ * One screen on the wall: a black panel with a thin frame and a single-stroke title.
+ * The body always has a positive size (see .screen-body in styles.css); canvases fill it.
+ */
+export function Screen(props: { title: string; sub?: string; focus?: boolean; className?: string; tools?: ReactNode; children: ReactNode; label?: string }) {
+ const { title, sub, focus, className, tools, children, label } = props;
+ return (
+ <section className={`screen${focus ? " focus" : ""}${className ? " " + className : ""}`} aria-label={label ?? title}>
+ <header className="screen-head">
+ <h2 className="screen-title">{title}</h2>
+ {sub && <span className="screen-sub">{sub}</span>}
+ {tools && <div className="screen-tools">{tools}</div>}
+ </header>
+ <div className="screen-body">{children}</div>
+ </section>
+ );
+}
+
+/** A framed caps button; `on` lights it and sets aria-pressed (a toggle) unless it's a plain action. */
+export function Chip(props: ButtonHTMLAttributes<HTMLButtonElement> & { on?: boolean; toggle?: boolean; tone?: "slot0" | "slot1" | "slot2" | "slot3" | "amber" }) {
+ const { on, toggle = true, tone, className, children, ...rest } = props;
+ return (
+ <button type="button" {...rest} className={`chip${on ? " on" : ""}${tone ? " " + tone : ""}${className ? " " + className : ""}`} aria-pressed={toggle ? !!on : undefined}>
+ {children}
+ </button>
+ );
+}
diff --git a/src/ui/components/SpectrumView.tsx b/src/ui/components/SpectrumView.tsx
index 901c2a1..16324b2 100644
--- a/src/ui/components/SpectrumView.tsx
+++ b/src/ui/components/SpectrumView.tsx
@@ -1,88 +1,117 @@
import { useRef } from "react";
-import { useCanvasLoop, font } from "../useCanvas.ts";
+import { usePhosphor } from "../usePhosphor.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";
+import { V } from "../colors.ts";
+import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";
const FMIN = 60, FMAX = 8000;
+const RANGE = 62; // dB shown
-/** Live output spectrum (filled) with the vocal-tract transfer function and formant calipers. */
-export function SpectrumView() {
+/**
+ * The live output as harmonic stems (from the analyser, at multiples of the sung f0), the vocal
+ * tract's transfer function over them, formant markers, and the pitch in the pitch colour.
+ * Pass `ring` to mark the singer's-ring band.
+ */
+export function SpectrumView(props: { ring?: boolean }) {
const model = useModel();
const bins = useRef<Float32Array | null>(null);
- const ref = useCanvasLoop(({ ctx, w, h }) => {
+ const ringRef = useRef(props.ring);
+ ringRef.current = props.ring;
+ const ref = usePhosphor(({ 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 left = 36, right = w - 14, top = 22, bot = h - 22;
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)";
+ const dbY = (db: number) => top + (Math.min(0, Math.max(-RANGE, db)) / -RANGE) * (bot - top);
+ const tele = engine.latest && engine.latest.body === st.body ? engine.latest : null;
+ const f0 = tele && tele.t.voicing > 0.3 ? tele.t.f0 : 0;
+
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);
+ seg(ctx, fx(f), top, fx(f), bot, V.frame, 1);
+ if (!(f0 && Math.abs(fx(f) - fx(f0)) < 40)) label(ctx, f >= 1000 ? `${f / 1000}K` : String(f), fx(f), h - 6, { size: 9, color: V.blueMid, align: "center", ls: 0.1 });
+ }
+ for (const db of [-20, -40]) {
+ seg(ctx, left, dbY(db), right, dbY(db), V.frame, 1, { dash: [2, 4] });
+ label(ctx, String(db), left - 6, dbY(db) + 3, { size: 8, color: V.blueDim, align: "right", ls: 0.05 });
}
- // live FFT
+ seg(ctx, left, bot, right, bot, V.blueDim, 1);
+ if (ringRef.current) {
+ const p = new Path2D();
+ p.rect(fx(2400), top - 6, fx(3600) - fx(2400), bot - top + 6);
+ beam(ctx, p, V.white, 1, { dash: [3, 4], alpha: 0.6 });
+ label(ctx, "RING", fx(3600) + 4, top + 4, { size: 9, color: V.white, ls: 0.16 });
+ }
+
+ // the output, from the analyser: stems at the harmonics while voiced, else the whole curve
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);
+ const binOf = (f: number) => Math.min(b.length - 1, Math.max(0, Math.round((f / sr) * 2 * b.length)));
+ const peak = (f: number, half: number) => {
+ let mx = -Infinity;
+ for (let k = binOf(f - half); k <= binOf(f + half); k++) mx = Math.max(mx, b[k]);
+ return mx;
+ };
+ if (f0 > 0) {
+ const hs: Pt[] = [];
+ for (let k = 1; k * f0 < FMAX; k++) if (k * f0 >= FMIN) hs.push([k * f0, peak(k * f0, f0 * 0.3)]);
+ const mx = Math.max(...hs.map((q) => q[1]));
+ const stems = new Path2D();
+ for (const [f, db] of hs) {
+ stems.moveTo(fx(f), bot);
+ stems.lineTo(fx(f), dbY(db - mx));
+ }
+ beam(ctx, stems, V.amber, 1.1, { alpha: 0.55 });
+ } else {
+ const pts: Pt[] = [];
+ let mx = -Infinity;
+ for (let x = left; x <= right; x += 2) {
+ const f = Math.exp(Math.log(FMIN) + ((x - left) / (right - left)) * (Math.log(FMAX) - Math.log(FMIN)));
+ const db = b[binOf(f)];
+ mx = Math.max(mx, db);
+ pts.push([x, db]);
+ }
+ beamPts(ctx, pts.map(([x, db]) => [x, dbY(db - mx)] as Pt), V.amber, 1, { alpha: 0.45 });
}
- 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;
+
+ // the transfer function of the tract, with its formants
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);
+ const env: Pt[] = [];
+ for (let i = 0; i < tf.freqs.length; i++) if (tf.freqs[i] >= FMIN && tf.freqs[i] <= FMAX) env.push([fx(tf.freqs[i]), dbY(tf.db[i] - mx)]);
+ beamPts(ctx, env, V.amber, 1.5, { hot: true });
+ tf.formants.slice(0, 3).forEach((F, i) => {
+ let near = 0;
+ for (let k = 0; k < tf.freqs.length; k++) if (Math.abs(tf.freqs[k] - F) < Math.abs(tf.freqs[near] - F)) near = k;
+ const x = fx(F), y = Math.max(top + 12, dbY(tf.db[near] - mx) - 8);
+ const tri = new Path2D();
+ tri.moveTo(x - 5, y - 8);
+ tri.lineTo(x + 5, y - 8);
+ tri.lineTo(x, y);
+ tri.closePath();
+ beam(ctx, tri, V.amber, 1.2);
+ label(ctx, `F${i + 1}`, x, y - 12, { size: 10, color: V.amber, align: "center", ls: 0.1 });
});
+ if (f0 > 0) {
+ const x = fx(f0);
+ const tri = new Path2D();
+ tri.moveTo(x - 5, bot + 9);
+ tri.lineTo(x + 5, bot + 9);
+ tri.lineTo(x, bot + 1);
+ tri.closePath();
+ beam(ctx, tri, V.green, 1.2);
+ label(ctx, `F0 ${Math.round(f0)}`, x - 9, bot + 13, { size: 9, color: V.green, align: "right", ls: 0.12 });
+ }
});
- return <canvas ref={ref} className="instrument-canvas" aria-label="Output spectrum and vocal tract transfer function" role="img" />;
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Output spectrum: harmonics, the vocal tract's resonances and its formants" role="img" />;
}
diff --git a/src/ui/components/Stroboscope.tsx b/src/ui/components/Stroboscope.tsx
index 91bcd9a..f1dfa99 100644
--- a/src/ui/components/Stroboscope.tsx
+++ b/src/ui/components/Stroboscope.tsx
@@ -1,18 +1,18 @@
import { useRef } from "react";
-import { useCanvasLoop, font } from "../useCanvas.ts";
+import { usePhosphor } from "../usePhosphor.ts";
import { engine } from "../../audio/AudioEngine.ts";
import { useStore } from "../store.ts";
-import { C } from "../colors.ts";
+import { V } from "../colors.ts";
+import { beam, beamPts, label, ring, seg, type Pt } from "../render/vector.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.
+ * The vocal folds from above, as through an endoscope, replayed slowly from the phase-locked
+ * glottal area trace (two cycles), with the area (white) and flow (amber) waveforms and a playhead.
*/
export function Stroboscope() {
const phase = useRef(0);
- const ref = useCanvasLoop(({ ctx, w, h, dt }) => {
+ const ref = usePhosphor(({ 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;
@@ -20,94 +20,75 @@ export function Stroboscope() {
// 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]);
+ let maxA = 0.02, minA = Infinity;
+ if (area) for (let i = 0; i < n; i++) {
+ maxA = Math.max(maxA, area[i]);
+ minA = Math.min(minA, 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;
+
+ // endoscope view: anterior at the top
+ const R = Math.max(20, Math.min(h * 0.4, w * 0.2));
+ const cx = R + 14, cy = h / 2 + 4;
+ ring(ctx, cx, cy, R, V.blue, 1.3);
+ ring(ctx, cx, cy, R + 5, V.blueDim, 0.8, { alpha: 0.8 });
+ const len = R * 1.22;
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();
+ const chink = area ? Math.min(R * 0.06, (minA / 0.05) * R * 0.08) : 0;
+ for (const sg of [-1, 1]) {
+ const edge = new Path2D();
+ edge.moveTo(cx, cy - len / 2);
+ edge.quadraticCurveTo(cx + sg * (open + chink), cy + len * 0.05, cx + sg * chink * 0.8, cy + len / 2);
+ beam(ctx, edge, V.white, 1.6, { hot: true });
+ const fold = new Path2D();
+ fold.moveTo(cx + sg * 3, cy - len / 2 - 2);
+ fold.quadraticCurveTo(cx + sg * R * 0.62, cy, cx + sg * R * 0.22, cy + len / 2 + 4);
+ beam(ctx, fold, V.blueMid, 1.1);
+ const falseFold = new Path2D();
+ falseFold.moveTo(cx + sg * 8, cy - len / 2 - 8);
+ falseFold.quadraticCurveTo(cx + sg * R * 0.92, cy - 2, cx + sg * R * 0.42, cy + len / 2 + 6);
+ beam(ctx, falseFold, V.blueDim, 1);
+ const ary = new Path2D();
+ ary.ellipse(cx + sg * R * 0.2, cy + len / 2 + R * 0.14, R * 0.13, R * 0.09, 0, 0, Math.PI * 2);
+ beam(ctx, ary, V.blueMid, 1.1);
}
- 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);
+ const epi = new Path2D();
+ epi.moveTo(cx - R * 0.42, cy - R * 0.62);
+ epi.quadraticCurveTo(cx, cy - R * 0.98, cx + R * 0.42, cy - R * 0.62);
+ beam(ctx, epi, V.blueMid, 1.2);
+ label(ctx, "FRONT", cx, cy - R - 8, { size: 8, color: V.blueDim, align: "center", ls: 0.18 });
+
+ // waveforms
+ const tx0 = cx + R + 22, tx1 = w - 12;
+ if (tx1 - tx0 < 40) return;
+ const bandH = Math.max(12, (h - 52) / 2);
+ const yA0 = 16, yA1 = yA0 + bandH, yF0 = yA1 + 18, yF1 = yF0 + bandH;
+ label(ctx, "AREA", tx1, yA0 - 4, { size: 9, color: V.blueMid, align: "right", ls: 0.18 });
+ label(ctx, "FLOW", tx1, yF0 - 4, { size: 9, color: V.blueMid, align: "right", ls: 0.18 });
+ seg(ctx, tx0, yA1, tx1, yA1, V.frame, 1);
+ seg(ctx, tx0, yF1, tx1, yF1, V.frame, 1);
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();
+ const band = (arr: ArrayLike<number>, y0: number, y1: number): Pt[] => {
+ let mx = -Infinity, mn = Infinity;
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);
+ mx = Math.max(mx, arr[i]);
+ mn = Math.min(mn, arr[i]);
}
- ctx.strokeStyle = color;
- ctx.lineWidth = wdt;
- ctx.stroke();
+ const o: Pt[] = [];
+ for (let i = 0; i < n; i++) o.push([tx0 + ((tx1 - tx0) * i) / (n - 1), y1 - ((arr[i] - mn) / Math.max(1e-9, mx - mn)) * (y1 - y0 - 4)]);
+ return o;
};
- 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);
+ beamPts(ctx, band(area, yA0, yA1), V.white, 1.3, { hot: true });
+ beamPts(ctx, band(flow, yF0, yF1), V.amber, 1.3, { hot: true });
+ const px = tx0 + ((tx1 - tx0) * idx) / (n - 1);
+ seg(ctx, px, yA0, px, yF1, V.white, 1, { alpha: 0.55, dash: [2, 3] });
+ let opened = 0;
+ for (let i = 0; i < n; i++) if (area[i] > minA + 0.002) opened++;
+ label(ctx, `OPEN ${Math.round((opened / n) * 100)}%`, tx0, h - 4, { size: 9, color: V.blueMid, ls: 0.16 });
+ label(ctx, `${(a * 100).toFixed(1)} MM²`, tx1, h - 4, { size: 9, color: V.blueMid, align: "right", ls: 0.12 });
} else {
- ctx.fillStyle = C.textDim;
- ctx.fillText("Start audio to see the folds vibrate", x0, h / 2);
+ label(ctx, "START AUDIO TO SEE THEM VIBRATE", tx0, h / 2, { size: 9, color: V.blueMid, ls: 0.16 });
}
});
- return <canvas ref={ref} className="instrument-canvas" aria-label="Vocal fold stroboscope and glottal waveforms" role="img" />;
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Vocal folds seen from above, replayed slowly, with the glottal area and flow" role="img" />;
}
diff --git a/src/ui/components/TubeView.tsx b/src/ui/components/TubeView.tsx
index 0f56634..199385d 100644
--- a/src/ui/components/TubeView.tsx
+++ b/src/ui/components/TubeView.tsx
@@ -1,21 +1,24 @@
-import { useCanvasLoop, font } from "../useCanvas.ts";
+import { usePhosphor } from "../usePhosphor.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";
+import { V, heat, pressureLevel } from "../colors.ts";
+import { beam, beamPts, label, seg, type Pt } from "../render/vector.ts";
-/** The simulated tube: diameter profile along the tract, lit by acoustic pressure, nasal branch above. */
+/**
+ * The simulated tube as a wireframe: one ring per section (diameter from the area function),
+ * lit by acoustic pressure, with the nasal branch above the velum junction.
+ */
export function TubeView() {
const model = useModel();
- const ref = useCanvasLoop(({ ctx, w, h }) => {
+ const ref = usePhosphor(({ 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;
+ let rms: ArrayLike<number> | null = null;
if (tele) {
ph = tele.t.phAreas;
or = tele.t.orAreas;
@@ -31,67 +34,60 @@ export function TubeView() {
}
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 x0 = 16, x1 = w - 16;
+ const sx = (x1 - x0) / total;
+ const axisY = h * 0.6;
+ const dS = (h * 0.3) / 4; // 4 cm diameter → 30% of the height
const a2d = (A: number) => 2 * Math.sqrt(Math.max(0, A) / Math.PI);
- // nasal branch (fixed profile) above, from the velum junction
+ const secs: { x: number; r: number; lv: number }[] = [];
+ for (let i = 0; i < nPh; i++) secs.push({ x: x0 + ((i + 0.5) / nPh) * phLen * sx, r: (a2d(ph[i]) * dS) / 2, lv: rms ? pressureLevel(rms[i]) : 0 });
+ for (let i = 0; i < nOr; i++) secs.push({ x: x0 + (phLen + ((i + 0.5) / nOr) * orLen) * sx, r: (a2d(or[i]) * dS) / 2, lv: rms ? pressureLevel(rms[nPh + i]) : 0 });
+
+ // nasal branch: dashed and dim while the velum is shut
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.bodyParams.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);
+ const open = velum > 0.02;
+ const jx = x0 + phLen * sx;
+ const nTop = axisY - h * 0.36;
+ const nLen = Math.min(x1 - jx - 40, 11.4 * m.bodyParams.scale * sx * 0.62);
+ const nc = open ? V.white : V.blueDim;
+ const dash = open ? undefined : [3, 4];
+ for (const off of [-5, 5]) {
+ const p = new Path2D();
+ p.moveTo(jx + off, axisY - 26);
+ p.lineTo(jx + off, nTop + off + 2);
+ p.quadraticCurveTo(jx + off, nTop + off, jx + 8, nTop + off);
+ p.lineTo(jx + nLen, nTop + off);
+ beam(ctx, p, nc, 1, { dash });
+ }
+ label(ctx, "NOSE", jx + nLen + 6, nTop + 3, { size: 9, color: nc, ls: 0.16 });
+ label(ctx, open ? `VELUM OPEN ${velum.toFixed(2)} CM²` : "VELUM SHUT", jx, nTop - 12, { size: 9, color: nc, ls: 0.16, align: "center" });
+
+ // silhouette and rings
+ const top: Pt[] = [[x0, axisY - 3], ...secs.map((q) => [q.x, axisY - q.r] as Pt), [x1, axisY - secs[secs.length - 1].r]];
+ const bot: Pt[] = [[x0, axisY + 3], ...secs.map((q) => [q.x, axisY + q.r] as Pt), [x1, axisY + secs[secs.length - 1].r]];
+ beamPts(ctx, top, V.blue, 1.3, { hot: true });
+ beamPts(ctx, bot, V.blue, 1.3, { hot: true });
+ for (const q of secs) {
+ const lv = Math.pow(q.lv, 0.85);
+ const p = new Path2D();
+ p.ellipse(q.x, axisY, Math.max(1.2, q.r * 0.28), Math.max(0.6, q.r), 0, 0, Math.PI * 2);
+ beam(ctx, p, rms ? heat(lv) : V.blueDim, 1.1, { alpha: rms ? 0.35 + 0.65 * lv : 0.6 });
+ }
+ seg(ctx, x0, axisY, x1, axisY, V.blueDim, 0.8, { dash: [2, 5], alpha: 0.8 });
+
// 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)";
+ const marks: [number, string][] = [[0, "GLOTTIS"], [phLen, "VELUM"], [f.teethS, "TEETH"], [total, "LIPS"]];
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);
+ const x = x0 + s * sx;
+ const tw = name.length * 9 * 0.78;
+ const lx = Math.min(w - tw - 2, Math.max(2, x - tw / 2));
+ if (lx < lastRight + 8) continue;
+ lastRight = lx + tw;
+ seg(ctx, x, h - 26, x, h - 21, V.blueDim, 1);
+ label(ctx, name, lx, h - 9, { size: 9, color: V.blueMid, ls: 0.16 });
}
});
- return <canvas ref={ref} className="instrument-canvas" aria-label="Area function of the simulated tube" role="img" />;
+ return <canvas ref={ref} className="instrument-canvas" aria-label="Area function of the simulated tube, lit by sound pressure" role="img" />;
}
diff --git a/src/ui/components/VoiceControls.tsx b/src/ui/components/VoiceControls.tsx
new file mode 100644
index 0000000..30ac66f
--- /dev/null
+++ b/src/ui/components/VoiceControls.tsx
@@ -0,0 +1,88 @@
+import { useStore } from "../store.ts";
+import { EncoderPages, type EncoderPage } from "./Encoder.tsx";
+import { Chip } from "./Screen.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}`;
+};
+
+const pct = (v: number) => ({ value: String(Math.round(v * 100)), unit: "%" });
+const cm = (v: number) => ({ value: v.toFixed(1), unit: "cm" });
+const signedCm = (v: number) => ({ value: `${v >= 0 ? "+" : ""}${v.toFixed(1)}`, unit: "cm" });
+
+/**
+ * Play mode's controls: the voice and the articulators without a handle, four at a time
+ * (OP-1 style). Values live in the store as before.
+ */
+export function VoiceControls() {
+ const s = useStore((st) => st.source);
+ const setSource = useStore((st) => st.setSource);
+ const a = useStore((st) => st.artic);
+ const setArtic = useStore((st) => st.setArtic);
+ const pages: EncoderPage[] = [
+ {
+ name: "Voice",
+ encoders: [
+ { label: "Pitch", value: s.f0, min: 40, max: 1100, log: true, onChange: (v) => setSource({ f0: v }), format: (v) => ({ value: v.toFixed(0), unit: `Hz ${noteName(v)}` }) },
+ { label: "Breath", value: s.pressure, min: 2, max: 22, onChange: (v) => setSource({ pressure: v }), format: (v) => ({ value: v.toFixed(1), unit: "cmH₂O" }) },
+ { label: "Pressed", value: s.tension, min: 0, max: 1, onChange: (v) => setSource({ tension: v }), format: pct },
+ { label: "Vibrato", value: s.vibratoDepth, min: 0, max: 120, onChange: (v) => setSource({ vibratoDepth: v }), format: (v) => ({ value: v.toFixed(0), unit: "cents" }) },
+ ],
+ },
+ {
+ name: "Tone",
+ encoders: [
+ { label: "Breathy", value: s.breathiness, min: 0, max: 1, onChange: (v) => setSource({ breathiness: v }), format: pct },
+ { label: "Rough", value: s.roughness, min: 0, max: 1, onChange: (v) => setSource({ roughness: v }), format: pct },
+ { label: "Fry", value: s.fry, min: 0, max: 1, onChange: (v) => setSource({ fry: v }), format: pct },
+ { label: "Glide", value: s.glide, min: 0.005, max: 0.6, log: true, onChange: (v) => setSource({ glide: v }), format: (v) => ({ value: (v * 1000).toFixed(0), unit: "ms" }) },
+ ],
+ },
+ {
+ name: "Mouth",
+ encoders: [
+ { label: "Rounding", value: 1 - a.lipWidth, min: 0, max: 1, onChange: (v) => setArtic({ lipWidth: 1 - v }), format: pct },
+ { label: "Lips open", value: a.lipAp, min: -0.3, max: 2.2, onChange: (v) => setArtic({ lipAp: v }), format: cm },
+ { label: "Protrude", value: a.lipProt, min: -0.1, max: 1.4, onChange: (v) => setArtic({ lipProt: v }), format: cm },
+ { label: "Jaw", value: a.jaw, min: 0, max: 2.4, onChange: (v) => setArtic({ jaw: v }), format: cm },
+ ],
+ },
+ {
+ name: "Tongue",
+ encoders: [
+ { label: "Root", value: a.root, min: -0.9, max: 0.9, onChange: (v) => setArtic({ root: v }), format: signedCm },
+ { label: "Tip curl", value: a.ttCurl, min: 0, max: 1, onChange: (v) => setArtic({ ttCurl: v }), format: pct },
+ ],
+ },
+ {
+ name: "Throat",
+ encoders: [
+ { label: "Soft palate", value: a.velum, min: -0.25, max: 1.2, onChange: (v) => setArtic({ velum: v }), format: (v) => (v <= 0 ? { value: "Shut", unit: "" } : { value: v.toFixed(2), unit: "cm²" }) },
+ { label: "Larynx", value: a.larynx, min: -1.5, max: 1.5, onChange: (v) => setArtic({ larynx: v }), format: signedCm },
+ { label: "Twang", value: a.epilarynx, min: 0, max: 1, onChange: (v) => setArtic({ epilarynx: v }), format: pct },
+ { label: "False folds", value: a.ventricular, min: 0, max: 1, onChange: (v) => setArtic({ ventricular: v }), format: pct },
+ ],
+ },
+ ];
+ return <EncoderPages label="Voice" pages={pages} />;
+}
+
+/** Hold breath and Whisper, for the voice screen's header. */
+export function VoiceToggles() {
+ const voiced = useStore((st) => st.source.voiced);
+ const setSource = useStore((st) => st.setSource);
+ const hold = useStore((st) => st.hold);
+ const setHold = useStore((st) => st.setHold);
+ return (
+ <>
+ <Chip on={hold} onClick={() => setHold(!hold)}>
+ Hold breath
+ </Chip>
+ <Chip on={!voiced} onClick={() => setSource({ voiced: !voiced })}>
+ Whisper
+ </Chip>
+ </>
+ );
+}
diff --git a/src/ui/components/VoicePanel.tsx b/src/ui/components/VoicePanel.tsx
deleted file mode 100644
index 5e94cf3..0000000
--- a/src/ui/components/VoicePanel.tsx
+++ /dev/null
@@ -1,32 +0,0 @@
-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.tsx
index 4db27ff..0a99c0f 100644
--- a/src/ui/components/VowelMap.tsx
+++ b/src/ui/components/VowelMap.tsx
@@ -1,15 +1,17 @@
import { useRef } from "react";
-import { useCanvasLoop, font } from "../useCanvas.ts";
+import { usePhosphor } from "../usePhosphor.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";
+import { V } from "../colors.ts";
+import { beamPts, handle, ipaGlyph, label, seg, type Pt } from "../render/vector.ts";
+import { nearestVowel } from "./AnatomyView.tsx";
/**
* 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).
+ * articulation between them; the green ring is the live tract's measured (F1, F2), with a trail.
*/
export function VowelMap() {
const model = useModel();
@@ -34,49 +36,36 @@ export function VowelMap() {
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 trail = useRef<{ x: number; y: number }[]>([]);
+ const ref = usePhosphor(({ ctx, w, h }) => {
const m = model.current;
if (!m) return;
const st = useStore.getState();
- ctx.clearRect(0, 0, w, h);
- // vowel trapezoid guide
+ // vowel trapezoid guide, like a border on a map
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
+ beamPts(ctx, corners.map((p) => [p.x, p.y] as Pt), V.blueDim, 1, { close: true, alpha: 0.9 });
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();
+ const live = fm.length >= 2 ? toXY(fm[0], fm[1], w, h) : null;
+ const near = fm.length >= 2 ? nearestVowel(m, fm[0], fm[1]) : "";
+ for (const v of m.vowels) {
+ if (v.ipa === near && live) continue;
+ const p = toXY(v.F1, v.F2, w, h);
+ ipaGlyph(ctx, p.x, p.y + 5, v.ipa, 15, V.blueMid);
+ }
+ if (live) {
+ // where the tongue has been: a fading trail of the last second or so
+ const tr = trail.current;
+ const last = tr[tr.length - 1];
+ if (!last || Math.hypot(last.x - live.x, last.y - live.y) > 0.5) tr.push(live);
+ if (tr.length > 40) tr.shift();
+ for (let i = 1; i < tr.length; i++) seg(ctx, tr[i - 1].x, tr[i - 1].y, tr[i].x, tr[i].y, V.green, 1.2, { alpha: 0.08 + (0.6 * i) / tr.length });
+ handle(ctx, live.x, live.y, V.green, 8);
+ ipaGlyph(ctx, live.x + 20, live.y - 8, near, 17, V.green);
}
- 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);
+ label(ctx, "F2", w - 6, h - 5, { size: 9, color: V.blueDim, align: "right", ls: 0.1 });
+ label(ctx, "F1", 4, h - 5, { size: 9, color: V.blueDim, ls: 0.1 });
});
const apply = (e: React.PointerEvent) => {
diff --git a/src/ui/render/anatomy.ts b/src/ui/render/anatomy.ts
index fbabba1..447e561 100644
--- a/src/ui/render/anatomy.ts
+++ b/src/ui/render/anatomy.ts
@@ -1,16 +1,21 @@
/**
- * 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.
+ * Vector-display midsagittal renderer for the human model (see docs/mockups/play.html).
+ * The anatomy is drawn as glowing outlines: blue for the body, the four handled articulators in
+ * their slot colours (tongue green, jaw red, lips pink, soft palate white). Physics overlays:
+ * acoustic pressure RMS lights each cross-section line of the airway (amber heat), airflow
+ * streaks move at the local particle velocity u = U/A, turbulence shows as white dots at the
+ * active noise source, and the tongue, jaw and lips leave a fading afterglow.
+ *
+ * Everything is in CSS pixels; the caller pre-scales the context by devicePixelRatio and adds
+ * the glow pass afterwards.
*/
import type { HumanArtic, HumanFrame } from "../../wasm/types.ts";
import type { Vec } from "./geom.ts";
import { rotateAbout, dist, catmullRom } from "./geom.ts";
import type { TelemetryMessage } from "../../worklet/protocol.ts";
import type { VoiceModel } from "../analysis.ts";
-import { C, hot, pressureLevel } from "../colors.ts";
+import { V, heat, pressureLevel } from "../colors.ts";
+import { beam, beamPts, chaikin, dot, handle, ipaGlyph, label, ring, seg, type Pt } from "./vector.ts";
export type HandleId = "tongue" | "tip" | "jaw" | "lips" | "velum" | "larynx";
@@ -27,6 +32,16 @@ export interface ViewFlags {
calipers: boolean;
}
+/** an OP-1 style readout in the space under the chin */
+export interface Slot {
+ label: string;
+ value: string;
+ unit?: string;
+ color: string;
+ /** value is an IPA symbol, drawn as strokes */
+ ipa?: boolean;
+}
+
interface Particle {
s: number;
u: number; // lateral position −1..1
@@ -35,83 +50,96 @@ interface Particle {
py: number;
}
-const VIEW = { x0: -7.2, x1: 12.2, y0: -4.2, y1: 15.8 };
+/** what the tongue, jaw and lips looked like a moment ago */
+interface Echo {
+ t: number;
+ tongue: Vec[];
+ jaw: Vec[];
+ upperLip: Pt[];
+ lowerLip: Pt[];
+}
+
+/** Body-space outlines for one frame (rebuilt when the frame changes). */
+interface Geometry {
+ f: HumanFrame;
+ model: VoiceModel;
+ skinLower: Vec[];
+ skinUpper: Vec[];
+ inset: Vec[];
+ skull: Vec[];
+ brain: Vec[];
+ sulcus: Vec[];
+ eye: Vec[];
+ lens: Vec[];
+ vertebrae: Vec[][];
+ cords: Vec[][];
+ nasal: Vec[];
+ turbinates: Vec[][];
+ palOral: Vec[];
+ palNasal: Vec[];
+ jawLower: Vec[];
+ jawUpper: Vec[];
+ hyoid: Vec[];
+ thyroid: Vec[];
+ trachea: Vec[][];
+ rings: Vec[][];
+ outerWall: Vec[];
+ glottisWall: Vec[];
+ fibres: Vec[][];
+ folds: Vec[][];
+ lowerTeeth: Vec[];
+}
+
+/** the visible part of the head, in body cm */
+const VIEW = { x0: -7.5, x1: 10.25, y0: -4.55, y1: 19.9 };
+const ECHO_AGES = [0.09, 0.06, 0.03];
export class AnatomyRenderer {
- private readonly canvas: HTMLCanvasElement;
- private readonly ctx: CanvasRenderingContext2D;
- private grain: CanvasPattern | null = null;
- /** tissue shapes, drawn sharp */
- private tissue: HTMLCanvasElement;
- private tctx: CanvasRenderingContext2D;
- /** the tissue layer softened by one blur pass, with film grain (what gets drawn) */
- private soft: HTMLCanvasElement;
- private sctx: CanvasRenderingContext2D;
- /** what the tissue layer was last drawn for: an unchanged frame needs no redraw */
- private tissueFor: { model: VoiceModel; f: HumanFrame } | null = null;
private particles: Particle[] = [];
private scale = 20;
private ox = 0;
private oy = 0;
- private dpr = 1;
+ private w = 0;
+ private h = 0;
private sparkSeed = 1;
- private readonly canFilter: boolean;
+ private geo: Geometry | null = null;
+ private echoes: Echo[] = [];
+ private clock = 0;
+ private lastEcho = -1;
- constructor(canvas: HTMLCanvasElement) {
- this.canvas = canvas;
- this.ctx = canvas.getContext("2d")!;
- this.tissue = document.createElement("canvas");
- this.tctx = this.tissue.getContext("2d")!;
- this.soft = document.createElement("canvas");
- this.sctx = this.soft.getContext("2d")!;
- this.canFilter = typeof this.tctx.filter === "string";
- this.makeGrain();
+ constructor() {
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");
+ /** size in CSS px */
+ resize(w: number, h: number): void {
+ this.w = w;
+ this.h = h;
+ const padX = 12, padT = 8, padB = 8;
+ this.scale = Math.max(1, Math.min((w - 2 * padX) / (VIEW.x1 - VIEW.x0), (h - padT - padB) / (VIEW.y1 - VIEW.y0)));
+ // left-aligned when there is room to spare, so the readouts get the space in front of the face
+ const spare = w - 2 * padX - (VIEW.x1 - VIEW.x0) * this.scale;
+ this.ox = padX + Math.min(spare / 2, Math.max(0, spare - 220)) - VIEW.x0 * this.scale;
+ this.oy = padT + Math.max(0, (h - padT - padB - (VIEW.y1 - VIEW.y0) * this.scale) / 2) + VIEW.y1 * this.scale;
+ for (const p of this.particles) p.px = NaN;
}
- 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;
- this.soft.width = this.canvas.width;
- this.soft.height = this.canvas.height;
- this.tissueFor = null;
- 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 */
+ /** body cm → CSS 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 */
+ private P(p: Vec): Pt {
+ return [this.ox + p.x * this.scale, this.oy - p.y * this.scale];
+ }
+ /** CSS px (relative to the canvas) → 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 };
+ return { x: (cx - this.ox) / this.scale, y: (this.oy - cy) / this.scale };
}
get pxPerCm(): number {
- return this.scale / this.dpr;
+ return this.scale;
}
handles(model: VoiceModel, f: HumanFrame, a: HumanArtic): Handle[] {
@@ -137,230 +165,224 @@ export class AnatomyRenderer {
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;
- if (!this.tissueFor || this.tissueFor.f !== f || this.tissueFor.model !== model) {
- this.drawTissue(model, f, a);
- this.tissueFor = { model, f };
- }
- ctx.globalCompositeOperation = "source-over";
- ctx.fillStyle = C.black;
- ctx.fillRect(0, 0, W, H);
- ctx.drawImage(this.soft, 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;
+ // ------------------------------------------------------------------ geometry
+ private geometry(model: VoiceModel, f: HumanFrame, a: HumanArtic): Geometry {
+ if (this.geo && this.geo.f === f && this.geo.model === model) return this.geo;
const t = model.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);
-
- 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.bodyParams.pharynx;
+ // facial profile in true body coordinates (P()'s oral-region x compression would flatten the nose)
const B = (x: number, y: number): Vec => ({ x: x * k, y: (y < 7 ? 7 - (7 - y) * ph : y) * k });
+ const ulOut = f.upperLip.slice(7); // edge → nose
+ const llOut = f.lowerLip.slice(7); // edge → chin
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 ellipse = (c: Vec, rx: number, ry: number, rot = 0, n = 40): Vec[] => {
+ // rotation is in screen space (y down) in the MRI renderer's convention: negate for body space
+ const cr = Math.cos(-rot), sr = Math.sin(-rot);
+ const o: Vec[] = [];
+ for (let i = 0; i <= n; i++) {
+ const an = (i / n) * Math.PI * 2;
+ const x = Math.cos(an) * rx, y = Math.sin(an) * ry;
+ o.push({ x: c.x + x * cr - y * sr, y: c.y + x * sr + y * cr });
+ }
+ return o;
+ };
+ const roundRect = (p0: Vec, p1: Vec, r: number): Vec[] => {
+ const x0 = Math.min(p0.x, p1.x), x1 = Math.max(p0.x, p1.x), y0 = Math.min(p0.y, p1.y), y1 = Math.max(p0.y, p1.y);
+ const rr = Math.min(r, (x1 - x0) / 2, (y1 - y0) / 2);
+ const o: Vec[] = [];
+ const corner = (cx: number, cy: number, a0: number) => {
+ for (let i = 0; i <= 6; i++) {
+ const an = a0 + (i / 6) * (Math.PI / 2);
+ o.push({ x: cx + Math.cos(an) * rr, y: cy + Math.sin(an) * rr });
+ }
+ };
+ corner(x1 - rr, y1 - rr, 0);
+ corner(x0 + rr, y1 - rr, Math.PI / 2);
+ corner(x0 + rr, y0 + rr, Math.PI);
+ corner(x1 - rr, y0 + rr, (3 * Math.PI) / 2);
+ o.push(o[0]);
+ return o;
+ };
const wallX = (y: number) => -1.2 - 0.025 * y;
+ const vertebrae: Vec[][] = [];
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();
+ vertebrae.push(roundRect(P(x0, y0 + 1.4), P(x0 + 1.6, y0), 0.32 * k));
}
- 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 palRaw: [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]];
+ const palOral = palRaw.map(([x, y]) => t.P(x, y));
+ // the mandible's body only: its ramus is lateral, not in the midsagittal plane
+ const jb = f.jawBone.filter((p) => p.x > 0.8 * k);
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);
+ const hy = { x: P(1.6, 0).x, y: P(0, 2.9).y + 0.6 * lar };
+ const rings: Vec[][] = [];
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);
+ rings.push([{ 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 }, { x: g.x + 0.8 * k, y }]);
}
- // ---- 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;
+ const fibres: Vec[][] = [];
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();
+ const ctrl = { x: tc.x, y: (tc.y + origin.y) / 2 };
+ const c: Vec[] = [];
+ for (let j = 0; j <= 12; j++) {
+ const u = j / 12;
+ c.push({ x: (1 - u) * (1 - u) * origin.x + 2 * (1 - u) * u * ctrl.x + u * u * end.x, y: (1 - u) * (1 - u) * origin.y + 2 * (1 - u) * u * ctrl.y + u * u * end.y });
+ }
+ fibres.push(c);
+ }
+ const wallAtGlottis = { x: wallX(g.y / k) * k, y: g.y };
+ const geo: Geometry = {
+ f,
+ model,
+ skinLower: [...neckFront, ...llOut.slice().reverse()],
+ skinUpper: [...ulOut, ...face.slice(1), ...cranium.slice(1)],
+ 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),
+ 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),
+ 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),
+ sulcus: catmullRom([B(5.4, 19.4), B(2.4, 20.5), B(-1.4, 20.4), B(-4.8, 18.4)], 4),
+ eye: ellipse(B(6.5, 15.4), 1.1 * k, 0.95 * k),
+ lens: ellipse(B(7.35, 15.4), 0.18 * k, 0.42 * k, 0, 20),
+ vertebrae,
+ cords: [[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)], [P(-5.1, -4.6), P(-4.7, -4.6), P(-4.72, 11.4), P(-5.15, 11.6)]],
+ nasal: 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),
+ turbinates: ([[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).map(([cx, cy, rx, ry]) => ellipse(B(cx, cy), rx * k, ry * k, -0.04)),
+ palOral,
+ palNasal: palOral.map((p) => ({ x: p.x, y: p.y + 0.55 * k })),
+ jawLower: jb,
+ jawUpper: jb.map((p) => ({ x: p.x, y: p.y + 0.75 * k })),
+ hyoid: ellipse(hy, 0.5 * k, 0.28 * k, 0.3, 28),
+ 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 }, { x: g.x + 0.75 * k, y: g.y - 1.6 * k }],
+ trachea: [[{ x: g.x - 0.65 * k, y: g.y }, { x: g.x - 0.75 * k, y: -4.8 }], [{ x: g.x + 0.75 * k, y: g.y }, { x: g.x + 0.95 * k, y: -4.8 }]],
+ rings,
+ outerWall: f.outer.filter((p) => p.y > g.y || p.x > 0),
+ glottisWall: [wallAtGlottis, f.outer.find((p) => p.y > g.y) ?? wallAtGlottis],
+ fibres,
+ folds: [
+ [{ 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 }, { x: g.x - 0.62 * k, y: g.y + 0.05 }],
+ [{ 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 }, { x: g.x + 0.72 * k, y: g.y + 0.05 }],
+ ],
+ lowerTeeth: [...f.lowerTeeth, J(6.8, 6.0), J(6.4, 6.2), f.lowerTeeth[0]],
+ };
+ this.geo = geo;
+ return geo;
+ }
+
+ // ------------------------------------------------------------------ main draw
+ draw(
+ ctx: CanvasRenderingContext2D,
+ model: VoiceModel,
+ f: HumanFrame,
+ a: HumanArtic,
+ tele: TelemetryMessage | null,
+ view: ViewFlags,
+ opts: { hover: HandleId | null; drag: HandleId | null; dt: number; formants: number[]; slots: Slot[]; info: string[] },
+ ): void {
+ this.clock += opts.dt;
+ const G = this.geometry(model, f, a);
+ const pts = (v: Vec[]) => v.map((p) => this.P(p));
+ const line = (v: Vec[], color: string, w: number, o: { alpha?: number; hot?: boolean; close?: boolean } = {}) => beamPts(ctx, pts(v), color, w, o);
+
+ // deep structures, dim blue
+ line(G.inset, V.blueDim, 0.9, { alpha: 0.9 });
+ line(G.skull, V.blueDim, 0.9, { close: true });
+ line(G.brain, V.blueMid, 1.1, { close: true });
+ line(G.sulcus, V.blueDim, 0.9);
+ line(G.eye, V.blueMid, 1.1);
+ line(G.lens, V.blueDim, 0.9);
+ for (const v of G.vertebrae) line(v, V.blueDim, 1);
+ line(G.cords[0], V.blueDim, 0.8, { alpha: 0.8 });
+ line(G.cords[1], V.blueDim, 0.8, { alpha: 0.6 });
+ line(G.nasal, V.blueMid, 1, { close: true });
+ for (const tb of G.turbinates) line(tb, V.blueDim, 0.9);
+ line(G.palOral, V.blueMid, 1.1);
+ line(G.palNasal, V.blueMid, 1.1);
+ line(G.hyoid, V.blueDim, 1);
+ line(G.thyroid, V.blueDim, 1);
+ for (const tr of G.trachea) line(tr, V.blueMid, 1);
+ for (const r of G.rings) line(r, V.blueDim, 0.9);
+
+ // the airway's cross-section lines: lit by sound pressure, else a dim measurement grid
+ if (view.pressure && tele) this.drawPressure(ctx, model, f, tele);
+ else if (view.grid) for (const gs of f.grid) seg(ctx, this.X(gs.inner), this.Y(gs.inner), this.X(gs.outer), this.Y(gs.outer), V.blueDim, 0.9, { alpha: 0.7 });
+ if (view.particles && tele) this.drawParticles(ctx, model, f, tele, opts.dt);
+
+ // afterglow: where the tongue, jaw and lips were a moment ago
+ if (tele && this.clock - this.lastEcho >= 0.028) {
+ this.lastEcho = this.clock;
+ this.echoes.push({ t: this.clock, tongue: f.tongue.slice(), jaw: G.jawLower, upperLip: chaikin(f.upperLip.map((p) => [p.x, p.y] as Pt)), lowerLip: chaikin(f.lowerLip.map((p) => [p.x, p.y] as Pt)) });
+ while (this.echoes.length && this.clock - this.echoes[0].t > 0.12) this.echoes.shift();
}
- 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");
- // soft edges: one blur pass over the finished layer. A filter set while drawing blurs every
- // fill separately (~60 full-canvas passes a frame), which held the app at a few fps.
- const s = this.sctx;
- s.setTransform(1, 0, 0, 1, 0, 0);
- s.globalCompositeOperation = "source-over";
- s.clearRect(0, 0, this.soft.width, this.soft.height);
- if (this.canFilter) s.filter = `blur(${(0.55 * this.dpr).toFixed(2)}px)`;
- s.drawImage(this.tissue, 0, 0);
- s.filter = "none";
- // film grain over tissue (multiplicative-ish), not blurred
- if (this.grain) {
- s.globalCompositeOperation = "overlay";
- s.globalAlpha = 0.22;
- s.fillStyle = this.grain;
- this.path(s, head);
- s.fill();
- s.globalAlpha = 1;
- s.globalCompositeOperation = "source-over";
+ if (tele) {
+ ECHO_AGES.forEach((age, i) => {
+ const e = this.nearestEcho(this.clock - age);
+ if (!e) return;
+ const o = 0.1 + 0.07 * i;
+ line(e.tongue, V.green, 1, { alpha: o });
+ line(e.jaw, V.red, 1, { alpha: o * 0.9 });
+ const lip = (q: Pt[]) => beamPts(ctx, q.map(([x, y]) => [this.ox + x * this.scale, this.oy - y * this.scale] as Pt), V.pink, 1, { alpha: o * 0.9 });
+ lip(e.upperLip);
+ lip(e.lowerLip);
+ });
}
+
+ // skin, airway walls, teeth, folds
+ line(G.skinLower, V.blue, 1.7, { hot: true });
+ line(G.skinUpper, V.blue, 1.7, { hot: true });
+ line(G.outerWall, V.blue, 1.4, { hot: true });
+ line(f.inner, V.blue, 1.3, { alpha: 0.9 });
+ line(G.glottisWall, V.blue, 1.2, { alpha: 0.8 });
+ line(f.epiglottis.slice(0, 3), V.blue, 2.2, { alpha: 0.85 });
+ line(f.upperTeeth, V.blueMid, 1.1, { close: true });
+ line(G.lowerTeeth, V.blueMid, 1.1);
+ for (const fo of G.folds) line(fo, V.blue, 1);
+
+ // the four handled articulators in their slot colours
+ const tongueOutline = pts(f.tongue);
+ ctx.save();
+ const clip = new Path2D();
+ tongueOutline.forEach(([x, y], i) => (i ? clip.lineTo(x, y) : clip.moveTo(x, y)));
+ clip.closePath();
+ ctx.clip(clip);
+ for (const fb of G.fibres) line(fb, V.green, 0.8, { alpha: 0.32 });
+ ctx.restore();
+ // left open: its closing chord runs along the floor of the mouth
+ beamPts(ctx, tongueOutline, V.green, 1.6, { hot: true });
+ line(G.jawLower, V.red, 1.5, { hot: true });
+ line(G.jawUpper, V.red, 1, { alpha: 0.45 });
+ const soft = (v: Vec[], it: number) => chaikin(v.map((p) => this.P(p)), it);
+ beamPts(ctx, soft(f.upperLip, 2), V.pink, 1.5, { hot: true });
+ beamPts(ctx, soft(f.lowerLip, 2), V.pink, 1.5, { hot: true });
+ beamPts(ctx, soft(f.velum, 3), V.white, 1.25, { alpha: 0.92 });
+
+ if (tele) this.drawTurbulence(ctx, model, f, tele);
+ if (view.calipers) this.drawCalipers(ctx, f);
+ this.drawHandles(ctx, model, f, a, opts.hover, opts.drag);
+ this.drawReadouts(ctx, opts.formants, opts.info, opts.slots);
}
- private palatePoints(model: VoiceModel): Vec[] {
- const t = model.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 nearestEcho(t: number): Echo | null {
+ let best: Echo | null = null, bd = 0.016;
+ for (const e of this.echoes) {
+ const d = Math.abs(e.t - t);
+ if (d < bd) {
+ bd = d;
+ best = e;
+ }
+ }
+ return best;
}
private gridPoint(f: HumanFrame, s: number, u: number): Vec | null {
@@ -389,8 +411,7 @@ export class AnatomyRenderer {
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)
+ private nodeValueAtS(values: ArrayLike<number>, nodeS: Float64Array, s: number): number {
let best = 0, bd = Infinity;
for (let i = 0; i < nodeS.length; i++) {
const d = Math.abs(nodeS[i] - s);
@@ -402,43 +423,24 @@ export class AnatomyRenderer {
return values[best] ?? 0;
}
- private drawPressure(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage): void {
- const ctx = this.ctx;
+ private drawPressure(ctx: CanvasRenderingContext2D, model: VoiceModel, f: HumanFrame, tele: TelemetryMessage): void {
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();
+ for (const g of f.grid) {
+ const lvl = Math.pow(pressureLevel(this.nodeValueAtS(t.pressureRms, nodeS, g.s)), 0.85);
+ seg(ctx, this.X(g.inner), this.Y(g.inner), this.X(g.outer), this.Y(g.outer), heat(lvl), 1.15, { alpha: 0.35 + 0.65 * lvl });
}
- ctx.globalCompositeOperation = "source-over";
}
- private drawParticles(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage, dt: number): void {
- const ctx = this.ctx;
+ private drawParticles(ctx: CanvasRenderingContext2D, model: VoiceModel, f: HumanFrame, tele: TelemetryMessage, dt: number): void {
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";
+ const path = [new Path2D(), new Path2D(), new Path2D()];
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));
@@ -447,9 +449,7 @@ export class AnatomyRenderer {
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 {
+ if (!(Math.abs(u) < 3 && p.life > 0)) {
p.s = Math.random() * 0.8;
p.u = Math.random() * 2 - 1;
p.life = 0.6 + Math.random() * 0.8;
@@ -460,131 +460,90 @@ export class AnatomyRenderer {
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();
+ // three brightness bands, one stroke each
+ const band = Math.min(2, Math.floor(Math.min(1, Math.abs(vis) / 6) * Math.min(1, p.life) * 3));
+ path[band].moveTo(p.px, p.py);
+ path[band].lineTo(x, y);
}
p.px = x;
p.py = y;
}
+ path.forEach((pa, i) => beam(ctx, pa, "#ffe2a8", 1.1, { alpha: 0.16 + 0.2 * i }));
}
- private drawTurbulence(model: VoiceModel, f: HumanFrame, tele: TelemetryMessage): void {
+ private drawTurbulence(ctx: CanvasRenderingContext2D, 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 rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
+ for (let i = 0; i < 30; 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();
+ dot(ctx, this.X(pos), this.Y(pos), 0.6 + rnd() * 1.4, "#f4fbff", 0.15 + 0.7 * intensity * rnd());
}
- ctx.globalCompositeOperation = "source-over";
}
- private drawCalipers(f: HumanFrame, tele: TelemetryMessage | null): void {
- const ctx = this.ctx;
- // narrowest constriction marker
+ private drawCalipers(ctx: CanvasRenderingContext2D, f: HumanFrame): void {
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;
+ if (mi < 0 || ma >= 1.2) return;
+ const g = f.grid[mi];
+ const [x0, y0] = this.P(g.inner), [x1, y1] = this.P(g.outer);
+ seg(ctx, x0, y0, x1, y1, V.white, 1.4, { hot: true });
+ const nx = -(y1 - y0), ny = x1 - x0, nl = Math.hypot(nx, ny) || 1;
+ for (const [x, y] of [[x0, y0], [x1, y1]]) seg(ctx, x - (nx / nl) * 4, y - (ny / nl) * 4, x + (nx / nl) * 4, y + (ny / nl) * 4, V.white, 1.2);
+ const lx = Math.max(x0, x1) + 10, ly = Math.min(y0, y1) - 4;
+ label(ctx, ma <= 0.0005 ? "CLOSED" : `${ma.toFixed(2)} CM²`, lx, ly, { size: 11, color: V.white, ls: 0.12 });
}
- private drawHandles(model: VoiceModel, f: HumanFrame, a: HumanArtic, hover: HandleId | null, drag: HandleId | null): void {
- const ctx = this.ctx;
+ private drawHandles(ctx: CanvasRenderingContext2D, model: VoiceModel, f: HumanFrame, a: HumanArtic, hover: HandleId | null, drag: HandleId | null): void {
+ const colour: Record<HandleId, string> = { tongue: V.green, jaw: V.red, lips: V.pink, velum: V.white, tip: V.blueMid, larynx: V.blueMid };
+ const size: Record<HandleId, number> = { tongue: 8, jaw: 7, lips: 7, velum: 6, tip: 5, larynx: 5 };
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();
+ handle(ctx, x, y, colour[h.id], size[h.id] + (active ? 2 : 0), active ? 1 : 0.9);
+ if (active) {
+ ring(ctx, x, y, 28, colour[h.id], 1, { alpha: 0.75 });
+ label(ctx, h.label.toUpperCase(), x + 32, y - 18, { size: 12, color: colour[h.id], ls: 0.18 });
}
- 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;
+ private drawReadouts(ctx: CanvasRenderingContext2D, formants: number[], info: string[], slots: Slot[]): void {
+ const fx = this.w - 18;
+ let y = 26;
+ if (formants.length >= 3) {
+ ["F1", "F2", "F3"].forEach((lab, i) => {
+ label(ctx, lab, fx - 78, y + i * 22, { size: 12, color: V.amber, ls: 0.12, alpha: 0.75 });
+ label(ctx, String(Math.round(formants[i])), fx, y + i * 22, { size: 15, color: V.amber, align: "right", ls: 0.08 });
+ });
+ label(ctx, "HZ", fx, y + 64, { size: 10, color: V.amber, align: "right", alpha: 0.6 });
+ y += 110;
+ }
+ for (const s of info) {
+ label(ctx, s, fx, y, { size: 10, color: V.blueMid, align: "right", ls: 0.14 });
+ y += 16;
+ }
+ if (!slots.length) return;
+ // the empty space under the chin and in front of the neck
+ const gx0 = this.X({ x: 3.35, y: 0 }), gy0 = this.Y({ x: 0, y: 2.05 });
+ const cellW = Math.max(60, (this.w - 14 - gx0) / 2);
+ const cellH = Math.max(56, Math.min(112, (this.h - 8 - gy0) / 2));
+ const big = Math.max(22, Math.min(44, cellH * 0.4, cellW * 0.32));
+ slots.slice(0, 4).forEach((s, i) => {
+ const cx = gx0 + (i % 2) * cellW, cy = gy0 + Math.floor(i / 2) * cellH;
+ dot(ctx, cx + 6, cy + 4, 4, s.color);
+ label(ctx, s.label.toUpperCase(), cx + 16, cy + 8, { size: 11, color: s.color, ls: 0.2, alpha: 0.85 });
+ const by = cy + 18 + big * 1.1;
+ if (s.ipa) ipaGlyph(ctx, cx + big * 0.6, by, s.value, big * 1.45, s.color);
+ else label(ctx, s.value.toUpperCase(), cx, by, { size: s.value.length > 3 ? big * 0.82 : big, color: s.color, weight: "m", ls: 0.04 });
+ if (s.unit) label(ctx, s.unit.toUpperCase(), s.ipa ? cx + big * 1.5 : cx + (s.value.length > 3 ? 0 : big * 1.64), s.ipa || s.value.length <= 3 ? by : by + 18, { size: 11, color: s.color, ls: 0.16, alpha: 0.7 });
+ });
}
}
diff --git a/src/ui/render/vector.ts b/src/ui/render/vector.ts
new file mode 100644
index 0000000..ed37e36
--- /dev/null
+++ b/src/ui/render/vector.ts
@@ -0,0 +1,252 @@
+/**
+ * Drawing kit for the vector-display screens: glowing beams, Hershey labels, handles, IPA
+ * glyphs drawn as strokes, and the shared glow pass. Coordinates are CSS pixels (the context is
+ * pre-scaled by usePhosphor / the anatomy view).
+ *
+ * Beams are drawn additively ("lighter"), so where lines cross they get brighter, like a beam.
+ */
+import { V, core } from "../colors.ts";
+
+export type Pt = [number, number];
+
+/** Hershey Simplex first; anything it lacks (IPA, ², ×) falls back to Archivo, which covers IPA. */
+export const HERSHEY = '"Hershey", "Archivo", system-ui, sans-serif';
+export const hfont = (size: number, weight: "l" | "m" = "l") => `${weight === "m" ? 500 : 300} ${size}px ${HERSHEY}`;
+
+const hasLetterSpacing = typeof CanvasRenderingContext2D !== "undefined" && "letterSpacing" in CanvasRenderingContext2D.prototype;
+
+export interface BeamOpts {
+ alpha?: number;
+ /** whitish core, for the brightest lines */
+ hot?: boolean;
+ dash?: number[];
+ close?: boolean;
+}
+
+/** a path through screen points */
+export function pathOf(pts: ArrayLike<Pt>, close = false): Path2D {
+ const p = new Path2D();
+ if (pts.length === 0) return p;
+ p.moveTo(pts[0][0], pts[0][1]);
+ for (let i = 1; i < pts.length; i++) p.lineTo(pts[i][0], pts[i][1]);
+ if (close) p.closePath();
+ return p;
+}
+
+/** stroke a path as a glowing beam */
+export function beam(ctx: CanvasRenderingContext2D, path: Path2D, color: string, width: number, o: BeamOpts = {}): void {
+ ctx.save();
+ ctx.globalCompositeOperation = "lighter";
+ ctx.globalAlpha = o.alpha ?? 1;
+ ctx.lineJoin = "round";
+ ctx.lineCap = "round";
+ ctx.setLineDash(o.dash ?? []);
+ ctx.strokeStyle = color;
+ ctx.lineWidth = width;
+ ctx.stroke(path);
+ if (o.hot) {
+ // the whitish core is laid over the line, not added to it (adding saturates to white)
+ ctx.globalCompositeOperation = "source-over";
+ ctx.strokeStyle = core(color);
+ ctx.lineWidth = width * 0.42;
+ ctx.stroke(path);
+ }
+ ctx.restore();
+}
+
+/** beam through points */
+export function beamPts(ctx: CanvasRenderingContext2D, pts: ArrayLike<Pt>, color: string, width: number, o: BeamOpts = {}): void {
+ if (pts.length < 2) return;
+ beam(ctx, pathOf(pts, o.close), color, width, o);
+}
+
+/** a single straight segment */
+export function seg(ctx: CanvasRenderingContext2D, x0: number, y0: number, x1: number, y1: number, color: string, width: number, o: BeamOpts = {}): void {
+ const p = new Path2D();
+ p.moveTo(x0, y0);
+ p.lineTo(x1, y1);
+ beam(ctx, p, color, width, o);
+}
+
+export function ring(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, color: string, width = 1.2, o: BeamOpts = {}): void {
+ const p = new Path2D();
+ p.arc(x, y, r, 0, Math.PI * 2);
+ beam(ctx, p, color, width, o);
+}
+
+export function dot(ctx: CanvasRenderingContext2D, x: number, y: number, r: number, color: string, alpha = 1): void {
+ ctx.save();
+ ctx.globalCompositeOperation = "lighter";
+ ctx.globalAlpha = alpha;
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.arc(x, y, r, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.restore();
+}
+
+/** a handle: ring with crosshair ticks */
+export function handle(ctx: CanvasRenderingContext2D, x: number, y: number, color: string, r = 7, alpha = 1): void {
+ const t = 4;
+ const p = new Path2D();
+ p.arc(x, y, r, 0, Math.PI * 2);
+ p.moveTo(x - r - t, y);
+ p.lineTo(x - r + 2, y);
+ p.moveTo(x + r - 2, y);
+ p.lineTo(x + r + t, y);
+ p.moveTo(x, y - r - t);
+ p.lineTo(x, y - r + 2);
+ p.moveTo(x, y + r - 2);
+ p.lineTo(x, y + r + t);
+ beam(ctx, p, color, 1.25, { alpha });
+}
+
+export interface LabelOpts {
+ size?: number;
+ color?: string;
+ align?: CanvasTextAlign;
+ baseline?: CanvasTextBaseline;
+ weight?: "l" | "m";
+ /** letter spacing as a fraction of the size */
+ ls?: number;
+ alpha?: number;
+}
+
+/** Hershey text (pass capitals for chrome-style labels) */
+export function label(ctx: CanvasRenderingContext2D, text: string, x: number, y: number, o: LabelOpts = {}): void {
+ const size = o.size ?? 11;
+ ctx.save();
+ ctx.globalCompositeOperation = "lighter";
+ ctx.globalAlpha = o.alpha ?? 1;
+ ctx.font = hfont(size, o.weight);
+ if (hasLetterSpacing) (ctx as CanvasRenderingContext2D & { letterSpacing: string }).letterSpacing = `${((o.ls ?? 0.14) * size).toFixed(2)}px`;
+ ctx.textAlign = o.align ?? "left";
+ ctx.textBaseline = o.baseline ?? "alphabetic";
+ ctx.fillStyle = o.color ?? V.blue;
+ ctx.fillText(text, x, y);
+ ctx.restore();
+}
+
+/** Chaikin corner cutting (closed shapes), for soft tissue the engine gives as coarse polygons */
+export function chaikin(p: Pt[], it = 2): Pt[] {
+ let q = p.length > 1 && p[0][0] === p[p.length - 1][0] && p[0][1] === p[p.length - 1][1] ? p.slice(0, -1) : p.slice();
+ for (let k = 0; k < it; k++) {
+ const o: Pt[] = [];
+ for (let i = 0; i < q.length; i++) {
+ const a = q[i], b = q[(i + 1) % q.length];
+ o.push([a[0] * 0.75 + b[0] * 0.25, a[1] * 0.75 + b[1] * 0.25], [a[0] * 0.25 + b[0] * 0.75, a[1] * 0.25 + b[1] * 0.75]);
+ }
+ q = o;
+ }
+ return q.length ? [...q, q[0]] : q;
+}
+
+// ------------------------------------------------------------------ IPA as strokes
+// Latin letters come from the Hershey font; vowels it lacks are built from strokes or from font
+// glyphs turned and mirrored; anything else falls back to the font stack (Archivo has IPA).
+
+/** Draw an IPA symbol centred on x with its baseline at y. Decorative: give the screen a text equivalent. */
+export function ipaGlyph(ctx: CanvasRenderingContext2D, x: number, y: number, ipa: string, size: number, color: string, alpha = 1): void {
+ const xh = size * 0.5;
+ const r = xh * 0.48;
+ const cy = y - xh / 2;
+ const sw = Math.max(0.9, size * 0.07);
+ const f = (n: number) => n.toFixed(2);
+ const stroke = (d: string) => {
+ ctx.save();
+ ctx.globalCompositeOperation = "lighter";
+ ctx.globalAlpha = alpha;
+ ctx.strokeStyle = color;
+ ctx.lineWidth = sw;
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ ctx.stroke(new Path2D(d));
+ ctx.restore();
+ };
+ const glyph = (s: string, tf?: (c: CanvasRenderingContext2D) => void) => {
+ ctx.save();
+ ctx.globalCompositeOperation = "lighter";
+ ctx.globalAlpha = alpha;
+ ctx.font = hfont(size);
+ ctx.textAlign = "center";
+ ctx.textBaseline = "alphabetic";
+ ctx.fillStyle = color;
+ if (tf) tf(ctx);
+ ctx.fillText(s, tf ? 0 : x, tf ? 0 : y);
+ ctx.restore();
+ };
+ const turned = (c: CanvasRenderingContext2D) => {
+ c.translate(x, cy);
+ c.rotate(Math.PI);
+ c.translate(0, xh / 2);
+ };
+ const mirrored = (c: CanvasRenderingContext2D) => {
+ c.translate(x, y);
+ c.scale(-1, 1);
+ };
+ const bowl = (c: number) => `M${f(c + r)} ${f(cy)}A${f(r)} ${f(xh / 2)} 0 1 0 ${f(c - r)} ${f(cy)}A${f(r)} ${f(xh / 2)} 0 1 0 ${f(c + r)} ${f(cy)}`;
+ switch (ipa) {
+ case "ɑ": { const c = x - 0.06 * size; return stroke(bowl(c) + `M${f(c + r)} ${f(y - xh)}L${f(c + r)} ${f(y)}`); }
+ case "ɒ": { const c = x + 0.06 * size; return stroke(bowl(c) + `M${f(c - r)} ${f(y - xh)}L${f(c - r)} ${f(y)}`); }
+ case "ɪ": return stroke(`M${f(x)} ${f(y - xh)}L${f(x)} ${f(y)}M${f(x - xh * 0.3)} ${f(y - xh)}L${f(x + xh * 0.3)} ${f(y - xh)}M${f(x - xh * 0.3)} ${f(y)}L${f(x + xh * 0.3)} ${f(y)}`);
+ case "ɛ": return stroke(`M${f(x + r * 0.9)} ${f(y - xh * 0.92)}Q${f(x - r * 1.1)} ${f(y - xh * 1.08)} ${f(x - r * 0.25)} ${f(cy)}Q${f(x - r * 1.3)} ${f(y + xh * 0.1)} ${f(x + r * 0.95)} ${f(y - xh * 0.06)}`);
+ case "ɜ": return stroke(`M${f(x - r * 0.9)} ${f(y - xh * 0.92)}Q${f(x + r * 1.1)} ${f(y - xh * 1.08)} ${f(x + r * 0.25)} ${f(cy)}Q${f(x + r * 1.3)} ${f(y + xh * 0.1)} ${f(x - r * 0.95)} ${f(y - xh * 0.06)}`);
+ case "ɝ": return stroke(`M${f(x - r * 0.9)} ${f(y - xh * 0.92)}Q${f(x + r * 1.1)} ${f(y - xh * 1.08)} ${f(x + r * 0.25)} ${f(cy)}Q${f(x + r * 1.3)} ${f(y + xh * 0.1)} ${f(x - r * 0.95)} ${f(y - xh * 0.06)}M${f(x + r * 0.55)} ${f(cy - xh * 0.1)}Q${f(x + r * 1.4)} ${f(cy - xh * 0.5)} ${f(x + r * 1.5)} ${f(cy - xh * 0.15)}`);
+ case "ʊ": return stroke(`M${f(x - r * 1.15)} ${f(y - xh)}Q${f(x - r * 0.5)} ${f(y - xh * 0.9)} ${f(x - r * 0.75)} ${f(cy)}Q${f(x - r)} ${f(y)} ${f(x)} ${f(y)}Q${f(x + r)} ${f(y)} ${f(x + r * 0.75)} ${f(cy)}Q${f(x + r * 0.5)} ${f(y - xh * 0.9)} ${f(x + r * 1.15)} ${f(y - xh)}`);
+ case "ʌ": return stroke(`M${f(x - r)} ${f(y)}L${f(x)} ${f(y - xh)}L${f(x + r)} ${f(y)}`);
+ case "ɤ": return stroke(`M${f(x - r)} ${f(y - xh)}L${f(x)} ${f(y - xh * 0.1)}L${f(x + r)} ${f(y - xh)}M${f(x)} ${f(y - xh * 0.1)}Q${f(x - r * 0.5)} ${f(y + xh * 0.4)} ${f(x)} ${f(y + xh * 0.45)}Q${f(x + r * 0.5)} ${f(y + xh * 0.4)} ${f(x)} ${f(y - xh * 0.1)}`);
+ case "ə": return stroke(`M${f(x - r)} ${f(cy)}L${f(x + r)} ${f(cy)}A${f(r)} ${f(xh / 2)} 0 1 1 ${f(x - r * 0.75)} ${f(y - xh * 0.85)}`);
+ case "ɐ": return glyph("a", turned);
+ case "ɔ": return glyph("c", mirrored);
+ case "ɯ": return glyph("m", turned);
+ case "ɨ": glyph("i"); return stroke(`M${f(x - r * 0.8)} ${f(cy)}L${f(x + r * 0.8)} ${f(cy)}`);
+ case "ø": glyph("o"); return stroke(`M${f(x - r * 1.1)} ${f(y + xh * 0.1)}L${f(x + r * 1.1)} ${f(y - xh * 1.1)}`);
+ case "æ": return glyph("æ");
+ case "œ": return glyph("œ");
+ default: return glyph(ipa);
+ }
+}
+
+// ------------------------------------------------------------------ the glow
+/**
+ * One reduced-resolution glow layer: the finished frame is copied down, blurred there (cheap:
+ * a fraction of the pixels), and added back on top. sigma is the halo radius in CSS px.
+ */
+export class Glow {
+ private readonly small: HTMLCanvasElement;
+ private readonly sctx: CanvasRenderingContext2D;
+ private readonly canFilter: boolean;
+ constructor(
+ private readonly sigma = 2,
+ private readonly alpha = 0.75,
+ private readonly down = 4,
+ ) {
+ this.small = document.createElement("canvas");
+ this.sctx = this.small.getContext("2d")!;
+ this.canFilter = typeof this.sctx.filter === "string";
+ }
+
+ apply(canvas: HTMLCanvasElement, ctx: CanvasRenderingContext2D, dpr: number): void {
+ const W = canvas.width, H = canvas.height;
+ const w = Math.max(1, Math.round(W / this.down)), h = Math.max(1, Math.round(H / this.down));
+ if (this.small.width !== w || this.small.height !== h) {
+ this.small.width = w;
+ this.small.height = h;
+ }
+ const s = this.sctx;
+ s.setTransform(1, 0, 0, 1, 0, 0);
+ s.globalCompositeOperation = "copy";
+ if (this.canFilter) s.filter = `blur(${((this.sigma * dpr) / this.down).toFixed(2)}px)`;
+ s.drawImage(canvas, 0, 0, w, h);
+ if (this.canFilter) s.filter = "none";
+ ctx.save();
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ // screen, not add: the halo brightens around a line without bleaching the line itself
+ ctx.globalCompositeOperation = "screen";
+ ctx.globalAlpha = this.alpha;
+ ctx.imageSmoothingEnabled = true;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(this.small, 0, 0, W, H);
+ ctx.restore();
+ }
+}
diff --git a/src/ui/styles.css b/src/ui/styles.css
index d305738..619f087 100644
--- a/src/ui/styles.css
+++ b/src/ui/styles.css
@@ -1,3 +1,15 @@
+@font-face {
+ font-family: "Hershey";
+ src: url("/fonts/AVHersheySimplexLight.otf") format("opentype");
+ font-weight: 100 400;
+ font-display: swap;
+}
+@font-face {
+ font-family: "Hershey";
+ src: url("/fonts/AVHersheySimplexMedium.otf") format("opentype");
+ font-weight: 401 900;
+ font-display: swap;
+}
@font-face {
font-family: "Archivo";
src: url("/fonts/archivo-latin.woff2") format("woff2");
@@ -16,17 +28,30 @@
}
:root {
+ /* the vector-display palette (src/ui/colors.ts V): blue is the body, amber is sound,
+ green/red/pink/white are the four control slots */
+ --blue: #4fb6f2;
+ --blue-mid: #3487c4;
+ --blue-dim: #1f5f8c;
+ --frame: #133954;
+ --green: #5be381;
+ --red: #ff5d40;
+ --pink: #ff73cf;
+ --white: #eef6f8;
+ --amber: #ffb340;
+ --glow-blue: 0 0 1.5px rgba(79, 182, 242, 0.9), 0 0 6px rgba(79, 182, 242, 0.4);
+ /* older names, remapped so screens not yet redrawn sit on black in blue and amber */
--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;
+ --console: #000000;
+ --inset: #000000;
+ --line: var(--frame);
+ --text: var(--blue);
+ --text-dim: var(--blue-mid);
+ --caliper: var(--amber);
+ --caliper-dim: rgba(255, 179, 64, 0.45);
+ --radius-s: 0;
+ --radius-m: 0;
+ --font: "Hershey", "Archivo", system-ui, -apple-system, "Segoe UI", "Noto Sans", sans-serif;
color-scheme: dark;
}
@@ -1327,3 +1352,621 @@ button.midi.on .midi-status {
justify-items: start;
color: var(--text);
}
+
+/* =====================================================================================
+ Vector display (issue #2, docs/mockups): a wall of black screens with thin frames,
+ single-stroke capitals and a restrained glow. Later rules here override the ones above.
+ ===================================================================================== */
+
+html,
+body {
+ background: #000;
+ color: var(--blue);
+ font-size: 13px;
+ letter-spacing: 0.06em;
+}
+
+:focus-visible {
+ outline: 1px dashed var(--blue);
+ outline-offset: 2px;
+}
+
+.app {
+ display: grid;
+ grid-template-rows: auto auto;
+ align-content: start;
+ min-height: 100vh;
+ gap: 8px;
+ padding: 6px 16px 16px;
+}
+
+/* ---------- top bar */
+.topbar {
+ gap: 18px 24px;
+ padding: 4px 2px;
+ min-height: 40px;
+}
+
+.brand {
+ gap: 18px;
+ align-items: baseline;
+}
+
+.wordmark {
+ font-weight: 500;
+ font-size: 22px;
+ letter-spacing: 0.34em;
+ text-transform: uppercase;
+ text-shadow: var(--glow-blue);
+}
+
+.tagline {
+ font-size: 10px;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--blue-dim);
+}
+
+.segmented {
+ background: transparent;
+ border: 0;
+ padding: 0;
+ gap: 8px;
+}
+
+.segmented button {
+ border: 1px solid transparent;
+ border-radius: 0;
+ padding: 4px 11px;
+ font-size: 12px;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: var(--blue-dim);
+}
+
+.segmented button:hover {
+ color: var(--blue-mid);
+}
+
+.segmented button.on {
+ background: transparent;
+ color: var(--blue);
+ border-color: var(--blue);
+ box-shadow: 0 0 5px rgba(79, 182, 242, 0.35), inset 0 0 4px rgba(79, 182, 242, 0.15);
+ text-shadow: var(--glow-blue);
+}
+
+.volume,
+.load {
+ font-size: 10px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--blue-dim);
+}
+
+/* ---------- buttons, chips */
+button.primary,
+button.ghost,
+.chip {
+ appearance: none;
+ background: transparent;
+ border: 1px solid var(--frame);
+ border-radius: 0;
+ color: var(--blue-mid);
+ padding: 5px 11px;
+ font-family: var(--font);
+ font-weight: 300;
+ font-size: 11px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ cursor: pointer;
+ filter: none;
+}
+
+button.primary {
+ color: var(--blue);
+ border-color: var(--blue);
+ box-shadow: 0 0 5px rgba(79, 182, 242, 0.35), inset 0 0 4px rgba(79, 182, 242, 0.15);
+ text-shadow: var(--glow-blue);
+}
+
+button.primary.large {
+ font-size: 13px;
+ padding: 10px 18px;
+}
+
+button.ghost:hover,
+.chip:hover {
+ color: var(--blue);
+ border-color: var(--blue-dim);
+}
+
+.chip.on,
+.chip[aria-pressed="true"] {
+ color: var(--blue);
+ border-color: var(--blue);
+ box-shadow: 0 0 5px rgba(79, 182, 242, 0.35), inset 0 0 4px rgba(79, 182, 242, 0.15);
+ text-shadow: var(--glow-blue);
+}
+
+/* ---------- the wall */
+.wall {
+ display: grid;
+ grid-template-columns: minmax(0, 700fr) minmax(0, 696fr);
+ gap: 12px;
+ height: max(760px, calc(100vh - 70px));
+}
+
+.right {
+ display: grid;
+ gap: 12px;
+ min-height: 0;
+ min-width: 0;
+}
+
+.right-play {
+ grid-template-columns: minmax(0, 284fr) minmax(0, 58fr) minmax(0, 342fr);
+ grid-template-rows: minmax(0, 200fr) minmax(0, 200fr) minmax(0, 224fr) minmax(0, 172fr);
+ grid-template-areas: "tube tube folds" "spec spec spec" "vowels voice voice" "keys keys keys";
+}
+
+.s-tube { grid-area: tube; }
+.s-folds { grid-area: folds; }
+.s-spec { grid-area: spec; }
+.s-vowels { grid-area: vowels; }
+.s-voice { grid-area: voice; }
+.s-keys { grid-area: keys; }
+
+/* modes not yet redrawn: their three instruments on the right, their deck below the wall */
+.right-legacy {
+ grid-template-rows: repeat(3, minmax(0, 1fr));
+}
+
+/* ---------- a screen */
+.screen {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+ background: #000;
+ border: 1px solid var(--frame);
+}
+
+.screen.focus {
+ border-color: var(--blue-dim);
+}
+
+.screen-head {
+ display: flex;
+ align-items: baseline;
+ gap: 6px 16px;
+ flex-wrap: wrap;
+ padding: 9px 14px 0;
+}
+
+.screen-title {
+ margin: 0;
+ font-size: 12px;
+ font-weight: 300;
+ letter-spacing: 0.2em;
+ text-transform: uppercase;
+ color: var(--blue);
+ text-shadow: var(--glow-blue);
+}
+
+.screen-sub {
+ font-size: 10px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--blue-mid);
+}
+
+.screen-tools {
+ margin-left: auto;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.screen-body {
+ position: relative;
+ flex: 1;
+ min-height: 110px;
+}
+
+.screen-body > canvas,
+.screen-body > .anatomy,
+.screen-body > .creature-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+}
+
+.left .screen-body {
+ min-height: 420px;
+}
+
+/* view options as chips in the face screen's header */
+.view-toggles {
+ position: static;
+ flex-direction: row;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.view-toggles .toggle {
+ position: relative;
+ display: inline-flex;
+}
+
+.view-toggles .toggle input {
+ position: absolute;
+ opacity: 0;
+ width: 1px;
+ height: 1px;
+}
+
+.view-toggles .toggle span {
+ border: 1px solid var(--frame);
+ padding: 2px 7px;
+ font-size: 9px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ color: var(--blue-dim);
+ cursor: pointer;
+}
+
+.view-toggles .toggle input:checked + span {
+ color: var(--blue);
+ border-color: var(--blue-dim);
+ text-shadow: var(--glow-blue);
+}
+
+.view-toggles .toggle input:focus-visible + span {
+ outline: 1px dashed var(--blue);
+ outline-offset: 1px;
+}
+
+/* the start prompt, over the left screen */
+.start-prompt {
+ background: rgba(0, 0, 0, 0.88);
+ border: 1px solid var(--blue-dim);
+ border-radius: 0;
+ backdrop-filter: none;
+ max-width: 380px;
+ padding: 22px 26px;
+ box-shadow: 0 0 10px rgba(79, 182, 242, 0.15);
+}
+
+.start-prompt p {
+ font-size: 12px;
+ line-height: 1.6;
+ color: var(--blue-mid);
+}
+
+.start-prompt .hint {
+ font-size: 11px;
+ color: var(--blue-dim);
+}
+
+.start-prompt .error {
+ color: var(--red);
+}
+
+/* ---------- encoders (OP-1 style) */
+.enc-pages {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 2px 10px 10px;
+ gap: 4px;
+}
+
+.enc-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+
+.screen-tools .chip {
+ padding: 2px 8px;
+ font-size: 9px;
+}
+
+.enc-tab {
+ appearance: none;
+ background: transparent;
+ border: 1px solid var(--frame);
+ color: var(--blue-dim);
+ padding: 2px 7px;
+ font-family: var(--font);
+ font-size: 9px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ cursor: pointer;
+}
+
+.enc-tab.on {
+ color: var(--blue);
+ border-color: var(--blue);
+ text-shadow: var(--glow-blue);
+}
+
+.enc-row {
+ flex: 1;
+ display: grid;
+ grid-template-columns: repeat(4, minmax(0, 1fr));
+ align-items: center;
+ min-height: 0;
+}
+
+.encoder {
+ display: grid;
+ justify-items: center;
+ align-content: center;
+ gap: 2px;
+ min-width: 0;
+ color: var(--slot);
+}
+
+.enc-label {
+ font-size: 10px;
+ letter-spacing: 0.2em;
+ text-transform: uppercase;
+ opacity: 0.85;
+ white-space: nowrap;
+}
+
+.enc-dial {
+ position: relative;
+ width: 76px;
+ height: 76px;
+ touch-action: pan-y;
+ cursor: ns-resize;
+}
+
+.enc-dial svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ overflow: visible;
+ filter: drop-shadow(0 0 2px var(--slot));
+}
+
+.enc-tick { stroke: var(--slot); stroke-width: 1; opacity: 0.35; }
+.enc-ring { fill: none; stroke: var(--slot); stroke-width: 1.1; opacity: 0.55; }
+.enc-arc { fill: none; stroke: var(--slot); stroke-width: 2.2; stroke-linecap: round; }
+.enc-pointer { stroke: var(--slot); stroke-width: 1.6; stroke-linecap: round; }
+.enc-hub { fill: var(--slot); }
+
+.enc-input {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ opacity: 0;
+ pointer-events: none;
+}
+
+.enc-dial:has(.enc-input:focus-visible) {
+ outline: 1px dashed var(--slot);
+ outline-offset: 4px;
+}
+
+.enc-value {
+ font-weight: 500;
+ font-size: 28px;
+ line-height: 1.05;
+ letter-spacing: 0.02em;
+ text-shadow: 0 0 2px var(--slot);
+}
+
+.enc-unit {
+ font-size: 9px;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+ opacity: 0.7;
+ white-space: nowrap;
+}
+
+.enc-footer {
+ display: flex;
+ gap: 6px;
+ justify-content: center;
+}
+
+/* ---------- keys */
+.s-keys .screen-body {
+ padding: 8px 14px 12px;
+ display: flex;
+ min-height: 90px;
+}
+
+.s-keys .keys-row {
+ flex: 1;
+ min-width: 0;
+}
+
+.keys {
+ height: auto;
+ flex: 1;
+}
+
+.key.white {
+ background: transparent;
+ border: 1px solid var(--blue-dim);
+ border-radius: 0;
+}
+
+.key.white.down {
+ background: rgba(91, 227, 129, 0.12);
+ border-color: var(--green);
+ box-shadow: 0 0 6px rgba(91, 227, 129, 0.5), inset 0 0 6px rgba(91, 227, 129, 0.25);
+}
+
+.key.black {
+ background: #000;
+ border: 1px solid var(--blue-mid);
+ border-radius: 0;
+}
+
+.key.black.down {
+ background: rgba(91, 227, 129, 0.2);
+ border-color: var(--green);
+ box-shadow: 0 0 6px rgba(91, 227, 129, 0.5);
+}
+
+button.midi {
+ border-radius: 0;
+ border-color: var(--frame);
+}
+
+.midi-name {
+ font-size: 10px;
+ font-weight: 300;
+ letter-spacing: 0.16em;
+ text-transform: uppercase;
+}
+
+.midi-status {
+ font-size: 9px;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--blue-dim);
+}
+
+button.midi.on {
+ border-color: var(--green);
+}
+
+button.midi.on .midi-status {
+ color: var(--green);
+}
+
+/* ---------- panels of modes not yet redrawn: framed, black, capital headings */
+.panel,
+.instrument,
+.keys-bar {
+ background: #000;
+ border: 1px solid var(--frame);
+ border-radius: 0;
+}
+
+.panel h2,
+.instrument figcaption {
+ font-weight: 300;
+ font-size: 12px;
+ letter-spacing: 0.2em;
+ text-transform: uppercase;
+ color: var(--blue);
+}
+
+textarea,
+input[type="text"],
+.sbn input {
+ background: #000;
+ color: var(--blue);
+ border: 1px solid var(--frame);
+ border-radius: 0;
+ font-family: var(--font);
+ letter-spacing: 0.06em;
+}
+
+.slider label,
+.toggle,
+.call-name,
+.pad-name,
+.specimen-name {
+ text-transform: uppercase;
+ letter-spacing: 0.12em;
+}
+
+/* sliders that remain: a thin line, the set part brighter, a small framed thumb */
+input[type="range"]::-webkit-slider-runnable-track {
+ height: 1px;
+ border-radius: 0;
+ background: linear-gradient(to right, var(--blue) 0, var(--blue) var(--pos, 0%), var(--blue-dim) var(--pos, 0%));
+}
+
+input[type="range"]::-moz-range-track {
+ height: 1px;
+ border-radius: 0;
+ background: var(--blue-dim);
+}
+
+input[type="range"]::-moz-range-progress {
+ height: 1px;
+ background: var(--blue);
+}
+
+input[type="range"]::-webkit-slider-thumb {
+ width: 7px;
+ height: 13px;
+ margin-top: -6px;
+ border-radius: 0;
+ background: #000;
+ border: 1px solid var(--blue);
+ box-shadow: 0 0 4px rgba(79, 182, 242, 0.5);
+}
+
+input[type="range"]::-moz-range-thumb {
+ width: 7px;
+ height: 13px;
+ border-radius: 0;
+ background: #000;
+ border: 1px solid var(--blue);
+ box-shadow: 0 0 4px rgba(79, 182, 242, 0.5);
+}
+
+/* ---------- narrow screens: one column, the face first */
+@media (max-width: 1100px) {
+ .wall {
+ grid-template-columns: minmax(0, 1fr);
+ height: auto;
+ }
+ .left .screen-body {
+ min-height: min(78vh, 760px);
+ }
+ .right-play {
+ grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);
+ grid-template-rows: none;
+ grid-auto-rows: auto;
+ grid-template-areas: "tube folds" "spec spec" "vowels vowels" "voice voice" "keys keys";
+ }
+ .right-play .screen-body {
+ min-height: 190px;
+ }
+ .s-voice .screen-body {
+ min-height: 230px;
+ }
+ .right-legacy {
+ grid-template-rows: none;
+ }
+ .right-legacy .screen-body {
+ min-height: 170px;
+ }
+}
+
+@media (max-width: 640px) {
+ .app {
+ padding: 6px 8px 12px;
+ }
+ .right-play {
+ grid-template-columns: minmax(0, 1fr);
+ grid-template-areas: "tube" "folds" "spec" "vowels" "voice" "keys";
+ }
+ .left .screen-body {
+ min-height: 118vw;
+ }
+ .enc-row {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ row-gap: 10px;
+ }
+ .s-voice .screen-body {
+ min-height: 380px;
+ }
+}
diff --git a/src/ui/useCanvas.ts b/src/ui/useCanvas.ts
index ee24320..8c4a09d 100644
--- a/src/ui/useCanvas.ts
+++ b/src/ui/useCanvas.ts
@@ -47,6 +47,8 @@ export function useCanvasLoop(draw: (f: CanvasFrame) => void) {
return ref;
}
+/** Canvas font in the Hershey stack (heavier weights map to its medium cut; IPA falls back to Archivo). */
export function font(size: number, weight = 450, width = 100): string {
- return `${weight} ${size}px Archivo, system-ui, sans-serif`;
+ void width;
+ return `${weight >= 550 ? 500 : 300} ${size}px "Hershey", "Archivo", system-ui, sans-serif`;
}
diff --git a/src/ui/usePhosphor.ts b/src/ui/usePhosphor.ts
new file mode 100644
index 0000000..67487b7
--- /dev/null
+++ b/src/ui/usePhosphor.ts
@@ -0,0 +1,53 @@
+import { useEffect, useRef } from "react";
+import { Glow } from "./render/vector.ts";
+import type { CanvasFrame } from "./useCanvas.ts";
+
+/**
+ * Canvas for a vector-display screen: devicePixelRatio scaling (capped at 2), resize observer,
+ * a rAF loop that clears to black, calls draw() in CSS pixels, then adds the glow.
+ * Screens draw every frame: telemetry, afterglow and scrolling views change outside the store.
+ */
+export function usePhosphor(draw: (f: CanvasFrame) => void, opts: { sigma?: number; alpha?: number } = {}) {
+ const ref = useRef<HTMLCanvasElement>(null);
+ const drawRef = useRef(draw);
+ drawRef.current = draw;
+ const { sigma, alpha } = opts;
+ useEffect(() => {
+ const canvas = ref.current!;
+ const ctx = canvas.getContext("2d")!;
+ const glow = new Glow(sigma, alpha);
+ 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(1, 0, 0, 1, 0, 0);
+ ctx.globalCompositeOperation = "source-over";
+ ctx.globalAlpha = 1;
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, canvas.width, canvas.height);
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ drawRef.current({ ctx, w, h, dpr, dt, now });
+ glow.apply(canvas, ctx, dpr);
+ }
+ raf = requestAnimationFrame(loop);
+ };
+ raf = requestAnimationFrame(loop);
+ return () => {
+ cancelAnimationFrame(raf);
+ ro.disconnect();
+ };
+ }, [sigma, alpha]);
+ return ref;
+}
diff --git a/tools/e2e.ts b/tools/e2e.ts
index a780910..3a77dee 100644
--- a/tools/e2e.ts
+++ b/tools/e2e.ts
@@ -200,3 +200,5 @@ 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|transcription|creature|held|back to|beatbox|silence|sing/i.test(l)).slice(0, 40).join("\n"));
+// a run that collected errors fails, so CI and agents can't read it as a pass
+if (errors.length) process.exit(1);