the ultimate vocal synthesizer - sing, speak, beatbox, and more
Rust
Review round 2: side-based ray crossings, honest jump refinement, epiglottis tip
Jameson Hodgec9020c3a4dab
diff --git a/src/engine/anatomy/geom.ts b/src/engine/anatomy/geom.tsindex 6a26a91..632485d 100644--- a/src/engine/anatomy/geom.ts+++ b/src/engine/anatomy/geom.ts@@ -64,18 +64,29 @@ export function rayPolyline(ox: number, oy: number, dx: number, dy: number, pl:let n = 0;const xs = pl.xs, ys = pl.ys;for (let i = 0; i < xs.length - 1; i++) {- const ax = xs[i], ay = ys[i];- const ex = xs[i + 1] - ax, ey = ys[i + 1] - ay;- const den = dx * ey - dy * ex;- if (Math.abs(den) < 1e-12) continue;- const wx = ax - ox, wy = ay - oy;- const t = (wx * ey - wy * ex) / den;- const u = (wx * dy - wy * dx) / den;- if (u >= 0 && u < 1 && t >= tMin && t <= tMax) out[n++] = t;+ const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);+ if (t >= tMin && t <= tMax && n < out.length) out[n++] = t;}return n;}+/**+ * Where segment A→B crosses the line through o along d (as t along d), or NaN. A segment+ * crosses only if its ends lie on different sides of the line, a point on the line counting as+ * the positive side: a polyline passing through a vertex then crosses once, and one that only+ * touches the line at a vertex crosses twice at the same t or not at all (a half-open rule on+ * the segment parameter kept one crossing of such a touch, an unmatched entry or exit).+ */+function crossingT(ox: number, oy: number, dx: number, dy: number, ax: number, ay: number, bx: number, by: number): number {+ const sa = dx * (ay - oy) - dy * (ax - ox) >= 0;+ const sb = dx * (by - oy) - dy * (bx - ox) >= 0;+ if (sa === sb) return NaN;+ const ex = bx - ax, ey = by - ay;+ const den = dx * ey - dy * ex;+ if (Math.abs(den) < 1e-15) return NaN;+ return ((ax - ox) * ey - (ay - oy) * ex) / den;+}+/*** Like rayPolyline, also telling for each crossing whether the ray leaves the tissue (the* polyline's right-hand side, along its direction) for the air: `exit[i]` is 1 then, else 0.@@ -84,16 +95,11 @@ export function rayCrossings(ox: number, oy: number, dx: number, dy: number, pl:let n = 0;const xs = pl.xs, ys = pl.ys;for (let i = 0; i < xs.length - 1; i++) {- const ax = xs[i], ay = ys[i];- const ex = xs[i + 1] - ax, ey = ys[i + 1] - ay;- const den = dx * ey - dy * ex;- if (Math.abs(den) < 1e-12) continue;- const wx = ax - ox, wy = ay - oy;- const t = (wx * ey - wy * ex) / den;- const u = (wx * dy - wy * dx) / den;- if (u >= 0 && u < 1 && t >= tMin && t <= tMax && n < outT.length) {+ const t = crossingT(ox, oy, dx, dy, xs[i], ys[i], xs[i + 1], ys[i + 1]);+ if (t >= tMin && t <= tMax && n < outT.length) {outT[n] = t;- exit[n] = den < 0 ? 1 : 0;+ // leaving the tissue (on the polyline's right) for the air: the ray turns left across it+ exit[n] = dx * (ys[i + 1] - ys[i]) - dy * (xs[i + 1] - xs[i]) < 0 ? 1 : 0;n++;}}diff --git a/src/engine/anatomy/human.ts b/src/engine/anatomy/human.tsindex 80ae3ac..c4255d5 100644--- a/src/engine/anatomy/human.ts+++ b/src/engine/anatomy/human.ts@@ -365,16 +365,23 @@ export class HumanVocalTract {// pharyngeal rays (a pocket makes ray crossings flip discontinuously)const inner = new Polyline();inner.push(epiBase).push(epiTip);+ // The wall leaves the epiglottis tip upward, for where the tongue's back (root, then the+ // dorsum arc) first rises above it: with the tongue low and the larynx high the whole root+ // can sit below the tip, and a wall coming back down from it made the tip a peak that a+ // horizontal ray measured past (to the root) or not (to the epiglottis) — a jump.const yRoot = epiTip.y + 0.05 * k;- let rootStart = root.findIndex((q) => q.y > yRoot);- if (rootStart < 0) rootStart = root.length - 1;- else if (rootStart > 0) {+ const back = [...root, ...arcPts.slice(1)];+ let start = back.findIndex((q) => q.y > yRoot);+ if (start < 0) start = back.length - 1;+ else if (start > 0) {// start exactly at that height, not at the next sample point (which jumped along the root)- const a = root[rootStart - 1], b = root[rootStart];+ const a = back[start - 1], b = back[start];inner.push(lerpV(a, b, clamp((yRoot - a.y) / Math.max(1e-9, b.y - a.y), 0, 1)));}- for (let i = rootStart; i < root.length; i++) inner.push(root[i]);- inner.append(arcPts, true);+ if (start < root.length) {+ for (let i = start; i < root.length; i++) inner.push(root[i]);+ inner.append(arcPts, true);+ } else inner.append(arcPts.slice(start - root.length + 1), true);inner.append(blade, true);inner.append(under, true);inner.append(floor, true);diff --git a/tests/geometry-continuity.test.ts b/tests/geometry-continuity.test.tsindex 62291cf..b40f103 100644--- a/tests/geometry-continuity.test.ts+++ b/tests/geometry-continuity.test.ts@@ -6,28 +6,43 @@import { describe, expect, test } from "bun:test";import { HumanVocalTract, NEUTRAL, BODY_MALE, BODY_FEMALE, BODY_CHILD, restTip, type HumanArtic } from "../src/engine/anatomy/human.ts";import { vowelArtic } from "../src/engine/phonetics/planner.ts";+import { Polyline, rayCrossings } from "../src/engine/anatomy/geom.ts";import TARGETS from "../src/engine/phonetics/vowelTargets.generated.json";/**- * Max area change across [u − h, u] for a path through postures; a true discontinuity keeps its- * size as h shrinks, a steep but continuous ramp does not.+ * The largest change that survives refinement of [u0, u1] to 2⁻²⁰ of its width: every half+ * still changing by more than `tol` is refined (keeping only the larger half could follow a+ * steep ramp and miss a real jump in the other). A true discontinuity keeps its size; a steep+ * but continuous ramp shrinks away.*/-function jumpSize(areas: (u: number) => number[], u0: number, u1: number): number {- // bisect towards the largest change inside the coarse step, down to a millionth of it- let lo = u0, hi = u1;+export function jumpSize(areas: (u: number) => number[], u0: number, u1: number, tol = 0.05): number {+ const memo = new Map<number, number[]>();+ const at = (u: number) => {+ let v = memo.get(u);+ if (!v) memo.set(u, (v = areas(u)));+ return v;+ };const diff = (a: number, b: number) => {- const x = areas(a), y = areas(b);+ const x = at(a), y = at(b);let m = 0;for (let j = 0; j < x.length; j++) m = Math.max(m, Math.abs(x[j] - y[j]));return m;};- for (let it = 0; it < 20; it++) {+ let worst = 0;+ const visit = (lo: number, hi: number, depth: number, d: number) => {+ if (depth === 20) {+ worst = Math.max(worst, d);+ return;+ }const mid = (lo + hi) / 2;- if (diff(lo, mid) >= diff(mid, hi)) hi = mid;- else lo = mid;- }- return diff(lo, hi);+ const d1 = diff(lo, mid), d2 = diff(mid, hi);+ if (d1 > tol) visit(lo, mid, depth + 1, d1);+ if (d2 > tol) visit(mid, hi, depth + 1, d2);+ };+ const d = diff(u0, u1);+ if (d > tol) visit(u0, u1, 0, d);+ return worst;}const SWEEPS: [keyof HumanArtic, number, number][] = [@@ -43,16 +58,17 @@ const SWEEPS: [keyof HumanArtic, number, number][] = [describe("tract geometry continuity", () => {test("no area jumps anywhere in the articulators' speech ranges", () => {- const tract = new HumanVocalTract(BODY_MALE);+ const jumps: string[] = [];+ const N = 400;+ for (const [bodyName, body] of [["male", BODY_MALE], ["female", BODY_FEMALE], ["child", BODY_CHILD]] as const) {+ const tract = new HumanVocalTract(body);const ph = new Float64Array(20), or = new Float64Array(24);const areas = (a: HumanArtic) => {tract.resample(a, tract.compute(a), 20, 24, ph, or);return [...ph, ...or];};- const jumps: string[] = [];- const N = 400;for (const vw of ["i", "ɑ", "u", "ə"]) {- const v = vowelArtic(vw, "male")!;+ const v = vowelArtic(vw, bodyName)!;const tip = restTip(v.jaw ?? NEUTRAL.jaw, v.tbX!, v.tbY!);const base: HumanArtic = { ...NEUTRAL, ...v, ttX: tip.x, ttY: tip.y };for (const [key, lo, hi] of SWEEPS) {@@ -71,10 +87,11 @@ describe("tract geometry continuity", () => {if (!(s > 0.25 && s > 6 * Math.max(med, 0.01))) return;const f = (u: number) => areas({ ...base, [key]: lo + (hi - lo) * u });const j = jumpSize(f, i / N, (i + 1) / N);- if (j > 0.05) jumps.push(`${vw} ${key}=${(lo + ((hi - lo) * (i + 1)) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);+ if (j > 0.05) jumps.push(`${bodyName} ${vw} ${key}=${(lo + ((hi - lo) * (i + 1)) / N).toFixed(3)}: ${j.toFixed(2)} cm²`);});}}+ }expect(jumps).toEqual([]);});@@ -114,4 +131,41 @@ describe("tract geometry continuity", () => {}expect(jumps).toEqual([]);});++ test("refinement finds a small jump beside a steep ramp", () => {+ const f = (u: number) => [Math.min(1.6 * u, 0.8) + (u >= 0.75 ? 0.1 : 0)];+ expect(jumpSize(f, 0, 1)).toBeCloseTo(0.1, 3);+ expect(jumpSize((u) => [Math.min(1.6 * u, 0.8)], 0, 1)).toBe(0); // a ramp alone is no jump+ });++ test("a ray grazing a polyline vertex sees no tissue layer that is not there", () => {+ // a polyline touching the ray's line at a vertex (from either side): no crossing, or an+ // entry and its exit at the same point, never one unmatched crossing+ const t: number[] = new Array(8), ex = new Uint8Array(8);+ for (const side of [-1, 1]) {+ const touch = new Polyline();+ touch.push({ x: side, y: -1 }).push({ x: 0, y: 0 }).push({ x: side, y: 1 });+ const n = rayCrossings(0, -5, 0, 1, touch, 0, 10, t, ex);+ expect(n === 0 || (n === 2 && t[0] === t[1] && ex[0] !== ex[1])).toBe(true);+ }+ // a polyline passing through the line at a vertex crosses it once+ const through = new Polyline();+ through.push({ x: -1, y: -1 }).push({ x: 0, y: 0 }).push({ x: 1, y: 1 });+ expect(rayCrossings(0, -5, 0, 1, through, 0, 10, t, ex)).toBe(1);+ // the reviewer's posture: a fan ray grazing the tip of a calibrated /ɝ/ exactly at a vertex+ const tract = new HumanVocalTract(BODY_MALE);+ const base = { ...NEUTRAL, ...(TARGETS as Record<string, Record<string, { artic: Partial<HumanArtic> }>>).male["ɝ"].artic, ttX: 5.625 } as HumanArtic;+ const ph = new Float64Array(20), or = new Float64Array(24);+ const areas = (ttY: number) => {+ const a = { ...base, ttY };+ tract.resample(a, tract.compute(a), 20, 24, ph, or);+ return [...ph, ...or];+ };+ const y = 8.588839057347066;+ const [a, b, c] = [areas(y - 1e-9), areas(y), areas(y + 1e-9)];+ for (let j = 0; j < a.length; j++) {+ expect(Math.abs(b[j] - a[j])).toBeLessThan(1e-3);+ expect(Math.abs(c[j] - b[j])).toBeLessThan(1e-3);+ }+ });});