/* ═══════════════════════════════════════════════════════════════════════════
x86 PCB Design Simulator — Frontend Application
═══════════════════════════════════════════════════════════════════════════ */
// ── Tab Navigation ──────────────────────────────────────────────────────────
document.querySelectorAll('.tab').forEach(btn => {
btn.addEventListener('click', () => {
document.querySelectorAll('.tab').forEach(b => b.classList.remove('active'));
document.querySelectorAll('.tab-panel').forEach(p => p.classList.remove('active'));
btn.classList.add('active');
document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
});
});
// ── Helpers ─────────────────────────────────────────────────────────────────
async function api(endpoint, body) {
const res = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!res.ok) {
const err = await res.json().catch(() => ({ detail: res.statusText }));
throw new Error(err.detail || 'API error');
}
return res.json();
}
function loading(el) {
el.innerHTML = '
Running simulation…
';
}
function fmt(n) { return typeof n === 'number' ? n.toLocaleString() : n; }
const COLORS = {
accent: '#4fc3f7', accent2: '#7c4dff', green: '#66bb6a', red: '#ef5350',
orange: '#ffa726', yellow: '#ffee58', cyan: '#26c6da', pink: '#ec407a',
teal: '#26a69a', grid: '#2e3d5f', text: '#8899b4', white: '#e0e6f0',
};
// Shared chart helpers
function drawGrid(ctx, pad, cw, ch, yLabels, xLabels) {
ctx.strokeStyle = COLORS.grid;
ctx.lineWidth = 0.5;
ctx.font = '11px Segoe UI';
ctx.fillStyle = COLORS.text;
if (yLabels) {
for (let i = 0; i < yLabels.length; i++) {
const y = pad.t + ch * (1 - i / (yLabels.length - 1));
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.textAlign = 'right';
ctx.fillText(yLabels[i], pad.l - 6, y + 4);
}
}
if (xLabels) {
ctx.textAlign = 'center';
for (let i = 0; i < xLabels.length; i++) {
const x = pad.l + (i / (xLabels.length - 1)) * cw;
ctx.fillText(xLabels[i], x, pad.t + ch + 18);
}
}
}
// ═══════════════════════════════════════════════════════════════════════════
// STACKUP TAB
// ═══════════════════════════════════════════════════════════════════════════
document.getElementById('stackup-run').addEventListener('click', async () => {
const statsEl = document.getElementById('stackup-stats');
const tableEl = document.getElementById('stackup-table');
const refsEl = document.getElementById('stackup-refs');
loading(statsEl);
tableEl.innerHTML = ''; refsEl.innerHTML = '';
try {
const data = await api('/api/stackup', {});
statsEl.innerHTML = `
Total Thickness
${data.total_thickness_mil} mil
Thickness (mm)
${data.total_thickness_mm} mm
Copper Layers
${data.copper_layer_count}
Dielectric Layers
${data.dielectric_layer_count}
`;
// Draw stackup visual
drawStackup(data.layers);
// Layer table
tableEl.innerHTML = `
Layer Type Material Thickness (mil) Details
${data.layers.map(l => `
${l.name}
${l.type}
${l.material}
${l.thickness_mil}
${l.type === 'dielectric'
? `εr=${l.er}, ${l.capacitance_pf_per_sq_in} pF/in²`
: l.sheet_resistance_mohm_sq ? `${l.sheet_resistance_mohm_sq} mΩ/□` : (l.net || '')
}
`).join('')}
`;
// Signal routing references
refsEl.innerHTML = `Signal Layer Reference Planes
Signal Layer Ref Above Dist Above (mil) Ref Below Dist Below (mil) Routing Type
${data.signal_layers.map(s => `
${s.layer}
${s.ref_above || '—'}
${s.dist_to_ref_above_mil || '—'}
${s.ref_below || '—'}
${s.dist_to_ref_below_mil || '—'}
${s.routing_type}
`).join('')}
`;
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawStackup(layers) {
const canvas = document.getElementById('stackup-visual');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = Math.max(420, layers.length * 45 + 80);
ctx.clearRect(0, 0, W, H);
const pad = { l: 140, r: 40, t: 40, b: 30 };
const cw = W - pad.l - pad.r;
const totalMil = layers.reduce((s, l) => s + l.thickness_mil, 0);
const minH = 18;
let y = pad.t;
ctx.fillStyle = COLORS.white;
ctx.font = 'bold 13px Segoe UI';
ctx.textAlign = 'center';
ctx.fillText('PCB Cross-Section (5-Layer Stackup)', W / 2, 22);
layers.forEach(l => {
const h = Math.max(minH, (l.thickness_mil / totalMil) * (H - pad.t - pad.b) * 0.9);
let color;
if (l.type === 'signal') color = '#d4a056';
else if (l.type === 'plane') color = '#c06030';
else color = l.material.includes('Prepreg') ? '#3a6040' : '#2a5050';
// Layer rectangle
ctx.fillStyle = color;
ctx.fillRect(pad.l, y, cw, h);
ctx.strokeStyle = '#0b0f19';
ctx.lineWidth = 1;
ctx.strokeRect(pad.l, y, cw, h);
// Pattern for copper layers
if (l.type === 'signal' || l.type === 'plane') {
ctx.save();
ctx.globalAlpha = 0.3;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 0.5;
for (let px = pad.l + 8; px < pad.l + cw; px += 14) {
ctx.beginPath(); ctx.moveTo(px, y + 2); ctx.lineTo(px, y + h - 2); ctx.stroke();
}
ctx.restore();
}
// Label left
ctx.fillStyle = COLORS.white;
ctx.font = '11px Segoe UI';
ctx.textAlign = 'right';
ctx.fillText(l.name, pad.l - 8, y + h / 2 + 4);
// Thickness right
ctx.fillStyle = COLORS.text;
ctx.textAlign = 'left';
ctx.fillText(`${l.thickness_mil} mil`, pad.l + cw + 6, y + h / 2 + 4);
y += h + 2;
});
}
// ═══════════════════════════════════════════════════════════════════════════
// IMPEDANCE TAB
// ═══════════════════════════════════════════════════════════════════════════
document.getElementById('imp-run').addEventListener('click', async () => {
const statsEl = document.getElementById('imp-stats');
const tableEl = document.getElementById('imp-table');
loading(statsEl); tableEl.innerHTML = '';
try {
const data = await api('/api/impedance', {
trace_type: document.getElementById('imp-type').value,
trace_width_mil: parseFloat(document.getElementById('imp-width').value),
trace_spacing_mil: parseFloat(document.getElementById('imp-spacing').value),
dielectric_thickness_mil: parseFloat(document.getElementById('imp-height').value),
copper_thickness_oz: parseFloat(document.getElementById('imp-copper').value),
er: parseFloat(document.getElementById('imp-er').value),
frequency_ghz: parseFloat(document.getElementById('imp-freq').value),
});
let stats = `
Single-Ended Z₀
${data.single_ended_impedance_ohm} Ω
Effective εr
${data.effective_er}
Prop. Delay
${data.propagation_delay_ps_per_inch} ps/in
Velocity
${data.velocity_mm_per_ns} mm/ns
Skin Depth
${data.skin_depth_um} µm
Total Loss
${data.total_loss_db_per_inch} dB/in
`;
if (data.differential_impedance_ohm) {
stats += `Differential Z
${data.differential_impedance_ohm} Ω
`;
stats += `Coupling Factor
${data.coupling_factor_k}
`;
}
statsEl.innerHTML = stats;
// Draw loss vs frequency chart
drawImpedanceChart(data.frequency_sweep);
// Frequency sweep table
tableEl.innerHTML = `
Frequency Skin Depth (µm) Conductor Loss (dB/in) Dielectric Loss (dB/in) Total Loss (dB/in)
${data.frequency_sweep.map(s => `
${s.freq_ghz} GHz
${s.skin_depth_um}
${s.conductor_loss_db_in}
${s.dielectric_loss_db_in}
${s.total_loss_db_in}
`).join('')}
`;
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawImpedanceChart(sweep) {
const canvas = document.getElementById('imp-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 350;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 30, b: 50, l: 60 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const maxLoss = Math.max(...sweep.map(s => s.total_loss_db_in), 0.1) * 1.2;
// Grid
for (let i = 0; i <= 5; i++) {
const y = pad.t + ch * (1 - i / 5);
const val = (maxLoss * i / 5).toFixed(2);
ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'right';
ctx.fillText(val, pad.l - 6, y + 4);
}
// X labels
ctx.textAlign = 'center';
sweep.forEach((s, i) => {
const x = pad.l + (i / (sweep.length - 1)) * cw;
ctx.fillStyle = COLORS.text; ctx.fillText(s.freq_ghz + ' GHz', x, H - pad.b + 18);
});
// Lines
const datasets = [
{ key: 'conductor_loss_db_in', color: COLORS.orange, label: 'Conductor' },
{ key: 'dielectric_loss_db_in', color: COLORS.cyan, label: 'Dielectric' },
{ key: 'total_loss_db_in', color: COLORS.red, label: 'Total' },
];
datasets.forEach(ds => {
ctx.beginPath();
ctx.strokeStyle = ds.color;
ctx.lineWidth = ds.key === 'total_loss_db_in' ? 2.5 : 1.5;
sweep.forEach((s, i) => {
const x = pad.l + (i / (sweep.length - 1)) * cw;
const y = pad.t + ch * (1 - s[ds.key] / maxLoss);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
});
// Legend
let lx = pad.l + 10;
datasets.forEach(ds => {
ctx.fillStyle = ds.color;
ctx.fillRect(lx, pad.t + 5, 16, 3);
ctx.fillStyle = COLORS.text;
ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText(ds.label, lx + 20, pad.t + 12);
lx += 100;
});
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('Loss vs Frequency (dB/inch)', pad.l, pad.t - 10);
}
// ═══════════════════════════════════════════════════════════════════════════
// SIGNAL INTEGRITY TAB
// ═══════════════════════════════════════════════════════════════════════════
(async function initSI() {
try {
const res = await fetch('/api/interfaces');
const data = await res.json();
const sel = document.getElementById('si-iface');
sel.innerHTML = Object.keys(data.interfaces).map(k =>
`${k} (${data.interfaces[k].data_rate_gbps} Gbps) `
).join('');
} catch (e) {}
})();
document.getElementById('si-run').addEventListener('click', async () => {
const statsEl = document.getElementById('si-stats');
const checksEl = document.getElementById('si-checks');
loading(statsEl); checksEl.innerHTML = '';
try {
const data = await api('/api/signal-integrity', {
interface: document.getElementById('si-iface').value,
trace_length_mm: parseFloat(document.getElementById('si-length').value),
trace_width_mil: parseFloat(document.getElementById('si-width').value),
layer: document.getElementById('si-layer').value,
via_count: parseInt(document.getElementById('si-vias').value),
er: parseFloat(document.getElementById('si-er').value),
loss_tangent: parseFloat(document.getElementById('si-loss').value),
});
if (data.error) {
statsEl.innerHTML = ``;
return;
}
statsEl.innerHTML = `
Interface
${data.interface}
Data Rate
${data.interface_info.data_rate_gbps} Gbps
Prop. Delay
${data.propagation_delay_ns} ns
Total IL
${data.total_insertion_loss_db} dB
Eye Height
${data.eye_height_pct}%
Eye Width
${data.eye_width_pct}%
Bit Period
${data.bit_period_ps} ps
λ @ Nyquist
${data.wavelength_at_nyquist_mm} mm
`;
// Eye diagram
drawEyeDiagram(data);
// Loss breakdown chart
drawSILossChart(data.loss_breakdown);
// Design checks
checksEl.innerHTML = data.design_checks.map(c => `
Value: ${c.value} · Limit: ${c.limit}
`).join('');
// Skew info
checksEl.innerHTML += `
Tolerance: ±${data.length_match_tolerance_mil} mil · Skew budget: ${data.skew_budget_ps} ps
`;
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawEyeDiagram(data) {
const canvas = document.getElementById('si-eye-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 300;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 20, b: 30, l: 20 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const cx = pad.l + cw / 2;
const cy = pad.t + ch / 2;
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText('Eye Diagram (Estimated)', W / 2, 18);
// Background
ctx.fillStyle = '#0d1525';
ctx.fillRect(pad.l, pad.t, cw, ch);
const eyeH = (data.eye_height_pct / 100) * ch * 0.4;
const eyeW = (data.eye_width_pct / 100) * cw * 0.35;
const jitter = (100 - data.eye_width_pct) / 100 * 0.3;
const noise = (100 - data.eye_height_pct) / 100 * 0.5;
// Draw many overlapping traces to form eye pattern
ctx.globalAlpha = 0.08;
ctx.strokeStyle = COLORS.green;
ctx.lineWidth = 1.5;
for (let trace = 0; trace < 120; trace++) {
ctx.beginPath();
const jitterOff = (Math.random() - 0.5) * jitter * cw * 0.3;
const noiseOff = (Math.random() - 0.5) * noise * ch * 0.3;
const bits = [Math.random() > 0.5 ? 1 : 0, Math.random() > 0.5 ? 1 : 0, Math.random() > 0.5 ? 1 : 0];
for (let bi = 0; bi < 3; bi++) {
const xStart = pad.l + (bi / 3) * cw + jitterOff;
const xEnd = pad.l + ((bi + 1) / 3) * cw + jitterOff;
const yLow = cy + ch * 0.35 + noiseOff;
const yHigh = cy - ch * 0.35 + noiseOff;
const yVal = bits[bi] ? yHigh : yLow;
if (bi === 0) {
ctx.moveTo(xStart, yVal);
}
// Transition
const nextY = bi < 2 ? (bits[bi + 1] ? yHigh : yLow) : yVal;
const rise = cw * 0.03;
ctx.lineTo(xEnd - rise, yVal);
ctx.lineTo(xEnd + rise, nextY);
}
ctx.stroke();
}
ctx.globalAlpha = 1.0;
// Eye opening rectangle
ctx.strokeStyle = COLORS.accent;
ctx.lineWidth = 2;
ctx.setLineDash([4, 4]);
ctx.strokeRect(cx - eyeW, cy - eyeH, eyeW * 2, eyeH * 2);
ctx.setLineDash([]);
// Labels
ctx.fillStyle = COLORS.accent;
ctx.font = '11px Segoe UI';
ctx.textAlign = 'center';
ctx.fillText(`Eye Height: ${data.eye_height_pct}%`, cx, cy + eyeH + 16);
ctx.fillText(`Eye Width: ${data.eye_width_pct}%`, cx, cy - eyeH - 8);
}
function drawSILossChart(losses) {
const canvas = document.getElementById('si-loss-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 300;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 20, b: 55, l: 55 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const maxLoss = Math.max(...losses.map(l => l.total_loss_db), 1) * 1.3;
const barW = Math.min(50, cw / (losses.length * 4));
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('Loss Breakdown by Frequency', pad.l, 18);
// Grid
for (let i = 0; i <= 4; i++) {
const y = pad.t + ch * (1 - i / 4);
ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
ctx.fillText((maxLoss * i / 4).toFixed(1) + ' dB', pad.l - 6, y + 4);
}
const catColors = [COLORS.orange, COLORS.cyan, COLORS.pink];
const catKeys = ['conductor_loss_db', 'dielectric_loss_db', 'via_loss_db'];
const catLabels = ['Conductor', 'Dielectric', 'Via'];
losses.forEach((l, li) => {
const cx = pad.l + (li + 0.5) * (cw / losses.length);
let yBase = pad.t + ch;
catKeys.forEach((key, ki) => {
const val = l[key];
const h = (val / maxLoss) * ch;
ctx.fillStyle = catColors[ki];
ctx.fillRect(cx - barW / 2, yBase - h, barW, h);
yBase -= h;
});
// Label
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText(l.label, cx, H - pad.b + 16);
ctx.fillText(l.frequency_ghz + ' GHz', cx, H - pad.b + 30);
});
// Legend
let lx = pad.l + cw - 220;
catLabels.forEach((label, i) => {
ctx.fillStyle = catColors[i]; ctx.fillRect(lx, pad.t + 4, 12, 10);
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText(label, lx + 16, pad.t + 13);
lx += 72;
});
}
// ═══════════════════════════════════════════════════════════════════════════
// PDN TAB
// ═══════════════════════════════════════════════════════════════════════════
(async function initPDN() {
try {
const res = await fetch('/api/power-rails');
const data = await res.json();
const sel = document.getElementById('pdn-rail');
sel.innerHTML = data.rails.map(r =>
`${r.name} (${r.voltage}V — ${r.description}) `
).join('');
} catch (e) {}
})();
document.getElementById('pdn-run').addEventListener('click', async () => {
const statsEl = document.getElementById('pdn-stats');
loading(statsEl);
try {
const data = await api('/api/pdn', {
rail: document.getElementById('pdn-rail').value,
load_current_a: parseFloat(document.getElementById('pdn-current').value),
plane_area_sq_in: parseFloat(document.getElementById('pdn-area').value),
decap_count: parseInt(document.getElementById('pdn-decap-n').value),
decap_value_uf: parseFloat(document.getElementById('pdn-decap-v').value),
bulk_cap_count: parseInt(document.getElementById('pdn-bulk-n').value),
bulk_cap_uf: parseFloat(document.getElementById('pdn-bulk-v').value),
});
if (data.error) {
statsEl.innerHTML = ``;
return;
}
const vc = data.verdict === 'PASS' ? 'green' : (data.verdict === 'MARGINAL' ? 'orange' : 'red');
statsEl.innerHTML = `
Target Z
${data.target_impedance_mohm.toFixed(2)} mΩ
Plane Cap
${data.plane_capacitance_nf} nF
DC Drop
${data.dc_voltage_drop_mv} mV
Violations
${data.target_violations}/${data.total_freq_points}
`;
drawPDNChart(data);
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawPDNChart(data) {
const canvas = document.getElementById('pdn-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 380;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 30, b: 55, l: 70 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const profile = data.impedance_profile;
// Log scale for Y (impedance) and X (frequency)
const zValues = profile.map(p => p.z_magnitude_mohm);
const minZ = Math.max(0.01, Math.min(...zValues) * 0.5);
const maxZ = Math.max(...zValues) * 2;
const logMinZ = Math.log10(minZ);
const logMaxZ = Math.log10(maxZ);
const freqs = profile.map(p => p.freq_hz);
const logMinF = Math.log10(freqs[0]);
const logMaxF = Math.log10(freqs[freqs.length - 1]);
function xPos(f) { return pad.l + ((Math.log10(f) - logMinF) / (logMaxF - logMinF)) * cw; }
function yPos(z) { return pad.t + ch * (1 - (Math.log10(Math.max(z, minZ)) - logMinZ) / (logMaxZ - logMinZ)); }
// Grid
ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
ctx.font = '10px Segoe UI'; ctx.fillStyle = COLORS.text;
// Y grid (log)
for (let exp = Math.floor(logMinZ); exp <= Math.ceil(logMaxZ); exp++) {
const z = Math.pow(10, exp);
if (z < minZ || z > maxZ) continue;
const y = yPos(z);
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.textAlign = 'right';
ctx.fillText(z >= 1 ? z.toFixed(0) + ' mΩ' : z.toFixed(2) + ' mΩ', pad.l - 4, y + 4);
}
// X grid (log freq)
const freqLabels = [1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10];
const freqNames = ['1kHz', '10kHz', '100kHz', '1MHz', '10MHz', '100MHz', '1GHz', '10GHz'];
ctx.textAlign = 'center';
freqLabels.forEach((f, i) => {
if (f < freqs[0] || f > freqs[freqs.length - 1]) return;
const x = xPos(f);
ctx.beginPath(); ctx.moveTo(x, pad.t); ctx.lineTo(x, pad.t + ch); ctx.stroke();
ctx.fillText(freqNames[i], x, H - pad.b + 18);
});
// Target impedance line
ctx.strokeStyle = COLORS.red;
ctx.lineWidth = 2;
ctx.setLineDash([6, 4]);
const yTarget = yPos(data.target_impedance_mohm);
ctx.beginPath(); ctx.moveTo(pad.l, yTarget); ctx.lineTo(pad.l + cw, yTarget); ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = COLORS.red; ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText(`Z_target = ${data.target_impedance_mohm.toFixed(2)} mΩ`, pad.l + 5, yTarget - 8);
// PDN impedance curve
ctx.beginPath();
ctx.strokeStyle = COLORS.accent;
ctx.lineWidth = 2.5;
profile.forEach((p, i) => {
const x = xPos(p.freq_hz);
const y = yPos(p.z_magnitude_mohm);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
// Fill violations
ctx.globalAlpha = 0.12;
profile.forEach((p, i) => {
if (!p.meets_target && i > 0) {
const x = xPos(p.freq_hz);
const y = yPos(p.z_magnitude_mohm);
ctx.fillStyle = COLORS.red;
ctx.fillRect(x - 3, Math.min(y, yTarget), 6, Math.abs(y - yTarget));
}
});
ctx.globalAlpha = 1.0;
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('PDN Impedance Profile (log-log)', pad.l, pad.t - 10);
// Legend
ctx.fillStyle = COLORS.accent; ctx.fillRect(W - pad.r - 160, pad.t + 5, 14, 3);
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI';
ctx.fillText('Z_PDN', W - pad.r - 142, pad.t + 12);
ctx.fillStyle = COLORS.red; ctx.fillRect(W - pad.r - 80, pad.t + 5, 14, 3);
ctx.fillText('Z_target', W - pad.r - 62, pad.t + 12);
}
// ═══════════════════════════════════════════════════════════════════════════
// THERMAL TAB
// ═══════════════════════════════════════════════════════════════════════════
const thCopper = document.getElementById('th-copper');
const thCopperVal = document.getElementById('th-copper-val');
thCopper.addEventListener('input', () => { thCopperVal.textContent = thCopper.value + '%'; });
document.getElementById('th-run').addEventListener('click', async () => {
const statsEl = document.getElementById('th-stats');
const resEl = document.getElementById('th-resistances');
loading(statsEl); resEl.innerHTML = '';
try {
const data = await api('/api/thermal', {
cpu_tdp_w: parseFloat(document.getElementById('th-tdp').value),
board_area_sq_in: parseFloat(document.getElementById('th-area').value),
ambient_temp_c: parseFloat(document.getElementById('th-ambient').value),
copper_coverage_pct: parseFloat(thCopper.value),
airflow_lfm: parseFloat(document.getElementById('th-airflow').value),
heatsink: document.getElementById('th-heatsink').value === 'true',
});
const tjC = data.tj_max_verdict === 'SAFE' ? 'green' : (data.tj_max_verdict === 'WARNING' ? 'orange' : 'red');
const vrmC = data.vrm_verdict === 'SAFE' ? 'green' : (data.vrm_verdict === 'WARNING' ? 'orange' : 'red');
statsEl.innerHTML = `
Junction Temp
${data.junction_temp_c}°C
Board Under CPU
${data.board_temp_under_cpu_c}°C
Board Average
${data.board_avg_temp_c}°C
VRM Surface
${data.vrm_surface_temp_c}°C
Thermal Vias
${data.thermal_vias_under_cpu}
k Lateral
${data.effective_k_lateral_w_mk} W/mK
`;
drawThermalHeatmap(data);
drawThermalBar(data);
resEl.innerHTML = `Thermal Resistances
Parameter Value
R_junction-case ${data.r_junction_case} °C/W
R_case-sink ${data.r_case_sink} °C/W
R_sink-ambient ${data.r_sink_ambient} °C/W
R_PCB through ${data.r_pcb_through} °C/W
Convection h ${data.convection_coeff_w_m2k} W/(m²·K)
k_through-plane ${data.effective_k_through_w_mk} W/(m·K)
`;
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawThermalHeatmap(data) {
const canvas = document.getElementById('th-heatmap');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = W; // Square
ctx.clearRect(0, 0, W, H);
const map = data.thermal_map;
const rows = map.length;
const cols = map[0].length;
const pad = 40;
const cellW = (W - pad * 2) / cols;
const cellH = (H - pad * 2) / rows;
// Find min/max temps
let minT = Infinity, maxT = -Infinity;
map.forEach(row => row.forEach(t => { minT = Math.min(minT, t); maxT = Math.max(maxT, t); }));
const range = maxT - minT || 1;
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText('Board Temperature Distribution (°C)', W / 2, 18);
// Draw cells
map.forEach((row, ri) => {
row.forEach((temp, ci) => {
const x = pad + ci * cellW;
const y = pad + ri * cellH;
const norm = (temp - minT) / range;
// Blue → Green → Yellow → Red
let r, g, b;
if (norm < 0.33) {
const t = norm / 0.33;
r = Math.round(30 + t * 30); g = Math.round(60 + t * 140); b = Math.round(200 - t * 80);
} else if (norm < 0.66) {
const t = (norm - 0.33) / 0.33;
r = Math.round(60 + t * 195); g = Math.round(200 - t * 20); b = Math.round(120 - t * 100);
} else {
const t = (norm - 0.66) / 0.34;
r = Math.round(255); g = Math.round(180 - t * 130); b = Math.round(20 - t * 20);
}
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fillRect(x, y, cellW + 0.5, cellH + 0.5);
// Temperature label for select cells
if (ri % 3 === 1 && ci % 3 === 1) {
ctx.fillStyle = norm > 0.5 ? '#000' : '#fff';
ctx.font = '9px Segoe UI';
ctx.textAlign = 'center';
ctx.fillText(temp.toFixed(0) + '°', x + cellW / 2, y + cellH / 2 + 3);
}
});
});
// CPU label at center
const cpuX = pad + (cols / 2 - 1) * cellW;
const cpuY = pad + (rows / 2 - 1) * cellH;
ctx.strokeStyle = '#fff';
ctx.lineWidth = 2;
ctx.strokeRect(cpuX, cpuY, cellW * 3, cellH * 3);
ctx.fillStyle = '#fff'; ctx.font = 'bold 10px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText('CPU', cpuX + cellW * 1.5, cpuY + cellH * 1.5 + 4);
// VRM label
ctx.fillStyle = '#fff'; ctx.font = '9px Segoe UI';
ctx.fillText('VRM', pad + cellW * 1.5, pad + cellH * 1.5 + 4);
// Color scale
const scaleW = 15;
const scaleH = H - pad * 2;
const scaleX = W - pad + 5;
for (let i = 0; i < scaleH; i++) {
const norm = 1 - i / scaleH;
let r, g, b;
if (norm < 0.33) { const t = norm / 0.33; r = Math.round(30 + t * 30); g = Math.round(60 + t * 140); b = Math.round(200 - t * 80); }
else if (norm < 0.66) { const t = (norm - 0.33) / 0.33; r = Math.round(60 + t * 195); g = Math.round(200 - t * 20); b = Math.round(120 - t * 100); }
else { const t = (norm - 0.66) / 0.34; r = 255; g = Math.round(180 - t * 130); b = Math.round(20 - t * 20); }
ctx.fillStyle = `rgb(${r},${g},${b})`;
ctx.fillRect(scaleX, pad + i, scaleW, 1);
}
ctx.fillStyle = COLORS.text; ctx.font = '9px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText(maxT.toFixed(0) + '°C', scaleX + scaleW + 3, pad + 8);
ctx.fillText(minT.toFixed(0) + '°C', scaleX + scaleW + 3, H - pad + 4);
}
function drawThermalBar(data) {
const canvas = document.getElementById('th-bar-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 280;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 20, b: 55, l: 55 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const temps = [
{ label: 'Junction', val: data.junction_temp_c, color: COLORS.red },
{ label: 'VRM', val: data.vrm_surface_temp_c, color: COLORS.orange },
{ label: 'Under CPU', val: data.board_temp_under_cpu_c, color: COLORS.yellow },
{ label: 'Board Avg', val: data.board_avg_temp_c, color: COLORS.green },
{ label: 'Ambient', val: data.ambient_temp_c, color: COLORS.accent },
];
const maxT = Math.max(...temps.map(t => t.val), 105) * 1.1;
const barW = Math.min(50, cw / (temps.length * 2));
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('Temperature Comparison (°C)', pad.l, 18);
// Grid
for (let i = 0; i <= 5; i++) {
const y = pad.t + ch * (1 - i / 5);
ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
ctx.fillText(Math.round(maxT * i / 5) + '°C', pad.l - 4, y + 4);
}
// Tj_max line at 100°C
const y100 = pad.t + ch * (1 - 100 / maxT);
ctx.strokeStyle = COLORS.red; ctx.lineWidth = 1.5; ctx.setLineDash([5, 4]);
ctx.beginPath(); ctx.moveTo(pad.l, y100); ctx.lineTo(pad.l + cw, y100); ctx.stroke();
ctx.setLineDash([]);
ctx.fillStyle = COLORS.red; ctx.font = '9px Segoe UI'; ctx.textAlign = 'right';
ctx.fillText('T_j max = 100°C', pad.l + cw, y100 - 5);
temps.forEach((t, i) => {
const cx = pad.l + (i + 0.5) * (cw / temps.length);
const h = (t.val / maxT) * ch;
const grad = ctx.createLinearGradient(0, pad.t + ch - h, 0, pad.t + ch);
grad.addColorStop(0, t.color);
grad.addColorStop(1, t.color + '44');
ctx.fillStyle = grad;
ctx.fillRect(cx - barW / 2, pad.t + ch - h, barW, h);
ctx.fillStyle = COLORS.white; ctx.font = 'bold 11px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText(t.val.toFixed(0) + '°', cx, pad.t + ch - h - 6);
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI';
ctx.fillText(t.label, cx, H - pad.b + 18);
});
}
// ═══════════════════════════════════════════════════════════════════════════
// CROSSTALK TAB
// ═══════════════════════════════════════════════════════════════════════════
document.getElementById('xt-run').addEventListener('click', async () => {
const statsEl = document.getElementById('xt-stats');
const recEl = document.getElementById('xt-recommendation');
loading(statsEl); recEl.innerHTML = '';
try {
const data = await api('/api/crosstalk', {
trace_type: document.getElementById('xt-type').value,
aggressor_width_mil: parseFloat(document.getElementById('xt-width').value),
victim_width_mil: parseFloat(document.getElementById('xt-width').value),
spacing_mil: parseFloat(document.getElementById('xt-spacing').value),
parallel_length_mm: parseFloat(document.getElementById('xt-length').value),
dielectric_height_mil: parseFloat(document.getElementById('xt-height').value),
er: parseFloat(document.getElementById('xt-er').value),
frequency_ghz: parseFloat(document.getElementById('xt-freq').value),
});
const nextC = data.next_db < -25 ? 'green' : (data.next_db < -15 ? 'orange' : 'red');
const fextC = data.fext_db < -30 ? 'green' : (data.fext_db < -20 ? 'orange' : 'red');
statsEl.innerHTML = `
3W Rule
${data.three_w_rule_met ? 'MET' : 'NOT MET'}
Guard Trace Δ
${data.guard_trace_reduction_db} dB
Elec. Length
${data.electrical_length_wavelengths}λ
`;
drawCrosstalkChart(data.spacing_sweep);
recEl.innerHTML = `
`;
} catch (e) {
statsEl.innerHTML = ``;
}
});
function drawCrosstalkChart(sweep) {
const canvas = document.getElementById('xt-chart');
const ctx = canvas.getContext('2d');
const W = canvas.width = canvas.parentElement.clientWidth - 32;
const H = canvas.height = 350;
ctx.clearRect(0, 0, W, H);
const pad = { t: 35, r: 30, b: 50, l: 55 };
const cw = W - pad.l - pad.r;
const ch = H - pad.t - pad.b;
const allVals = sweep.flatMap(s => [s.next_db, s.fext_db]);
const minDB = Math.min(...allVals, -70);
const maxDB = Math.max(...allVals, -5);
const rangeDB = maxDB - minDB || 1;
// Grid
ctx.strokeStyle = COLORS.grid; ctx.lineWidth = 0.5;
for (let i = 0; i <= 5; i++) {
const y = pad.t + ch * (1 - i / 5);
const val = Math.round(minDB + rangeDB * i / 5);
ctx.beginPath(); ctx.moveTo(pad.l, y); ctx.lineTo(pad.l + cw, y); ctx.stroke();
ctx.fillStyle = COLORS.text; ctx.font = '10px Segoe UI'; ctx.textAlign = 'right';
ctx.fillText(val + ' dB', pad.l - 4, y + 4);
}
// X labels
ctx.textAlign = 'center';
sweep.forEach((s, i) => {
const x = pad.l + (i / (sweep.length - 1)) * cw;
if (i % 2 === 0) {
ctx.fillStyle = COLORS.text; ctx.fillText(s.spacing_mil + ' mil', x, H - pad.b + 16);
}
});
// NEXT line
ctx.beginPath(); ctx.strokeStyle = COLORS.orange; ctx.lineWidth = 2;
sweep.forEach((s, i) => {
const x = pad.l + (i / (sweep.length - 1)) * cw;
const y = pad.t + ch * (1 - (s.next_db - minDB) / rangeDB);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
// FEXT line
ctx.beginPath(); ctx.strokeStyle = COLORS.cyan; ctx.lineWidth = 2;
sweep.forEach((s, i) => {
const x = pad.l + (i / (sweep.length - 1)) * cw;
const y = pad.t + ch * (1 - (s.fext_db - minDB) / rangeDB);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
});
ctx.stroke();
// Legend
ctx.fillStyle = COLORS.orange; ctx.fillRect(pad.l + 10, pad.t + 5, 16, 3);
ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('NEXT', pad.l + 30, pad.t + 12);
ctx.fillStyle = COLORS.cyan; ctx.fillRect(pad.l + 90, pad.t + 5, 16, 3);
ctx.fillStyle = COLORS.text; ctx.fillText('FEXT', pad.l + 110, pad.t + 12);
ctx.fillStyle = COLORS.white; ctx.font = 'bold 12px Segoe UI'; ctx.textAlign = 'left';
ctx.fillText('Crosstalk vs Trace Spacing', pad.l, pad.t - 10);
ctx.fillStyle = COLORS.text; ctx.font = '11px Segoe UI'; ctx.textAlign = 'center';
ctx.fillText('Trace Spacing (mil)', W / 2, H - 5);
}