App · project 26 of 37

Solar Permit Check.

Check a rooftop solar layout the way a permit reviewer will: overlaps, edges, crooked rows, vents and what the street sees.

Open the project ↗Get the skill and the code
After: Nine checks on the roof plan: overlaps, edges, crooked rows, vents, heights, what the street sees and the city's estimate, with the problem modules in red. Before: A solar layout from a design tool that looks fine, a borough that judges it from the street, and nobody checking until the reviewer does.

BeforeA solar layout from a design tool that looks fine, a borough that judges it from the street, and nobody checking until the reviewer does.

AfterNine checks on the roof plan: overlaps, edges, crooked rows, vents, heights, what the street sees and the city's estimate, with the problem modules in red.

What it is worthCrooked arrays, panels on vents and edge problems caught in minutes, and honest street numbers to put in the file. Instead of filing and waiting to hear what is wrong.

More like this: see your numbers at a glance ›

How to use it

  1. Press Show me how for the six-step tour, or pick Demo A and look at the First draft: red modules break a rule.
  2. Tap a check on the right to light up its modules on the plan, and tap a module to see its numbers. Switch to Fixed to see the same roof done right.
  3. Set your borough's rules under Rules to check against: edge clearance, gaps, vent clearance, the direction of the street, the city's rooftop estimate and your module size.
  4. Choose Your roof, paste your roof faces, module list and vents (or start from Demo A and edit it), and press Check my roof.
  5. Fix what is red, then press Copy the report and keep it with your permit notes. Confirm vents, pitches and edges on site.

Where it helps most

  • Homeowners and installers about to file a rooftop solar permit where the borough reviews how it looks from the street.
  • A second look at a layout from a design tool or a quick sketch: crooked arrays, panels on vents and edge clearances are cheap to fix before filing and slow to fix after.
  • Explaining a layout to a reviewer, a neighbour or a client with honest numbers: what faces the street, what it sees at an angle, and how the system compares with the city's estimate.

The idea

I helped a friend prepare the visuals for two rooftop solar permits in a borough that reviews how panels look from the street. The design tool produced a layout, and it looked fine. An independent check found what a reviewer would have found: the street-face panels turned 36° off the roof, panels sitting on plumbing vents, numbers that disagreed between pages, and "facing the street" counted where "seen from the street" was the honest number. None of it needed an engineer, only a careful second look. So I turned that second look into a tool anyone can run before filing.

The build

Claude built it from the check it ran on the real layouts, then rebuilt everything around two invented houses so nothing points to a real address, owner or photo. The geometry is plain: each roof face is a plane with a downhill direction and a pitch; each module is a rectangle in that plane, rebuilt from its centre, its long-side bearing and its orientation. Clearance and gaps are measured along the sloped roof, which is longer than it looks from above. The demo results were checked against a separate Python calculation (shapely), and the tool was stress-tested at four screen sizes, in light and dark, with broken inputs and a 1,500-module roof. Limits, said plainly: it checks geometry and how a layout reads to a reviewer; it is not an electrical, structural or fire-code design, the vents and roof outlines are only as good as what you mark, and every borough has its own rules.

Free to take

Build your own.

Copy the skill, paste it into your own AI, and say what you want different. How to use a skill, step by step ›

Get the skillThe instructions your AI follows. Works in Claude, ChatGPT, Gemini or any other

# Master prompt: Solar Permit Check

You are a solar designer who has sat on the borough side of the counter, and a front-end developer. Build "Solar Permit Check": a free, private web tool that checks a rooftop solar panel layout the way a permit reviewer looks at it, before anyone files. It checks geometry and how the layout reads from the street. It is not an electrical, structural or fire-code design, and it says so.

DELIVERABLE
One page: index.html, one CSS file, one JS file, plus a small data file with two demo roofs. No libraries, no CDN, no inline scripts or style attributes (it must run under a strict Content-Security-Policy; set styles only through element.style or classes). Light and dark from the same CSS variables (prefers-color-scheme). Works from 320 px wide to a desktop, and on a phone held sideways. Nothing is uploaded: every check runs in the browser.

THE MODEL (local metres, x = east, y = north)
- A roof face: id, name, downhill azimuth az (the way water runs off, 0 = north, clockwise), pitch in degrees, and its outline seen from above as [east, north] points. Under 2° counts as a flat roof.
- A module: id, face, orientation, the bearing of its long side seen from above, its centre (east, north) and height. Module size and watts are settings (default 2382 x 1134 mm, 620 W).
- Corners: d = unit(az), a = unit(az + 90). In-plane downhill S = (d·cos p, -sin p), across A = (a, 0). Turn the long-side bearing b into the in-plane angle th = atan2(sin(b - az)·cos p, cos(b - az)); long side U = cos th·S + sin th·A, short side V = -sin th·S + cos th·A; corners = centre ± L/2·U ± W/2·V; keep east and north.
- Roof-surface coordinates: s = (point·d) / cos p, t = point·a. Measure edge clearance and gaps in these, because the slope is longer than it looks from above.

THE CHECKS (each a line with a coloured dot; a tap lights its modules on the plan)
1 Modules and power: count, kW DC, faces used; any module naming a face that does not exist is an error.
2 No overlaps: separating-axis test on every pair seen from above (skip pairs whose centres are further apart than a module length plus 0.6 m).
3 Edge clearance (default 25 cm): every corner inside its face, no outline vertex inside the module, then the shortest distance between module and outline in roof-surface coordinates. Report the tightest; say plainly when a module runs over the edge.
4 Gaps (default 5 cm, an amber "check", not red): shortest distance between neighbouring modules on the same face, in roof-surface coordinates.
5 Square to the roof (default within 2°): skew = the in-plane angle th folded to 0-45° from the slope or the eave. A tilted array reads as crooked from the street.
6 Vents and chimneys (default 0.35 m): distance from each marked vent to each module seen from above; a vent inside a module is "covers a vent". Ring the hit vents in red.
7 Heights: for each face, h + (centre·d)·tan p must be the same for every module within 5 cm; otherwise the pitch or the face is wrong.
8 What the street sees: with the street's bearing as a setting, a face within 45° of it faces the street, 45-100° is seen at an angle, beyond that faces away, flat roofs are their own group. Report all the numbers, not only the first.
9 Against the city estimate: total kW as a share of the city's rooftop-solar figure, and kW x the city's yield as a rough upper kWh a year. Call the city figure indicative, never a ceiling or an approval.
Verdict on top: red "Fix N things before filing", amber "Close", green "Ready for a reviewer's eyes, now confirm on site".

