main.js entry 33.7 KB
Copy main.js
// Circuit builder — extended edition
// New vs. original: diode + LED (nonlinear, forward-voltage model), fuse (blows above rated current),
// ideal ammeter / voltmeter probes, unified DC/Square/Sine source, hover highlighting, keyboard shortcuts,
// 4 new example presets, wider board/toolbar. Same visual language as the original (schematic symbols,
// node-voltage coloring, live formula view).
SimKit.define({
title: "Circuit builder: place parts, wire them, read the formulas",
dt: 2e-5, speed: 0.05, height: 640,
params: {
view: { label: "View: schematic (0) / formulas (1)", unit: "", min: 0, max: 1, value: 0, step: 1 },
preset: { label: "Load example: 0 keep,1 series,2 parallel,3 mixed,4 RC,5 RL,6 lamp,7 diode,8 LED,9 fuse,10 meters", unit: "", min: 0, max: 10, value: 3, step: 1 },
clear: { label: "Remove everything (pulse 1, then back to 0)", unit: "", min: 0, max: 1, value: 0, step: 1 },
Vb: { label: "Battery voltage", unit: "V", min: 1, max: 24, value: 12, step: 0.5 },
Rv: { label: "Resistor value", unit: "Ω", min: 10, max: 100000, value: 100, log: true },
Rl: { label: "Lamp resistance", unit: "Ω", min: 5, max: 500, value: 20, log: true },
Cv: { label: "Capacitor value", unit: "µF", min: 0.1, max: 1000, value: 100, log: true },
Lv: { label: "Inductor value", unit: "mH", min: 1, max: 1000, value: 100, log: true },
Vf: { label: "Diode / LED forward voltage", unit: "V", min: 0.1, max: 4, value: 0.65, step: 0.05 },
If: { label: "Fuse current rating", unit: "A", min: 0.05, max: 10, value: 1, log: true },
pulse: { label: "Source waveform: 0 DC / 1 Square / 2 Sine", unit: "", min: 0, max: 2, value: 0, step: 1 },
f: { label: "Source / square-wave frequency", unit: "Hz", min: 1, max: 200, value: 10, log: true }
},
_C: 34, _RW: 14, _GS: 28, _GX: 24, _GY: 84,
_DRON: 2, _LEDREF: 0.05,
_pre: { bat: "E", res: "R", sw: "S", lamp: "LP", cap: "C", ind: "L", gnd: "GND", diode: "D", led: "LED", fuse: "F", amm: "A", volt: "V" },
_RL: { res: 1, lamp: 1, sw: 1, fuse: 1, amm: 1, volt: 1 },
_tools: [
{ id: "sel", name: "EDIT" }, { id: "wire", name: "WIRE" }, { id: "bat", name: "BATTERY" },
{ id: "res", name: "RESISTOR" }, { id: "sw", name: "SWITCH" }, { id: "lamp", name: "LAMP" },
{ id: "cap", name: "CAPACITOR" }, { id: "ind", name: "INDUCTOR" },
{ id: "diode", name: "DIODE" }, { id: "led", name: "LED" }, { id: "fuse", name: "FUSE" },
{ id: "amm", name: "AMMETER" }, { id: "volt", name: "VOLTMETER" },
{ id: "gnd", name: "GROUND" }, { id: "del", name: "DELETE" }
],
init(P, S) {
S.comps = []; S.wires = []; S.cnt = {}; S.ver = 0; S.built = -1; S.dtb = 0;
S.tool = "sel"; S.start = null; S.mx = -1e3; S.my = -1e3;
S.W = 1000; S.H = 640; S.s = 1; S.ox = 0; S.oy = 0; S.lp = -1; S.P = P;
S.nd = new Int16Array(this._C * this._RW).fill(-1);
S.vn = [0]; S.inv = []; S.sz = 0; S.m = 0; S.vm = 1; S.rhs = new Float64Array(0); S.xs = new Float64Array(0);
S.ps = 0; S.pd = 0; S.es = 0; S.on = true; S.srcFactor = 1;
},
_cl(v, a, b) { return v < a ? a : v > b ? b : v; },
_pt(x, y) { return y * this._C + x; },
_px(p) { return this._GX + (p % this._C) * this._GS; },
_py(p) { return this._GY + Math.floor(p / this._C) * this._GS; },
_tbx(i) { return 14 + i * 65; },
_walk(a, b, fn) {
const C = this._C, ax = a % C, ay = (a - ax) / C, bx = b % C, by = (b - bx) / C;
if (ax === bx) { const s = ay < by ? 1 : -1; for (let y = ay; y !== by + s; y += s) fn(y * C + ax); }
else { const s = ax < bx ? 1 : -1; for (let x = ax; x !== bx + s; x += s) fn(ay * C + x); }
},
_empty(S) { S.comps = []; S.wires = []; S.cnt = {}; S.start = null; S.ver++; },
_add(S, t, x1, y1, x2, y2, val, on) {
const c = { t, a: this._pt(x1, y1), b: this._pt(x2, y2), val, on: on !== false, v: 0, i: 0, vp: 0, ip: 0, pa: 0 };
S.cnt[t] = (S.cnt[t] || 0) + 1;
c.name = this._pre[t] + (t === "gnd" ? "" : S.cnt[t]);
S.comps.push(c); S.ver++;
return c;
},
_wire(S, x1, y1, x2, y2) { S.wires.push({ a: this._pt(x1, y1), b: this._pt(x2, y2) }); S.ver++; },
_load(S, P, k) {
this._empty(S);
const A = (t, a, b, c, d, v, on) => this._add(S, t, a, b, c, d, v, on);
const W = (a, b, c, d) => this._wire(S, a, b, c, d);
const E = P.Vb;
if (k === 1) {
A("bat", 3, 3, 3, 9, E);
W(3, 3, 6, 3); A("res", 6, 3, 9, 3, 100); W(9, 3, 11, 3); A("res", 11, 3, 14, 3, 220);
W(14, 3, 16, 3); A("res", 16, 3, 19, 3, 470); W(19, 3, 21, 3);
W(21, 3, 21, 9); W(21, 9, 3, 9); A("gnd", 12, 9, 12, 9, 0);
} else if (k === 2) {
A("bat", 3, 3, 3, 11, E);
W(3, 3, 21, 3); W(3, 11, 21, 11);
A("res", 8, 3, 8, 11, 100); A("res", 13, 3, 13, 11, 220); A("res", 18, 3, 18, 11, 470);
A("gnd", 5, 11, 5, 11, 0);
} else if (k === 3) {
A("bat", 3, 3, 3, 11, E);
W(3, 3, 5, 3); A("res", 5, 3, 9, 3, 100); W(9, 3, 21, 3); W(3, 11, 21, 11);
A("res", 13, 3, 13, 11, 220); A("res", 17, 3, 17, 11, 470); A("res", 21, 3, 21, 11, 1000);
A("gnd", 5, 11, 5, 11, 0);
} else if (k === 4 || k === 5) {
A("bat", 3, 3, 3, 9, E);
W(3, 3, 6, 3); A("sw", 6, 3, 10, 3, 0, true); W(10, 3, 12, 3);
A("res", 12, 3, 16, 3, k === 4 ? 1000 : 100); W(16, 3, 19, 3);
if (k === 4) A("cap", 19, 3, 19, 9, 100e-6); else A("ind", 19, 3, 19, 9, 0.1);
W(19, 9, 3, 9); A("gnd", 11, 9, 11, 9, 0);
} else if (k === 6) {
A("bat", 3, 3, 3, 9, E);
W(3, 3, 7, 3); A("sw", 7, 3, 11, 3, 0, true); W(11, 3, 14, 3); A("lamp", 14, 3, 18, 3, 20);
W(18, 3, 21, 3); W(21, 3, 21, 9); W(21, 9, 3, 9); A("gnd", 12, 9, 12, 9, 0);
} else if (k === 7) {
// Half-wave rectifier: set Source waveform = Sine to see it rectify
A("bat", 3, 3, 3, 9, E);
W(3, 3, 6, 3); A("diode", 6, 3, 10, 3, P.Vf); W(10, 3, 13, 3);
A("res", 13, 3, 17, 3, 470); W(17, 3, 19, 3);
A("cap", 19, 3, 19, 9, 47e-6);
W(19, 9, 3, 9); A("gnd", 10, 9, 10, 9, 0);
} else if (k === 8) {
A("bat", 3, 3, 3, 9, E);
W(3, 3, 6, 3); A("sw", 6, 3, 9, 3, 0, true); W(9, 3, 12, 3);
A("res", 12, 3, 16, 3, 330); W(16, 3, 19, 3);
A("led", 19, 3, 19, 9, P.Vf);
W(19, 9, 3, 9); A("gnd", 10, 9, 10, 9, 0);
} else if (k === 9) {
A("bat", 3, 3, 3, 9, E);
W(3, 3, 6, 3);
const fz = A("fuse", 6, 3, 10, 3, 0.5); fz.rating = 0.6; fz.blown = false;
W(10, 3, 13, 3); A("res", 13, 3, 17, 3, 10); W(17, 3, 19, 3);
A("lamp", 19, 3, 19, 9, 20);
W(19, 9, 3, 9); A("gnd", 10, 9, 10, 9, 0);
} else if (k === 10) {
A("bat", 3, 3, 3, 11, E);
W(3, 3, 6, 3); A("amm", 6, 3, 10, 3, 0); W(10, 3, 13, 3);
A("res", 13, 3, 13, 11, 220); W(13, 11, 3, 11);
W(13, 3, 17, 3); W(13, 11, 17, 11); A("volt", 17, 3, 17, 11, 0);
A("gnd", 5, 11, 5, 11, 0);
}
},
_tick(P, S) {
S.P = P;
const k = Math.round(P.preset);
if (S.lp !== k) {
if (k > 0) this._load(S, P, k);
S.lp = k;
}
if (P.clear >= 0.5 && (S.comps.length || S.wires.length)) this._empty(S);
},
_inv(A, n) {
const M = [];
for (let i = 0; i < n; i++) {
const r = new Float64Array(2 * n);
for (let j = 0; j < n; j++) r[j] = A[i * n + j];
r[n + i] = 1;
M.push(r);
}
for (let c = 0; c < n; c++) {
let p = c, b = Math.abs(M[c][c]);
for (let r = c + 1; r < n; r++) { const v = Math.abs(M[r][c]); if (v > b) { b = v; p = r; } }
if (b < 1e-13) return null;
if (p !== c) { const t = M[p]; M[p] = M[c]; M[c] = t; }
const rc = M[c], d = 1 / rc[c];
for (let j = 0; j < 2 * n; j++) rc[j] *= d;
for (let r = 0; r < n; r++) {
if (r === c) continue;
const f = M[r][c];
if (f === 0) continue;
const rr = M[r];
for (let j = 0; j < 2 * n; j++) rr[j] -= f * rc[j];
}
}
return M.map(r => r.subarray(n));
},
_build(S, dt) {
const N = this._C * this._RW, par = new Array(N);
for (let i = 0; i < N; i++) par[i] = i;
const f = i => { while (par[i] !== i) { par[i] = par[par[i]]; i = par[i]; } return i; };
const un = (a, b) => { a = f(a); b = f(b); if (a !== b) par[a] = b; };
const used = new Set();
for (const w of S.wires) {
let prev = -1;
this._walk(w.a, w.b, p => { if (prev >= 0) un(prev, p); prev = p; });
used.add(w.a); used.add(w.b);
}
for (const c of S.comps) { used.add(c.a); used.add(c.b); }
let gr = -1;
const gc = S.comps.find(c => c.t === "gnd");
if (gc) gr = f(gc.a);
else {
const bt = S.comps.find(c => c.t === "bat");
if (bt) gr = f(bt.b);
else if (used.size) gr = f(used.values().next().value);
}
const map = new Map();
if (gr >= 0) map.set(gr, 0);
let m = 0;
for (const p of used) { const r = f(p); if (!map.has(r)) map.set(r, ++m); }
S.nd.fill(-1);
for (const p of used) S.nd[p] = map.get(f(p));
let ex = 0;
for (const c of S.comps) if (c.t === "bat" || c.t === "ind") c.k = m + ex++;
const sz = m + ex, A = new Float64Array(sz * sz);
const st = (r, c, v) => { if (r >= 0 && c >= 0) A[r * sz + c] += v; };
for (let i = 0; i < m; i++) A[i * sz + i] += 1e-9;
let vm = 1;
for (const c of S.comps) {
if (c.t === "gnd") continue;
const ia = S.nd[c.a] - 1, ib = S.nd[c.b] - 1;
let g = 0;
if (c.t === "res" || c.t === "lamp") g = 1 / c.val;
else if (c.t === "sw") g = c.on ? 1e3 : 1e-9;
else if (c.t === "cap") g = c.val / dt;
else if (c.t === "diode" || c.t === "led") g = c.on ? (1 / this._DRON) : 1e-9;
else if (c.t === "fuse") g = c.blown ? 1e-9 : (1 / c.val);
else if (c.t === "amm") g = 1e4;
else if (c.t === "volt") g = 1e-9;
if (c.t === "bat") {
st(ia, c.k, 1); st(ib, c.k, -1); st(c.k, ia, 1); st(c.k, ib, -1);
vm = Math.max(vm, c.val);
} else if (c.t === "ind") {
st(ia, c.k, 1); st(ib, c.k, -1); st(c.k, ia, 1); st(c.k, ib, -1); st(c.k, c.k, -c.val / dt);
c.g = c.val / dt;
} else {
c.g = g;
st(ia, ia, g); st(ib, ib, g); st(ia, ib, -g); st(ib, ia, -g);
}
}
S.m = m; S.sz = sz; S.vm = vm; S.dtb = dt; S.built = S.ver;
S.inv = sz ? this._inv(A, sz) : [];
S.rhs = new Float64Array(sz); S.xs = new Float64Array(sz);
S.vn = new Array(m + 1).fill(0);
},
step(dt, P, S, t) {
this._tick(P, S);
// Resolve diode/LED conduction state (hysteresis, based on last step's voltage)
// and check fuses for overload. A change here forces a matrix rebuild.
let structChanged = false;
for (const c of S.comps) {
if (c.t === "diode" || c.t === "led") {
const was = c.on;
if (c.on) { if (c.vp < c.val - 0.05) c.on = false; }
else { if (c.vp > c.val) c.on = true; }
if (c.on !== was) structChanged = true;
} else if (c.t === "fuse" && !c.blown && Math.abs(c.i) > (c.rating || 1)) {
c.blown = true; structChanged = true;
}
}
if (structChanged) S.ver++;
if (S.built !== S.ver || S.dtb !== dt) this._build(S, dt);
const mode = Math.round(P.pulse);
let factor = 1;
if (mode === 1) factor = (Math.floor(t * P.f * 2) % 2 === 0) ? 1 : -1;
else if (mode === 2) factor = Math.sin(2 * Math.PI * P.f * t);
S.srcFactor = factor; S.on = factor >= 0;
const sz = S.sz;
if (S.inv === null) {
for (const c of S.comps) { c.v = 0; c.i = 0; }
S.ps = S.pd = S.es = 0;
return;
}
const rhs = S.rhs, x = S.xs, nd = S.nd;
rhs.fill(0);
for (const c of S.comps) {
if (c.t === "bat") rhs[c.k] = c.val * factor;
else if (c.t === "cap") {
const ia = nd[c.a] - 1, ib = nd[c.b] - 1;
if (ia >= 0) rhs[ia] += c.g * c.vp;
if (ib >= 0) rhs[ib] -= c.g * c.vp;
} else if (c.t === "ind") rhs[c.k] = -c.g * c.ip;
else if ((c.t === "diode" || c.t === "led") && c.on) {
const ia = nd[c.a] - 1, ib = nd[c.b] - 1;
if (ia >= 0) rhs[ia] += c.g * c.val;
if (ib >= 0) rhs[ib] -= c.g * c.val;
}
}
for (let i = 0; i < sz; i++) {
const row = S.inv[i];
let s = 0;
for (let j = 0; j < sz; j++) s += row[j] * rhs[j];
x[i] = s;
}
const vn = S.vn;
for (let j = 1; j <= S.m; j++) vn[j] = x[j - 1];
let ps = 0, pd = 0, es = 0;
for (const c of S.comps) {
const na = nd[c.a], nb = nd[c.b];
c.v = (na > 0 ? vn[na] : 0) - (nb > 0 ? vn[nb] : 0);
if (c.t === "gnd") { c.i = 0; continue; }
if (this._RL[c.t]) c.i = c.v * c.g;
else if (c.t === "cap") { c.i = c.g * (c.v - c.vp); c.vp = c.v; es += 0.5 * c.val * c.v * c.v; }
else if (c.t === "ind") { c.i = x[c.k]; c.ip = c.i; es += 0.5 * c.val * c.i * c.i; }
else if (c.t === "bat") c.i = x[c.k];
else if (c.t === "diode" || c.t === "led") { c.i = c.on ? c.g * (c.v - c.val) : c.v * c.g; c.vp = c.v; }
const p = Math.abs(c.v * c.i);
c.pa += (p - c.pa) * 0.002;
if (c.t === "bat") ps += -c.v * c.i;
else if (this._RL[c.t] || c.t === "diode" || c.t === "led") pd += c.v * c.i;
}
S.ps = ps; S.pd = pd; S.es = es;
},
_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();
},
_rr(g, x, y, w, h, c, fill) {
g.save(); g.beginPath(); g.rect(x, y, w, h);
if (fill) { g.fillStyle = fill; g.fill(); }
g.strokeStyle = c; g.lineWidth = 1.5; 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();
},
_sym(g, t, x1, y1, x2, y2, col, glow, mini, on, blown) {
if (t === "gnd") {
this._ln(g, x1, y1, x1, y1 + 8, col);
this._ln(g, x1 - 10, y1 + 8, x1 + 10, y1 + 8, col);
this._ln(g, x1 - 6, y1 + 13, x1 + 6, y1 + 13, col);
this._ln(g, x1 - 2, y1 + 18, x1 + 2, y1 + 18, col);
return;
}
const dx = x2 - x1, dy = y2 - y1, L = Math.hypot(dx, dy);
const body = mini || Math.min(40, L * 0.7), h = body / 2;
g.save();
g.translate((x1 + x2) / 2, (y1 + y2) / 2);
g.rotate(Math.atan2(dy, dx));
if (t === "res") {
this._ln(g, -L / 2, 0, -h, 0, col); this._ln(g, h, 0, L / 2, 0, col);
const pts = [[-h, 0]];
for (let i = 0; i < 6; i++) pts.push([-h + (i + 0.5) * body / 6, i % 2 ? 6 : -6]);
pts.push([h, 0]);
this._poly(g, pts, col, false);
} else if (t === "bat") {
this._ln(g, -L / 2, 0, -3.5, 0, col); this._ln(g, 3.5, 0, L / 2, 0, col);
this._ln(g, -3.5, -11, -3.5, 11, col, 2.5);
this._ln(g, 3.5, -6, 3.5, 6, col, 3);
} else if (t === "cap") {
this._ln(g, -L / 2, 0, -3.5, 0, col); this._ln(g, 3.5, 0, L / 2, 0, col);
this._ln(g, -3.5, -10, -3.5, 10, col, 2.5);
this._ln(g, 3.5, -10, 3.5, 10, col, 2.5);
} else if (t === "sw") {
this._ln(g, -L / 2, 0, -h, 0, col); this._ln(g, h, 0, L / 2, 0, col);
this._circ(g, -h, 0, 2.5, col, true); this._circ(g, h, 0, 2.5, col, true);
if (on) this._ln(g, -h, 0, h, 0, col);
else this._ln(g, -h, 0, h - 4, -14, col);
} else if (t === "lamp") {
this._ln(g, -L / 2, 0, -11, 0, col); this._ln(g, 11, 0, L / 2, 0, col);
if (glow > 0) {
g.save(); g.fillStyle = "rgba(255,200,40," + (0.12 + 0.75 * glow) + ")";
g.beginPath(); g.arc(0, 0, 11, 0, 6.2832); g.fill(); g.restore();
}
this._circ(g, 0, 0, 11, col, false);
this._ln(g, -7.8, -7.8, 7.8, 7.8, col, 1.6); this._ln(g, -7.8, 7.8, 7.8, -7.8, col, 1.6);
} else if (t === "ind") {
this._ln(g, -L / 2, 0, -h, 0, col); this._ln(g, h, 0, L / 2, 0, col);
g.save(); g.strokeStyle = col; g.lineWidth = 2; g.lineCap = "round";
for (let i = 0; i < 4; i++) {
g.beginPath(); g.arc(-h + (i + 0.5) * body / 4, 0, body / 8, Math.PI, 0); g.stroke();
}
g.restore();
} else if (t === "diode" || t === "led") {
this._ln(g, -L / 2, 0, -h, 0, col); this._ln(g, h, 0, L / 2, 0, col);
if (t === "led" && glow > 0) {
g.save(); g.fillStyle = "rgba(60,220,120," + (0.12 + 0.75 * glow) + ")";
g.beginPath(); g.arc(0, 0, 14, 0, 6.2832); g.fill(); g.restore();
}
this._poly(g, [[-h, -8], [-h, 8], [h, 0]], col, true);
this._ln(g, h, -8, h, 8, col, 2.5);
} else if (t === "fuse") {
this._ln(g, -L / 2, 0, -h, 0, col); this._ln(g, h, 0, L / 2, 0, col);
this._rr(g, -h, -6, body, 12, col, null);
this._ln(g, -h + 3, 0, h - 3, 0, col, 1.5);
if (blown) { this._ln(g, -h, -6, h, 6, "#d03030", 2); this._ln(g, -h, 6, h, -6, "#d03030", 2); }
} else if (t === "amm" || t === "volt") {
this._ln(g, -L / 2, 0, -11, 0, col); this._ln(g, 11, 0, L / 2, 0, col);
this._circ(g, 0, 0, 11, col, false);
}
g.restore();
},
_snap(x, y) {
const gx = Math.round((x - this._GX) / this._GS), gy = Math.round((y - this._GY) / this._GS);
if (gx < 0 || gy < 0 || gx >= this._C || gy >= this._RW) return null;
return { x: gx, y: gy };
},
_ortho(s, p) {
const dx = p.x - s.x, dy = p.y - s.y;
if (dx && dy) return Math.abs(dx) >= Math.abs(dy) ? { x: p.x, y: s.y } : { x: s.x, y: p.y };
return p;
},
_dseg(x, y, ax, ay, bx, by) {
const dx = bx - ax, dy = by - ay, l2 = dx * dx + dy * dy;
let u = l2 ? ((x - ax) * dx + (y - ay) * dy) / l2 : 0;
u = this._cl(u, 0, 1);
return Math.hypot(x - (ax + u * dx), y - (ay + u * dy));
},
_pick(S, x, y) {
let best = null, bd = 14;
for (const c of S.comps) {
const ax = this._px(c.a), ay = this._py(c.a);
const d = c.t === "gnd" ? Math.hypot(x - ax, y - ay - 8) : this._dseg(x, y, ax, ay, this._px(c.b), this._py(c.b));
if (d < bd) { bd = d; best = c; }
}
return best;
},
_pickW(S, x, y) {
let best = null, bd = 8;
for (const w of S.wires) {
const d = this._dseg(x, y, this._px(w.a), this._py(w.a), this._px(w.b), this._py(w.b));
if (d < bd) { bd = d; best = w; }
}
return best;
},
_val(t, P) {
if (t === "bat") return P.Vb;
if (t === "res") return P.Rv;
if (t === "lamp") return P.Rl;
if (t === "cap") return P.Cv * 1e-6;
if (t === "ind") return P.Lv * 1e-3;
if (t === "diode" || t === "led") return P.Vf;
if (t === "fuse") return 0.5;
return 0;
},
_click(S, x, y) {
const P = S.P;
if (!P || P.view >= 0.5) return;
if (y < 66) {
for (let i = 0; i < this._tools.length; i++) {
const bx = this._tbx(i);
if (x >= bx && x < bx + 60 && y >= 8 && y <= 58) { S.tool = this._tools[i].id; S.start = null; }
}
return;
}
const t = S.tool;
if (t === "sel") {
const c = this._pick(S, x, y);
if (c) {
if (c.t === "sw") c.on = !c.on;
else if (c.t !== "gnd") {
c.val = this._val(c.t, P);
if (c.t === "fuse") { c.blown = false; c.rating = P.If; }
}
S.ver++;
}
return;
}
if (t === "del") {
const c = this._pick(S, x, y);
if (c) { S.comps.splice(S.comps.indexOf(c), 1); S.ver++; return; }
const w = this._pickW(S, x, y);
if (w) { S.wires.splice(S.wires.indexOf(w), 1); S.ver++; }
return;
}
const p = this._snap(x, y);
if (!p) return;
if (t === "gnd") { this._add(S, "gnd", p.x, p.y, p.x, p.y, 0); return; }
if (!S.start) { S.start = p; return; }
const q = this._ortho(S.start, p);
if (q.x === S.start.x && q.y === S.start.y) { S.start = null; return; }
if (t === "wire") { this._wire(S, S.start.x, S.start.y, q.x, q.y); S.start = q; }
else {
const nc = this._add(S, t, S.start.x, S.start.y, q.x, q.y, this._val(t, P));
if (t === "fuse") { nc.rating = P.If; nc.blown = false; }
S.start = null;
}
},
_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(); S.start = null; });
const keyMap = {
"1": "sel", "2": "wire", "3": "bat", "4": "res", "5": "sw", "6": "lamp", "7": "cap", "8": "ind",
"9": "diode", "0": "led", "f": "fuse", "a": "amm", "v": "volt", "g": "gnd", "x": "del"
};
window.addEventListener("keydown", e => {
if (e.key === "Escape") { S.start = null; return; }
const k = keyMap[e.key.toLowerCase()];
if (k) { S.tool = k; S.start = null; }
});
},
_nc(S, p) {
const n = S.nd[p];
if (n < 0 || !S.vn || n >= S.vn.length) return "#999";
const v = S.vn[n];
return Math.abs(v) < 0.01 ? "#666" : SimKit.voltColor(v, S.vm);
},
_vs(c) {
const F = SimKit.fmt;
if (c.t === "bat") return F(c.val, "V");
if (c.t === "res" || c.t === "lamp") return F(c.val, "Ω");
if (c.t === "cap") return F(c.val, "F");
if (c.t === "ind") return F(c.val, "H");
if (c.t === "sw") return c.on ? "ON" : "OFF";
if (c.t === "diode" || c.t === "led") return "Vf=" + F(c.val, "V") + (c.on ? " ON" : " OFF");
if (c.t === "fuse") return c.blown ? "BLOWN" : F(c.rating || 1, "A") + " rated";
if (c.t === "amm" || c.t === "volt") return "ideal";
return "";
},
_status(S) {
if (!S.comps.length) return ["Empty board: pick a part, click two grid points, or load an example", "#c08000"];
if (S.inv === null) return ["SHORT CIRCUIT or source loop: the circuit has no solution", "#d03030"];
const b = S.comps.find(c => c.t === "bat");
if (!b) return ["No battery in the circuit", "#c08000"];
const blown = S.comps.find(c => c.t === "fuse" && c.blown);
if (blown) return [blown.name + " has blown — circuit opened. Click it in EDIT mode to replace it", "#d03030"];
if (Math.abs(b.i) < 1e-9) return ["Open circuit: no current flows", "#c08000"];
return ["Circuit running", "#3cb371"];
},
_formulas(g, P, S) {
const F = SimKit.fmt, ab = Math.abs;
const L = [];
L.push(["FORMULA VIEW", "#5aa0ff", 1, 13]);
L.push(["Ohm: V = I·R Power: P = V·I Capacitor: I = C·dV/dt Inductor: V = L·dI/dt", "#666", 0, 11]);
L.push(["Diode/LED: conducts (V≈Vf) above threshold, blocks below it Fuse: opens once |I| exceeds its rating", "#666", 0, 11]);
L.push(["KCL: ΣI(in) = ΣI(out) at a node KVL: ΣV = 0 around a loop", "#666", 0, 11]);
L.push(["", "#444", 0, 11]);
if (S.inv === null) {
L.push(["No solution: short circuit or ideal source loop", "#d03030", 1, 12]);
} else {
let nl = "Node voltages: ";
const k = Math.min(S.m, 6);
for (let n = 1; n <= k; n++) nl += "N" + n + " = " + F(S.vn[n], "V") + " ";
nl += "GND = 0 V";
L.push([nl, "#5aa0ff", 0, 11]);
L.push(["", "#444", 0, 11]);
L.push(["Components:", "#444", 1, 12]);
const parts = S.comps.filter(c => c.t !== "gnd");
parts.slice(0, 14).forEach(c => {
const nm = c.name + " = " + this._vs(c) + ": ";
let s = "";
if (c.t === "bat") s = "E = " + F(c.v, "V") + ", I = " + F(-c.i, "A") + ", P = E·I = " + F(-c.v * c.i, "W") + " delivered";
else if (c.t === "res" || c.t === "lamp") s = "V = I·R = " + F(ab(c.i), "A") + " × " + F(c.val, "Ω") + " = " + F(ab(c.v), "V") + ", P = V·I = " + F(ab(c.v * c.i), "W");
else if (c.t === "sw") s = c.on ? "closed, V = " + F(ab(c.v), "V") + ", I = " + F(ab(c.i), "A") : "open, R → ∞, V = " + F(ab(c.v), "V") + ", I ≈ 0";
else if (c.t === "cap") s = "V = " + F(c.v, "V") + ", I = C·dV/dt = " + F(ab(c.i), "A") + ", E = ½CV² = " + F(0.5 * c.val * c.v * c.v, "J");
else if (c.t === "ind") s = "I = " + F(c.i, "A") + ", V = L·dI/dt = " + F(ab(c.v), "V") + ", E = ½LI² = " + F(0.5 * c.val * c.i * c.i, "J");
else if (c.t === "diode" || c.t === "led") s = c.on ? "conducting: V ≈ " + F(c.val, "V") + ", I = " + F(ab(c.i), "A") : "blocking: V = " + F(ab(c.v), "V") + ", I ≈ 0";
else if (c.t === "fuse") s = c.blown ? "BLOWN (open), rated " + F(c.rating || 1, "A") : "V = " + F(ab(c.v), "V") + ", I = " + F(ab(c.i), "A") + " / rated " + F(c.rating || 1, "A");
else if (c.t === "amm" || c.t === "volt") s = "V = " + F(ab(c.v), "V") + ", I = " + F(ab(c.i), "A");
L.push([nm + s, c.t === "bat" ? "#d03030" : "#444", 0, 11]);
});
if (parts.length > 14) L.push(["... and " + (parts.length - 14) + " more", "#888", 0, 11]);
L.push(["", "#444", 0, 11]);
L.push(["Kirchhoff current law:", "#444", 1, 12]);
const k2 = Math.min(S.m, 4);
for (let n = 1; n <= k2; n++) {
let inn = 0, out = 0;
for (const c of S.comps) {
if (c.t === "gnd") continue;
const na = S.nd[c.a], nb = S.nd[c.b];
if (na === nb) continue;
if (na === n) { if (c.i > 0) out += c.i; else inn -= c.i; }
if (nb === n) { if (c.i > 0) inn += c.i; else out -= c.i; }
}
L.push(["N" + n + ": ΣI in = " + F(inn, "A") + " ΣI out = " + F(out, "A") + " difference = " + F(ab(inn - out), "A"), "#444", 0, 11]);
}
L.push(["", "#444", 0, 11]);
L.push(["Power balance:", "#444", 1, 12]);
L.push(["P supplied = ΣE·I = " + F(S.ps, "W") + " P dissipated = ΣV·I = " + F(S.pd, "W"), "#d03030", 0, 11]);
L.push(["Energy stored in C and L = " + F(S.es, "J") + " P supplied = P dissipated + dE/dt", "#444", 0, 11]);
const bs = S.comps.filter(c => c.t === "bat");
if (bs.length === 1 && ab(bs[0].i) > 1e-9 && S.on) {
L.push(["R_eq = E / I = " + F(bs[0].val, "V") + " / " + F(ab(bs[0].i), "A") + " = " + F(bs[0].val / ab(bs[0].i), "Ω"), "#3cb371", 1, 12]);
}
}
let y = 26;
for (const l of L) { this._tx(g, l[0], 24, y, l[1], l[3], "left", l[2]); y += 17; }
},
draw(g, W, H, P, S) {
S.W = W; S.H = H;
const sc = Math.min(W / 1000, H / 640);
S.s = sc; S.ox = (W - 1000 * sc) / 2; S.oy = (H - 640 * sc) / 2;
this._bind(g, S);
if (S.built !== S.ver) this._build(S, S.dtb || 2e-5);
const F = SimKit.fmt;
g.save();
g.translate(S.ox, S.oy);
g.scale(sc, sc);
if (P.view >= 0.5) {
this._formulas(g, P, S);
g.restore();
return;
}
for (let i = 0; i < this._tools.length; i++) {
const tl = this._tools[i], bx = this._tbx(i), sel = S.tool === tl.id;
this._rr(g, bx, 8, 60, 50, sel ? "#5aa0ff" : "#888", sel ? "rgba(90,160,255,0.18)" : null);
const cy = 28, cx = bx + 30, col = sel ? "#5aa0ff" : "#555";
if (tl.id === "wire") { this._ln(g, cx - 20, cy, cx + 20, cy, col); this._circ(g, cx - 20, cy, 2.5, col, true); this._circ(g, cx + 20, cy, 2.5, col, true); }
else if (tl.id === "sel") { this._poly(g, [[cx - 6, cy - 10], [cx - 6, cy + 10], [cx - 1, cy + 5], [cx + 6, cy + 5]], col, true); }
else if (tl.id === "del") { this._ln(g, cx - 8, cy - 8, cx + 8, cy + 8, "#d03030", 2.5); this._ln(g, cx - 8, cy + 8, cx + 8, cy - 8, "#d03030", 2.5); }
else this._sym(g, tl.id, cx - 22, cy, cx + 22, cy, col, 0, 24, true, false);
this._tx(g, tl.name, cx, 50, "#444", 7);
}
g.save(); g.fillStyle = "rgba(128,128,128,0.4)";
for (let gy = 0; gy < this._RW; gy++) for (let gx = 0; gx < this._C; gx++) g.fillRect(this._GX + gx * this._GS - 1, this._GY + gy * this._GS - 1, 2, 2);
g.restore();
const deg = {};
const dg = (p, n) => { deg[p] = (deg[p] || 0) + n; };
for (const w of S.wires) {
this._walk(w.a, w.b, p => dg(p, 2));
dg(w.a, -1); dg(w.b, -1);
}
for (const c of S.comps) { dg(c.a, 1); if (c.b !== c.a) dg(c.b, 1); }
for (const w of S.wires) {
this._ln(g, this._px(w.a), this._py(w.a), this._px(w.b), this._py(w.b), this._nc(S, w.a), 2.4);
}
const hc = S.mx > -500 && S.my > 66 && (S.tool === "sel" || S.tool === "del") ? this._pick(S, S.mx, S.my) : null;
for (const c of S.comps) {
const x1 = this._px(c.a), y1 = this._py(c.a), x2 = this._px(c.b), y2 = this._py(c.b);
const na = S.nd[c.a], nb = S.nd[c.b];
const hv = Math.max(na > 0 ? S.vn[na] || 0 : 0, nb > 0 ? S.vn[nb] || 0 : 0);
let col = hv > 0.01 ? SimKit.voltColor(hv, S.vm) : "#666";
if (c.t === "fuse" && c.blown) col = "#999";
let glow = 0;
if (c.t === "lamp") { const rated = P.Vb * P.Vb / Math.max(c.val, 1); glow = this._cl(Math.sqrt(c.pa / rated), 0, 1); }
else if (c.t === "led") glow = this._cl(c.pa / this._LEDREF, 0, 1);
if (c === hc) {
g.save(); g.strokeStyle = "#5aa0ff"; g.lineWidth = 6; g.lineCap = "round"; g.globalAlpha = 0.3;
g.beginPath(); g.moveTo(x1, y1); g.lineTo(x2, y2); g.stroke(); g.restore();
}
this._sym(g, c.t, x1, y1, x2, y2, col, glow, 0, c.on, c.blown);
const mx = (x1 + x2) / 2, my = (y1 + y2) / 2;
if (c.t === "gnd") { this._tx(g, "GND", x1, y1 + 32, "#888", 9); continue; }
const cur = c.t === "bat" ? -c.i : c.i;
const nm = c.name + " " + this._vs(c), is = F(Math.abs(cur), "A");
if (y1 === y2) {
this._tx(g, nm, mx, my - 26, "#444", 10);
this._tx(g, is, mx, my + 26, "#d03030", 9);
} else {
this._tx(g, nm, mx + 22, my - 8, "#444", 10, "left");
this._tx(g, is, mx + 22, my + 8, "#d03030", 9, "left");
}
if (c.t === "bat") {
const L = Math.hypot(x2 - x1, y2 - y1), ux = (x2 - x1) / L, uy = (y2 - y1) / L;
this._tx(g, "+", mx - 14 * ux - 14 * uy, my - 14 * uy + 14 * ux, "#d03030", 12, "center", true);
}
}
const tagged = {};
for (let p = 0; p < S.nd.length; p++) {
const n = S.nd[p];
if (n > 0 && !tagged[n]) {
tagged[n] = 1;
this._tx(g, "N" + n, this._px(p) + 12, this._py(p) - 10, "#999", 8);
}
}
for (const k in deg) {
const d = deg[k], p = +k;
if (d <= 0) continue;
this._circ(g, this._px(p), this._py(p), d >= 3 ? 4.5 : 2.8, this._nc(S, p), true);
}
const hp = S.mx > -500 && S.my > 66 ? this._snap(S.mx, S.my) : null;
if (hp && S.tool !== "sel" && S.tool !== "del") this._circ(g, this._GX + hp.x * this._GS, this._GY + hp.y * this._GS, 8, "#5aa0ff", false);
if (S.start) {
const sx = this._GX + S.start.x * this._GS, sy = this._GY + S.start.y * this._GS;
this._circ(g, sx, sy, 8, "#e8a020", false);
if (hp) {
const q = this._ortho(S.start, hp), qx = this._GX + q.x * this._GS, qy = this._GY + q.y * this._GS;
if (S.tool === "wire") this._ln(g, sx, sy, qx, qy, "#e8a020", 2);
else if (qx !== sx || qy !== sy) this._sym(g, S.tool, sx, sy, qx, qy, "#e8a020", 0, 0, true, false);
}
}
const st = this._status(S);
this._tx(g, st[0], 500, 476, st[1], 12, "center", true);
this._tx(g, "P supplied " + F(S.ps, "W") + " P dissipated " + F(S.pd, "W") + " Stored energy " + F(S.es, "J"), 500, 498, "#444", 11);
let tip;
if (hc && hc.t !== "gnd") tip = hc.name + " = " + this._vs(hc) + ", V = " + F(Math.abs(hc.v), "V") + ", I = " + F(Math.abs(hc.t === "bat" ? -hc.i : hc.i), "A");
else {
const h = {
sel: "EDIT: click a switch to toggle it, a part to set it to the slider value, a blown fuse to replace it",
wire: "WIRE: click the start point, then the end point (horizontal or vertical). Right-click to stop",
del: "DELETE: click a part or a wire",
gnd: "GROUND: click a grid point to place the 0 V reference",
diode: "DIODE: conducts only from the flat-triangle side toward the bar (anode → cathode)",
led: "LED: like a diode, but glows and drops a visible forward voltage while conducting",
fuse: "FUSE: behaves like a wire until current exceeds its rating, then opens permanently",
amm: "AMMETER: place IN SERIES, in the current path — it has almost no resistance",
volt: "VOLTMETER: place IN PARALLEL, across two points — it draws almost no current"
};
tip = h[S.tool] || "Click the first terminal point, then the second one. Right-click cancels";
}
this._tx(g, tip, 500, 520, "#5aa0ff", 11);
this._tx(g, "Set View = 1 to see the formulas with the live numbers", 500, 542, "#888", 10);
this._tx(g, "Keys: 1-0 quick parts, F/A/V/G/X fuse/ammeter/voltmeter/ground/delete, Esc cancels", 500, 562, "#888", 9);
g.restore();
},
scope: {
span: P => 4 / P.f, unit: "mA",
traces: [
{ label: "I src", color: "#888888", get: S => { const c = S.comps.find(x => x.t === "bat"); return c ? -c.i * 1000 : 0; } },
{ label: "I R", color: "#5aa0ff", get: S => { const c = S.comps.find(x => x.t === "res"); return c ? c.i * 1000 : 0; } },
{ label: "I lamp", color: "#e8a020", get: S => { const c = S.comps.find(x => x.t === "lamp"); return c ? c.i * 1000 : 0; } },
{ label: "I C", color: "#3cb371", get: S => { const c = S.comps.find(x => x.t === "cap"); return c ? c.i * 1000 : 0; } },
{ label: "I L", color: "#a060e0", get: S => { const c = S.comps.find(x => x.t === "ind"); return c ? c.i * 1000 : 0; } },
{ label: "I D", color: "#ff6060", get: S => { const c = S.comps.find(x => x.t === "diode"); return c ? c.i * 1000 : 0; } },
{ label: "I LED", color: "#30d080", get: S => { const c = S.comps.find(x => x.t === "led"); return c ? c.i * 1000 : 0; } }
]
}
});