@rulecad/pcb 0.5.5 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,31 @@
3
3
  What changed in each release, for someone upgrading a workspace. A **drilled size** here is a dimension the fab
4
4
  makes (a hole's diameter in the drill file). Each release says whether any drilled or printed size moved, and why.
5
5
 
6
+ ## 0.6.0: diodes are wired the right way round, with pad 1 as the cathode; routeStore keeps the autorouter's results where its caller says; pcb ships tscircuit's notice for the code it follows
7
+
8
+ ### Fixed
9
+
10
+ - A net or track joined to a diode's `cathode` now reaches the diode's cathode. The board engine used to name a diode's two ports by the order of its pads, the first one the anode, whatever the pads said they were. On a DO-35 diode (`do35()`) the first pad is the square cathode pad, so every net joined to `D.cathode` went to the round anode pad instead, against the band printed on the board. A pad named `cathode` or `anode` (or `K`, `A`) is now that end; a diode whose pads are only numbered has pad 1 as its cathode, as KiCad and assemblers number a diode's pads.
11
+ - A diode's cathode is now its pin 1 in every file the board makes: the KiCad board and schematic, and the placement file. The keyboard's SOD-123 diodes (`keyboard()`) are turned half round on the back so that pad 1, the cathode, is on the row's side. Their copper and the bar printed by each one do not move; the KiCad files and the placement file change (each diode is placed at 180° rather than 0°).
12
+ - A diode with other than two pads, or with both pads at the same end, is refused with a message saying how to name them.
13
+
14
+ ### Changed
15
+
16
+ - A diode's ports are `pin1` (also `cathode`, `neg`, `K`, `1`) and `pin2` (also `anode`, `pos`, `A`, `2`). The names `left` and `right`, which meant the first and second pad, are gone: use `cathode` and `anode`.
17
+
18
+ ### Boards made before this change
19
+
20
+ - **thin-picro macropads** (`examples/thin-picro`, `macropad:front` and `macropad:rear`), and any other board with `do35()` diodes: every diode was wired backwards. Fitted by the band on the board, no key reads with COL2ROW firmware. To tell: on the old board, the row's track (the one running along to the next diode in the row) goes to the round pad. A board already made works if each diode is fitted with its band at the round pad, the opposite of the band printed on the board, or with firmware set to ROW2COL.
21
+ - **Keyboards made with `keyboard()`**, hand-soldered by the printed bar: these were right, and still are. Assembled by a fab from the old placement file, or drawn from the old KiCad files, every diode may be reversed, because those files gave the anode as pad 1. To tell: in the old KiCad board, each diode's pad 1 is on its switch's net. Check an assembled board's diodes: the band (cathode) should be on the side of the row track; if it is on the switch's side, set the firmware to ROW2COL.
22
+ - Build the boards again to get new Gerbers, KiCad files and placement files. The macropads' tracks to their diodes move; no printed size moves.
23
+
24
+ ### Added
25
+
26
+ - `routeStore({ get, put })` sets where the autorouter's results are kept, in place of the `RULECAD_ROUTE_CACHE` folder: `get(key)` gives a route's JSON text or nothing, `put(key, text)` keeps one, each key the 64 hex digits of a SHA-256 of the router's input and version, as the folder's file names are. `routeStore(null)` goes back to the folder. cad uses it to run board designs in its sandbox, which can't write files: the routes found there go back to cad, which writes them.
27
+ - Upgrading: nothing to do; without a store the folder is used as before. No printed size changes.
28
+
29
+ - A note, THIRD-PARTY.md, shipped with the package and linked from a new Licence section in the README: `fixedTraces` in circuit.mjs follows `withFixedTraces` in tscircuit's core, which is under the MIT licence, and the note carries that licence's copyright notice and text, as the licence asks. It also says that `@tscircuit/copper-pour-solver`, one of pcb's dependencies, is published without a licence although its repository is MIT. The code is unchanged: no board, and no printed size, changes.
30
+
6
31
  ## 0.5.5: tracks finished for the fab, a route cache, a footprint for MX or Choc switches
7
32
 
8
33
  ### Added
package/README.md CHANGED
@@ -141,7 +141,9 @@ export function main(v) {
141
141
  `{ rect: { w, h, offset } }` is an oval (a rounded rectangle) round its hole, which can sit off-centre.
142
142
  - **Any board shape:** give `outline: [{ x, y }, ...]` in place of a centre and size. `shape.rounded(w, h, r)`,
143
143
  `shape.bevelled(w, h, b)`, `shape.circle(d)` and `shape.rect(w, h)` make common ones. The router keeps tracks
144
- inside the outline, and a check finds any pad outside it.
144
+ inside the outline, and a check finds any pad outside it. Every hole, on a board of any shape, is checked as a circle
145
+ against the edge: one that breaks through it fails, named, with how far it breaks out (`mounting hole 2 (3.4 mm)
146
+ breaks through the board's edge by 1.2 mm at (14.5, 0)`), so that the fab doesn't mill a notch where a screw goes.
145
147
  - **Copper of any shape:** a pad `{ pin, smd: true, x, y, points: [[x, y], ...] }` (x, y: where tracks join it), such
146
148
  as a ring from `shape.ring(r0, r1)` (a rotary contact, a touch pad). The router sees it as strips that follow its shape.
147
149
  - **Nets:** each net's pins are joined by the shortest set of links between them, at `board.track` (or the net's own
@@ -190,3 +192,8 @@ npx cad export macropad/board # <name>-fab.zip for JLCPCB, KiCad files, the
190
192
  the newest, and since its 0.0.3032 that has pulled in an old circuit-json that the design checks can't load
191
193
  (tscircuit/circuit-json-to-gerber#200).
192
194
  - Ordering is your click: `cad export` makes the fab zip and never places an order.
195
+
196
+ ## Licence
197
+
198
+ MIT (see [LICENSE](LICENSE)). `fixedTraces` in circuit.mjs follows tscircuit's MIT-licensed `withFixedTraces`: its
199
+ copyright notice is in [THIRD-PARTY.md](THIRD-PARTY.md), which goes with any copy of the package.
package/THIRD-PARTY.md ADDED
@@ -0,0 +1,42 @@
1
+ # Code in @rulecad/pcb that follows someone else's
2
+
3
+ Most of `@rulecad/pcb` is rulecad's own work, under the MIT licence in [LICENSE](LICENSE). One part is not.
4
+
5
+ ## `fixedTraces` in circuit.mjs
6
+
7
+ `fixedTraces`, in `circuit.mjs`, turns the tracks already drawn on a board into obstacles the autorouter keeps clear
8
+ of: each piece of track a box a track wide, each via a square. It follows the function `withFixedTraces` in tscircuit's
9
+ core (https://github.com/tscircuit/core), so that a board is routed around its drawn tracks in the same way there. That
10
+ code is under the MIT licence, whose notice follows. It asks only that the notice goes with any copy.
11
+
12
+ ```
13
+ MIT License
14
+
15
+ Copyright (c) 2024 tscircuit Inc.
16
+
17
+ Permission is hereby granted, free of charge, to any person obtaining a copy
18
+ of this software and associated documentation files (the "Software"), to deal
19
+ in the Software without restriction, including without limitation the rights
20
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
21
+ copies of the Software, and to permit persons to whom the Software is
22
+ furnished to do so, subject to the following conditions:
23
+
24
+ The above copyright notice and this permission notice shall be included in all
25
+ copies or substantial portions of the Software.
26
+
27
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
32
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
33
+ SOFTWARE.
34
+ ```
35
+
36
+ ## The packages pcb installs
37
+
38
+ pcb uses many of tscircuit's packages, installed from npm with their own licences; they are not copied into pcb. One
39
+ of them, `@tscircuit/copper-pour-solver`, is published without a licence field or file, though its repository
40
+ (https://github.com/tscircuit/copper-pour-solver) is under the MIT licence. The repository's test
41
+ `test/notices.test.mjs` lists every installed package's licence that is not one of the usual permissive ones, with the
42
+ reason it is accepted.
package/circuit.mjs CHANGED
@@ -15,6 +15,8 @@
15
15
  // holes: [{ x, y, d }], courtyard: { w, h } | null,
16
16
  // footprint: 'sod123' | 'jst4_sh' | 'pinrow4' ... (a footprinter string, SMD or through-hole, instead of pads),
17
17
  // sch: { x, y, symbol?, pinLabels? } }
18
+ // a diode's two ports are its 'cathode' (pin 1, also 'K') and 'anode' (pin 2, also 'A'): a pad whose pin is
19
+ // 'cathode' or 'anode' is that end, else pad 1 is the cathode, as KiCad and assemblers number a diode's pads
18
20
  // trace { from: [part, port], to: [part, port], width, path: [{ x, y }] (absolute, between the two ports), layer }; a trace
19
21
  // without a path is left to the autorouter when board.autoroute is set
20
22
  // nets { GND: ['U1.GND', 'J1.1', 'J2.1'] } or { GND: { pins: [...], width } }: each net's pins are joined by the
@@ -802,15 +804,31 @@ async function pours(out, add, board, nets, netOf) {
802
804
  }
803
805
  }
804
806
 
805
- // A part's port names, in pad order: a switch's pin1 and pin2, a diode's anode and cathode, a chip's pins by label
807
+ // A part's port names, in pad order: a switch's pin1 and pin2, a diode's cathode and anode by its pads (diodePorts), a chip's pins by label
806
808
  function portNames(part, pads) {
807
- if (part.ftype === 'simple_diode') return [{ name: 'pin1', n: 1, hints: ['pin1', 'pos', 'anode', 'left', '1'] }, { name: 'pin2', n: 2, hints: ['pin2', 'neg', 'cathode', 'right', '2'] }];
809
+ if (part.ftype === 'simple_diode') return diodePorts(part, pads);
808
810
  return (part.pads || pads).map((p) => {
809
811
  const n = Number(p.pin.replace(/\D/g, '')), label = part.sch?.pinLabels?.[p.pin];
810
812
  return { name: label || p.pin, n, hints: label ? [label, p.pin, String(n)] : [p.pin, String(n)] };
811
813
  });
812
814
  }
813
815
 
816
+ // A diode's two ports, each named for the end of the diode its pad is. A pad that says which end it is (do35's
817
+ // 'cathode' and 'anode') is that end; otherwise pad 1 is the cathode (K) and pad 2 the anode (A), as KiCad's diode
818
+ // footprints and assemblers number them. The cathode is port 1 and the anode port 2, whatever order the pads come in,
819
+ // so a KiCad export and a placement file give pad 1 as the cathode, and the band goes at that end.
820
+ function diodePorts(part, pads) {
821
+ if (pads.length !== 2) throw new Error(`${part.name}: a diode has two pads, one for each end, and this one has ${pads.length}`);
822
+ const said = pads.map((p) => (/^(anode|a)$/i.test(p.pin) ? 'anode' : /^(cathode|k)$/i.test(p.pin) ? 'cathode' : null));
823
+ const other = (end) => (end === 'anode' ? 'cathode' : 'anode');
824
+ const byNumber = (p) => (Number(String(p.hint ?? p.pin).replace(/\D/g, '')) === 1 ? 'cathode' : 'anode');
825
+ const ends = said.map((s, i) => s ?? (said[1 - i] ? other(said[1 - i]) : byNumber(pads[i])));
826
+ if (ends[0] === ends[1]) throw new Error(`${part.name}: both of the diode's pads are its ${ends[0]}. Name one pad 'cathode' and the other 'anode', or number them 1 (cathode) and 2 (anode)`);
827
+ return ends.map((end) => end === 'cathode'
828
+ ? { name: 'pin1', n: 1, end, hints: ['pin1', 'cathode', 'neg', 'K', '1'] }
829
+ : { name: 'pin2', n: 2, end, hints: ['pin2', 'anode', 'pos', 'A', '2'] });
830
+ }
831
+
814
832
  // A net's connections: its pins joined by the shortest set of straight links between them (Prim's minimum spanning
815
833
  // tree, ties to the earlier pin), so the router gets short, sensible connections to route rather than a long chain
816
834
  function netTraces(board, port, joined = new Map()) {
@@ -876,9 +894,11 @@ function schematic(out, add, placed, board, port, netOf = new Map()) {
876
894
  // one symbol pin per pin: a pin with more than one pad (a hybrid switch's) draws its other pads as that one
877
895
  const firsts = sourcePorts.filter((sp, i) => sourcePorts.findIndex((o) => o.name === sp.name) === i);
878
896
  firsts.forEach((sp, i) => {
879
- const q = symbol.ports[i], center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
897
+ // (the diode symbol's first port is its anode, at the top: each diode port goes to its own end of the symbol)
898
+ const k = part.ftype === 'simple_diode' ? (sp.port_hints.includes('anode') ? 0 : 1) : i;
899
+ const q = symbol.ports[k], center = { x: s.x + q.x - symbol.center.x, y: s.y + q.y - symbol.center.y };
880
900
  sch.set(sp.source_port_id, add('schematic_port', { schematic_component_id: c.schematic_component_id, center, source_port_id: sp.source_port_id,
881
- facing_direction: part.ftype === 'simple_diode' ? (i ? 'down' : 'up') : (i ? 'right' : 'left'), distance_from_component_edge: 0.4 }));
901
+ facing_direction: part.ftype === 'simple_diode' ? (k ? 'down' : 'up') : (k ? 'right' : 'left'), distance_from_component_edge: 0.4 }));
882
902
  });
883
903
  for (const sp of sourcePorts) if (!sch.has(sp.source_port_id)) sch.set(sp.source_port_id, sch.get(firsts.find((o) => o.name === sp.name).source_port_id));
884
904
  }
@@ -967,7 +987,7 @@ export async function routeInput(json, toRoute, board = {}) {
967
987
 
968
988
  // The drawn tracks become fixed obstacles for the router: each segment a box a track wide (a diagonal one, a run of
969
989
  // boxes about a track-width long), each via a square. Ported from tscircuit core's withFixedTraces (MIT licence,
970
- // github.com/tscircuit/core), so a board is routed around them as it is there.
990
+ // github.com/tscircuit/core), so a board is routed around them as it is there: its notice is in THIRD-PARTY.md.
971
991
  function fixedTraces(input) {
972
992
  const obstacles = [];
973
993
  for (const trace of input.traces) {
@@ -1113,14 +1133,32 @@ export async function neckDown(json, traces, neck) {
1113
1133
  // The autorouter's pipelines, tried in order until one routes the board: its own, then its others, each a different search
1114
1134
  const PIPELINES = ['AutoroutingPipelineSolver', 'AutoroutingPipelineSolver4', 'AutoroutingPipelineSolver5', 'AutoroutingPipelineSolver6', 'AutoroutingPipelineSolver8'];
1115
1135
 
1116
- // The route cache: a file per router input, named by its hash and the router's version. Nothing (null) when unset
1136
+ // The route cache: a route per router input, keyed by the SHA-256 (64 hex digits) of the input and the router's
1137
+ // version. Kept in the store routeStore() was given, else as a file of that name in the folder RULECAD_ROUTE_CACHE
1138
+ // names; nothing (null) when neither is set. (cad's design sandbox can't write files: its runner sets a store that
1139
+ // reads the folder and hands what it routed back to the tool, which writes it.)
1140
+ let routes = null;
1141
+ /**
1142
+ * Where the autorouter's results are kept, in place of the RULECAD_ROUTE_CACHE folder: `get(key)` gives a route's
1143
+ * text (JSON) or undefined, `put(key, text)` keeps one; null goes back to the folder. Keys are 64 hex digits.
1144
+ * @param {{ get: (key: string) => string | undefined, put: (key: string, text: string) => void } | null} store
1145
+ */
1146
+ export function routeStore(store) { routes = store; }
1117
1147
  async function routeCache(input) {
1118
1148
  const dir = typeof process !== 'undefined' && process.env?.RULECAD_ROUTE_CACHE;
1119
- if (!dir) return null;
1149
+ if (!dir && !routes) return null;
1120
1150
  const [fs, path, crypto, { createRequire }] = await Promise.all([import('node:fs'), import('node:path'), import('node:crypto'), import('node:module')]);
1121
1151
  let version = '?';
1122
1152
  try { version = createRequire(import.meta.url)('@tscircuit/capacity-autorouter/package.json').version; } catch {}
1123
- const file = path.join(dir, `${crypto.createHash('sha256').update(JSON.stringify([version, input])).digest('hex')}.json`);
1153
+ const key = crypto.createHash('sha256').update(JSON.stringify([version, input])).digest('hex');
1154
+ if (routes) {
1155
+ const store = routes;
1156
+ return {
1157
+ read: () => { try { const text = store.get(key); return text === undefined ? null : JSON.parse(text); } catch { return null; } },
1158
+ write: (traces) => { try { store.put(key, JSON.stringify(traces)); } catch {} },
1159
+ };
1160
+ }
1161
+ const file = path.join(dir, `${key}.json`);
1124
1162
  return {
1125
1163
  read: () => { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return null; } },
1126
1164
  write: (traces) => { try { fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(file, JSON.stringify(traces)); } catch {} }, // (a cache that can't be written is only slower)
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@rulecad/pcb",
3
- "version": "0.5.5",
3
+ "version": "0.6.0",
4
4
  "description": "Circuit boards from rules: parts from rule sets or any standard footprint, quarter-turn rotation, nets and autorouting; keyboards with every matrix track drawn by rule. Gerbers, KiCad files and a JLCPCB BOM. Circuit JSON written directly: no React.",
5
5
  "type": "module",
6
6
  "exports": "./pcb.mjs",
7
7
  "files": [
8
- "pcb.mjs",
9
- "circuit.mjs",
10
- "kicad.mjs",
8
+ "*.mjs",
11
9
  "README.md",
12
10
  "CHANGELOG.md",
13
- "LICENSE"
11
+ "LICENSE",
12
+ "THIRD-PARTY.md",
13
+ "!test.mjs"
14
14
  ],
15
15
  "license": "MIT",
16
16
  "keywords": [
@@ -38,8 +38,8 @@
38
38
  "dependencies": {
39
39
  "@flatten-js/core": "1.6.14",
40
40
  "@jscad/modeling": "^2.12.0",
41
- "@rulecad/fixings": "^0.1.3",
42
- "@rulecad/rules": "^0.3.7",
41
+ "@rulecad/fixings": "^0.1.9",
42
+ "@rulecad/rules": "^0.3.31",
43
43
  "@resvg/resvg-js": "2.6.2",
44
44
  "@rulecad/smooth": "^0.2.0",
45
45
  "@tscircuit/capacity-autorouter": "0.0.982",
package/pcb.mjs CHANGED
@@ -6,15 +6,15 @@
6
6
  // draws every track by rule, from the switch's footprint (mx rules) and our margins (the board's track and clear):
7
7
  // columns on the front copper: down each column from pin 2 to pin 2, jogging between the centre post and the left
8
8
  // peg; then below the keys, right, and up a lane beside the Pico to its pin
9
- // diodes SOD-123s on the back, under each switch below the centre post; pin 1 runs to the anode up a lane right
10
- // of the right peg
9
+ // diodes SOD-123s on the back, under each switch below the centre post, turned half round so that pad 1, the
10
+ // cathode, is on the row's side; the switch's pin 1 runs to the anode (pad 2) up a lane right of the right peg
11
11
  // rows on the back copper: cathode to cathode under each row of switches, then right and up or down a lane
12
12
  // beside the Pico to its pin
13
13
  // Diodes point from the switch to the row (COL2ROW in QMK's terms).
14
14
  import fs from 'node:fs';
15
15
  import path from 'node:path';
16
- import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps } from './circuit.mjs';
17
- export { bounds };
16
+ import { circuitJson, bounds, smtBounds, slideClear, viaHoleGaps, routeStore } from './circuit.mjs';
17
+ export { bounds, routeStore }; // (routeStore: where the autorouter's results are kept, circuit.mjs)
18
18
  import { createRequire } from 'node:module';
19
19
  // The published rule sets a footprint's pins come from (a Pico's GPIO, a XIAO's labels): read from @rulecad/rules as
20
20
  // published, not through @rulecad/cad, which pcb would then depend on (and cad names pcb: a loop), and which copies a
@@ -248,7 +248,9 @@ export function keyboard(v, keys) {
248
248
  // Around each switch (from its centre): the diode on the back below the post, its anode lane right of the right peg,
249
249
  // the row line below the diodes; the column lane on the front between the post and the left peg
250
250
  const anodeX = m.pcb_peg_x + m.pcb_peg_hole / 2 + v.clear + v.track / 2;
251
- const diode = { x: anodeX - d.pad_x, y: -(m.pcb_centre_hole / 2 + v.clear + d.pad_h / 2) }; // on the back, the anode is at +pad_x
251
+ // On the back, turned half round, the diode's pad 1 (its cathode, as KiCad and assemblers number it) is at -pad_x
252
+ // and its anode at +pad_x: the anode by its switch's pin, the cathode on the row line's side
253
+ const diode = { x: anodeX - d.pad_x, y: -(m.pcb_centre_hole / 2 + v.clear + d.pad_h / 2) };
252
254
  const cathodeX = anodeX - 2 * d.pad_x, lineY = diode.y - d.pad_h / 2 - v.clear - v.track / 2;
253
255
  const jogX = -(m.pcb_centre_hole / 2 + (m.pcb_peg_x - m.pcb_peg_hole / 2 - m.pcb_centre_hole / 2) / 2), slant = Math.abs(m.pcb_pin2_x) - Math.abs(jogX);
254
256
  const pegEdge = m.pcb_peg_x + m.pcb_peg_hole / 2 + v.clear + v.track / 2; // a track this far from a key's centre clears its pegs
@@ -299,7 +301,7 @@ export function keyboard(v, keys) {
299
301
  const pts = (list) => list.map(([x, y]) => ({ x, y })); // a track's corners between its two pads, on the board
300
302
  for (const k of keys) {
301
303
  parts.push(mx(`K${k.n}`, k.x, k.y, m, { x: k.c * SX, y: -k.r * SY }),
302
- { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
304
+ { name: `D${k.n}`, ftype: 'simple_diode', footprint: 'sod123', package: 'SOD-123', mpn: '1N4148W', x: k.x + diode.x, y: k.y + diode.y, layer: 'bottom', rotation: 180, sch: { x: k.c * SX + 1, y: -k.r * SY - 0.8 } });
303
305
  traces.push({ from: [`D${k.n}`, 'anode'], to: [`K${k.n}`, 'pin1'], width: v.track, path: pts([[k.x + anodeX, k.y + m.pcb_pin1_y]]) });
304
306
  }
305
307
 
@@ -1127,6 +1129,16 @@ export function inside(points, x, y) {
1127
1129
  }
1128
1130
  return hit;
1129
1131
  }
1132
+ // How far the point is from the nearest side of the outline (a closed list of points), in mm
1133
+ function toEdge(points, x, y) {
1134
+ let d = Infinity;
1135
+ for (let i = 0; i < points.length; i++) {
1136
+ const a = points[i], b = points[(i + 1) % points.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy;
1137
+ const t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0;
1138
+ d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy));
1139
+ }
1140
+ return d;
1141
+ }
1130
1142
 
1131
1143
  // ---------- building ----------
1132
1144
  // render(board) -> Circuit JSON (circuit.mjs)
@@ -1316,8 +1328,24 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1316
1328
  : { level: 'pass', text: `tracks ${mm(narrow)} mm or wider${tight ? `, ${mm(tight.d)} mm or more apart` : ''}, measured on the board: over JLCPCB's ${j.track_min} / ${j.gap_min} mm` });
1317
1329
  // A board that can't be made: no size, a hole through its edge, two parts of one name, a pin in two nets
1318
1330
  const named = json.filter((e) => e.type === 'source_component').map((e) => e.name), twice = named.filter((n, i) => named.indexOf(n) !== i);
1319
- const edgeHoles = b.outline ? [] : json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id)).filter((e) => { const r = (e.outer_diameter ?? e.hole_diameter ?? e.hole_width ?? 0) / 2; return Math.abs(e.x - b.center.x) + r > b.width / 2 + 1e-6 || Math.abs(e.y - b.center.y) + r > b.height / 2 + 1e-6; });
1320
- const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`, edgeHoles.length && `${edgeHoles.length} holes break through the board's edge`, twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1331
+ // A hole through the edge: every hole, and the copper round a round plated one, tested as a circle against the board's
1332
+ // outline (a rectangular board's is its four corners), so a shaped board and a rectangular one are held to one test:
1333
+ // its centre inside, and as far from the nearest side as its radius. Half holes and parts that reach past the edge as
1334
+ // a clone's source has them are on the edge by design (checked above and below)
1335
+ const reaching = same && b.outline ? same.reaching : new Set(); // (on a shaped board only, as before: a rectangle has no notch to reach into)
1336
+ const edge = b.outline || [[-1, -1], [1, -1], [1, 1], [-1, 1]].map(([sx, sy]) => ({ x: b.center.x + (sx * b.width) / 2, y: b.center.y + (sy * b.height) / 2 }));
1337
+ const refOf = new Map(json.filter((e) => e.type === 'pcb_component').map((e) => [e.pcb_component_id, json.find((c) => c.type === 'source_component' && c.source_component_id === e.source_component_id)?.name]));
1338
+ const boardHoles = json.filter((e) => e.type === 'pcb_hole' && !e.pcb_component_id);
1339
+ const holeName = (e) => (e.type === 'pcb_plated_hole' ? `${refOf.get(e.pcb_component_id) ?? 'a part'}.${e.port_hints?.[1] ?? 'pin'}'s hole`
1340
+ : e.pcb_component_id ? `${refOf.get(e.pcb_component_id) ?? 'a part'}'s hole` : `mounting hole ${boardHoles.indexOf(e) + 1}`);
1341
+ const edgeHoles = json.filter((e) => (e.type === 'pcb_hole' || e.type === 'pcb_plated_hole') && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)).map((e) => {
1342
+ const copper = e.shape === 'circle' && e.outer_diameter != null, r = (copper ? e.outer_diameter : e.hole_diameter ?? e.hole_width ?? 0) / 2;
1343
+ const x = e.x + (copper ? 0 : e.hole_offset_x ?? 0), y = e.y + (copper ? 0 : e.hole_offset_y ?? 0), d = toEdge(edge, x, y), from = inside(edge, x, y) ? d : -d; // from: to the edge, inward
1344
+ return { e, r, x, y, copper, past: r - from }; // past: how far it reaches beyond the edge
1345
+ }).filter((h) => h.past > 1e-6);
1346
+ const holeText = (h) => `${holeName(h.e)} (${mm(2 * h.r)} mm${h.copper ? ' across its copper' : ''}) ${h.past >= 2 * h.r - 1e-6 ? 'is outside the board\'s edge' : `breaks through the board's edge by ${mm(h.past)} mm`} at (${mm(h.x)}, ${mm(h.y)})`;
1347
+ const broken = [!(b.width > 0 && b.height > 0) && `the board is ${mm(b.width)} × ${mm(b.height)} mm`,
1348
+ edgeHoles.length && (edgeHoles.length === 1 ? holeText(edgeHoles[0]) : `${edgeHoles.length} holes break through the board's edge: ${edgeHoles.slice(0, 3).map(holeText).join(', ')}${edgeHoles.length > 3 ? ', …' : ''}`), twice.length && `two parts named ${[...new Set(twice)].join(', ')}`].filter(Boolean); // (a pin in two nets is refused as the board is built)
1321
1349
  if (broken.length) out.push({ level: 'fail', text: `the board can't be made as drawn: ${broken.join('; ')}` });
1322
1350
  // Vias and plated holes against the fab's sizes, each measured from the board: the hole, the pad, and the ring
1323
1351
  // between them (under the recommended ring a warning, under the least a failure). A via's ring and a plated hole's
@@ -1358,10 +1386,12 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1358
1386
  const drills = json.filter((e) => e.type === 'pcb_hole' || e.type === 'pcb_plated_hole' || e.type === 'pcb_via').map((e) => e.hole_diameter ?? e.hole_width);
1359
1387
  if (drills.length) out.push(Math.min(...drills) < j.drill_min ? { level: 'fail', text: `a hole under JLCPCB's ${j.drill_min} mm` } : { level: 'pass', text: `${drills.length} holes, smallest ${Math.min(...drills)} mm (JLCPCB: ${j.drill_min} mm)` });
1360
1388
  const size = `${b.width.toFixed(1)} × ${b.height.toFixed(1)} mm`;
1361
- if (b.outline) { // a shaped board: every pad and hole inside it
1362
- const reaching = same ? same.reaching : new Set();
1363
- const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id)), out_ = pads.filter((e) => (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)));
1364
- out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x)}, ${mm(out_[0].y)} mm)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
1389
+ if (b.outline) { // a shaped board: every pad and hole inside it (its holes and round plated pads tested above, as circles)
1390
+ const pads = json.filter((e) => ['pcb_smtpad', 'pcb_plated_hole', 'pcb_hole'].includes(e.type) && !halves.has(e.pcb_plated_hole_id) && !reaching.has(e.pcb_component_id));
1391
+ const circles = new Set(json.filter((e) => e.type === 'pcb_hole' || (e.type === 'pcb_plated_hole' && e.shape === 'circle' && e.outer_diameter != null))); // (said above when they cross)
1392
+ const out_ = pads.filter((e) => !circles.has(e) && (e.type === 'pcb_smtpad' && e.shape === 'circle' ? !inside(b.outline, e.x, e.y) || toEdge(b.outline, e.x, e.y) < e.radius - 1e-6 // a round pad: as a circle
1393
+ : (e.points || [e]).some((q) => !inside(b.outline, q.x, q.y)))); // a polygon pad by its corners; any other by its centre
1394
+ out.push(out_.length ? { level: 'fail', text: `${out_.length} pads or holes outside the board's outline (first at ${mm(out_[0].x ?? out_[0].points[0].x)}, ${mm(out_[0].y ?? out_[0].points[0].y)} mm)` } : edgeHoles.length ? { level: 'info', text: `shaped board (${b.outline.length} points): its pads are inside it, but not its holes (above)` } : { level: 'pass', text: `shaped board (${b.outline.length} points): all ${pads.length} pads and holes inside it` });
1365
1395
  }