THE SCREEN
- Header with the name, one line on what it does and a "Show me how" button.
- A bar: Demo A / Demo B / Your roof, and First draft / Fixed for the demos, with one line about the demo.
- Left: the roof plan as SVG (y flipped), faces as tinted polygons with a downhill arrow, "id · count" labels, modules as dark rectangles (red = problem, amber = check), vents as dots with a dashed clearance ring, a north arrow, a "street" arrow and a 5 m scale bar. Tapping a module shows its face, orientation, skew, edge distance, nearest vent and its problems.
- Right: the verdict, the checks, a table by face (compass direction, pitch, modules, kW, how the street sees it) and "Copy the report" (plain text, ready to paste into permit notes).
- Rules: edge clearance, gap, vent clearance, squareness, street bearing, the city's kW and yield, module size and watts. Every check updates as you type; clamp silly values and never show NaN.
- Your roof: paste faces (JSON), modules (CSV; accept common column names such as panel_id, section, long_axis_bearing_deg, centre_east_m) and vents (east,north lines), or load the files. Clear errors that name the line, and a "Start from Demo A" button.
- A short "what a reviewer looks at" list explaining each check.

THE DEMOS (invented houses, never a real address, lot, owner or photo)
- Demo A: a two-storey hip roof, street to the south, four faces, four vents. The first draft holds typical mistakes: a street-face array turned 30° off the slope (which also overlaps), modules over vents, a side face 12 cm from its edge. The fixed layout is square, off the vents and inside the edges.
- Demo B: a bungalow turned 45°, street to the south-west, a pyramid hip roof plus a low flat roof at the back. The draft fills the street face and runs the flat-roof modules to the edge; the fixed one leaves the street face empty and sets the flat roof back.
Generate the layouts with a small fill routine (rows parallel to the eave, inside the face shrunk by the clearance, clear of vents), then plant the mistakes.

THE TUTORIAL
"Show me how" runs a six-step guided tour that highlights each part in turn with a card at the bottom (at the side on a short sideways phone): pick a roof, read the plan, go through the checks, see it fixed, set your own rules, check your own roof. Esc or Close ends it; ?tour=1 starts it.

FINISH AND STRESS TEST
Check the demos against an independent calculation (for example shapely in Python): the same overlaps, edge failures, skewed modules and vent hits. Then test at 320x568, 393x700, 740x360 and 1366x800 in light and dark: no console errors or security-policy refusals, no sideways scroll, the tour never hides the part it points to, every check tapped, every setting at 0, negative, empty and huge, 40 fast demo switches, broken JSON and CSV, a face that does not exist, and a 1,500-module roof checked in about a second.
Get the code4 files, exactly as they run on this site · free under the MIT license
index.html109 lines

