// Shared by the labs: one double pendulum as an audio-rate voice (time scaling, strikes that add // energy, signal extraction, DC removal). import { DoublePendulum } from "../physics/doublePendulum.ts"; import type { Signal } from "./protocol.ts"; /** ω of the lower small-swing mode (sim units), for the time scaling. */ export function lowMode(p: DoublePendulum): number { const { m1, m2, l1, l2, g } = p.cfg; const a = (m1 + m2) * l1 * l1, b = m2 * l1 * l2, c = m2 * l2 * l2; const ka = (m1 + m2) * g * l1, kc = m2 * g * l2; const det = a * c - b * b; const tr = (ka * c + kc * a) / det, dt = (ka * kc) / det; const lam = (tr - Math.sqrt(Math.max(0, tr * tr - 4 * dt))) / 2; return Math.sqrt(Math.max(lam, 1e-9)); } /** * Add `add` (absolute) energy: a momentum kick along the current momentum (like pushing a swing * in time, so it always adds), or in a random direction from rest, sized exactly. */ export function kick(p: DoublePendulum, add: number, rand: () => number) { const y = p.y; if (!(add > 0)) return; let u0 = y[2], u1 = y[3]; const pn = Math.hypot(u0, u1); if (pn > 1e-9) { u0 /= pn; u1 /= pn; } else { const a = rand() * 2 * Math.PI; u0 = Math.cos(a); u1 = Math.sin(a); } // energy after p → p + a·u is E + a·(u·ω) + ½a²·(u·M⁻¹u); solve for the positive a const now = p.derived(); const b = u0 * now.w1 + u1 * now.w2; const wu = p.derived([y[0], y[1], u0, u1]); const c = u0 * wu.w1 + u1 * wu.w2; const a = (-b + Math.sqrt(Math.max(0, b * b + 2 * c * add))) / c; y[2] += a * u0; y[3] += a * u1; } /** A state quantity as an audio signal, roughly normalized to ±1. */ export function signal(p: DoublePendulum, sig: Signal, w1: number, w2: number): number { const { l1, l2, m2 } = p.cfg; const y = p.y; const L = l1 + l2; const vmax = Math.sqrt((2 * p.vTop) / m2) + 1e-9; const s1 = Math.sin(y[0]), c1 = Math.cos(y[0]), s2 = Math.sin(y[1]), c2 = Math.cos(y[1]); switch (sig) { case "x2": return (l1 * s1 + l2 * s2) / L; case "y2": return -(l1 * c1 + l2 * c2) / L; case "vx2": return (l1 * c1 * w1 + l2 * c2 * w2) / vmax; case "vy2": return (l1 * s1 * w1 + l2 * s2 * w2) / vmax; case "x1": return s1; case "vx1": return (l1 * c1 * w1) / vmax; case "θ1": return Math.atan2(s1, c1) / Math.PI; case "θ2": return Math.atan2(s2, c2) / Math.PI; case "θ2−θ1": return Math.atan2(Math.sin(y[1] - y[0]), Math.cos(y[1] - y[0])) / Math.PI; case "ω1": return (w1 * l1) / vmax; case "ω2": return (w2 * l2) / vmax; case "p1": return y[2] / (vmax * (1 + m2) * l1 * l1 + 1e-9); case "p2": return y[3] / (vmax * m2 * l2 * l2 + 1e-9); case "speed2": return Math.hypot(l1 * c1 * w1 + l2 * c2 * w2, l1 * s1 * w1 + l2 * s2 * w2) / vmax; } } /** One-pole DC blocker. */ export class DcBlock { private x = 0; private y = 0; run(v: number, r: number): number { const o = v - this.x + r * this.y; this.x = v; this.y = o; return o; } }