1366
1396
  if (castellated.length) { // JLCPCB's rules for half holes: big enough, far enough apart
1367
1397
  const small = castellated.filter((e) => e.hole_diameter < (j.castellated_drill_min ?? 0.6));
@@ -1408,7 +1438,6 @@ export async function checks(json, v, matrix, source) { // source: a clone's { c
1408
1438
  // a part that reaches past the outline there too, and the source's own vias, kept, where they touch its pads. Returns a test for a design-rule error, with .reaching:
1409
1439
  // the board's components that reach past it as on the source.
1410
1440
  function asSource(json, circuit, kept) {
1411
- const toEdge = (pts, x, y) => { let d = Infinity; for (let i = 0; i < pts.length; i++) { const a = pts[i], b = pts[(i + 1) % pts.length], dx = b.x - a.x, dy = b.y - a.y, l = dx * dx + dy * dy, t = l ? Math.max(0, Math.min(1, ((x - a.x) * dx + (y - a.y) * dy) / l)) : 0; d = Math.min(d, Math.hypot(x - a.x - t * dx, y - a.y - t * dy)); } return d; };
1412
1441
  const src = new Map(), past = new Set(), so = circuit.outline;
1413
1442
  if (!so) return null;
1414
1443
  for (const p of circuit.parts) {