Raw file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Solar Permit Check: test a solar layout before you file</title>
<meta name="description" content="Free: check a rooftop solar panel layout the way a permit reviewer will: overlaps, edge clearance, crooked rows, panels on vents and what the street sees.">
<link rel="icon" href="../../favicon.svg" type="image/svg+xml">
<link rel="stylesheet" href="./solar.css">
</head>
<body>
<div class="shell">
  <header class="mast">
    <div class="ttl">
      <div class="eyebrow">Free tool · rooftop solar permits</div>
      <h1>Solar Permit Check</h1>
      <p class="sub">Test a rooftop solar layout the way a permit reviewer will, before you file. Everything runs in your browser; nothing is sent anywhere.</p>
    </div>
    <div class="mastbtns">
      <button type="button" class="btn pri" id="tourBtn">Show me how</button>
      <a class="btn" href="/all/">Free tools ›</a>
    </div>
  </header>

  <section class="bar" id="pickBar" aria-label="Choose a roof">
    <div class="seg" role="group" aria-label="Roof">
      <button type="button" data-demo="0" aria-pressed="true">Demo A</button>
      <button type="button" data-demo="1" aria-pressed="false">Demo B</button>
      <button type="button" data-demo="own" aria-pressed="false">Your roof</button>
    </div>
    <div class="seg" role="group" aria-label="Layout" id="laySeg">
      <button type="button" data-lay="draft" aria-pressed="true">First draft</button>
      <button type="button" data-lay="fixed" aria-pressed="false">Fixed</button>
    </div>
    <p class="blurb" id="blurb"></p>
  </section>

  <div class="main">
    <section class="card plancard" id="planCard" aria-label="Roof plan">
      <div class="cardhead"><h2>Roof plan, from above</h2><span class="legend"><i class="lg ok"></i>module <i class="lg bad"></i>problem <i class="lg warn"></i>check <i class="lg vent"></i>vent</span></div>
      <svg id="plan" viewBox="0 0 100 100" role="img" aria-label="Roof plan with the solar modules"></svg>
      <p class="hint" id="planHint">Tap a module to see its numbers.</p>
      <div class="detail" id="detail" hidden></div>
    </section>

    <section class="card checkcard" id="checkCard" aria-label="Checks">
      <div class="verdict" id="verdict"></div>
      <ol class="checks" id="checks"></ol>
      <div class="facetab"><h3>By roof face</h3><table><thead><tr><th>Face</th><th>Faces</th><th>Pitch</th><th>Modules</th><th>kW</th><th>Seen from street</th></tr></thead><tbody id="faceBody"></tbody></table></div>
      <div class="row"><button type="button" class="btn" id="copyBtn">Copy the report</button><span class="msg" id="copyMsg" role="status"></span></div>
    </section>
  </div>

  <section class="card setcard" id="setCard" aria-label="Rules">
    <h2>Rules to check against</h2>
    <div class="sets">
      <label>Edge clearance <span><input type="number" id="sEdge" min="0" max="200" step="1" value="25"> cm</span></label>
      <label>Gap between modules <span><input type="number" id="sGap" min="0" max="50" step="0.5" value="5"> cm</span></label>
      <label>Clear of vents <span><input type="number" id="sVent" min="0" max="3" step="0.05" value="0.35"> m</span></label>
      <label>Square to the roof within <span><input type="number" id="sSq" min="0" max="45" step="0.5" value="2"> °</span></label>
      <label>Street is toward <span><input type="number" id="sStreet" min="0" max="359" step="1" value="180"> ° (0 = north)</span></label>
      <label>City rooftop estimate <span><input type="number" id="sCity" min="0" max="100000" step="0.1" value="38"> kW</span></label>
      <label>City yield <span><input type="number" id="sYield" min="0" max="2000" step="1" value="760"> kWh/kW·yr</span></label>
      <label>Module <span><input type="number" id="sL" min="500" max="3000" step="1" value="2382"> × <input type="number" id="sW" min="300" max="2000" step="1" value="1134"> mm, <input type="number" id="sWatt" min="50" max="1000" step="5" value="620"> W</span></label>
    </div>
    <p class="note">Use your own borough's numbers. These defaults are common design rules, not a by-law. Edge clearance and gaps are measured on the sloped roof surface, not on the flat plan.</p>
  </section>

  <section class="card owncard" id="ownCard" aria-label="Your roof" hidden>
    <h2>Your roof</h2>
    <p>Paste three things, or load the files. Coordinates are in metres on a local grid (east, north), the same grid for all three. A design tool export, a traced plan or a spreadsheet all work.</p>
    <div class="owngrid">
      <label>1 · Roof faces (JSON)<textarea id="inFaces" rows="7" spellcheck="false"></textarea><small>[{"id":"S1","az":180,"pitch":26,"outline":[[e,n],…]}] · az = the way water runs off (downhill), 0 = north</small></label>
      <label>2 · Modules (CSV)<textarea id="inMods" rows="7" spellcheck="false"></textarea><small>id,face,orientation,bearing,east,north,height — bearing = the module's long side, seen from above</small></label>
      <label>3 · Vents and chimneys (optional)<textarea id="inVents" rows="7" spellcheck="false"></textarea><small>one per line: east,north</small></label>
    </div>
    <div class="row"><button type="button" class="btn pri" id="runOwn">Check my roof</button><button type="button" class="btn" id="fillOwn">Start from Demo A</button><label class="btn file">Load files<input type="file" id="fileIn" multiple accept=".json,.csv,.txt"></label><span class="msg" id="ownMsg" role="status"></span></div>
  </section>

  <section class="card howcard" aria-label="What each check means">
    <h2>What a reviewer looks at, and what each check means</h2>
    <dl class="how">
      <dt>Overlaps</dt><dd>Two modules cannot share roof. Usually a copy-paste or a row nudged by hand.</dd>
      <dt>Edge clearance</dt><dd>Every module stays a set distance inside its roof face: wind, snow, access. Measured along the slope, which is longer than it looks from above.</dd>
      <dt>Gaps</dt><dd>Rails and clamps need room. A gap under the rule usually means modules were placed one by one.</dd>
      <dt>Square to the roof</dt><dd>Rows run with the eave. A tilted array looks crooked from the street, and the street view is what an appearance review judges.</dd>
      <dt>Vents</dt><dd>Plumbing vents and chimneys must stay uncovered. Mark them from a photo and check on site.</dd>
      <dt>Heights</dt><dd>Each module's height should sit on its roof plane. A jump means a wrong pitch or the wrong face.</dd>
      <dt>Seen from the street</dt><dd>Facing the street (within 45°) and seen at an angle (45–100°) are different things. Say both numbers.</dd>
      <dt>City estimate</dt><dd>Many cities publish a rooftop-solar estimate per building. It is indicative, not a ceiling or an approval.</dd>
    </dl>
    <p class="note">This checks geometry and how it reads to a reviewer. It is not an electrical, structural or fire-code design, and it does not replace your borough's rules.</p>
  </section>
</div>

<div class="tour" id="tour" hidden>
  <div class="tcard" role="dialog" aria-modal="false" aria-labelledby="tTitle">
    <div class="tstep" id="tStep"></div>
    <h3 id="tTitle"></h3>
    <p id="tText"></p>
    <div class="row"><button type="button" class="btn" id="tBack">Back</button><button type="button" class="btn pri" id="tNext">Next</button><button type="button" class="btn ghost" id="tClose">Close</button></div>
  </div>
</div>

<script src="./demos.js" defer></script>
<script src="./solar.js" defer></script>
</body>
</html>
solar.js (the geometry, the nine checks, the plan, the tour)387 lines

Raw file

// 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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[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 ? `<b>Fix ${bad.length} thing${bad.length > 1 ? 's' : ''} before filing.</b> Red modules on the plan show where.`
    : warn.length ? `<b>Close.</b> ${warn.length} item${warn.length > 1 ? 's' : ''} to look at, nothing blocking.` : `<b>Ready for a reviewer's eyes.</b> Geometry checks pass; now confirm on site.`;
  $('#checks').innerHTML = res.checks.map(k => `<li class="ck ${k.level}${st.focus && st.focusId === k.id ? ' on' : ''}"><button type="button" data-ck="${k.id}"${k.ids.length ? '' : ' disabled'} aria-pressed="${st.focusId === k.id}"><i class="dotl" aria-hidden="true"></i><span class="ckt">${esc(k.title)}</span><span class="ckd">${esc(k.text)}</span>${k.ids.length ? `<span class="cks">Show ${k.ids.length} on the plan ›</span>` : ''}</button></li>`).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 ? '<b>faces it</b>' : angDiff(f.az, c.street) <= 100 ? 'at an angle' : 'faces away';
    return `<tr><td><b>${esc(f.id)}</b>${f.name ? ' ' + esc(f.name) : ''}</td><td>${f.pitch < 2 ? '—' : compass(f.az) + ' ' + Math.round(f.az) + '°'}</td><td>${fmt(f.pitch, 1)}°</td><td>${ms.length}</td><td>${fmt(ms.length * c.watt / 1000, 2)}</td><td>${s}</td></tr>`;
  }).join('');
  showDetail();
}
function showDetail() {
  const d = $('#detail'), m = last && last.res.mods.find(x => x.id === st.sel);
  if (!m || !m.pts) { d.hidden = true; $('#planHint').hidden = false; return; }
  $('#planHint').hidden = true; d.hidden = false;
  const f = last.res.faces[m.face];
  d.innerHTML = `<b>${esc(m.id)}</b> on face ${esc(m.face)} (${f.pitch < 2 ? 'flat' : compass(f.az) + ', ' + fmt(f.pitch, 1) + '°'}) · ${m.o === 'P' ? 'portrait' : 'landscape'} · ${fmt(m.skew, 1)}° off square · ${fmt(m.edge * 100, 1)} cm from the edge${Number.isFinite(m.vent) ? ` · ${m.vent < 0 ? 'covers a vent' : fmt(m.vent, 2) + ' m from the nearest vent'}` : ''}${m.notes.length ? `<br><span class="bad">${esc([...new Set(m.notes)].join(' · '))}</span>` : '<br><span class="okt">No problems.</span>'}`;
}
$('#plan').addEventListener('click', e => { const id = e.target.dataset && e.target.dataset.id; st.sel = id && st.sel !== id ? id : null; render(); });
$('#plan').addEventListener('keydown', e => { if ((e.key === 'Enter' || e.key === ' ') && e.target.dataset.id) { e.preventDefault(); st.sel = e.target.dataset.id; render(); } });

