// Solar Permit Check: checks a rooftop solar layout the way a permit reviewer looks at it. // All geometry is local metres: x = east, y = north. A roof face is a plane with a downhill azimuth (the way water runs // off, 0 = north, clockwise) and a pitch. A module is a rectangle lying in that plane, given by its centre, its long-side // bearing seen from above and its orientation. Everything runs here in the browser; nothing is sent anywhere. 'use strict'; (() => { const $ = s => document.querySelector(s), $$ = s => [...document.querySelectorAll(s)]; const R = Math.PI / 180, SVGNS = 'http://www.w3.org/2000/svg'; const COMPASS = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; const compass = az => COMPASS[Math.round(((az % 360) + 360) % 360 / 45) % 8]; const angDiff = (a, b) => { const d = Math.abs(((a - b) % 360 + 540) % 360 - 180); return d; }; const fmt = (v, d = 1) => Number.isFinite(v) ? v.toFixed(d) : '—'; const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); // ---------- 2D geometry ---------- const dot = (a, b) => a[0] * b[0] + a[1] * b[1]; const sub = (a, b) => [a[0] - b[0], a[1] - b[1]]; function pointInPoly(p, poly) { let ins = false; for (let i = 0, j = poly.length - 1; i < poly.length; j = i++) { const a = poly[i], b = poly[j]; if ((a[1] > p[1]) !== (b[1] > p[1]) && p[0] < (b[0] - a[0]) * (p[1] - a[1]) / (b[1] - a[1]) + a[0]) ins = !ins; } return ins; } function segDist(p, a, b) { const ab = sub(b, a), t = Math.max(0, Math.min(1, dot(sub(p, a), ab) / (dot(ab, ab) || 1))); return Math.hypot(p[0] - a[0] - t * ab[0], p[1] - a[1] - t * ab[1]); } function cross(o, a, b) { return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]); } function segCross(a, b, c, d) { const d1 = cross(c, d, a), d2 = cross(c, d, b), d3 = cross(a, b, c), d4 = cross(a, b, d); return ((d1 > 1e-9 && d2 < -1e-9) || (d1 < -1e-9 && d2 > 1e-9)) && ((d3 > 1e-9 && d4 < -1e-9) || (d3 < -1e-9 && d4 > 1e-9)); } const edges = P => P.map((p, i) => [p, P[(i + 1) % P.length]]); // Do two convex polygons overlap (more than touching)? Separating-axis test. function convexOverlap(P, Q, tol = 1e-4) { for (const poly of [P, Q]) for (const [a, b] of edges(poly)) { const n = [a[1] - b[1], b[0] - a[0]], L = Math.hypot(n[0], n[1]) || 1; const pr = X => X.map(p => dot(p, n) / L); const p = pr(P), q = pr(Q); if (Math.max(...p) <= Math.min(...q) + tol || Math.max(...q) <= Math.min(...p) + tol) return false; } return true; } // Shortest distance between two polygons that do not cross (0 if they cross or one holds a vertex of the other). function polyDist(P, Q) { for (const [a, b] of edges(P)) for (const [c, d] of edges(Q)) if (segCross(a, b, c, d)) return 0; let m = Infinity; for (const p of P) for (const [a, b] of edges(Q)) m = Math.min(m, segDist(p, a, b)); for (const q of Q) for (const [a, b] of edges(P)) m = Math.min(m, segDist(q, a, b)); return m; } function centroid(P) { let a = 0, x = 0, y = 0; for (const [p, q] of edges(P)) { const c = p[0] * q[1] - q[0] * p[1]; a += c; x += (p[0] + q[0]) * c; y += (p[1] + q[1]) * c; } return a ? [x / (3 * a), y / (3 * a)] : P[0]; } // ---------- roof geometry ---------- const unit = az => [Math.sin(az * R), Math.cos(az * R)]; function frame(face) { const d = unit(face.az), a = unit(face.az + 90), p = face.pitch * R; return { d, a, p, toPlane: v => [dot(v, d) / Math.cos(p), dot(v, a)] }; } // Four plan corners of a module, plus how far its long side sits from square (the slope or the eave), in degrees. function corners(m, face, L, W) { const { d, a, p } = frame(face); const S = [d[0] * Math.cos(p), d[1] * Math.cos(p), -Math.sin(p)], A = [a[0], a[1], 0]; const dl = (m.bearing - face.az) * R; const th = Math.atan2(Math.sin(dl) * Math.cos(p), Math.cos(dl)); // in-plane angle of the long side from the fall line const U = S.map((s, i) => Math.cos(th) * s + Math.sin(th) * A[i]); const V = S.map((s, i) => -Math.sin(th) * s + Math.cos(th) * A[i]); const c = [m.e, m.n, m.h]; const pts = [[1, 1], [1, -1], [-1, -1], [-1, 1]].map(([u, v]) => [c[0] + u * L / 2 * U[0] + v * W / 2 * V[0], c[1] + u * L / 2 * U[1] + v * W / 2 * V[1]]); const deg = Math.abs(th / R) % 90; return { pts, skew: Math.min(deg, 90 - deg) }; } // ---------- state ---------- const st = { demo: 0, lay: 'draft', own: null, sel: null, focus: null }; const num = (sel, lo, hi, dflt) => { const v = +$(sel).value; return Number.isFinite(v) && $(sel).value !== '' ? Math.min(hi, Math.max(lo, v)) : dflt; }; const cfg = () => ({ edge: num('#sEdge', 0, 200, 25) / 100, gap: num('#sGap', 0, 50, 5) / 100, vent: num('#sVent', 0, 3, 0.35), sq: num('#sSq', 0, 45, 2), street: ((num('#sStreet', -720, 720, 180) % 360) + 360) % 360, city: num('#sCity', 0, 1e5, 0), yield: num('#sYield', 0, 2000, 0), L: num('#sL', 300, 3000, 2382) / 1000, W: num('#sW', 200, 2000, 1134) / 1000, watt: num('#sWatt', 1, 1000, 620) }); function current() { if (st.demo === 'own') return st.own; const D = DEMOS[st.demo]; return { name: D.name, faces: D.faces, vents: D.vents, mods: D.layouts[st.lay].map(([id, face, o, b, e, n, h]) => ({ id, face, o, bearing: b, e, n, h })) }; } // ---------- the checks ---------- function analyse(roof, c) { const faces = Object.fromEntries(roof.faces.map(f => [f.id, f])); const mods = roof.mods.map(m => ({ ...m, flags: {}, notes: [] })); const unknown = mods.filter(m => !faces[m.face]); for (const m of mods) { const f = faces[m.face]; if (!f) continue; const g = corners(m, f, c.L, c.W); m.pts = g.pts; m.skew = g.skew; const fr = frame(f); m.plane = m.pts.map(fr.toPlane); m.fr = fr; } const ok = mods.filter(m => m.pts); const res = { checks: [], mods, faces, unknown }; const add = (id, title, level, text, ids = []) => res.checks.push({ id, title, level, text, ids }); // 1. counts const kw = ok.length * c.watt / 1000; add('count', 'Modules and power', 'info', `${ok.length} modules × ${c.watt} W = ${fmt(kw, 2)} kW DC on ${new Set(ok.map(m => m.face)).size} roof face${new Set(ok.map(m => m.face)).size === 1 ? '' : 's'}.` + (unknown.length ? ` ${unknown.length} module(s) name a face that does not exist: ${unknown.map(m => m.id).join(', ')}.` : ''), unknown.map(m => m.id)); if (unknown.length) res.checks[0].level = 'bad'; // 2. overlaps (any two modules, seen from above) const ov = []; const near = (a, b) => Math.hypot(a.e - b.e, a.n - b.n) < c.L + 0.6; for (let i = 0; i < ok.length; i++) for (let j = i + 1; j < ok.length; j++) if (near(ok[i], ok[j]) && convexOverlap(ok[i].pts, ok[j].pts)) ov.push([ok[i], ok[j]]); ov.forEach(([a, b]) => { a.flags.overlap = b.flags.overlap = 'bad'; a.notes.push('overlaps ' + b.id); b.notes.push('overlaps ' + a.id); }); add('overlap', 'No overlaps', ov.length ? 'bad' : 'ok', ov.length ? `${ov.length} pair(s) overlap: ${ov.slice(0, 6).map(([a, b]) => a.id + '–' + b.id).join(', ')}${ov.length > 6 ? '…' : ''}.` : 'No two modules share roof.', [...new Set(ov.flat().map(m => m.id))]); // 3. edge clearance, measured on the sloped roof surface const edgeBad = []; let tight = Infinity; for (const m of ok) { const f = faces[m.face], F = f.outline.map(m.fr.toPlane); const inside = m.plane.every(p => pointInPoly(p, F)) && !F.some(v => pointInPoly(v, m.plane)); const dd = polyDist(m.plane, F); m.edge = inside ? dd : -dd; tight = Math.min(tight, m.edge); if (m.edge < c.edge - 0.002) { edgeBad.push(m); m.flags.edge = 'bad'; m.notes.push(inside ? `${fmt(m.edge * 100)} cm from the edge` : 'sticks out of its face'); } } add('edge', `At least ${fmt(c.edge * 100, 0)} cm inside each roof edge`, edgeBad.length ? 'bad' : 'ok', edgeBad.length ? `${edgeBad.length} module(s) too close to the edge or outside their face. ${tight <= 0 ? 'At least one runs over the edge of its face.' : `Tightest: ${fmt(tight * 100)} cm.`}` : `Every module clears its edge. Tightest: ${fmt(tight * 100)} cm.`, edgeBad.map(m => m.id)); // 4. gaps between modules on the same face const gapBad = []; let minGap = Infinity; for (let i = 0; i < ok.length; i++) for (let j = i + 1; j < ok.length; j++) { const a = ok[i], b = ok[j]; if (a.face !== b.face || !near(a, b)) continue; const g = polyDist(a.plane, b.plane); if (g > 0.5) continue; if (a.flags.overlap && b.flags.overlap && g === 0) continue; minGap = Math.min(minGap, g); if (g < c.gap - 0.003) { gapBad.push(a, b); a.flags.gap = b.flags.gap = 'warn'; a.notes.push(`${fmt(g * 100)} cm to ${b.id}`); b.notes.push(`${fmt(g * 100)} cm to ${a.id}`); } } const gb = [...new Set(gapBad.map(m => m.id))]; add('gap', `Gaps of at least ${fmt(c.gap * 100, 1)} cm`, gb.length ? 'warn' : 'ok', gb.length ? `${gb.length} module(s) sit closer than the rule. Smallest gap: ${fmt(minGap * 100)} cm.` : (Number.isFinite(minGap) ? `Smallest gap: ${fmt(minGap * 100)} cm.` : 'No neighbouring modules.'), gb); // 5. square to the roof const sk = ok.filter(m => m.skew > c.sq + 1e-6); sk.forEach(m => { m.flags.skew = 'bad'; m.notes.push(`${fmt(m.skew)}° off square`); }); add('square', 'Rows square to the roof', sk.length ? 'bad' : 'ok', sk.length ? `${sk.length} module(s) turned ${fmt(Math.max(...sk.map(m => m.skew)), 0)}° off the slope. From the street they read as a crooked array.` : 'Every module runs with the slope or the eave.', sk.map(m => m.id)); // 6. vents and chimneys const vents = roof.vents || []; const vBad = []; res.ventHits = vents.map(() => false); for (const m of ok) vents.forEach((v, k) => { const inside = pointInPoly(v, m.pts), d = inside ? 0 : Math.min(...edges(m.pts).map(([a, b]) => segDist(v, a, b))); m.vent = Math.min(m.vent ?? Infinity, inside ? -1 : d); if (inside || d < c.vent - 0.005) { vBad.push(m); m.flags.vent = 'bad'; res.ventHits[k] = true; m.notes.push(inside ? 'covers a vent' : `${fmt(d, 2)} m from a vent`); } }); add('vents', `Vents clear by ${fmt(c.vent, 2)} m`, !vents.length ? 'info' : vBad.length ? 'bad' : 'ok', !vents.length ? 'No vents marked. Mark plumbing vents and chimneys from a photo, then check on site.' : vBad.length ? `${new Set(vBad.map(m => m.id)).size} module(s) on or too close to ${res.ventHits.filter(Boolean).length} of ${vents.length} vents.` : `All ${vents.length} marked vents stay clear.`, [...new Set(vBad.map(m => m.id))]); // 7. heights sit on each face's plane const spreadBad = []; for (const f of roof.faces) { const ms = ok.filter(m => m.face === f.id && Number.isFinite(m.h)); if (ms.length < 2) continue; const { d, p } = frame(f); const v = ms.map(m => m.h + dot([m.e, m.n], d) * Math.tan(p)); const spread = Math.max(...v) - Math.min(...v); if (spread > 0.05) { spreadBad.push(f.id); ms.forEach(m => { m.flags.height = 'warn'; }); } } add('heights', 'Heights sit on each roof plane', spreadBad.length ? 'warn' : 'ok', spreadBad.length ? `Face(s) ${spreadBad.join(', ')}: module heights do not fit one plane (more than 5 cm off). Check the pitch or the face each module is on.` : 'Every module height fits its face within 5 cm.', ok.filter(m => m.flags.height).map(m => m.id)); // 8. what the street sees const vis = { face: 0, angle: 0, hidden: 0, flat: 0 }; for (const m of ok) { const f = faces[m.face]; m.seen = f.pitch < 2 ? 'flat' : angDiff(f.az, c.street) <= 45 ? 'face' : angDiff(f.az, c.street) <= 100 ? 'angle' : 'hidden'; vis[m.seen]++; } add('street', 'What the street sees', vis.face ? 'warn' : 'info', `${vis.face} face the street, ${vis.angle} are seen at an angle, ${vis.hidden} face away${vis.flat ? `, ${vis.flat} on a flat roof (check the parapet and the setback from the front wall)` : ''}. Say both numbers in the file, not only the first.`, ok.filter(m => m.seen === 'face').map(m => m.id)); // 9. the city's rooftop estimate if (c.city > 0) add('city', 'Against the city estimate', 'info', `${fmt(kw, 2)} kW is ${fmt(kw / c.city * 100, 0)} % of the city's ${fmt(c.city, 1)} kW estimate. At ${fmt(c.yield, 0)} kWh per kW, about ${Math.round(kw * c.yield).toLocaleString('en-US')} kWh a year: a rough upper figure, because faces turned away from the sun make less. The city figure is indicative, not a limit.`); res.kw = kw; res.vis = vis; return res; } // ---------- drawing ---------- const el = (n, a = {}, parent) => { const e = document.createElementNS(SVGNS, n); for (const k in a) e.setAttribute(k, a[k]); if (parent) parent.appendChild(e); return e; }; const PAL = ['#5b9bd5', '#e8a33d', '#8e6bbf', '#3fa98f', '#d9677a', '#8a96a3', '#b5654a', '#6aa84f']; function levelOf(m) { const v = Object.values(m.flags); return v.includes('bad') ? 'bad' : v.includes('warn') ? 'warn' : 'ok'; } function draw(roof, res, c) { const svg = $('#plan'); svg.textContent = ''; const all = roof.faces.flatMap(f => f.outline).concat(res.mods.filter(m => m.pts).flatMap(m => m.pts)); if (!all.length) return; const xs = all.map(p => p[0]), ys = all.map(p => -p[1]); const pad = 2.6, x0 = Math.min(...xs) - pad, x1 = Math.max(...xs) + pad, y0 = Math.min(...ys) - pad, y1 = Math.max(...ys) + pad; svg.setAttribute('viewBox', `${x0} ${y0} ${x1 - x0} ${y1 - y0}`); const sw = Math.max(x1 - x0, y1 - y0) / 400; const P = pts => pts.map(p => `${p[0].toFixed(3)},${(-p[1]).toFixed(3)}`).join(' '); const gF = el('g', {}, svg), gM = el('g', {}, svg), gV = el('g', {}, svg), gT = el('g', { class: 'lbl' }, svg); roof.faces.forEach((f, i) => { el('polygon', { points: P(f.outline), fill: PAL[i % PAL.length], 'fill-opacity': '.16', stroke: PAL[i % PAL.length], 'stroke-width': sw * 2.2, 'stroke-linejoin': 'round' }, gF); const cc = centroid(f.outline), u = unit(f.az), Lr = 0.9; if (f.pitch >= 2) el('line', { x1: cc[0] - u[0] * Lr, y1: -(cc[1] - u[1] * Lr), x2: cc[0] + u[0] * Lr, y2: -(cc[1] + u[1] * Lr), stroke: 'currentColor', 'stroke-opacity': '.45', 'stroke-width': sw * 2, 'marker-end': 'url(#arr)' }, gF); const n = res.mods.filter(m => m.face === f.id && m.pts).length; const t = el('text', { x: cc[0], y: -cc[1] + 1.55, 'font-size': Math.max(0.55, (x1 - x0) / 34), 'text-anchor': 'middle' }, gT); t.textContent = `${f.id} · ${n}`; }); const defs = el('defs', {}, svg); const mk = el('marker', { id: 'arr', viewBox: '0 0 10 10', refX: '5', refY: '5', markerWidth: '4', markerHeight: '4', orient: 'auto-start-reverse' }, defs); el('path', { d: 'M0,0 L10,5 L0,10 z', fill: 'currentColor', 'fill-opacity': '.5' }, mk); for (const m of res.mods) { if (!m.pts) continue; const lv = levelOf(m), foc = st.focus && st.focus.includes(m.id); const p = el('polygon', { points: P(m.pts), class: `mod ${lv}${st.sel === m.id ? ' sel' : ''}${st.focus && !foc ? ' dim' : ''}`, 'stroke-width': sw * (st.sel === m.id ? 4 : 1.6), tabindex: '0', role: 'button', 'aria-label': `Module ${m.id}, face ${m.face}${lv === 'ok' ? '' : ', has a problem'}` }, gM); p.dataset.id = m.id; } (roof.vents || []).forEach((v, k) => { const hit = res.ventHits[k]; el('circle', { cx: v[0], cy: -v[1], r: c.vent, class: 'vhalo' + (hit ? ' hit' : ''), 'stroke-width': sw * 1.4 }, gV); el('circle', { cx: v[0], cy: -v[1], r: 0.16, class: 'vent' + (hit ? ' hit' : '') }, gV); }); // north arrow, street arrow, 5 m scale const fs = Math.max(0.55, (x1 - x0) / 34); const nx = x1 - 1.2, ny = y0 + 1.9; el('line', { x1: nx, y1: ny, x2: nx, y2: ny - 1.3, stroke: 'currentColor', 'stroke-width': sw * 3, 'marker-end': 'url(#arr)' }, gT); el('text', { x: nx, y: ny + fs * 1.1, 'font-size': fs, 'text-anchor': 'middle' }, gT).textContent = 'N'; const cx = (x0 + x1) / 2, cy = (y0 + y1) / 2, su = unit(c.street), rr = Math.min(x1 - x0, y1 - y0) / 2 - 0.9; const sx = cx + su[0] * rr, sy = cy - su[1] * rr; el('line', { x1: cx + su[0] * (rr - 1.6), y1: cy - su[1] * (rr - 1.6), x2: sx, y2: sy, class: 'street', 'stroke-width': sw * 4, 'marker-end': 'url(#arr)' }, gT); el('text', { x: sx - su[0] * 0.4, y: sy + su[1] * 0.4 - fs * 0.7, 'font-size': fs, 'text-anchor': 'middle', class: 'streettxt' }, gT).textContent = 'street'; const bx = x0 + 0.8, by = y1 - 0.8; el('line', { x1: bx, y1: by, x2: bx + 5, y2: by, stroke: 'currentColor', 'stroke-width': sw * 3 }, gT); el('text', { x: bx + 2.5, y: by - fs * 0.5, 'font-size': fs, 'text-anchor': 'middle' }, gT).textContent = '5 m'; } // ---------- panel ---------- let last = null; function render() { const c = cfg(), roof = current(); if (!roof) { $('#checks').textContent = ''; $('#verdict').textContent = 'Paste your roof below and press Check my roof.'; $('#plan').textContent = ''; $('#faceBody').textContent = ''; return; } const res = analyse(roof, c); last = { roof, res, c }; draw(roof, res, c); const bad = res.checks.filter(k => k.level === 'bad'), warn = res.checks.filter(k => k.level === 'warn'); $('#verdict').className = 'verdict ' + (bad.length ? 'bad' : warn.length ? 'warn' : 'ok'); $('#verdict').innerHTML = bad.length ? `Fix ${bad.length} thing${bad.length > 1 ? 's' : ''} before filing. Red modules on the plan show where.` : warn.length ? `Close. ${warn.length} item${warn.length > 1 ? 's' : ''} to look at, nothing blocking.` : `Ready for a reviewer's eyes. Geometry checks pass; now confirm on site.`; $('#checks').innerHTML = res.checks.map(k => `
`).join(''); $$('[data-ck]').forEach(b => b.onclick = () => { const k = res.checks.find(x => x.id === b.dataset.ck); if (st.focusId === k.id) { st.focus = null; st.focusId = null; } else { st.focus = k.ids; st.focusId = k.id; } render(); $('#planCard').scrollIntoView({ behavior: 'smooth', block: 'nearest' }); }); $('#faceBody').innerHTML = roof.faces.map(f => { const ms = res.mods.filter(m => m.face === f.id && m.pts); const s = f.pitch < 2 ? 'flat roof' : angDiff(f.az, c.street) <= 45 ? 'faces it' : angDiff(f.az, c.street) <= 100 ? 'at an angle' : 'faces away'; return `