main.js entry 67.8 KB
Copy main.js
SimKit.define({
title: "Car audio installation: wire the whole system yourself",
dt: 2e-5, speed: 0.05, height: 975,
params: {
wiring: { label: "Wiring: preset (1) / build it yourself (0)", unit: "", min: 0, max: 1, value: 1, step: 1 },
clear: { label: "Remove all wires (pulse 1, then back to 0)", unit: "", min: 0, max: 1, value: 0, step: 1 },
undo: { label: "Undo last wire (pulse 1, then back to 0)", unit: "", min: 0, max: 1, value: 0, step: 1 },
reset: { label: "Repair fuses and speakers (pulse 1, then back to 0)", unit: "", min: 0, max: 1, value: 0, step: 1 },
snd: { label: "Sound ON (1) / OFF (0)", unit: "", min: 0, max: 1, value: 0, step: 1 },
src: { label: "Head unit source: CD (0) / Radio (1)", unit: "", min: 0, max: 1, value: 0, step: 1 },
ign: { label: "Ignition key ON (1) / OFF (0)", unit: "", min: 0, max: 1, value: 1, step: 1 },
Vcc: { label: "Battery voltage", unit: "V", min: 9, max: 15, value: 13.8, step: 0.1 },
vol: { label: "Head unit volume", unit: "", min: 0, max: 1, value: 0.6, step: 0.01 },
gain: { label: "Amplifier gain", unit: "x", min: 0.2, max: 2, value: 1, step: 0.1 },
fc: { label: "Low-pass filter cutoff", unit: "Hz", min: 40, max: 400, value: 150, log: true },
C1: { label: "C1 (tweeter T1 capacitor)", unit: "µF", min: 1, max: 47, value: 10, log: true },
C2: { label: "C2 (tweeter T2 capacitor)", unit: "µF", min: 1, max: 47, value: 10, log: true },
F1: { label: "Fuse F1", unit: "A", min: 1, max: 40, value: 10, step: 1 },
F2: { label: "Fuse F2", unit: "A", min: 1, max: 40, value: 5, step: 1 },
F3: { label: "Fuse F3", unit: "A", min: 1, max: 40, value: 30, step: 1 },
F4: { label: "Fuse F4", unit: "A", min: 1, max: 40, value: 5, step: 1 }
},
_F: [100, 1000, 5000],
_PR: [0.5, 0.35, 0.2],
_cn: { hL: "Head unit L", hR: "Head unit R", aL: "Amp L", aR: "Amp R" },
_kind: {
tw: { k: 0.7, resp: [0.05, 0.3, 1], lim: [0.02, 0.2, 1] },
wf: { k: 1, resp: [1, 1, 0.3], lim: [1, 1, 1] },
sw: { k: 1.15, resp: [1, 0.1, 0], lim: [1, 0.3, 0.05] }
},
_WC: { r: "#e02424", k: "#161616", y: "#f2c40c", o: "#f28c0c", b: "#2f7be8", w: "#f4f4f4" },
_SC: { t1: "#1fb6c9", t2: "#f06ab0", w1: "#f4f4f4", w2: "#8a8a8a", r1: "#2eaa4a", r2: "#8e44ad", s1: "#8b5a2b", s2: "#0f7a6b" },
_PK: ["auto", "red", "black", "blue", "yellow", "orange", "green", "white", "brown", "purple", "gray", "pink", "cyan", "bw", "rw", "kw", "yk", "gw"],
_PAL: {
red: { c: "#e02424", n: "Red" }, black: { c: "#161616", n: "Black" }, blue: { c: "#2f7be8", n: "Blue" },
yellow: { c: "#f2c40c", n: "Yellow" }, orange: { c: "#f28c0c", n: "Orange" }, green: { c: "#2eaa4a", n: "Green" },
white: { c: "#f4f4f4", n: "White" }, brown: { c: "#8b5a2b", n: "Brown" }, purple: { c: "#8e44ad", n: "Purple" },
gray: { c: "#8a8a8a", n: "Gray" }, pink: { c: "#f06ab0", n: "Pink" }, cyan: { c: "#1fb6c9", n: "Cyan" },
bw: { c: "#2f7be8", s: "#f4f4f4", n: "Blue / white stripe" }, rw: { c: "#e02424", s: "#f4f4f4", n: "Red / white stripe" },
kw: { c: "#161616", s: "#f4f4f4", n: "Black / white stripe" }, yk: { c: "#f2c40c", s: "#161616", n: "Yellow / black stripe" },
gw: { c: "#2eaa4a", s: "#f4f4f4", n: "Green / white stripe" }
},
_spk: [
{ id: "t1", name: "T1", k: "tw", z: 4, p: 20, x: 156, y: 50, u: -1 },
{ id: "t2", name: "T2", k: "tw", z: 4, p: 20, x: 444, y: 50, u: 1 },
{ id: "w1", name: "W1", k: "wf", z: 8, p: 50, x: 44, y: 110, u: 1 },
{ id: "w2", name: "W2", k: "wf", z: 8, p: 50, x: 556, y: 110, u: -1 },
{ id: "r1", name: "R1", k: "wf", z: 8, p: 50, x: 44, y: 330, u: 1 },
{ id: "r2", name: "R2", k: "wf", z: 8, p: 50, x: 556, y: 330, u: -1 },
{ id: "s1", name: "S1", k: "sw", z: 4, p: 150, x: 44, y: 550, u: 1 },
{ id: "s2", name: "S2", k: "sw", z: 4, p: 150, x: 556, y: 550, u: -1 }
],
_roots: [110, 87.31, 130.81, 98],
_arps: [[440, 523.25, 659.25], [349.23, 440, 523.25], [523.25, 659.25, 783.99], [392, 493.88, 587.33]],
_bells: [2637, 2793, 3136, 2349],
_tt: null, _tm: null, _ix: null,
// ── Device specifications shown on each box ─────────────────────────
_spec: {
head: { ch: 4, rms: 20, impMin: 4 },
amp: { ch: 2, rms: 150, impMin: 2, bridge: 300 },
filt: { ch: 2 },
ant: { v: 12 }
},
_terms() {
if (this._tt) return this._tt;
const t = [];
const A = (id, x, y, k, lab, pos, tip) => t.push({ id, x, y, k, lab, pos, tip });
A("head.preL", 160, 210, "rcaL", "L", "r", "Head unit pre-out L (line level, white RCA)");
A("head.preR", 160, 240, "rcaR", "R", "r", "Head unit pre-out R (line level, red RCA)");
A("head.lp", 210, 270, "spk", "+", "u", "Head unit speaker out L+ (20W RMS, ≥4Ω)");
A("head.lm", 240, 270, "spk", "\u2212", "u", "Head unit speaker out L-");
A("head.rp", 280, 270, "spk", "+", "u", "Head unit speaker out R+ (20W RMS, ≥4Ω)");
A("head.rm", 310, 270, "spk", "\u2212", "u", "Head unit speaker out R-");
A("head.rem", 340, 270, "rem", "REMOTE", "v", "Head unit remote output (blue/white, 12V @ 300mA when on)");
A("head.ant", 370, 270, "pwr", "ANT 12V", "v", "Head unit antenna 12V output (blue, 300mA max)");
A("head.mem", 400, 270, "pwr", "MEM 12V", "v", "Head unit memory input (yellow, always-on 12V via fuse F2)");
A("head.acc", 430, 270, "pwr", "ACC 12V", "v", "Head unit accessory input (orange, 12V via key + fuse F1)");
A("head.gnd", 460, 270, "gnd", "GND", "v", "Head unit ground (black wire)");
A("head.antin", 420, 210, "rf", "ANT IN", "l", "Head unit antenna input (coax)");
// ── Stereo low-pass filter: 2 inputs, 2 outputs ────────────────────
A("filt.inL", 200, 410, "rcaL", "L", "d", "Filter input L (connect head PRE OUT L)");
A("filt.inR", 230, 410, "rcaR", "R", "d", "Filter input R (connect head PRE OUT R)");
A("filt.outL", 285, 410, "rcaL", "L", "d", "Filter output L (connect amp LOW IN L)");
A("filt.outR", 315, 410, "rcaR", "R", "d", "Filter output R (connect amp LOW IN R)");
A("filt.pwr", 365, 410, "pwr", "12V+", "u", "Filter 12V+ input (via fuse F4)");
A("filt.gnd", 395, 410, "gnd", "GND", "u", "Filter ground (to chassis)");
A("amp.inL", 160, 530, "rcaL", "L", "r", "Amplifier low-level input L (2×150W RMS, ≥2Ω)");
A("amp.inR", 160, 570, "rcaR", "R", "r", "Amplifier low-level input R");
A("amp.lp", 210, 600, "spk", "+", "u", "Amplifier speaker out L+");
A("amp.lm", 240, 600, "spk", "\u2212", "u", "Amplifier speaker out L-");
A("amp.rp", 280, 600, "spk", "+", "u", "Amplifier speaker out R+");
A("amp.rm", 310, 600, "spk", "\u2212", "u", "Amplifier speaker out R-");
A("amp.rem", 400, 600, "rem", "ON/OFF", "v", "Amplifier remote turn-on input (from head REMOTE)");
A("amp.vcc", 430, 600, "pwr", "12V+", "v", "Amplifier 12V+ input (thick wire, fuse F3 at battery)");
A("amp.gnd", 460, 600, "gnd", "GND", "v", "Amplifier ground (short thick wire to chassis)");
for (const s of this._spk) {
const sx = s.x + s.u * 26, pos = s.u === 1 ? "r" : "l";
A(s.id + ".p", sx, s.y - 10, "spk", "+", pos, s.name + " speaker +");
A(s.id + ".m", sx, s.y + 10, "spk", "\u2212", pos, s.name + " speaker -");
}
A("c1.a", 200, 130, "cap", "", "", "Capacitor C1 terminal A");
A("c1.b", 160, 130, "cap", "", "", "Capacitor C1 terminal B");
A("c2.a", 400, 130, "cap", "", "", "Capacitor C2 terminal A");
A("c2.b", 440, 130, "cap", "", "", "Capacitor C2 terminal B");
A("ant.sig", 280, 130, "rf", "RF", "u", "Antenna signal output (coax)");
A("ant.pwr", 320, 130, "pwr", "12V", "u", "Antenna amplifier 12V+ (from head ANT output, 300mA)");
A("ant.gnd", 360, 130, "gnd", "GND", "u", "Antenna ground");
for (let k = 1; k <= 4; k++) {
const y = 620 + k * 30;
A("f" + k + ".a", 250, y, "ter", "", "", "Fuse F" + k + " terminal A");
A("f" + k + ".b", 330, y, "ter", "", "", "Fuse F" + k + " terminal B");
}
A("sw.a", 130, 690, "ter", "", "", "Ignition key terminal A");
A("sw.b", 190, 690, "ter", "", "", "Ignition key terminal B");
A("bat.pos", 70, 670, "pwr", "", "", "Battery positive (+12V, red)");
A("bat.neg", 70, 770, "gnd", "", "", "Battery negative (chassis)");
A("g1", 500, 230, "gnd", "", "", "Chassis ground lug 1");
A("g2", 500, 400, "gnd", "", "", "Chassis ground lug 2");
A("g3", 500, 620, "gnd", "", "", "Chassis ground lug 3");
A("g4", 140, 750, "gnd", "", "", "Chassis ground lug 4");
const ex = x => {
const id = x.id;
if (id === "head.antin") return 3;
if (id.indexOf("head.pre") === 0 || id.indexOf("amp.in") === 0) return 2;
if (/^(head|filt|amp|ant)\./.test(id)) return 1;
const m = /^([a-z]\d)\.([pm])$/.exec(id);
if (m) { const sp = this._spk.find(q => q.id === m[1]); return sp.u === 1 ? 0 : 2; }
if (id === "c1.a" || id === "c2.b") return 0;
if (id === "c1.b" || id === "c2.a") return 2;
if (/\.a$/.test(id)) return 2;
if (/\.b$/.test(id)) return 0;
if (id === "bat.pos" || id === "bat.neg") return 0;
if (/^g\d$/.test(id)) return 3;
return -1;
};
t.forEach(x => { x.ex = ex(x); });
this._tt = t;
return t;
},
_prep() {
if (this._tm) return;
const t = this._terms();
this._tm = {}; this._ix = {};
t.forEach((x, i) => { this._tm[x.id] = x; this._ix[x.id] = i; });
},
_preset() {
return [
["bat.pos", "f1.a"], ["f1.b", "sw.a"], ["sw.b", "head.acc"],
["bat.pos", "f2.a"], ["f2.b", "head.mem"],
["bat.pos", "f3.a"], ["f3.b", "amp.vcc"],
["sw.b", "f4.a"], ["f4.b", "filt.pwr"],
["head.rem", "amp.rem"],
["head.antin", "ant.sig"], ["head.ant", "ant.pwr"], ["ant.gnd", "g1"],
["head.gnd", "g1"], ["filt.gnd", "g2"], ["amp.gnd", "g3"],
["head.lp", "w1.p"], ["head.lm", "w1.m"], ["head.rp", "w2.p"], ["head.rm", "w2.m"],
["head.lp", "r1.p"], ["head.lm", "r1.m"], ["head.rp", "r2.p"], ["head.rm", "r2.m"],
["head.lp", "c1.a"], ["c1.b", "t1.p"], ["head.lm", "t1.m"],
["head.rp", "c2.a"], ["c2.b", "t2.p"], ["head.rm", "t2.m"],
// ── Stereo filter: both channels wired through ──────────────────
["head.preL", "filt.inL"], ["head.preR", "filt.inR"],
["filt.outL", "amp.inL"], ["filt.outR", "amp.inR"],
["amp.lp", "s1.p"], ["amp.lm", "s1.m"], ["amp.rp", "s2.p"], ["amp.rm", "s2.m"]
];
},
init(P, S) {
S.wires = []; S.lw = null; S.lu = 0; S.pend = null; S.pts = []; S.mx = -1e3; S.my = -1e3;
S.sig = ""; S.net = null;
S.rt = []; S.rsig = null; S.hw = -1; S.fr = 0;
S.fh = [0, 0, 0, 0]; S.fb = [false, false, false, false]; S.fi = [0, 0, 0, 0];
S.sh = {}; S.sb = {};
S.pw = { hL: 0, hR: 0, aL: 0, aR: 0 };
S.lv = {}; S.zl = {}; S.prot = {}; S.clip = { hL: 0, hR: 0, aL: 0, aR: 0 };
S.spp = {}; S.sv = {}; S.ca = {}; S.sa = {};
S.sc = { pre: 0, fo: 0, hL: 0, aL: 0, t1: 0, s1: 0 };
S.fan = 0; S.W = 600; S.H = 975; S.col = null; S.rad = 0; S.s = 1; S.ox = 0; S.oy = 0;
S.au = null; S.auErr = false; S.sndOn = false; S.lsnd = P.snd;
},
_cl(v, a, b) { return v < a ? a : v > b ? b : v; },
_tick(P, S) {
this._prep();
const w = P.wiring >= 0.5 ? 1 : 0;
if (S.lw !== w) { S.lw = w; S.wires = w ? this._preset() : []; S.pend = null; S.pts = []; }
if (P.clear >= 0.5 && S.wires.length) { S.wires = []; S.pend = null; S.pts = []; }
const u = P.undo >= 0.5 ? 1 : 0;
if (u && !S.lu) S.wires.pop();
S.lu = u;
if (P.reset >= 0.5) { S.fh = [0, 0, 0, 0]; S.fb = [false, false, false, false]; S.sh = {}; S.sb = {}; }
const sig = S.wires.map(x => x[0] + ">" + x[1]).join(",") + "|" +
S.fb.map(x => x ? 1 : 0).join("") + (P.ign >= 0.5 ? 1 : 0) +
this._spk.map(s => S.sb[s.id] ? 1 : 0).join("");
if (sig !== S.sig || !S.net) { S.sig = sig; S.net = this._solve(P, S); }
},
_solve(P, S) {
const ix = this._ix, n = this._tt.length;
const mk = () => { const p = []; for (let i = 0; i < n; i++) p.push(i); return p; };
const dcp = mk(), aup = mk();
const fd = (p, i) => { while (p[i] !== i) { p[i] = p[p[i]]; i = p[i]; } return i; };
const un = (p, a, b) => { a = fd(p, ix[a]); b = fd(p, ix[b]); if (a !== b) p[a] = b; };
for (const w of S.wires) { un(dcp, w[0], w[1]); un(aup, w[0], w[1]); }
if (P.ign >= 0.5) un(dcp, "sw.a", "sw.b");
["g1", "g2", "g3", "g4"].forEach(g => un(dcp, "bat.neg", g));
const nd = id => fd(dcp, ix[id]), na = id => fd(aup, ix[id]);
const hot = nd("bat.pos"), gnd = nd("bat.neg");
const fz = [1, 2, 3, 4].map(k => ({ a: nd("f" + k + ".a"), b: nd("f" + k + ".b"), ok: !S.fb[k - 1] }));
const energize = roots => {
const en = new Set(roots), par = new Map();
let ch = true;
while (ch) {
ch = false;
fz.forEach((f, k) => {
if (!f.ok) return;
if (en.has(f.a) && !en.has(f.b)) { en.add(f.b); par.set(f.b, { k, from: f.a }); ch = true; }
else if (en.has(f.b) && !en.has(f.a)) { en.add(f.a); par.set(f.a, { k, from: f.b }); ch = true; }
});
}
return { en, par };
};
const direct = hot === gnd;
const E1 = energize([hot]);
const short = direct || E1.en.has(gnd);
const pok = (E, id) => !short && E.en.has(nd(id));
const gok = id => nd(id) === gnd;
const hp = { mem: pok(E1, "head.mem"), acc: pok(E1, "head.acc"), gnd: gok("head.gnd") };
const headOn = hp.mem && hp.acc && hp.gnd;
const roots = [hot];
if (headOn) [nd("head.rem"), nd("head.ant")].forEach(x => { if (x !== gnd) roots.push(x); });
const E = energize(roots);
const ap = { vcc: pok(E, "amp.vcc"), rem: pok(E, "amp.rem"), gnd: gok("amp.gnd") };
const fp = { pwr: pok(E, "filt.pwr"), gnd: gok("filt.gnd") };
const ampOn = ap.vcc && ap.rem && ap.gnd, filtOn = fp.pwr && fp.gnd;
const fl = [[], [], [], []], sf = [false, false, false, false];
for (const [id, key] of [["head.mem", "mem"], ["head.acc", "head"], ["amp.vcc", "amp"], ["filt.pwr", "filt"]]) {
let x = nd(id);
if (!E.en.has(x)) continue;
while (E.par.has(x)) { const p = E.par.get(x); fl[p.k].push(key); x = p.from; }
}
if (!direct && E.en.has(gnd)) {
let x = gnd;
while (E.par.has(x)) { const p = E.par.get(x); sf[p.k] = true; x = p.from; }
}
// ── Detect unfused power connections ───────────────────────────────
const unfused = {
mem: pok(E1, "head.mem") && !E1.par.has(nd("head.mem")),
acc: pok(E1, "head.acc") && !E1.par.has(nd("head.acc")),
amp: pok(E, "amp.vcc") && !E.par.has(nd("amp.vcc")),
filt: pok(E, "filt.pwr") && !E.par.has(nd("filt.pwr"))
};
// ── Detect speakers connected directly across battery (DC burn) ────
const spkDC = {}, spkShort = {};
for (const s of this._spk) {
const Pp = nd(s.id + ".p"), Mm = nd(s.id + ".m");
spkDC[s.id] = (Pp === hot && Mm === gnd) || (Pp === gnd && Mm === hot);
spkShort[s.id] = (Pp === Mm);
}
const caps = [1, 2].map(k => ({ a: na("c" + k + ".a"), b: na("c" + k + ".b") }));
const reach = (f, t) => {
if (f === t) return [];
for (let i = 0; i < 2; i++) {
const c = caps[i];
for (const [a, b] of [[c.a, c.b], [c.b, c.a]]) {
if (a !== f) continue;
if (b === t) return [i];
const j = 1 - i, d = caps[j];
if ((d.a === b && d.b === t) || (d.b === b && d.a === t)) return [i, j];
}
}
return null;
};
const chs = [
{ key: "hL", src: "head", p: na("head.lp"), m: na("head.lm"), min: 3 },
{ key: "hR", src: "head", p: na("head.rp"), m: na("head.rm"), min: 3 },
{ key: "aL", src: "amp", p: na("amp.lp"), m: na("amp.lm"), min: 3 },
{ key: "aR", src: "amp", p: na("amp.rp"), m: na("amp.rm"), min: 3 }
];
for (const c of chs) { c.sp = []; c.short = c.p === c.m; }
for (const s of this._spk) {
const X = na(s.id + ".p"), Y = na(s.id + ".m");
if (X === Y) continue;
for (const c of chs) {
if (c.short) continue;
let a = reach(X, c.p), b = reach(Y, c.m), pol = 1;
if (!a || !b) { a = reach(X, c.m); b = reach(Y, c.p); pol = -1; }
if (a && b) { c.sp.push({ s, caps: a.concat(b), pol, h: [1, 1, 1] }); break; }
}
}
const ak = {};
for (const [k, id] of [["preL", "head.preL"], ["preR", "head.preR"],
["foL", "filt.outL"], ["foR", "filt.outR"],
["hL", "head.lp"], ["hL", "head.lm"], ["hR", "head.rp"], ["hR", "head.rm"],
["aL", "amp.lp"], ["aL", "amp.lm"], ["aR", "amp.rp"], ["aR", "amp.rm"]]) {
const r = na(id);
(ak[r] = ak[r] || []).push(k);
}
for (const c of caps) {
if (ak[c.a] && !ak[c.b]) ak[c.b] = ak[c.a].slice();
else if (ak[c.b] && !ak[c.a]) ak[c.a] = ak[c.b].slice();
}
const srcOf = id => {
const r = na(id);
for (const k of ["preL", "preR", "foL", "foR"]) if (ak[r] && ak[r].indexOf(k) >= 0) return k;
return null;
};
// Filter inputs: exclude feedback from own outputs
let fsrcL = srcOf("filt.inL");
if (fsrcL === "foL" || fsrcL === "foR") fsrcL = null;
let fsrcR = srcOf("filt.inR");
if (fsrcR === "foL" || fsrcR === "foR") fsrcR = null;
const coax = na("head.antin") === na("ant.sig");
const antPow = pok(E, "ant.pwr"), antGnd = gok("ant.gnd");
const antOk = headOn && coax && antPow && antGnd;
// Amp powered from low-current output?
const ampFromRem = nd("amp.vcc") === nd("head.rem") && nd("amp.vcc") !== hot;
const ampFromAnt = nd("amp.vcc") === nd("head.ant") && nd("amp.vcc") !== hot;
// Amp input connected to speaker-level output?
const ampInFromSpk = (r => (ak[r] && (ak[r].indexOf("hL") >= 0 || ak[r].indexOf("hR") >= 0)))(na("amp.inL")) ||
(r => (ak[r] && (ak[r].indexOf("hL") >= 0 || ak[r].indexOf("hR") >= 0)))(na("amp.inR"));
// Filter in/out shorted?
const filtLoopL = na("filt.inL") === na("filt.outL") && fsrcL;
const filtLoopR = na("filt.inR") === na("filt.outR") && fsrcR;
return {
nd, na, hot, gnd, E, short, direct, headOn, ampOn, filtOn, hp, ap, fp, fl, sf, coax, antPow, antGnd, antOk,
chs, ak, fsrcL, fsrcR, a1: srcOf("amp.inL"), a2: srcOf("amp.inR"),
unfused, spkDC, spkShort, ampFromRem, ampFromAnt, ampInFromSpk, filtLoopL, filtLoopR
};
},
step(dt, P, S, t) {
this._tick(P, S);
const N = S.net, F = this._F, PR = this._PR, TP = 6.2831853;
const sn = [Math.sin(TP * F[0] * t), Math.sin(TP * F[1] * t), Math.sin(TP * F[2] * t)];
const wv = a => a[0] * sn[0] + a[1] * sn[1] + a[2] * sn[2];
const vol = P.vol, Vh = P.Vcc, Va = 1.8 * P.Vcc;
// ── Burn speakers that are directly across DC (+12V and ground) ──
for (const s of this._spk) {
if (N.spkDC && N.spkDC[s.id] && !S.sb[s.id]) S.sb[s.id] = true;
}
S.rad = !N.headOn ? 0 : (P.src >= 0.5 ? (N.antOk ? 1 : 2) : 0);
const hOn = N.headOn, aOn = N.ampOn, fOn = N.filtOn;
// ── Stereo pre-out signal (same in this simplified model) ────────
const pre = [0, 0, 0], foL = [0, 0, 0], foR = [0, 0, 0];
for (let b = 0; b < 3; b++) {
pre[b] = hOn ? 3 * vol * PR[b] : 0;
const lp = 1 / Math.sqrt(1 + (F[b] / P.fc) * (F[b] / P.fc));
foL[b] = (fOn && N.fsrcL) ? pre[b] * lp : 0;
foR[b] = (fOn && N.fsrcR) ? pre[b] * lp : 0;
}
const sg = k => k === "foL" ? foL : k === "foR" ? foR : (k === "preL" || k === "preR") ? pre : null;
// ── Live levels for wire animation ──────────────────────────────
S.lv.preL = S.lv.preR = (pre[0] + pre[1] + pre[2]) / 3.2;
S.lv.foL = (foL[0] + foL[1] + foL[2]) / 3.2;
S.lv.foR = (foR[0] + foR[1] + foR[2]) / 3.2;
S.lv.fo = S.lv.foL;
const cap = [P.C1 * 1e-6, P.C2 * 1e-6];
const dr = {};
for (const c of N.chs) {
let a = [0, 0, 0], on = false;
if (c.src === "head") {
if (hOn) { on = true; for (let b = 0; b < 3; b++) a[b] = PR[b] * vol * Vh; }
} else if (aOn) {
on = true;
const inp = sg(c.key === "aL" ? N.a1 : N.a2);
if (inp) for (let b = 0; b < 3; b++) a[b] = inp[b] * Va / 2 * P.gain;
}
const Vc = c.src === "head" ? Vh : Va;
const G = [0, 0, 0];
for (const e of c.sp) {
if (S.sb[e.s.id]) continue;
let ce = 0;
for (const i of e.caps) ce += 1 / cap[i];
e.h = [1, 1, 1];
if (ce > 0) {
const fcut = 1 / (TP * e.s.z / ce);
for (let b = 0; b < 3; b++) e.h[b] = 1 / Math.sqrt(1 + (fcut / F[b]) * (fcut / F[b]));
}
for (let b = 0; b < 3; b++) G[b] += e.h[b] * e.h[b] / e.s.z;
}
let num = 0, den = 0;
for (let b = 0; b < 3; b++) { num += PR[b] * PR[b]; den += PR[b] * PR[b] * G[b]; }
const Z = den > 0 ? num / den : Infinity;
const prot = on && (c.short || Z < c.min);
S.prot[c.key] = prot;
S.zl[c.key] = c.short ? 0 : Z;
if (prot) a = [0, 0, 0];
let sm = a[0] + a[1] + a[2];
if (sm > Vc) { const k = Vc / sm; a = [a[0] * k, a[1] * k, a[2] * k]; sm = Vc; S.clip[c.key] = 1500; }
if (S.clip[c.key] > 0) S.clip[c.key]--;
S.lv[c.key] = sm / Vc;
S.ca[c.key] = a;
let Pt = 0;
for (let b = 0; b < 3; b++) Pt += a[b] * a[b] / 2 * G[b];
S.pw[c.key] += (Pt - S.pw[c.key]) * 0.002;
for (const e of c.sp) {
const s = e.s, kd = this._kind[s.k];
if (S.sb[s.id]) continue;
dr[s.id] = 1;
let m = 0, pw = 0, v = 0;
const ac = [0, 0, 0];
for (let b = 0; b < 3; b++) {
const vb = a[b] * e.h[b], pb = vb * vb / 2 / s.z;
pw += pb; m += pb / (s.p * kd.lim[b]); v += vb * sn[b];
ac[b] = kd.resp[b] * Math.sqrt(pb) / 6;
}
S.sa[s.id] = ac;
S.sv[s.id] = e.pol * v;
S.spp[s.id] = (S.spp[s.id] || 0) + (pw - (S.spp[s.id] || 0)) * 0.002;
const h = S.sh[s.id] || 0;
S.sh[s.id] = m > 1.2 ? h + dt * (m - 1.2) * 30 : Math.max(0, h - dt * 2);
if (S.sh[s.id] >= 1) S.sb[s.id] = true;
}
}
for (const s of this._spk) {
if (!dr[s.id]) {
S.sv[s.id] = 0;
S.sa[s.id] = null;
S.spp[s.id] = (S.spp[s.id] || 0) * 0.998;
S.sh[s.id] = Math.max(0, (S.sh[s.id] || 0) - dt * 2);
}
}
const cur = {
mem: N.hp.mem ? 0.1 : 0,
head: hOn ? 0.7 + (S.pw.hL + S.pw.hR) / (Vh * 0.4) : 0,
amp: aOn ? 1.2 + (S.pw.aL + S.pw.aR) / (P.Vcc * 0.5) : 0,
filt: fOn ? 0.15 : 0
};
const rt = [P.F1, P.F2, P.F3, P.F4];
for (let k = 0; k < 4; k++) {
if (S.fb[k]) { S.fi[k] = 0; continue; }
let I = N.sf[k] ? 250 : 0;
for (const key of N.fl[k]) I += cur[key];
S.fi[k] = I;
const r = I / rt[k];
if (r > 1) S.fh[k] += dt * (r * r - 1) * 30;
else S.fh[k] = Math.max(0, S.fh[k] - dt * 2);
if (S.fh[k] >= 1) S.fb[k] = true;
}
S.fan += dt * (aOn ? 60 + (S.pw.aL + S.pw.aR) * 2 : 0);
S.sc = {
pre: wv(pre), fo: wv(foL), hL: wv(S.ca.hL), aL: wv(S.ca.aL),
t1: S.sv.t1 || 0, s1: S.sv.s1 || 0
};
},
// ---------------------------------------------------------------- SOUND
_audioInit(S) {
if (S.au || S.auErr) return;
const AC = typeof window !== "undefined" && (window.AudioContext || window.webkitAudioContext);
if (!AC) { S.auErr = true; return; }
let ctx;
try { ctx = new AC(); } catch (e) { S.auErr = true; return; }
const mixAll = ctx.createGain(), sh = ctx.createWaveShaper();
const comp = ctx.createDynamicsCompressor(), master = ctx.createGain();
const mkc = f => { const c = new Float32Array(1024); for (let i = 0; i < 1024; i++) c[i] = f(i / 511.5 - 1); return c; };
const soft = mkc(x => Math.tanh(x * 1.1)), hard = mkc(x => Math.max(-1, Math.min(1, x * 5)));
sh.curve = soft;
mixAll.connect(sh); sh.connect(comp); comp.connect(master); master.connect(ctx.destination);
master.gain.value = 0;
const bus = [0, 1, 2].map(() => ctx.createGain());
const sp = {};
for (const s of this._spk) {
const mix = ctx.createGain();
const g = bus.map(b => { const x = ctx.createGain(); x.gain.value = 0; b.connect(x); x.connect(mix); return x; });
if (ctx.createStereoPanner) {
const pan = ctx.createStereoPanner();
pan.pan.value = this._cl((s.x - 300) / 280, -1, 1);
mix.connect(pan); pan.connect(mixAll);
} else mix.connect(mixAll);
sp[s.id] = g;
}
const nb = ctx.createBuffer(1, ctx.sampleRate, ctx.sampleRate);
const d = nb.getChannelData(0);
for (let i = 0; i < d.length; i++) d[i] = Math.random() * 2 - 1;
const au = { ctx, master, sh, soft, hard, hardOn: false, bus, sp, nb, n: 0, next: ctx.currentTime + 0.1 };
S.au = au;
au.timer = setInterval(() => this._seq(S), 40);
const res = () => { if (S.sndOn && ctx.state === "suspended") ctx.resume().catch(() => {}); };
document.addEventListener("pointerdown", res);
document.addEventListener("keydown", res);
res();
},
_toggleSnd(S) {
S.sndOn = !S.sndOn;
if (S.sndOn) {
this._audioInit(S);
if (S.au && S.au.ctx.state === "suspended") S.au.ctx.resume().catch(() => {});
}
},
_seq(S) {
const au = S.au;
if (!au) return;
const ctx = au.ctx;
if (!S.sndOn || ctx.state !== "running") { au.next = Math.max(au.next, ctx.currentTime + 0.05); return; }
const spd = 60 / 112 / 4;
if (au.next < ctx.currentTime) au.next = ctx.currentTime + 0.05;
while (au.next < ctx.currentTime + 0.15) { this._note(au, au.n, au.next); au.n++; au.next += spd; }
},
_note(au, n, t) {
const ctx = au.ctx, st = n % 16, bar = (n >> 4) % 4;
const env = (bus, peak, a, d) => {
const g = ctx.createGain();
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(peak, t + a);
g.gain.exponentialRampToValueAtTime(0.0001, t + a + d);
g.connect(au.bus[bus]);
return g;
};
const osc = (type, f, dest, len) => {
const o = ctx.createOscillator(); o.type = type; o.frequency.setValueAtTime(f, t);
o.connect(dest); o.start(t); o.stop(t + len); return o;
};
const noise = (ftype, f, q, dest, len) => {
const s = ctx.createBufferSource(); s.buffer = au.nb;
const fl = ctx.createBiquadFilter(); fl.type = ftype; fl.frequency.value = f; fl.Q.value = q;
s.connect(fl); fl.connect(dest); s.start(t); s.stop(t + len);
};
if (au.rad === 2) {
[120, 1200, 6000].forEach((f, b) => noise("bandpass", f, 0.5, env(b, 0.35, 0.005, 0.12), 0.2));
return;
}
if (st % 4 === 0 || st === 10) {
const o = ctx.createOscillator(); o.type = "sine";
o.frequency.setValueAtTime(130, t); o.frequency.exponentialRampToValueAtTime(42, t + 0.12);
o.connect(env(0, 1, 0.003, 0.3)); o.start(t); o.stop(t + 0.4);
}
if (st === 0 || st === 3 || st === 6 || st === 8 || st === 11 || st === 14) {
const f = this._roots[bar] * ((st === 6 || st === 14) ? 2 : 1);
const lp = ctx.createBiquadFilter(); lp.type = "lowpass"; lp.frequency.value = 220; lp.Q.value = 3;
lp.connect(env(0, 0.55, 0.01, 0.22));
osc("sawtooth", f, lp, 0.3);
}
if (st % 2 === 0) {
const f = this._arps[bar][[0, 1, 2, 1, 0, 2, 1, 2][(st >> 1) % 8]];
const bp = ctx.createBiquadFilter(); bp.type = "bandpass"; bp.frequency.value = 1100; bp.Q.value = 0.8;
bp.connect(env(1, 0.3, 0.005, 0.2));
osc("sawtooth", f, bp, 0.3);
}
if (st === 4 || st === 12) noise("bandpass", 1800, 0.8, env(1, 0.5, 0.002, 0.12), 0.2);
noise("highpass", 6500, 0.7, env(2, st % 2 ? 0.35 : 0.15, 0.002, st === 6 ? 0.18 : (st % 2 ? 0.05 : 0.03)), 0.25);
if (st === 0 || st === 8) osc("sine", this._bells[bar], env(2, 0.12, 0.005, 0.9), 1.1);
if (au.rad === 1) noise("highpass", 3000, 0.5, env(2, 0.05, 0.005, 0.12), 0.2);
},
_audio(P, S) {
if (S.lsnd !== P.snd) { S.lsnd = P.snd; S.sndOn = P.snd >= 0.5; }
if (S.sndOn && !S.au) this._audioInit(S);
const au = S.au;
if (!au) return;
const ctx = au.ctx, t = ctx.currentTime;
if (S.sndOn && ctx.state === "suspended") ctx.resume().catch(() => {});
au.master.gain.setTargetAtTime(S.sndOn ? 0.5 : 0, t, 0.05);
au.rad = S.rad;
if (!S.sndOn) return;
for (const s of this._spk) {
const a = S.sa[s.id], g = au.sp[s.id];
for (let b = 0; b < 3; b++) {
const v = a ? (a[b] || 0) : 0;
g[b].gain.setTargetAtTime(isFinite(v) ? v : 0, t, 0.04);
}
}
const hard = S.clip.hL > 0 || S.clip.hR > 0 || S.clip.aL > 0 || S.clip.aR > 0;
if (hard !== au.hardOn) { au.hardOn = hard; au.sh.curve = hard ? au.hard : au.soft; }
},
// ---------------------------------------------------------------- ROUTING
_elbow(list) {
const out = [list[0].slice()];
let pd = null;
for (let i = 1; i < list.length; i++) {
const p = out[out.length - 1], q = list[i];
if (p[0] === q[0] && p[1] === q[1]) continue;
if (p[0] === q[0]) { out.push(q.slice()); pd = "v"; }
else if (p[1] === q[1]) { out.push(q.slice()); pd = "h"; }
else {
const hf = pd !== "h";
out.push(hf ? [q[0], p[1]] : [p[0], q[1]]);
out.push(q.slice());
pd = hf ? "v" : "h";
}
}
if (out.length < 3) return out;
const r = [out[0]];
for (let i = 1; i < out.length - 1; i++) {
const a = r[r.length - 1], b = out[i], c = out[i + 1];
if ((a[0] === b[0] && b[0] === c[0]) || (a[1] === b[1] && b[1] === c[1])) continue;
r.push(b);
}
r.push(out[out.length - 1]);
return r;
},
_routeAll(S) {
const G = 10, C = 61, R = 80, N = C * R, tm = this._tm, NT = S.net;
const base = new Float32Array(N), oH = new Int16Array(N), oV = new Int16Array(N);
const rect = (x0, y0, x1, y1, c) => {
for (let j = Math.max(0, Math.ceil(y0 / G)); j <= Math.min(R - 1, Math.floor(y1 / G)); j++)
for (let i = Math.max(0, Math.ceil(x0 / G)); i <= Math.min(C - 1, Math.floor(x1 / G)); i++) base[j * C + i] += c;
};
rect(130, 160, 470, 290, 10);
rect(175, 365, 425, 430, 10);
rect(130, 470, 470, 620, 10);
rect(250, 80, 390, 120, 25);
rect(48, 690, 92, 725, 12); rect(100, 708, 140, 724, 12); rect(45, 648, 95, 662, 8);
rect(135, 680, 185, 730, 15);
rect(165, 112, 195, 148, 12); rect(405, 112, 435, 148, 12);
for (const s of this._spk) rect(s.x - 24, s.y - 26, s.x + 24, s.y + 56, 20);
for (let k = 0; k < 4; k++) rect(255, 650 + k * 30 - 20, 325, 650 + k * 30 + 8, 15);
for (const t of this._tt) {
const cx = Math.round(t.x / G), cy = Math.round(t.y / G);
base[cy * C + cx] += 40;
const pen = (dx, dy) => { const i = cx + dx, j = cy + dy; if (i >= 0 && i < C && j >= 0 && j < R) base[j * C + i] += 6; };
if (t.pos === "r") pen(1, 0); else if (t.pos === "l") pen(-1, 0);
else if (t.pos === "u") pen(0, -1); else if (t.pos === "d") pen(0, 1);
else if (t.pos === "v") for (let k = 1; k <= 4; k++) pen(0, -k);
}
const mark = (pts, nid) => {
for (let i = 0; i + 1 < pts.length; i++) {
const a = pts[i], b = pts[i + 1], hz = a[1] === b[1];
const len = Math.round(Math.max(Math.abs(b[0] - a[0]), Math.abs(b[1] - a[1])) / G);
const sx = Math.sign(b[0] - a[0]), sy = Math.sign(b[1] - a[1]);
for (let k = 0; k <= len; k++) {
const c = Math.round((a[1] + sy * k * G) / G) * C + Math.round((a[0] + sx * k * G) / G);
if (c >= 0 && c < N) (hz ? oH : oV)[c] = nid;
}
}
};
const DX = [1, 0, -1, 0], DY = [0, 1, 0, -1];
const ast = (ta, tb, nid) => {
const a = [ta.x, ta.y], b = [tb.x, tb.y];
const s = Math.round(a[1] / G) * C + Math.round(a[0] / G), t = Math.round(b[1] / G) * C + Math.round(b[0] / G);
const tx = t % C, ty = (t / C) | 0;
const sex = ta.ex === undefined ? -1 : ta.ex, tex = tb.ex === undefined ? -1 : tb.ex;
const gS = new Float32Array(N * 5).fill(Infinity), par = new Int32Array(N * 5).fill(-1);
const hf = [], hs = [];
const push = (f, st) => {
let i = hf.length; hf.push(f); hs.push(st);
while (i > 0) { const p = (i - 1) >> 1; if (hf[p] <= f) break; hf[i] = hf[p]; hs[i] = hs[p]; i = p; }
hf[i] = f; hs[i] = st;
};
const pop = () => {
const rs = hs[0], lf = hf.pop(), ls = hs.pop(), n = hf.length;
if (n > 0) {
let i = 0;
for (;;) {
let c = 2 * i + 1;
if (c >= n) break;
if (c + 1 < n && hf[c + 1] < hf[c]) c++;
if (hf[c] >= lf) break;
hf[i] = hf[c]; hs[i] = hs[c]; i = c;
}
hf[i] = lf; hs[i] = ls;
}
return rs;
};
const s0 = s * 5 + 4;
gS[s0] = 0; push(0, s0);
let end = -1;
while (hf.length) {
const st = pop(), cell = (st / 5) | 0, d = st % 5;
if (cell === t) { end = st; break; }
const gc = gS[st], cx = cell % C, cy = (cell / C) | 0;
for (let nd = 0; nd < 4; nd++) {
if (d < 4 && nd === ((d + 2) & 3)) continue;
const nx = cx + DX[nd], ny = cy + DY[nd];
if (nx < 0 || ny < 0 || nx >= C || ny >= R) continue;
const nc = ny * C + nx;
let c = 1;
if (nc !== t) c += base[nc];
const same = (nd & 1) ? oV[nc] : oH[nc], cross = (nd & 1) ? oH[nc] : oV[nc];
if (same) c += same === nid ? -0.6 : 12;
if (cross && cross !== nid) c += 1.5;
if (d < 4 && d !== nd) c += 4;
if (d === 4 && sex >= 0 && nd !== sex) c += 8;
if (nc === t && tex >= 0 && nd !== ((tex + 2) & 3)) c += 8;
const ns = nc * 5 + nd, ng = gc + c;
if (ng < gS[ns]) { gS[ns] = ng; par[ns] = st; push(ng + 0.7 * (Math.abs(nx - tx) + Math.abs(ny - ty)), ns); }
}
}
if (end < 0) return this._elbow([a, b]);
const cells = [];
for (let st = end; st >= 0; st = par[st]) cells.push((st / 5) | 0);
cells.reverse();
const xy = c => [(c % C) * G, ((c / C) | 0) * G];
const pts = [xy(cells[0])];
for (let i = 1; i < cells.length - 1; i++) {
if (cells[i + 1] - cells[i] !== cells[i] - cells[i - 1]) pts.push(xy(cells[i]));
}
pts.push(xy(cells[cells.length - 1]));
return pts;
};
const out = new Array(S.wires.length);
const man = [], aut = [];
S.wires.forEach((w, i) => (w[2] && w[2].length ? man : aut).push(i));
const nidOf = w => NT.na(w[0]) + 1;
for (const i of man) {
const w = S.wires[i], a = tm[w[0]], b = tm[w[1]];
out[i] = this._elbow([[a.x, a.y]].concat(w[2], [[b.x, b.y]]));
mark(out[i], nidOf(w));
}
const dist = i => { const w = S.wires[i], a = tm[w[0]], b = tm[w[1]]; return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); };
aut.sort((i, j) => dist(i) - dist(j));
for (const i of aut) {
const w = S.wires[i];
out[i] = ast(tm[w[0]], tm[w[1]], nidOf(w));
mark(out[i], nidOf(w));
}
S.rt = out;
},
_segDist(px, py, a, b) {
const dx = b[0] - a[0], dy = b[1] - a[1], l2 = dx * dx + dy * dy;
let t = l2 ? ((px - a[0]) * dx + (py - a[1]) * dy) / l2 : 0;
t = t < 0 ? 0 : t > 1 ? 1 : t;
const qx = a[0] + t * dx, qy = a[1] + t * dy;
return Math.sqrt((px - qx) * (px - qx) + (py - qy) * (py - qy));
},
_wireAt(S, x, y) {
if (!S.rt || S.rt.length !== S.wires.length || typeof x !== "number") return -1;
for (let i = S.rt.length - 1; i >= 0; i--) {
const p = S.rt[i];
if (!p) continue;
for (let k = 0; k + 1 < p.length; k++) if (this._segDist(x, y, p[k], p[k + 1]) < 6) return i;
}
return -1;
},
// ---------------------------------------------------------------- DRAWING HELPERS
_ln(g, x1, y1, x2, y2, c, w) {
g.save(); g.strokeStyle = c; g.lineWidth = w || 2; g.lineCap = "round";
g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.restore();
},
_poly(g, pts, c, closed) {
g.save(); g.strokeStyle = c; g.lineWidth = 2; g.lineJoin = "round";
g.beginPath(); g.moveTo(pts[0][0], pts[0][1]);
for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]);
if (closed) g.closePath();
g.stroke(); g.restore();
},
_circ(g, x, y, r, c, fill) {
g.save(); g.strokeStyle = c; g.lineWidth = 2;
g.beginPath(); g.arc(x, y, r, 0, 6.2832);
if (fill) { g.fillStyle = c; g.fill(); }
g.stroke(); g.restore();
},
_arc(g, x, y, r, a1, a2, c) {
g.save(); g.strokeStyle = c; g.lineWidth = 1.8; g.lineCap = "round";
g.beginPath(); g.arc(x, y, r, a1, a2); g.stroke(); g.restore();
},
_rr(g, x, y, w, h, r, c, lw, fill) {
g.save();
g.beginPath();
g.moveTo(x + r, y); g.lineTo(x + w - r, y); g.quadraticCurveTo(x + w, y, x + w, y + r);
g.lineTo(x + w, y + h - r); g.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
g.lineTo(x + r, y + h); g.quadraticCurveTo(x, y + h, x, y + h - r);
g.lineTo(x, y + r); g.quadraticCurveTo(x, y, x + r, y); g.closePath();
if (fill) { g.fillStyle = fill; g.fill(); }
g.strokeStyle = c; g.lineWidth = lw || 2; g.stroke();
g.restore();
},
_tx(g, s, x, y, c, sz, al, b) {
g.save(); g.font = (b ? "bold " : "") + sz + "px sans-serif"; g.fillStyle = c;
g.textAlign = al || "center"; g.textBaseline = "middle"; g.fillText(s, x, y); g.restore();
},
_tv(g, s, x, y, c, sz) {
g.save(); g.translate(x, y); g.rotate(-1.5708);
g.font = sz + "px sans-serif"; g.fillStyle = c; g.textAlign = "left"; g.textBaseline = "middle";
g.fillText(s, 0, 0); g.restore();
},
_gnd(g, x, y, c) {
this._ln(g, x, y, x, y + 6, c);
this._ln(g, x - 8, y + 6, x + 8, y + 6, c);
this._ln(g, x - 5, y + 10, x + 5, y + 10, c);
this._ln(g, x - 2, y + 14, x + 2, y + 14, c);
},
_dsp(g, s, col, defl, play, burnt) {
const k = this._kind[s.k].k, u = s.u, x = s.x, y = s.y;
const q = (dx, dy) => [x + u * dx, y + dy];
this._poly(g, [q(6 * k, -8 * k), q(18 * k, -8 * k), q(18 * k, 8 * k), q(6 * k, 8 * k)], col, true);
this._poly(g, [q(6 * k, -8 * k), q(-14 * k + defl, -22 * k), q(-14 * k + defl, 22 * k), q(6 * k, 8 * k)], col, true);
const tp = this._tm[s.id + ".p"], tn = this._tm[s.id + ".m"];
let a = q(18 * k, -8 * k);
this._poly(g, [a, [a[0], tp.y], [tp.x, tp.y]], col);
a = q(18 * k, 8 * k);
this._poly(g, [a, [a[0], tn.y], [tn.x, tn.y]], col);
if (play) {
const c = q(-14 * k - 4, 0);
for (const r of [10, 17]) {
if (u === 1) this._arc(g, c[0], c[1], r, Math.PI - 0.7, Math.PI + 0.7, col);
else this._arc(g, c[0], c[1], r, -0.7, 0.7, col);
}
}
if (burnt) {
a = q(-10 * k, -14 * k); let b = q(2 * k, 14 * k);
this._ln(g, a[0], a[1], b[0], b[1], "#d03030", 2.5);
a = q(-10 * k, 14 * k); b = q(2 * k, -14 * k);
this._ln(g, a[0], a[1], b[0], b[1], "#d03030", 2.5);
}
},
_hit(S, x, y) {
if (!this._tt || typeof x !== "number") return null;
let best = null, bd = 121;
for (const t of this._tt) {
const d = (t.x - x) * (t.x - x) + (t.y - y) * (t.y - y);
if (d < bd) { bd = d; best = t; }
}
return best;
},
_click(S, x, y) {
if (x >= 240 && x <= 360 && y >= 6 && y <= 30) { this._toggleSnd(S); return; }
const pk = this._palAt(x, y);
if (pk) { S.col = pk === "auto" ? null : pk; return; }
const h = this._hit(S, x, y);
if (!S.pend) {
if (h) { S.pend = h.id; S.pts = []; return; }
const wi = this._wireAt(S, x, y);
if (wi >= 0) S.wires[wi][3] = S.col || null;
return;
}
if (h) {
if (S.pend === h.id) { S.pend = null; S.pts = []; return; }
const a = S.pend, b = h.id, route = S.pts.length ? S.pts.map(p => p.slice()) : null;
const ex = S.wires.find(w => (w[0] === a && w[1] === b) || (w[0] === b && w[1] === a));
if (ex) { ex[2] = ex[0] === a ? route : (route ? route.slice().reverse() : null); if (S.col) ex[3] = S.col; }
else S.wires.push([a, b, route, S.col || null]);
S.pend = null; S.pts = [];
return;
}
const gx = this._cl(Math.round(x / 10) * 10, 0, 600), gy = this._cl(Math.round(y / 10) * 10, 0, 790);
const last = S.pts[S.pts.length - 1];
if (!last || last[0] !== gx || last[1] !== gy) S.pts.push([gx, gy]);
},
_ctx(S, x, y) {
if (S.pend) { if (S.pts.length) S.pts.pop(); else S.pend = null; return; }
const h = this._hit(S, x, y);
if (h) { S.wires = S.wires.filter(w => w[0] !== h.id && w[1] !== h.id); return; }
const i = this._wireAt(S, x, y);
if (i >= 0) S.wires.splice(i, 1);
},
_bind(g, S) {
const cv = g.canvas;
if (!cv || S.bound === cv) return;
S.bound = cv;
const pos = e => {
const r = cv.getBoundingClientRect();
const px = (e.clientX - r.left) * (S.W / r.width), py = (e.clientY - r.top) * (S.H / r.height);
return [(px - S.ox) / S.s, (py - S.oy) / S.s];
};
cv.addEventListener("mousemove", e => { const p = pos(e); S.mx = p[0]; S.my = p[1]; });
cv.addEventListener("mouseleave", () => { S.mx = -1e3; S.my = -1e3; });
cv.addEventListener("click", e => { const p = pos(e); this._click(S, p[0], p[1]); });
cv.addEventListener("contextmenu", e => { e.preventDefault(); const p = pos(e); this._ctx(S, p[0], p[1]); });
},
_tcol(t) {
const W = this._WC, id = t.id;
if (id === "head.rem" || id === "amp.rem") return { c: W.b, s: W.w, p: 3 };
if (id === "head.ant") return { c: W.b, p: 3 };
if (id === "head.mem") return { c: W.y, p: 3 };
if (id === "head.acc") return { c: W.o, p: 3 };
if (t.k === "rf") return { c: "#4a4a4a", s: "#bdbdbd", p: 3 };
const m = /^([a-z]\d)\.([pm])$/.exec(id);
if (m && this._SC[m[1]]) return { c: this._SC[m[1]], s: m[2] === "m" ? W.k : null, p: 4 };
switch (t.k) {
case "gnd": return { c: W.k, p: 1 };
case "pwr": return { c: W.r, p: 1 };
case "rcaL": return { c: W.w, p: 2 };
case "rcaR": return { c: W.r, p: 2 };
case "spk": return { c: t.lab === "+" ? W.r : W.k, p: 1 };
}
return null;
},
_wstyle(P, S, w) {
const N = S.net, W = this._WC, a = this._tm[w[0]], b = this._tm[w[1]];
const au = k => k === "rca" || k === "rcaL" || k === "rcaR" || k === "spk" || k === "rf";
const pw = k => k === "pwr" || k === "gnd" || k === "rem";
const A = au(a.k), B = au(b.k);
const err = (A && pw(b.k)) || (B && pw(a.k));
// level mismatch: line-level ↔ speaker-level
const lvl = (k) => k === "rca" || k === "rcaL" || k === "rcaR" ? "line" : k === "spk" ? "spk" : null;
const la = lvl(a.k), lb = lvl(b.k);
const mismatch = (la === "line" && lb === "spk") || (la === "spk" && lb === "line");
const r = N.nd(w[0]);
let sp;
if (w[3] && this._PAL[w[3]]) sp = this._PAL[w[3]];
else {
const ca = this._tcol(a), cb = this._tcol(b);
sp = ca && cb ? (cb.p > ca.p ? cb : ca) : (ca || cb);
if (!sp) sp = { c: r === N.gnd ? W.k : W.r };
}
let live = false, short = false;
if (A || B) {
const ks = N.ak[N.na(w[0])] || [];
let l = 0;
for (const k of ks) l = Math.max(l, S.lv[k] || 0);
live = l > 0.02;
if (a.k === "rf" || b.k === "rf") live = !!N.antOk && S.rad === 1;
} else if (N.short && (r === N.gnd || N.E.en.has(r))) short = true;
else if (r === N.gnd) live = N.headOn || N.ampOn || N.filtOn;
else live = N.E.en.has(r);
return { c: sp.c, s: sp.s || null, err, live, short, mismatch };
},
_palAt(x, y) {
if (typeof x !== "number") return null;
if (x >= 22 && x <= 60 && y >= 930 && y <= 950) return "auto";
for (let i = 1; i < this._PK.length; i++) {
const cx = 80 + (i - 1) * 29;
if ((x - cx) * (x - cx) + (y - 940) * (y - 940) <= 121) return this._PK[i];
}
return null;
},
_wire(g, pts, st, fr, hl) {
if (!pts || pts.length < 2) return;
g.save(); g.lineJoin = "round"; g.lineCap = "round";
const path = () => { g.beginPath(); g.moveTo(pts[0][0], pts[0][1]); for (let i = 1; i < pts.length; i++) g.lineTo(pts[i][0], pts[i][1]); };
if (st.short) { path(); g.strokeStyle = "rgba(255,40,40,0.45)"; g.lineWidth = 9; g.stroke(); }
if (hl) { path(); g.strokeStyle = "rgba(90,160,255,0.55)"; g.lineWidth = 9; g.stroke(); }
path(); g.strokeStyle = "rgba(140,140,140,0.5)"; g.lineWidth = 5.4; g.stroke();
path(); g.strokeStyle = st.c; g.lineWidth = 3.4; g.stroke();
if (st.s) { path(); g.setLineDash([5, 5]); g.strokeStyle = st.s; g.lineWidth = 3.4; g.stroke(); g.setLineDash([]); }
if (st.err) { path(); g.setLineDash([4, 6]); g.strokeStyle = "#ff2020"; g.lineWidth = 3.4; g.stroke(); g.setLineDash([]); }
else if (st.mismatch) { path(); g.setLineDash([8, 4]); g.strokeStyle = "#ffaa00"; g.lineWidth = 3.4; g.stroke(); g.setLineDash([]); }
if (st.live) {
path(); g.setLineDash([2, 12]); g.lineDashOffset = -fr * 0.6;
g.strokeStyle = st.c === this._WC.w ? "#2a7be0" : "rgba(255,255,255,0.8)"; g.lineWidth = 1.6; g.stroke();
g.setLineDash([]);
}
g.restore();
},
// ── Enhanced diagnostics ─────────────────────────────────────────────
_diag(P, S) {
const N = S.net, o = [], R = "#d03030", Y = "#c08000", G = "#3cb371";
// Critical shorts
if (N.direct) o.push(["CATASTROPHIC SHORT: battery + is directly connected to ground — disconnect immediately!", R]);
else {
const f = N.sf.map((v, k) => v ? "F" + (k + 1) : null).filter(Boolean);
if (f.length) o.push(["Short to ground through " + f.join(", ") + " — fuse will blow", R]);
}
S.fb.forEach((b, k) => { if (b) o.push(["Fuse F" + (k + 1) + " BLOWN — fix the fault, then pulse Repair", R]); });
// Burnt speakers
for (const s of this._spk) {
if (!S.sb[s.id]) continue;
if (N.spkDC && N.spkDC[s.id]) o.push([s.name + ": BURNT by DC — connected directly between +12V and ground!", R]);
else if (s.k === "tw") o.push([s.name + ": BURNT — bass or too much power reached the tweeter", R]);
else o.push([s.name + ": BURNT — overloaded (too much power for " + s.z + "Ω " + s.p + "W)", R]);
}
// Protect mode
for (const c of N.chs) {
if (S.prot[c.key]) {
o.push([this._cn[c.key] + " in PROTECT — " + (c.short ? "output is shorted" : "load " + S.zl[c.key].toFixed(1) + "Ω < " + c.min + "Ω minimum"), R]);
}
}
// Power faults
if (!N.short) {
if (!N.headOn) {
if (!N.hp.mem) o.push(["Head unit OFF: MEM (yellow) needs constant 12V via fuse F2", Y]);
else if (!N.hp.acc) o.push(["Head unit OFF: ACC (orange) needs 12V through key + fuse F1", Y]);
else if (!N.hp.gnd) o.push(["Head unit OFF: GND not connected to chassis", Y]);
}
if (!N.ampOn) {
if (!N.ap.vcc) o.push(["Amp OFF: 12V+ needs a thick fused wire from the battery (F3)", Y]);
else if (!N.ap.rem) o.push(["Amp OFF: ON/OFF needs 12V from head REMOTE (blue/white)", Y]);
else if (!N.ap.gnd) o.push(["Amp OFF: GND not connected to chassis", Y]);
}
if (!N.filtOn) {
if (!N.fp.pwr) o.push(["Filter OFF: 12V+ needs fused feed (F4)", Y]);
else if (!N.fp.gnd) o.push(["Filter OFF: GND not connected", Y]);
}
}
// Unfused warnings
if (N.unfused) {
if (N.unfused.mem) o.push(["WARNING: Head MEM is UNFUSED — add fuse F2 at battery end", Y]);
if (N.unfused.acc) o.push(["WARNING: Head ACC is UNFUSED — use fuse F1 + ignition", Y]);
if (N.unfused.amp) o.push(["WARNING: Amp 12V+ is UNFUSED — add fuse F3 at battery", Y]);
if (N.unfused.filt) o.push(["WARNING: Filter 12V+ is UNFUSED — add fuse F4", Y]);
}
// Amp powered from low-current output
if (N.ampOn && N.ampFromRem) o.push(["Amp 12V+ connected to REMOTE — remote can only supply ~300mA, not enough!", R]);
if (N.ampOn && N.ampFromAnt) o.push(["Amp 12V+ connected to ANT 12V — antenna output can only supply ~300mA!", R]);
// Amp input from speaker-level
if (N.ampInFromSpk) o.push(["Amp LOW IN connected to head SPEAKER output — use PRE OUT for proper line level", Y]);
// Antenna
if (N.headOn && P.src >= 0.5 && !N.short) {
if (!N.coax) o.push(["Radio: connect ANT IN to antenna RF output (coax)", Y]);
else if (!N.antPow) o.push(["Antenna: 12V needs head unit ANT 12V output", Y]);
else if (!N.antGnd) o.push(["Antenna: GND not connected to chassis", Y]);
}
// No speakers
if (N.headOn && !N.chs.some(c => c.src === "head" && c.sp.length))
o.push(["Head unit: no speakers connected to its outputs", Y]);
if (N.ampOn && !N.chs.some(c => c.src === "amp" && c.sp.length))
o.push(["Amp: no speakers connected", Y]);
// Signal routing
if (N.ampOn && !N.a1 && !N.a2) o.push(["Amp: no signal on LOW IN (connect filter OUT or head PRE OUT)", Y]);
else {
if (N.ampOn && !N.a1) o.push(["Amp L: no signal connected to LOW IN L", Y]);
if (N.ampOn && !N.a2) o.push(["Amp R: no signal connected to LOW IN R", Y]);
}
if (N.filtOn && !N.fsrcL && !N.fsrcR) o.push(["Filter: no signal on inputs (connect head PRE OUT)", Y]);
else {
if (N.filtOn && !N.fsrcL) o.push(["Filter L: input not connected", Y]);
if (N.filtOn && !N.fsrcR) o.push(["Filter R: input not connected", Y]);
}
// Filter loop
if (N.filtLoopL) o.push(["Filter L: input shorted to output — no filtering", Y]);
if (N.filtLoopR) o.push(["Filter R: input shorted to output — no filtering", Y]);
// Speaker wiring
for (const c of N.chs) {
for (const e of c.sp) {
if (e.s.k === "tw" && e.caps.length === 0) o.push([e.s.name + ": tweeter without series capacitor — bass will destroy it", Y]);
if (e.pol < 0) o.push([e.s.name + ": polarity reversed (+ and - swapped)", Y]);
}
}
if (!o.length) {
const n = this._spk.filter(s => (S.spp[s.id] || 0) > 0.01).length;
o.push(["System OK — " + n + " speaker(s) playing", G]);
}
return o;
},
// ── Contextual best-practice tips ───────────────────────────────────
_tips(P, S) {
const N = S.net;
if (!N) return "";
if (N.direct) return "DISCONNECT the short immediately! Trace every wire from bat.pos to find the fault.";
if (N.short) return "Remove the short before powering on. Check for wires touching ground that shouldn't.";
if (S.fb.some(b => b)) return "Fuses blow to protect equipment. Fix the short, then pulse 'Repair fuses and speakers'.";
if (Object.values(S.sb).some(b => b)) return "Burnt speakers need replacement — fix the cause first (DC / overdrive / bass to tweeter).";
if (!N.headOn && N.hp.mem && N.hp.acc && !N.hp.gnd) return "TIP: Ground the head unit directly to bare chassis metal — short thick wire = less noise.";
if (!N.ampOn && !N.ap.vcc) return "TIP: Run a thick fused wire straight from battery + to the amp. Fuse within 30cm of the battery.";
if (!N.ampOn && !N.ap.gnd) return "TIP: Amp ground must be to bare metal, as short as possible, same gauge as power wire.";
if (!N.ampOn && !N.ap.rem) return "TIP: The amp's ON/OFF (remote) wire is thin — it only needs a signal, not power.";
if (N.headOn && !N.ampOn) return "TIP: Use PRE OUT (RCA) with an amplifier instead of speaker-level — cleaner sound, less distortion.";
// Detect tweeter without cap
let twNoCap = false;
for (const c of N.chs) for (const e of c.sp) if (e.s.k === "tw" && e.caps.length === 0) twNoCap = true;
if (twNoCap) return "TIP: A tweeter MUST have a series capacitor (or crossover) — it will burn instantly on bass.";
if (N.filtOn && (!N.fsrcL || !N.fsrcR)) return "TIP: For proper stereo, wire both filter channels (L and R) from head PRE OUT.";
if (!N.ampOn && N.a1 && N.a2 && !N.filtOn) return "TIP: The filter needs 12V and GND to work — otherwise the amp gets no signal.";
// Best-practice rotation
const tips = [
"TIP: Route power wires away from audio cables to avoid alternator whine.",
"TIP: Keep the ground wire as short as possible — long grounds pick up noise.",
"TIP: Set the amp gain so the head unit can play at 70% volume without clipping.",
"TIP: Low-pass filter cutoff 80–120 Hz is typical for subwoofers.",
"TIP: Twist speaker wires (+/-) together to reduce electromagnetic interference.",
"TIP: Always fuse the power wire at the battery end — protects against fire.",
"TIP: Match speaker impedance to amp specs — too low = protect mode.",
"TIP: Use both filter channels for true stereo; mono wiring loses separation.",
"TIP: The head unit's built-in amp is ~20W; use an external amp for subs.",
"TIP: Never connect a speaker directly to the battery — DC burns the voice coil."
];
const idx = Math.floor(S.fr / 600) % tips.length;
return tips[idx];
},
draw(g, W, H, P, S) {
this._prep();
if (!S.net) this._tick(P, S);
const N = S.net, T = this._tt, tm = this._tm;
S.W = W; S.H = H; S.fr++;
const sc = Math.min(W / 600, H / 975);
S.s = sc; S.ox = (W - 600 * sc) / 2; S.oy = (H - 975 * sc) / 2;
this._bind(g, S);
this._audio(P, S);
const rsig = S.wires.map(w => w[0] + ">" + w[1] + (w[2] ? ":" + w[2].join(";") : "")).join(",");
if (rsig !== S.rsig || S.rt.length !== S.wires.length) { S.rsig = rsig; this._routeAll(S); }
const hov = this._hit(S, S.mx, S.my);
S.hw = (!hov && !S.pend) ? this._wireAt(S, S.mx, S.my) : -1;
const hot = SimKit.voltColor(P.Vcc, P.Vcc);
const dc = o => o ? hot : "#555";
const hOn = N.headOn, aOn = N.ampOn, fOn = N.filtOn;
const deg = {};
for (const w of S.wires) { deg[w[0]] = (deg[w[0]] || 0) + 1; deg[w[1]] = (deg[w[1]] || 0) + 1; }
g.save();
g.translate(S.ox, S.oy);
g.scale(sc, sc);
// Sound button
const so = S.sndOn;
this._rr(g, 240, 8, 120, 24, 6, so ? "#3cb371" : "#888", 1.5, so ? "rgba(60,179,113,0.15)" : "rgba(128,128,128,0.12)");
const susp = S.au && S.au.ctx.state === "suspended";
this._tx(g, so ? (susp ? "\u266a click to start" : "\u266a SOUND ON") : "\u266a SOUND OFF", 300, 20, so ? "#3cb371" : "#888", 11, "center", true);
// ── Head unit ─────────────────────────────────────────────────────
this._rr(g, 130, 160, 340, 130, 10, dc(hOn), 2);
this._tx(g, "CD PLAYER / HEAD UNIT", 300, 174, "#444", 10, "center", true);
this._tx(g, "4 × " + this._spec.head.rms + "W RMS · ≥" + this._spec.head.impMin + "Ω · 12V", 300, 186, "#888", 8);
this._tx(g, "PRE OUT", 165, 200, "#666", 9);
this._tx(g, "SPK L", 225, 283, "#666", 9);
this._tx(g, "SPK R", 295, 283, "#666", 9);
this._rr(g, 205, 195, 120, 46, 4, "#777", 1.2, "rgba(128,128,128,0.15)");
const radio = P.src >= 0.5;
this._tx(g, !hOn ? "OFF" : (radio ? (N.antOk ? "RADIO FM 98.4" : "RADIO: NO ANT") : "CD PLAYER"), 265, 207,
!hOn ? "#888" : (radio && !N.antOk ? "#d08000" : "#3cb371"), 10, "center", true);
this._tx(g, hOn ? "VOL " + Math.round(P.vol * 100) + "%" : "NO POWER", 265, 221, "#666", 9);
if (S.prot.hL || S.prot.hR) this._tx(g, "PROTECT", 265, 233, "#d03030", 9, "center", true);
else if (S.clip.hL > 0 || S.clip.hR > 0) this._tx(g, "CLIPPING", 265, 233, "#d03030", 9, "center", true);
// ── Stereo low-pass filter ────────────────────────────────────────
this._rr(g, 175, 365, 250, 65, 8, dc(fOn), 2);
this._tx(g, "STEREO LOW-PASS FILTER · " + Math.round(P.fc) + " Hz", 300, 377, "#444", 10, "center", true);
this._tx(g, "2ch · 12V", 300, 388, "#888", 8);
this._tx(g, "IN", 215, 396, "#666", 9);
this._tx(g, "OUT", 300, 396, "#666", 9);
if (N.filtLoopL || N.filtLoopR) this._tx(g, "LOOP!", 300, 403, "#d03030", 8, "center", true);
// ── Amplifier ─────────────────────────────────────────────────────
this._rr(g, 130, 470, 340, 150, 10, dc(aOn), 2);
this._tx(g, "POWER AMPLIFIER", 300, 484, "#444", 10, "center", true);
this._tx(g, "2 × " + this._spec.amp.rms + "W RMS · ≥" + this._spec.amp.impMin + "Ω · Bridge " + this._spec.amp.bridge + "W", 300, 496, "#888", 8);
this._tx(g, "LOW IN", 165, 512, "#666", 9);
this._tx(g, "SPK L", 225, 613, "#666", 9);
this._tx(g, "SPK R", 295, 613, "#666", 9);
this._rr(g, 205, 504, 120, 50, 4, "#777", 1.2, "rgba(128,128,128,0.15)");
this._tx(g, aOn ? "AMP ON" : "AMP OFF", 265, 516, aOn ? "#3cb371" : "#888", 10, "center", true);
this._tx(g, "L " + S.pw.aL.toFixed(1) + " W R " + S.pw.aR.toFixed(1) + " W", 265, 530, "#666", 9);
if (S.prot.aL || S.prot.aR) this._tx(g, "PROTECT", 265, 544, "#d03030", 9, "center", true);
else if (S.clip.aL > 0 || S.clip.aR > 0) this._tx(g, "CLIPPING", 265, 544, "#d03030", 9, "center", true);
else this._tx(g, "GAIN ×" + P.gain.toFixed(1), 265, 544, "#666", 9);
this._circ(g, 362, 524, 20, dc(aOn), false);
for (let i = 0; i < 6; i++) {
const an = S.fan + i * 1.0472;
this._ln(g, 362, 524, 362 + 17 * Math.cos(an), 524 + 17 * Math.sin(an), dc(aOn), 1.8);
}
this._circ(g, 362, 524, 3, dc(aOn), true);
// ── Speakers ─────────────────────────────────────────────────────
for (const s of this._spk) {
const id = s.id, burnt = !!S.sb[id], k = this._kind[s.k].k;
const vis = burnt ? 0 : this._cl(Math.sqrt((S.spp[id] || 0) / (s.p * 0.1)), 0, 1);
const col = burnt ? "#d03030" : (vis < 0.03 ? "#555" : SimKit.voltColor(vis * P.Vcc, P.Vcc));
this._dsp(g, s, col, burnt ? 0 : this._cl((S.sv[id] || 0) * 0.3, -5, 5), !burnt && vis >= 0.03, burnt);
const ly = s.y + Math.round(22 * k) + 14;
this._tx(g, s.name + " " + s.z + "\u03a9 · " + s.p + "W RMS", s.x, ly, burnt ? "#d03030" : "#444", 9);
this._tx(g, burnt ? "BURNT" : (S.spp[id] || 0).toFixed(1) + " W", s.x, ly + 11, burnt ? "#d03030" : "#666", 9);
}
// ── Capacitors ───────────────────────────────────────────────────
[[180, 130, "C1", P.C1], [420, 130, "C2", P.C2]].forEach(c => {
this._ln(g, c[0] - 20, c[1], c[0] - 3, c[1], "#555");
this._ln(g, c[0] - 3, c[1] - 9, c[0] - 3, c[1] + 9, "#555", 2.5);
this._ln(g, c[0] + 3, c[1] - 9, c[0] + 3, c[1] + 9, "#555", 2.5);
this._ln(g, c[0] + 3, c[1], c[0] + 20, c[1], "#555");
this._tx(g, c[2], c[0], c[1] - 16, "#444", 9);
this._tx(g, Math.round(c[3] * 10) / 10 + " \u00b5F", c[0], c[1] + 17, "#666", 9);
});
// ── Fuses ────────────────────────────────────────────────────────
const rt = [P.F1, P.F2, P.F3, P.F4];
for (let k = 0; k < 4; k++) {
const y = 650 + k * 30, bl = S.fb[k];
const col = bl ? "#d03030" : dc(N.E.en.has(N.nd("f" + (k + 1) + ".a")) && !N.short);
this._ln(g, 250, y, 260, y, col);
this._poly(g, [[260, y - 6], [320, y - 6], [320, y + 6], [260, y + 6]], col, true);
this._ln(g, 320, y, 330, y, col);
if (bl) {
this._ln(g, 264, y, 284, y, col, 1.5);
this._ln(g, 296, y, 316, y, col, 1.5);
this._ln(g, 286, y - 4, 294, y + 4, col, 1.5);
this._ln(g, 286, y + 4, 294, y - 4, col, 1.5);
this._tx(g, "F" + (k + 1) + " BLOWN", 290, y - 13, "#d03030", 9, "center", true);
} else {
this._ln(g, 264, y, 316, y, col, 1.5);
this._tx(g, "F" + (k + 1) + " " + rt[k] + "A " + S.fi[k].toFixed(1) + "A", 290, y - 13, "#444", 9);
}
}
// ── Ignition key ─────────────────────────────────────────────────
const on = P.ign >= 0.5;
this._ln(g, 130, 690, 143, 690, "#555");
this._circ(g, 143, 690, 2.5, "#555", true);
this._circ(g, 177, 690, 2.5, "#555", true);
this._ln(g, 177, 690, 190, 690, "#555");
if (on) this._ln(g, 143, 690, 177, 690, hot, 2.5);
else this._ln(g, 143, 690, 175, 676, "#555", 2.5);
this._tx(g, "IGNITION KEY", 160, 712, "#444", 9);
this._tx(g, on ? "ON" : "OFF", 160, 725, on ? "#3cb371" : "#888", 9, "center", true);
// ── Battery ──────────────────────────────────────────────────────
this._tx(g, "BATTERY", 70, 655, "#444", 9);
this._ln(g, 70, 672, 70, 698, hot);
this._ln(g, 53, 698, 87, 698, hot, 3);
this._ln(g, 59, 705, 81, 705, "#555", 3);
this._ln(g, 53, 714, 87, 714, hot, 3);
this._ln(g, 59, 721, 81, 721, "#555", 3);
this._ln(g, 70, 721, 70, 770, "#555");
this._tx(g, "+", 97, 698, hot, 11, "center", true);
this._tx(g, P.Vcc.toFixed(1) + " V", 105, 716, "#666", 9, "left");
this._gnd(g, 70, 774, "#555");
// ── Chassis grounds ──────────────────────────────────────────────
[["g1", 500, 230], ["g2", 500, 400], ["g3", 500, 620], ["g4", 140, 750]].forEach(l => {
this._gnd(g, l[1], l[2] + 4, "#555");
this._tx(g, "CHASSIS", l[1], l[2] + 28, "#888", 8);
});
// ── Active antenna ──────────────────────────────────────────────
const antc = dc(N.antPow && !N.short);
this._rr(g, 250, 80, 140, 60, 6, antc, 2);
this._ln(g, 355, 80, 372, 52, antc, 2); this._circ(g, 372, 52, 3, antc, true);
this._tx(g, "ACTIVE ANTENNA", 320, 92, "#444", 9, "center", true);
this._tx(g, N.antOk ? "SIGNAL OK" : "NO SIGNAL", 320, 106, N.antOk ? "#3cb371" : "#888", 9, "center", true);
// ── Wires ───────────────────────────────────────────────────────
S.wires.forEach((w, i) => this._wire(g, S.rt[i], this._wstyle(P, S, w), S.fr, i === S.hw));
// ── Terminals ───────────────────────────────────────────────────
for (const t of T) {
const tc = this._tcol(t), cn = deg[t.id] > 0;
if (t.k.indexOf("rca") === 0) {
this._circ(g, t.x, t.y, 6, "#777", false);
g.save(); g.fillStyle = tc ? tc.c : "#999"; g.beginPath(); g.arc(t.x, t.y, 3.4, 0, 6.2832); g.fill(); g.restore();
} else {
const r = (t.k === "cap" || t.k === "ter") ? 3.5 : 4.8;
g.save(); g.globalAlpha = cn ? 1 : 0.7;
g.fillStyle = tc ? tc.c : "#888";
g.beginPath(); g.arc(t.x, t.y, r, 0, 6.2832); g.fill();
g.lineWidth = 1.5; g.strokeStyle = "#666"; g.stroke();
g.restore();
}
if (t.lab) {
if (t.pos === "r") this._tx(g, t.lab, t.x + 9, t.y, "#555", 9, "left");
else if (t.pos === "l") this._tx(g, t.lab, t.x - 9, t.y, "#555", 9, "right");
else if (t.pos === "u") this._tx(g, t.lab, t.x, t.y - 10, "#555", 9);
else if (t.pos === "d") this._tx(g, t.lab, t.x, t.y + 11, "#555", 9);
else if (t.pos === "v") this._tv(g, t.lab, t.x, t.y - 9, "#555", 9);
}
}
if (hov) this._circ(g, hov.x, hov.y, 9, "#5aa0ff", false);
// Wire being drawn
if (S.pend && tm[S.pend]) {
const p = tm[S.pend];
this._circ(g, p.x, p.y, 9, "#e8a020", false);
let endp = null;
if (hov && hov.id !== S.pend) endp = [hov.x, hov.y];
else if (S.mx > -500) endp = [this._cl(Math.round(S.mx / 10) * 10, 0, 600), this._cl(Math.round(S.my / 10) * 10, 0, 790)];
const list = [[p.x, p.y]].concat(S.pts);
if (endp) list.push(endp);
if (list.length > 1) {
const pl = this._elbow(list);
g.save(); g.setLineDash([6, 5]); g.lineJoin = "round";
g.strokeStyle = "#e8a020"; g.lineWidth = 2.4;
g.beginPath(); g.moveTo(pl[0][0], pl[0][1]);
for (let i = 1; i < pl.length; i++) g.lineTo(pl[i][0], pl[i][1]);
g.stroke(); g.restore();
}
for (const q of S.pts) {
g.save(); g.fillStyle = "#e8a020"; g.fillRect(q[0] - 3.5, q[1] - 3.5, 7, 7); g.restore();
}
}
// ── Status line ─────────────────────────────────────────────────
this._tx(g, "Key " + (on ? "ON" : "OFF") + " Head " + (hOn ? "ON" : "OFF") + " Amp " + (aOn ? "ON" : "OFF") + " Filter " + (fOn ? "ON" : "OFF") + " Battery " + P.Vcc.toFixed(1) + " V", 300, 818, "#444", 11);
// ── Diagnostics (up to 3 issues) ────────────────────────────────
const dg = this._diag(P, S);
for (let i = 0; i < Math.min(3, dg.length); i++) {
this._tx(g, dg[i][0], 300, 834 + i * 15, dg[i][1], 10);
}
// ── Loads & fuses ───────────────────────────────────────────────
const zf = z => (z === undefined || z === Infinity) ? "--" : z.toFixed(1) + "\u03a9";
this._tx(g, "Loads Head L " + zf(S.zl.hL) + " R " + zf(S.zl.hR) + " Amp L " + zf(S.zl.aL) + " R " + zf(S.zl.aR), 300, 884, "#666", 10);
const any = S.fb.some(b => b);
this._tx(g, "Fuses " + S.fb.map((b, k) => b ? "F" + (k + 1) + " BLOWN" : "F" + (k + 1) + " " + S.fi[k].toFixed(1) + "/" + rt[k] + "A").join(" "), 300, 899, any ? "#d03030" : "#666", 10);
// ── Contextual tip ──────────────────────────────────────────────
const tip = this._tips(P, S);
if (tip) this._tx(g, tip, 300, 914, "#2a7be0", 10);
// ── Colour picker ───────────────────────────────────────────────
const pk = this._palAt(S.mx, S.my), selk = S.col || "auto";
this._tx(g, "WIRE COLOUR: pick one, then draw wires, or click an existing wire to repaint it", 300, 926, "#666", 10);
this._PK.forEach((k, i) => {
if (i === 0) {
this._rr(g, 22, 930, 38, 20, 5, selk === "auto" ? "#5aa0ff" : "#888", selk === "auto" ? 2.5 : 1.2, "rgba(128,128,128,0.15)");
this._tx(g, "AUTO", 41, 940, "#555", 9, "center", true);
return;
}
const cx = 80 + (i - 1) * 29, cy = 940, pl = this._PAL[k];
g.save();
g.fillStyle = pl.c; g.beginPath(); g.arc(cx, cy, 9, 0, 6.2832); g.fill();
if (pl.s) { g.fillStyle = pl.s; g.beginPath(); g.arc(cx, cy, 9, -1.5708, 1.5708); g.closePath(); g.fill(); }
g.lineWidth = 1.5; g.strokeStyle = "#777"; g.beginPath(); g.arc(cx, cy, 9, 0, 6.2832); g.stroke();
if (selk === k) { g.strokeStyle = "#5aa0ff"; g.lineWidth = 2.5; g.beginPath(); g.arc(cx, cy, 12.5, 0, 6.2832); g.stroke(); }
g.restore();
});
// ── Hint line ───────────────────────────────────────────────────
let hint;
if (pk) hint = "Wire colour: " + (pk === "auto" ? "automatic (by connector type)" : this._PAL[pk].n);
else if (hov) hint = hov.tip;
else if (S.pend) hint = "Click empty space to add a bend (" + S.pts.length + "), click a terminal to finish. Right-click: undo bend / cancel.";
else if (S.hw >= 0) hint = "Click: paint this wire with the selected colour. Right-click: remove it.";
else hint = "Click a terminal, optionally click empty space for bends, then click the target terminal.";
this._tx(g, hint, 300, 962, "#5aa0ff", 10);
g.restore();
},
scope: {
span: P => 0.03, unit: "V",
traces: [
{ label: "PRE", color: "#5aa0ff", get: S => S.sc ? S.sc.pre : 0 },
{ label: "LPF", color: "#3cb371", get: S => S.sc ? S.sc.fo : 0 },
{ label: "HU L", color: "#e8a020", get: S => S.sc ? S.sc.hL : 0 },
{ label: "AMP L", color: "#ff6060", get: S => S.sc ? S.sc.aL : 0 },
{ label: "T1", color: "#a060e0", get: S => S.sc ? S.sc.t1 : 0 },
{ label: "S1", color: "#20c0c0", get: S => S.sc ? S.sc.s1 : 0 }
]
}
});