// ---------- choosing a roof ----------
function setDemo(v) {
  st.demo = v === 'own' ? 'own' : +v; st.sel = null; st.focus = null; st.focusId = null;
  $$('[data-demo]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.demo === String(v))));
  $('#laySeg').hidden = st.demo === 'own'; $('#ownCard').hidden = st.demo !== 'own';
  if (st.demo !== 'own') { const D = DEMOS[st.demo]; $('#sStreet').value = D.street; $('#sCity').value = D.cityKw; $('#sYield').value = D.cityYield; $('#blurb').textContent = D.blurb; }
  else $('#blurb').textContent = 'Your own roof: paste faces, modules and vents below. Nothing leaves this page.';
  render();
}
function setLay(v) { st.lay = v; st.sel = null; st.focus = null; st.focusId = null; $$('[data-lay]').forEach(b => b.setAttribute('aria-pressed', String(b.dataset.lay === v))); render(); }
$$('[data-demo]').forEach(b => b.onclick = () => setDemo(b.dataset.demo));
$$('[data-lay]').forEach(b => b.onclick = () => setLay(b.dataset.lay));
$$('.sets input').forEach(i => i.addEventListener('input', () => { if (i.value === '' || !Number.isFinite(+i.value)) return; render(); }));

// ---------- your roof ----------
function parseOwn() {
  const msg = [];
  let faces;
  try { faces = JSON.parse($('#inFaces').value); } catch (e) { throw new Error('Roof faces: not valid JSON (' + e.message + ').'); }
  if (!Array.isArray(faces) || !faces.length) throw new Error('Roof faces: expected a list of faces.');
  faces = faces.map((f, i) => {
    const o = (f.outline || []).map(p => [+p[0], +p[1]]);
    if (!f.id || o.length < 3 || o.some(p => !p.every(Number.isFinite))) throw new Error(`Roof face ${i + 1}: needs an id and an outline of at least 3 [east, north] points.`);
    const az = +f.az, pitch = +f.pitch;
    if (!Number.isFinite(az) || !Number.isFinite(pitch) || pitch < 0 || pitch >= 80) throw new Error(`Roof face ${f.id}: az (0–360) and pitch (0–80°) must be numbers.`);
    return { id: String(f.id), name: f.name ? String(f.name) : '', az: ((az % 360) + 360) % 360, pitch, outline: o };
  });
  const lines = $('#inMods').value.trim().split(/\r?\n/).filter(l => l.trim());
  if (!lines.length) throw new Error('Modules: paste at least one line.');
  const head = lines[0].toLowerCase().split(/[,;\t]/).map(s => s.trim());
  const pick = (...names) => head.findIndex(h => names.includes(h));
  const hasHead = head.some(h => /[a-z]/.test(h) && !/^-?[\d.]+$/.test(h)) && pick('east', 'centre_east_m', 'center_east_m', 'e', 'x') >= 0;
  const ix = hasHead ? { id: pick('id', 'panel_id', 'module'), face: pick('face', 'section', 'plane'), o: pick('orientation', 'o'), b: pick('bearing', 'long_axis_bearing_deg'), e: pick('east', 'centre_east_m', 'center_east_m', 'e', 'x'), n: pick('north', 'centre_north_m', 'center_north_m', 'n', 'y'), h: pick('height', 'centre_height_m', 'center_height_m', 'h', 'z') }
    : { id: 0, face: 1, o: 2, b: 3, e: 4, n: 5, h: 6 };
  for (const k of ['face', 'b', 'e', 'n']) if (ix[k] < 0) throw new Error('Modules: missing a column for ' + ({ face: 'face', b: 'bearing', e: 'east', n: 'north' })[k] + '.');
  const mods = lines.slice(hasHead ? 1 : 0).map((l, i) => {
    const c = l.split(/[,;\t]/).map(s => s.trim().replace(/^"|"$/g, ''));
    const m = { id: ix.id >= 0 && c[ix.id] ? c[ix.id] : 'M' + String(i + 1).padStart(3, '0'), face: c[ix.face], o: /^p/i.test(c[ix.o] || '') ? 'P' : 'L', bearing: +c[ix.b], e: +c[ix.e], n: +c[ix.n], h: ix.h >= 0 ? +c[ix.h] : NaN };
    if (![m.bearing, m.e, m.n].every(Number.isFinite)) throw new Error(`Modules, line ${i + (hasHead ? 2 : 1)}: bearing, east and north must be numbers.`);
    return m;
  });
  if (mods.length > 2000) throw new Error('Modules: more than 2,000 lines. Split the roof.');
  const vents = $('#inVents').value.trim() ? $('#inVents').value.trim().split(/\r?\n/).filter(l => l.trim()).map((l, i) => {
    const v = l.split(/[,;\t ]+/).map(Number); if (v.length < 2 || !v.slice(0, 2).every(Number.isFinite)) throw new Error(`Vents, line ${i + 1}: write east,north.`); return v.slice(0, 2);
  }) : [];
  return { name: 'Your roof', faces, mods, vents, msg };
}
$('#runOwn').onclick = () => {
  try { st.own = parseOwn(); st.sel = null; st.focus = null; st.focusId = null; $('#ownMsg').textContent = `Checked ${st.own.mods.length} modules on ${st.own.faces.length} face${st.own.faces.length === 1 ? '' : 's'}.`; $('#ownMsg').className = 'msg ok'; render(); $('#checkCard').scrollIntoView({ behavior: 'smooth', block: 'start' }); }
  catch (e) { $('#ownMsg').textContent = e.message; $('#ownMsg').className = 'msg err'; }
};
$('#fillOwn').onclick = () => {
  const D = DEMOS[0];
  $('#inFaces').value = JSON.stringify(D.faces.map(f => ({ id: f.id, az: f.az, pitch: f.pitch, outline: f.outline })), null, 0).replace(/\},\{/g, '},\n{');
  $('#inMods').value = 'id,face,orientation,bearing,east,north,height\n' + D.layouts.draft.map(([id, f, o, b, e, n, h]) => [id, f, o === 'P' ? 'portrait' : 'landscape', b, e, n, h].join(',')).join('\n');
  $('#inVents').value = D.vents.map(v => v.join(',')).join('\n');
  $('#sStreet').value = D.street;
  $('#ownMsg').textContent = 'Demo A draft loaded. Edit it, then press Check my roof.'; $('#ownMsg').className = 'msg';
};
$('#fileIn').onchange = async e => {
  for (const f of e.target.files) {
    if (f.size > 2e6) { $('#ownMsg').textContent = f.name + ' is over 2 MB.'; continue; }
    const t = await f.text();
    if (/\.json$/i.test(f.name) || /^\s*\[/.test(t)) $('#inFaces').value = t; else if (/east|centre_east|,/.test(t.split('\n')[0]) && t.split('\n').length > 1 && t.split('\n')[0].split(',').length > 3) $('#inMods').value = t; else $('#inVents').value = t;
  }
  $('#ownMsg').textContent = 'Files loaded. Press Check my roof.'; $('#ownMsg').className = 'msg';
  e.target.value = '';
};

// ---------- report ----------
$('#copyBtn').onclick = async () => {
  if (!last) return;
  const { roof, res, c } = last;
  const t = [`Solar Permit Check: ${roof.name}${st.demo === 'own' ? '' : ' (' + (st.lay === 'draft' ? 'first draft' : 'fixed') + ')'}`,
    `Rules: edge ${fmt(c.edge * 100, 0)} cm, gap ${fmt(c.gap * 100, 1)} cm, vents ${fmt(c.vent, 2)} m, square within ${fmt(c.sq, 1)}°, street toward ${Math.round(c.street)}°, module ${Math.round(c.L * 1000)} × ${Math.round(c.W * 1000)} mm ${c.watt} W`, '',
    ...res.checks.map(k => `[${({ ok: 'PASS', bad: 'FIX', warn: 'CHECK', info: 'NOTE' })[k.level]}] ${k.title}: ${k.text}${k.ids.length ? ' (' + k.ids.join(', ') + ')' : ''}`), '',
    'By face:', ...roof.faces.map(f => `  ${f.id}${f.name ? ' ' + f.name : ''}: ${res.mods.filter(m => m.face === f.id && m.pts).length} modules, ${f.pitch < 2 ? 'flat' : compass(f.az) + ' ' + fmt(f.pitch, 1) + '°'}`), '',
    'Geometry check only: not an electrical, structural or fire-code design. Confirm vents, pitches and edges on site.'].join('\n');
  try { await navigator.clipboard.writeText(t); $('#copyMsg').textContent = 'Copied.'; }
  catch { $('#copyMsg').textContent = 'Copy was blocked. Select the checks and copy by hand.'; }
  setTimeout(() => { $('#copyMsg').textContent = ''; }, 2500);
};

// ---------- guided tour ----------
const TOUR = [
  ['#pickBar', 'Pick a roof', 'Two made-up houses come with the tool. Demo A starts on its first draft, the kind of layout a design tool or a quick sketch produces.', () => { setDemo(0); setLay('draft'); }],
  ['#planCard', 'Read the plan', 'This is the roof from above. Coloured shapes are roof faces with arrows pointing downhill; dark rectangles are modules. Red ones break a rule. Red rings are vents a module covers.', null],
  ['#checkCard', 'Go through the checks', 'Each line is one thing a reviewer looks for. Tap a line to light up its modules on the plan. Here: overlaps, a crooked street-face array, modules on vents and one face too close to the edge.', () => { st.focus = null; st.focusId = null; render(); }],
  ['#pickBar', 'See it fixed', 'The Fixed layout keeps every module square, off the vents and inside the edges. The red goes away; what is left is a note to explain the modules the street can see.', () => setLay('fixed')],
  ['#setCard', 'Use your own rules', 'Set your borough\'s clearances, the way the street lies, the city\'s rooftop estimate and your module size. Every check updates as you type.', null],
  ['#ownCard', 'Check your own roof', 'Paste your roof faces, module list and vents (or load the files), press Check my roof, then copy the report into your permit notes.', () => setDemo('own')]
];
let ti = 0;
function tourShow() {
  const [sel, title, text, act] = TOUR[ti];
  if (act) act();
  $$('.lit').forEach(x => x.classList.remove('lit'));
  const t = $(sel); t.classList.add('lit');
  const top = t.getBoundingClientRect().top + scrollY - 10; scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
  $('#tStep').textContent = `Step ${ti + 1} of ${TOUR.length}`; $('#tTitle').textContent = title; $('#tText').textContent = text;
  $('#tBack').disabled = ti === 0; $('#tNext').textContent = ti === TOUR.length - 1 ? 'Done' : 'Next';
}
function tourEnd() { $('#tour').hidden = true; $$('.lit').forEach(x => x.classList.remove('lit')); document.body.classList.remove('touring'); }
$('#tourBtn').onclick = () => { ti = 0; $('#tour').hidden = false; document.body.classList.add('touring'); tourShow(); $('#tNext').focus(); };
$('#tNext').onclick = () => { if (ti === TOUR.length - 1) { tourEnd(); setDemo(0); setLay('draft'); return; } ti++; tourShow(); };
$('#tBack').onclick = () => { if (ti > 0) { ti--; tourShow(); } };
$('#tClose').onclick = tourEnd;
document.addEventListener('keydown', e => { if (e.key === 'Escape' && !$('#tour').hidden) tourEnd(); });

setDemo(0);
if (/[?&]tour=1/.test(location.search)) $('#tourBtn').click();
window.__solar = { analyse, cfg, current, DEMOS };   // for tests
})();
solar.css (layout, light and dark)99 lines

Raw file

:root{--paper:#f3f5f7;--sheet:#fff;--ink:#16202a;--soft:#566474;--rule:#dbe1e7;--accent:#1f4fb5;--bad:#c62828;--badbg:#fde8e7;--warn:#9a5a00;--warnbg:#fcefd6;--ok:#16794d;--okbg:#e2f3ea;--mod:#1d2b4a;--gold:#c9a227;
  color-scheme:light;font:15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,Arial,sans-serif}
@media (prefers-color-scheme:dark){:root{--paper:#0e141a;--sheet:#161f28;--ink:#e6edf3;--soft:#9fb0c0;--rule:#2a3745;--accent:#8db1ff;--bad:#ff7b72;--badbg:#3a1614;--warn:#ffc266;--warnbg:#3a2a10;--ok:#6fd3a2;--okbg:#13301f;--mod:#0a0f1a;color-scheme:dark}}
*{box-sizing:border-box}
html,body{margin:0;background:var(--paper);color:var(--ink)}
body{overflow-x:hidden}
.shell{max-width:1240px;margin:0 auto;padding:18px 16px 40px}
.mast{display:flex;justify-content:space-between;gap:16px;align-items:flex-end;flex-wrap:wrap;margin-bottom:12px}
.eyebrow{font:700 12px/1.2 system-ui,sans-serif;letter-spacing:.08em;text-transform:uppercase;color:var(--accent)}
h1{font-size:clamp(26px,4vw,38px);line-height:1.1;margin:6px 0 4px}
.sub{margin:0;color:var(--soft);max-width:64ch}
.mastbtns{display:flex;gap:8px;flex-wrap:wrap}
h2{font-size:17px;margin:0}
h3{font-size:15px;margin:14px 0 6px}
.btn{display:inline-flex;align-items:center;gap:6px;min-height:40px;padding:8px 14px;border-radius:10px;border:1px solid var(--rule);background:var(--sheet);color:var(--ink);font:600 14px/1.2 inherit;cursor:pointer;text-decoration:none}
.btn:hover{border-color:var(--accent)}
.btn.pri{background:var(--accent);border-color:var(--accent);color:#fff}
.btn.ghost{background:transparent}
.btn:disabled{opacity:.45;cursor:default}
.btn.file{position:relative;overflow:hidden}
.btn.file input{position:absolute;inset:0;opacity:0;cursor:pointer}
:focus-visible{outline:3px solid var(--gold);outline-offset:2px}
.bar{display:flex;flex-wrap:wrap;gap:10px 14px;align-items:center;background:var(--sheet);border:1px solid var(--rule);border-radius:14px;padding:10px 12px;margin-bottom:14px}
.seg{display:inline-flex;border:1px solid var(--rule);border-radius:10px;overflow:hidden}
.seg[hidden]{display:none}
.seg button{border:0;background:transparent;color:var(--ink);font:600 14px/1.2 inherit;padding:9px 13px;min-height:40px;cursor:pointer}
.seg button+button{border-left:1px solid var(--rule)}
.seg button[aria-pressed="true"]{background:var(--ink);color:var(--sheet)}
.blurb{margin:0;color:var(--soft);font-size:14px;flex:1 1 260px}
.main{display:grid;grid-template-columns:minmax(0,1.25fr) minmax(0,1fr);gap:14px;align-items:start}
.card{background:var(--sheet);border:1px solid var(--rule);border-radius:14px;padding:14px;margin-bottom:14px}
.main .card{margin-bottom:0}
.cardhead{display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap;align-items:baseline}
.legend{font-size:12.5px;color:var(--soft);display:flex;gap:6px;align-items:center;flex-wrap:wrap}
.lg{display:inline-block;width:14px;height:9px;border-radius:2px;margin-left:6px}
.lg.ok{background:var(--mod)}.lg.bad{background:var(--bad)}.lg.warn{background:#e39b1b}.lg.vent{background:#444;border-radius:50%;width:9px}
#plan{width:100%;height:auto;aspect-ratio:1/1;max-height:70vh;display:block;margin-top:8px;color:var(--ink);touch-action:manipulation}
#plan .mod{fill:var(--mod);stroke:#8fa3c2;cursor:pointer;transition:opacity .15s}
#plan .mod.bad{fill:var(--bad);stroke:#fff}
#plan .mod.warn{fill:#e39b1b;stroke:#fff}
#plan .mod.sel{stroke:var(--gold)}
#plan .mod.dim{opacity:.18}
#plan .vent{fill:#333}
#plan .vent.hit{fill:var(--bad)}
#plan .vhalo{fill:none;stroke:#555;stroke-dasharray:.12 .12;opacity:.7}
#plan .vhalo.hit{stroke:var(--bad);stroke-dasharray:none;opacity:1}
#plan .lbl text{fill:currentColor;font-weight:700;paint-order:stroke;stroke:var(--sheet);stroke-width:.14px}
#plan .street{stroke:var(--accent)}
#plan .streettxt{fill:var(--accent)}
@media (prefers-color-scheme:dark){#plan .vent{fill:#ddd}#plan .vhalo{stroke:#bbb}}
.hint{margin:6px 0 0;color:var(--soft);font-size:13px}
.detail{margin-top:8px;font-size:13.5px;background:var(--paper);border-radius:10px;padding:10px 12px}
.detail .bad{color:var(--bad);font-weight:600}.detail .okt{color:var(--ok);font-weight:600}
.verdict{border-radius:10px;padding:12px 14px;font-size:15px;margin-bottom:10px}
.verdict.bad{background:var(--badbg);border-left:4px solid var(--bad)}
.verdict.warn{background:var(--warnbg);border-left:4px solid #e39b1b}
.verdict.ok{background:var(--okbg);border-left:4px solid var(--ok)}
.checks{list-style:none;margin:0;padding:0;display:grid;gap:6px}
.ck button{width:100%;text-align:left;display:grid;grid-template-columns:16px 1fr;gap:2px 10px;padding:9px 10px;border-radius:10px;border:1px solid var(--rule);background:transparent;color:var(--ink);font:inherit;cursor:pointer}
.ck button:disabled{cursor:default;opacity:1}
.ck button[aria-pressed="true"]{border-color:var(--accent);background:var(--paper)}
.dotl{grid-row:1/4;width:12px;height:12px;border-radius:50%;margin-top:5px;background:var(--soft)}
.ck.ok .dotl{background:var(--ok)}.ck.bad .dotl{background:var(--bad)}.ck.warn .dotl{background:#e39b1b}.ck.info .dotl{background:var(--accent)}
.ckt{font-weight:700;font-size:14.5px}
.ckd{font-size:13.5px;color:var(--soft)}
.cks{font-size:12.5px;font-weight:600;color:var(--accent)}
.facetab{overflow-x:auto}
table{border-collapse:collapse;width:100%;font-size:13px}
th,td{text-align:left;padding:6px 6px;border-bottom:1px solid var(--rule);vertical-align:top}
th{color:var(--soft);font-weight:600;font-size:12px}
.row{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-top:12px}
.msg{font-size:13.5px;color:var(--soft)}
.msg.ok{color:var(--ok)}.msg.err{color:var(--bad);font-weight:600}
.sets{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:10px 16px;margin-top:10px}
.sets label{display:flex;flex-direction:column;gap:4px;font-size:13px;font-weight:600;color:var(--soft)}
.sets span{display:flex;flex-wrap:wrap;gap:6px;align-items:center;color:var(--ink);font-weight:400}
input[type=number]{width:84px;min-height:38px;padding:6px 8px;border-radius:8px;border:1px solid var(--rule);background:var(--paper);color:var(--ink);font:inherit}
.note{font-size:13px;color:var(--soft);margin:10px 0 0}
.owngrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:10px}
.owngrid label{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:13.5px}
textarea{width:100%;font:12.5px/1.45 ui-monospace,"SFMono-Regular",Menlo,Consolas,monospace;padding:8px;border-radius:8px;border:1px solid var(--rule);background:var(--paper);color:var(--ink);resize:vertical}
small{font-weight:400;color:var(--soft);font-size:12px}
.how{display:grid;grid-template-columns:max-content 1fr;gap:6px 14px;margin:10px 0 0;font-size:14px}
.how dt{font-weight:700}.how dd{margin:0;color:var(--soft)}
.tour{position:fixed;left:0;right:0;bottom:0;z-index:20;display:flex;justify-content:center;padding:0 10px 12px;pointer-events:none}
.tour[hidden]{display:none}
.tcard{pointer-events:auto;max-width:560px;width:100%;background:var(--ink);color:var(--sheet);border-radius:14px;padding:14px 16px;box-shadow:0 10px 40px rgba(0,0,0,.35)}
.tcard h3{margin:2px 0 4px;font-size:17px}
.tcard p{margin:0;font-size:14px;opacity:.92}
.tstep{font-size:12px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--gold)}
.tcard .row{margin-top:10px}
.tcard .btn{background:transparent;color:var(--sheet);border-color:rgba(255,255,255,.35)}
.tcard .btn.pri{background:var(--gold);border-color:var(--gold);color:#16202a}
.lit{outline:3px solid var(--gold);outline-offset:3px}
body.touring .shell{padding-bottom:240px}
@media (max-width:900px){.main{grid-template-columns:1fr}.owngrid{grid-template-columns:1fr}}
@media (max-width:520px){.shell{padding:12px 10px 30px}.how{grid-template-columns:1fr}.how dd{margin-bottom:6px}.seg button{padding:9px 10px}th:nth-child(2),td:nth-child(2){display:none}}
@media (max-height:520px) and (orientation:landscape){#plan{max-height:85vh}.tour{justify-content:flex-end}.tcard{max-width:300px;padding:10px 12px}.tcard p{font-size:13px}}
demos.js (two invented houses: draft and fixed layouts)4 lines

Raw file

// Two made-up houses. Every number here is invented; no real address, lot or photo.
// Module rows: [id, face, P(ortrait)/L(andscape), long-axis bearing °, east m, north m, height m]
const DEMOS = [{"name":"Demo A \u00b7 two-storey hip roof","blurb":"Made-up house, street to the south. The draft has the kind of mistakes a first layout often has.","street":180,"faces":[{"id":"S","name":"Front (street) face","az":180,"pitch":26.0,"outline":[[-7.5,-5.5],[7.5,-5.5],[2,0],[-2,0]]},{"id":"N","name":"Rear face","az":0,"pitch":26.0,"outline":[[-7.5,5.5],[-2,0],[2,0],[7.5,5.5]]},{"id":"E","name":"Right side face","az":90,"pitch":26.0,"outline":[[7.5,-5.5],[7.5,5.5],[2,0]]},{"id":"W","name":"Left side face","az":270,"pitch":26.0,"outline":[[-7.5,-5.5],[-2,0],[-7.5,5.5]]}],"vents":[[-3.2,-3.0],[1.5,3.2],[5.6,-0.6],[-1.0,4.4]],"layouts":{"draft":[["M001","S","L",297.43,3.204,-4.721,6.58],["M002","S","L",297.43,0.772,-4.721,6.58],["M003","S","L",297.43,-1.66,-4.721,6.58],["M004","S","L",297.43,-4.092,-4.721,6.58],["M005","S","L",297.43,3.204,-3.657,7.099],["M006","S","L",297.43,0.772,-3.657,7.099],["M007","N","P",0.0,-4.206,4.196,6.836],["M008","N","P",0.0,-3.102,4.196,6.836],["M009","N","P",0.0,-1.838,4.196,6.836],["M010","N","P",0.0,-0.654,4.196,6.836],["M011","N","P",0.0,0.53,4.196,6.836],["M012","N","P",0.0,1.714,4.196,6.836],["M013","N","P",0.0,2.898,4.196,6.836],["M014","N","P",0.0,4.082,4.196,6.836],["M015","N","P",0.0,-1.614,2.01,7.902],["M016","N","P",0.0,-0.43,2.01,7.902],["M017","N","P",0.0,0.754,2.01,7.902],["M018","N","P",0.0,1.938,2.01,7.902],["M019","E","L",180.0,6.883,3.02,6.501],["M020","E","L",180.0,6.883,0.588,6.501],["M021","E","L",180.0,6.883,-1.844,6.501],["M022","E","L",180.0,5.818,1.608,7.02],["M023","E","L",180.0,4.754,-0.824,7.539],["M024","W","L",0.0,-6.721,-2.616,6.58],["M025","W","L",0.0,-6.721,-0.184,6.58],["M026","W","L",0.0,-6.721,2.248,6.58],["M027","W","L",0.0,-5.657,-1.204,7.099],["M028","W","L",0.0,-5.657,1.228,7.099],["M029","W","L",0.0,-4.592,-0.484,7.618]],"fixed":[["M001","S","L",270.0,3.204,-4.721,6.58],["M002","S","L",270.0,0.772,-4.721,6.58],["M003","S","L",270.0,-1.66,-4.721,6.58],["M004","S","L",270.0,-4.092,-4.721,6.58],["M005","S","L",270.0,3.204,-3.657,7.099],["M006","S","L",270.0,0.772,-3.657,7.099],["M007","N","P",0.0,-3.492,4.16,6.854],["M008","N","P",0.0,-2.308,4.16,6.854],["M009","N","P",0.0,0.06,4.16,6.854],["M010","N","P",0.0,2.428,4.16,6.854],["M011","N","P",0.0,3.612,4.16,6.854],["M012","N","P",0.0,-1.928,1.974,7.92],["M013","N","P",0.0,-0.744,1.974,7.92],["M014","N","P",0.0,0.44,1.974,7.92],["M015","E","L",180.0,6.721,2.616,6.58],["M016","E","L",180.0,6.721,0.184,6.58],["M017","E","L",180.0,6.721,-2.248,6.58],["M018","E","L",180.0,5.657,1.204,7.099],["M019","E","L",180.0,4.592,0.484,7.618],["M020","W","L",0.0,-6.721,-2.616,6.58],["M021","W","L",0.0,-6.721,-0.184,6.58],["M022","W","L",0.0,-6.721,2.248,6.58],["M023","W","L",0.0,-5.657,-1.204,7.099],["M024","W","L",0.0,-5.657,1.228,7.099],["M025","W","L",0.0,-4.592,-0.484,7.618]]},"cityKw":38.0,"cityYield":760},{"name":"Demo B \u00b7 bungalow with a flat rear roof","blurb":"Made-up house turned 45\u00b0, street to the south-west, with a low flat roof at the back.","street":225,"faces":[{"id":"F1","name":"Front (street) face","az":225,"pitch":24.0,"outline":[[-8.485,-0.0],[0.0,-8.485],[0.0,0.0]]},{"id":"F2","name":"Right side face","az":135,"pitch":24.0,"outline":[[0.0,-8.485],[8.485,0.0],[0.0,0.0]]},{"id":"F3","name":"Rear face","az":45,"pitch":24.0,"outline":[[8.485,0.0],[-0.0,8.485],[0.0,0.0]]},{"id":"F4","name":"Left side face","az":315,"pitch":24.0,"outline":[[-0.0,8.485],[-8.485,-0.0],[0.0,0.0]]},{"id":"A1","name":"Flat rear roof","az":45,"pitch":0.0,"outline":[[1.344,7.707],[7.707,1.344],[9.829,3.465],[3.465,9.829]]}],"vents":[[0.566,2.263],[1.98,-0.283],[-1.556,-2.121],[7.495,3.253]],"layouts":{"draft":[["M001","F1","P",225.0,-1.593,-4.965,4.106],["M002","F1","P",225.0,-2.431,-4.128,4.106],["M003","F1","P",225.0,-3.268,-3.291,4.106],["M004","F1","P",225.0,-4.105,-2.454,4.106],["M005","F1","P",225.0,-4.942,-1.617,4.106],["M006","F1","P",225.0,-1.697,-1.72,5.096],["M007","F2","P",135.0,4.965,-1.593,4.106],["M008","F2","P",135.0,4.128,-2.431,4.106],["M009","F2","P",135.0,3.291,-3.268,4.106],["M010","F2","P",135.0,2.454,-4.105,4.106],["M011","F2","P",135.0,1.617,-4.942,4.106],["M012","F2","P",135.0,1.72,-1.697,5.096],["M013","F3","P",45.0,1.593,4.965,4.106],["M014","F3","P",45.0,2.431,4.128,4.106],["M015","F3","P",45.0,3.268,3.291,4.106],["M016","F3","P",45.0,4.105,2.454,4.106],["M017","F3","P",45.0,4.942,1.617,4.106],["M018","F3","P",45.0,1.697,1.72,5.096],["M019","F4","P",315.0,-4.965,1.593,4.106],["M020","F4","P",315.0,-4.128,2.431,4.106],["M021","F4","P",315.0,-3.291,3.268,4.106],["M022","F4","P",315.0,-2.454,4.105,4.106],["M023","F4","P",315.0,-1.617,4.942,4.106],["M024","F4","P",315.0,-1.72,1.697,5.096],["M025","A1","L",135,3.906,8.515,3.0],["M026","A1","L",135,5.626,6.796,3.0],["M027","A1","L",135,7.346,5.076,3.0],["M028","A1","L",135,3.069,7.678,3.0],["M029","A1","L",135,4.789,5.958,3.0]],"fixed":[["M001","F2","P",135.0,4.965,-1.593,4.106],["M002","F2","P",135.0,4.128,-2.431,4.106],["M003","F2","P",135.0,3.291,-3.268,4.106],["M004","F2","P",135.0,2.454,-4.105,4.106],["M005","F2","P",135.0,1.617,-4.942,4.106],["M006","F2","P",135.0,1.72,-1.697,5.096],["M007","F3","P",45.0,1.593,4.965,4.106],["M008","F3","P",45.0,2.431,4.128,4.106],["M009","F3","P",45.0,3.268,3.291,4.106],["M010","F3","P",45.0,4.105,2.454,4.106],["M011","F3","P",45.0,4.942,1.617,4.106],["M012","F3","P",45.0,1.697,1.72,5.096],["M013","F4","P",315.0,-4.965,1.593,4.106],["M014","F4","P",315.0,-4.128,2.431,4.106],["M015","F4","P",315.0,-3.291,3.268,4.106],["M016","F4","P",315.0,-2.454,4.105,4.106],["M017","F4","P",315.0,-1.617,4.942,4.106],["M018","F4","P",315.0,-1.72,1.697,5.096],["M019","A1","L",135,3.906,7.737,3.0],["M020","A1","L",135,5.626,6.018,3.0]]},"cityKw":26.0,"cityYield":690}];

Want the full solar permit package for your own address?

The tool runs on an invented house. Send me your address, in any city: I read that municipality's solar rules, design your roof and prepare the full permit package for that address, checked the way the plan reviewer will before you file. Fixed price agreed up front, and the first call is free.

How it works and what it costs Book a free call ↗

Or write to me · how to use what is here