copperflow 0.3.2 → 0.3.4

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.
Files changed (243) hide show
  1. package/README.md +39 -0
  2. package/dist/app/assets/{NewPartDialog-Qb7NwhBb.js → NewPartDialog-C4sKWnGI.js} +38 -38
  3. package/dist/app/assets/index-BgzJedaB.css +1 -0
  4. package/dist/app/assets/index-C_U9me2P.js +19 -0
  5. package/dist/app/index.html +2 -2
  6. package/dist/cli-commands.d.ts +3 -0
  7. package/dist/cli-commands.js +74 -8
  8. package/dist/cli-commands.js.map +1 -1
  9. package/dist/cli-library.d.ts +5 -0
  10. package/dist/cli-library.js +58 -0
  11. package/dist/cli-library.js.map +1 -0
  12. package/dist/cli-modules.d.ts +6 -0
  13. package/dist/cli-modules.js +33 -0
  14. package/dist/cli-modules.js.map +1 -0
  15. package/dist/cli-studio.d.ts +1 -0
  16. package/dist/cli-studio.js +27 -0
  17. package/dist/cli-studio.js.map +1 -0
  18. package/dist/core/board-import.d.ts +39 -0
  19. package/dist/core/board-import.js +114 -0
  20. package/dist/core/board-import.js.map +1 -0
  21. package/dist/core/board-shape-edit.d.ts +13 -0
  22. package/dist/core/board-shape-edit.js +134 -0
  23. package/dist/core/board-shape-edit.js.map +1 -0
  24. package/dist/core/edit.js +9 -3
  25. package/dist/core/edit.js.map +1 -1
  26. package/dist/core/fabrication.d.ts +6 -0
  27. package/dist/core/fabrication.js +1 -1
  28. package/dist/core/fabrication.js.map +1 -1
  29. package/dist/core/git.d.ts +16 -0
  30. package/dist/core/git.js +51 -0
  31. package/dist/core/git.js.map +1 -0
  32. package/dist/core/home.d.ts +2 -0
  33. package/dist/core/home.js +10 -0
  34. package/dist/core/home.js.map +1 -0
  35. package/dist/core/index.d.ts +2 -0
  36. package/dist/core/index.js +2 -0
  37. package/dist/core/index.js.map +1 -1
  38. package/dist/core/instance-copper.d.ts +25 -0
  39. package/dist/core/instance-copper.js +142 -0
  40. package/dist/core/instance-copper.js.map +1 -0
  41. package/dist/core/instance-move.d.ts +23 -0
  42. package/dist/core/instance-move.js +59 -0
  43. package/dist/core/instance-move.js.map +1 -0
  44. package/dist/core/instance-requests.d.ts +3 -2
  45. package/dist/core/instance-requests.js +17 -3
  46. package/dist/core/instance-requests.js.map +1 -1
  47. package/dist/core/library-modules.d.ts +29 -0
  48. package/dist/core/library-modules.js +324 -0
  49. package/dist/core/library-modules.js.map +1 -0
  50. package/dist/core/library-sources.d.ts +33 -0
  51. package/dist/core/library-sources.js +179 -0
  52. package/dist/core/library-sources.js.map +1 -0
  53. package/dist/core/modules.d.ts +44 -0
  54. package/dist/core/modules.js +284 -0
  55. package/dist/core/modules.js.map +1 -0
  56. package/dist/core/new-circuit-sheets.d.ts +11 -2
  57. package/dist/core/new-circuit-sheets.js +35 -6
  58. package/dist/core/new-circuit-sheets.js.map +1 -1
  59. package/dist/core/placement-write.d.ts +2 -0
  60. package/dist/core/placement-write.js +12 -6
  61. package/dist/core/placement-write.js.map +1 -1
  62. package/dist/core/plain-sheet.d.ts +12 -0
  63. package/dist/core/plain-sheet.js +169 -0
  64. package/dist/core/plain-sheet.js.map +1 -0
  65. package/dist/core/render.d.ts +45 -0
  66. package/dist/core/render.js +57 -0
  67. package/dist/core/render.js.map +1 -0
  68. package/dist/core/sheet-card.d.ts +33 -0
  69. package/dist/core/sheet-card.js +118 -0
  70. package/dist/core/sheet-card.js.map +1 -0
  71. package/dist/core/types.d.ts +20 -0
  72. package/dist/core/workspace.d.ts +4 -0
  73. package/dist/core/workspace.js +13 -2
  74. package/dist/core/workspace.js.map +1 -1
  75. package/dist/engine/checks/drc-parts.js +7 -7
  76. package/dist/engine/checks/drc-parts.js.map +1 -1
  77. package/dist/engine/checks/erc.js +35 -3
  78. package/dist/engine/checks/erc.js.map +1 -1
  79. package/dist/engine/component.d.ts +2 -0
  80. package/dist/engine/component.js +18 -1
  81. package/dist/engine/component.js.map +1 -1
  82. package/dist/engine/dxf/board.d.ts +42 -0
  83. package/dist/engine/dxf/board.js +218 -0
  84. package/dist/engine/dxf/board.js.map +1 -0
  85. package/dist/engine/dxf/index.d.ts +2 -0
  86. package/dist/engine/dxf/index.js +3 -0
  87. package/dist/engine/dxf/index.js.map +1 -0
  88. package/dist/engine/dxf/reader.d.ts +43 -0
  89. package/dist/engine/dxf/reader.js +142 -0
  90. package/dist/engine/dxf/reader.js.map +1 -0
  91. package/dist/engine/elaborate.js +14 -4
  92. package/dist/engine/elaborate.js.map +1 -1
  93. package/dist/engine/fab/designator-places.d.ts +101 -0
  94. package/dist/engine/fab/designator-places.js +259 -0
  95. package/dist/engine/fab/designator-places.js.map +1 -0
  96. package/dist/engine/fab/designators.d.ts +26 -14
  97. package/dist/engine/fab/designators.js +320 -70
  98. package/dist/engine/fab/designators.js.map +1 -1
  99. package/dist/engine/fab/layers.js +6 -6
  100. package/dist/engine/fab/layers.js.map +1 -1
  101. package/dist/engine/fab/stroke-font.d.ts +2 -2
  102. package/dist/engine/fab/stroke-font.js +7 -6
  103. package/dist/engine/fab/stroke-font.js.map +1 -1
  104. package/dist/engine/footprints/file.d.ts +33 -0
  105. package/dist/engine/footprints/file.js +13 -5
  106. package/dist/engine/footprints/file.js.map +1 -1
  107. package/dist/engine/model.d.ts +15 -1
  108. package/dist/engine/model.js.map +1 -1
  109. package/dist/engine/pcb-place/block-board.d.ts +9 -0
  110. package/dist/engine/pcb-place/block-board.js +256 -0
  111. package/dist/engine/pcb-place/block-board.js.map +1 -0
  112. package/dist/engine/pcb-place/blocks.d.ts +31 -6
  113. package/dist/engine/pcb-place/blocks.js +37 -8
  114. package/dist/engine/pcb-place/blocks.js.map +1 -1
  115. package/dist/engine/pcb-place/constructive.d.ts +3 -2
  116. package/dist/engine/pcb-place/constructive.js +14 -2
  117. package/dist/engine/pcb-place/constructive.js.map +1 -1
  118. package/dist/engine/pcb-place/index.d.ts +8 -0
  119. package/dist/engine/pcb-place/index.js +7 -0
  120. package/dist/engine/pcb-place/index.js.map +1 -1
  121. package/dist/engine/pcb-place/scope.js +6 -1
  122. package/dist/engine/pcb-place/scope.js.map +1 -1
  123. package/dist/engine/pcb.d.ts +6 -0
  124. package/dist/engine/pcb.js +12 -1
  125. package/dist/engine/pcb.js.map +1 -1
  126. package/dist/engine/router/replicate.js +4 -0
  127. package/dist/engine/router/replicate.js.map +1 -1
  128. package/dist/engine/router/route-board.d.ts +2 -0
  129. package/dist/engine/router/route-board.js +27 -1
  130. package/dist/engine/router/route-board.js.map +1 -1
  131. package/dist/engine/sheet-ports.d.ts +17 -1
  132. package/dist/engine/sheet-ports.js +38 -1
  133. package/dist/engine/sheet-ports.js.map +1 -1
  134. package/dist/mcp/batch.d.ts +2 -2
  135. package/dist/mcp/batch.js +12 -12
  136. package/dist/mcp/batch.js.map +1 -1
  137. package/dist/mcp/board-import-tool.d.ts +25 -0
  138. package/dist/mcp/board-import-tool.js +25 -0
  139. package/dist/mcp/board-import-tool.js.map +1 -0
  140. package/dist/mcp/board-summary.d.ts +1 -1
  141. package/dist/mcp/board-summary.js +1 -1
  142. package/dist/mcp/board-summary.js.map +1 -1
  143. package/dist/mcp/compact.js +17 -5
  144. package/dist/mcp/compact.js.map +1 -1
  145. package/dist/mcp/copper-tools.d.ts +4 -4
  146. package/dist/mcp/copper-tools.js +19 -19
  147. package/dist/mcp/copper-tools.js.map +1 -1
  148. package/dist/mcp/create-part.d.ts +4 -4
  149. package/dist/mcp/create-part.js +12 -10
  150. package/dist/mcp/create-part.js.map +1 -1
  151. package/dist/mcp/datasheet-tools.d.ts +1 -1
  152. package/dist/mcp/datasheet-tools.js +4 -4
  153. package/dist/mcp/datasheet-tools.js.map +1 -1
  154. package/dist/mcp/fillet-tools.d.ts +2 -2
  155. package/dist/mcp/fillet-tools.js +6 -6
  156. package/dist/mcp/fillet-tools.js.map +1 -1
  157. package/dist/mcp/guide.d.ts +1 -1
  158. package/dist/mcp/guide.js +4 -3
  159. package/dist/mcp/guide.js.map +1 -1
  160. package/dist/mcp/import-part.d.ts +1 -1
  161. package/dist/mcp/import-part.js +4 -4
  162. package/dist/mcp/import-part.js.map +1 -1
  163. package/dist/mcp/make-sheet.d.ts +1 -1
  164. package/dist/mcp/make-sheet.js +6 -6
  165. package/dist/mcp/make-sheet.js.map +1 -1
  166. package/dist/mcp/module-tools.d.ts +4 -0
  167. package/dist/mcp/module-tools.js +21 -0
  168. package/dist/mcp/module-tools.js.map +1 -0
  169. package/dist/mcp/new-circuit.d.ts +13 -2
  170. package/dist/mcp/new-circuit.js +30 -28
  171. package/dist/mcp/new-circuit.js.map +1 -1
  172. package/dist/mcp/open-studio.d.ts +30 -0
  173. package/dist/mcp/open-studio.js +97 -0
  174. package/dist/mcp/open-studio.js.map +1 -0
  175. package/dist/mcp/place-tools.d.ts +2 -2
  176. package/dist/mcp/place-tools.js +14 -11
  177. package/dist/mcp/place-tools.js.map +1 -1
  178. package/dist/mcp/pour-tools.d.ts +4 -4
  179. package/dist/mcp/pour-tools.js +18 -18
  180. package/dist/mcp/pour-tools.js.map +1 -1
  181. package/dist/mcp/project-tools.d.ts +3 -3
  182. package/dist/mcp/project-tools.js +8 -8
  183. package/dist/mcp/project-tools.js.map +1 -1
  184. package/dist/mcp/render-tool.d.ts +30 -0
  185. package/dist/mcp/render-tool.js +33 -0
  186. package/dist/mcp/render-tool.js.map +1 -0
  187. package/dist/mcp/route-tools.d.ts +2 -2
  188. package/dist/mcp/route-tools.js +10 -10
  189. package/dist/mcp/route-tools.js.map +1 -1
  190. package/dist/mcp/server.d.ts +3 -0
  191. package/dist/mcp/server.js +49 -31
  192. package/dist/mcp/server.js.map +1 -1
  193. package/dist/mcp/sheet-card-tools.d.ts +28 -0
  194. package/dist/mcp/sheet-card-tools.js +45 -0
  195. package/dist/mcp/sheet-card-tools.js.map +1 -0
  196. package/dist/render/render.js +2060 -0
  197. package/dist/studio/idle.d.ts +7 -0
  198. package/dist/studio/idle.js +34 -0
  199. package/dist/studio/idle.js.map +1 -0
  200. package/dist/studio/place-runner.js +1 -1
  201. package/dist/studio/place-runner.js.map +1 -1
  202. package/dist/studio/run-studio.d.ts +21 -0
  203. package/dist/studio/run-studio.js +68 -0
  204. package/dist/studio/run-studio.js.map +1 -0
  205. package/dist/studio/server.d.ts +5 -0
  206. package/dist/studio/server.js +24 -2
  207. package/dist/studio/server.js.map +1 -1
  208. package/dist/studio/studio-control.d.ts +6 -0
  209. package/dist/studio/studio-control.js +14 -0
  210. package/dist/studio/studio-control.js.map +1 -0
  211. package/dist/studio/studio-note.d.ts +33 -0
  212. package/dist/studio/studio-note.js +130 -0
  213. package/dist/studio/studio-note.js.map +1 -0
  214. package/dist/version.d.ts +1 -1
  215. package/dist/version.js +1 -1
  216. package/library/modules/CanNode/CanNode.sheet.tsx +65 -0
  217. package/library/modules/CanNode/module.json +4 -0
  218. package/library/modules/CanNode/parts/MCP2515-I-SO/MCP2515_I_SO.tsx +10 -0
  219. package/library/modules/CanNode/parts/MCP2515-I-SO/part.yaml +64 -0
  220. package/library/modules/CanNode/parts/MCP2515-I-SO/verification.md +42 -0
  221. package/library/modules/CanNode/parts/TJA1051T-3/TJA1051T_3.tsx +10 -0
  222. package/library/modules/CanNode/parts/TJA1051T-3/part.yaml +34 -0
  223. package/library/modules/CanNode/parts/TJA1051T-3/verification.md +28 -0
  224. package/library/modules/DigitalInput24V/DigitalInput24V.sheet.tsx +24 -0
  225. package/library/modules/DigitalInput24V/module.json +4 -0
  226. package/library/modules/RelayDriver/RelayDriver.sheet.tsx +39 -0
  227. package/library/modules/RelayDriver/module.json +4 -0
  228. package/library/modules/RelayDriver/parts/AO3400A/AO3400A.tsx +11 -0
  229. package/library/modules/RelayDriver/parts/AO3400A/part.yaml +21 -0
  230. package/library/modules/RelayDriver/parts/AO3400A/verification.md +24 -0
  231. package/library/modules/RelayDriver/parts/SRD-12VDC-SL-C/SRD_12VDC_SL_C.tsx +11 -0
  232. package/library/modules/RelayDriver/parts/SRD-12VDC-SL-C/footprint.yaml +70 -0
  233. package/library/modules/RelayDriver/parts/SRD-12VDC-SL-C/part.yaml +31 -0
  234. package/library/modules/RelayDriver/parts/SRD-12VDC-SL-C/verification.md +37 -0
  235. package/package.json +6 -2
  236. package/skills/copperflow/SKILL.md +20 -20
  237. package/skills/copperflow/references/copper.md +83 -6
  238. package/skills/copperflow/references/modules.md +80 -0
  239. package/skills/copperflow/references/planning.md +55 -11
  240. package/skills/copperflow/references/writing-circuits.md +29 -3
  241. package/skills/copperflow-plan/SKILL.md +7 -4
  242. package/dist/app/assets/index-CSWIIMFE.css +0 -1
  243. package/dist/app/assets/index-C_TXwo-N.js +0 -19
@@ -0,0 +1,2060 @@
1
+ // studio/src/pcb/ctx.ts
2
+ var HIGHLIGHT_DIM = 0.3;
3
+ var PCB_DIM = 0.5;
4
+ var UI_FONT_STACK = '"Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Helvetica Neue", sans-serif';
5
+ var CANVAS_FONT_FAMILY = UI_FONT_STACK;
6
+ var CANVAS_MONO_FAMILY = '"Cascadia Mono", "JetBrains Mono", ui-monospace, Consolas, monospace';
7
+ var TEXT_WEIGHT = { strong: 600, regular: 400 };
8
+ var canvasFont = (weight, px, family = CANVAS_FONT_FAMILY) => `${weight} ${px}px ${family}`;
9
+ var PALETTE = {
10
+ background: "#000000",
11
+ boardEdge: "#ff00ff",
12
+ topCopper: "#ff0000",
13
+ bottomCopper: "#0000ff",
14
+ /** The inner copper layers of a 4-layer board, which draw only their pours so far. */
15
+ inner1Copper: "#cc9933",
16
+ inner2Copper: "#9966cc",
17
+ /** Pads of plated through-holes and via rings. */
18
+ multiLayer: "#c0c0c0",
19
+ viaRing: "#c0c0c0",
20
+ /** A highlighted net, drawn in white over its layer colour. */
21
+ highlight: "#ffffff",
22
+ drill: "#222222",
23
+ topSilk: "#ffcc00",
24
+ bottomSilk: "#66cc33",
25
+ /** Courtyards and fabrication outlines follow the assembly layers. */
26
+ topAssembly: "#33cc99",
27
+ bottomAssembly: "#5555ff",
28
+ ratsnest: "#6464ff",
29
+ keepout: "#f022f0",
30
+ /** The document layer: our notes for the agent and the lock badges. */
31
+ document: "#ffffff",
32
+ /** The grid: white at 30% on minor lines and crossings, 50% on every fifth. */
33
+ grid: "rgb(255 255 255 / 30%)",
34
+ gridFifth: "rgb(255 255 255 / 50%)",
35
+ /** The selection outline and its wash, and the dashed hover outline. */
36
+ selection: "#ffffff",
37
+ selectionFill: "rgb(255 255 255 / 50%)",
38
+ hover: "rgb(255 255 255 / 60%)",
39
+ /** The selection box, dotted, and its wash. */
40
+ selectionBox: "#00ffff",
41
+ selectionBoxFill: "rgb(0 255 255 / 10%)",
42
+ /** Behind a note's text, so it reads over copper. */
43
+ notePanel: "rgb(0 0 0 / 80%)",
44
+ /** Violation markers, on both canvases. */
45
+ error: "#e5534b",
46
+ warning: "#e0a63a",
47
+ /** The halos just outside and just inside a violation ring, on the PCB only. */
48
+ ringHaloOuter: "#ffffff",
49
+ ringHaloInner: "#000000"
50
+ };
51
+ function anchorAlignment(anchor) {
52
+ const parts = anchor.split("_");
53
+ const vertical = parts.includes("top") ? "top" : parts.includes("bottom") ? "bottom" : "middle";
54
+ const horizontal = parts.includes("left") ? "left" : parts.includes("right") ? "right" : "center";
55
+ return [vertical, horizontal];
56
+ }
57
+
58
+ // src/engine/order.ts
59
+ var collator = new Intl.Collator("en", { numeric: true });
60
+
61
+ // src/engine/checks/geometry.ts
62
+ var DEG = Math.PI / 180;
63
+
64
+ // src/engine/fab/stroke-font.ts
65
+ var GLYPH_WIDTH = 4;
66
+ var GLYPH_HEIGHT = 6;
67
+ var ADVANCE = 6;
68
+ function textWidth(text2, height) {
69
+ const count = [...text2].length;
70
+ return count === 0 ? 0 : ((count - 1) * ADVANCE + GLYPH_WIDTH) * height / GLYPH_HEIGHT;
71
+ }
72
+
73
+ // src/engine/fab/designator-places.ts
74
+ var SILK_WIDTH = 0.15;
75
+ var DESIGNATOR_HEIGHT = 1;
76
+ var RINGS = [0, 0.4, 0.8, 1.2, 1.6];
77
+ var SLIDE_STEP = 0.5;
78
+ var MAX_SLIDES = 4;
79
+ function boxOf(points) {
80
+ const xs = points.map((c) => c.x);
81
+ const ys = points.map((c) => c.y);
82
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) };
83
+ }
84
+ function slides(half, textHalf) {
85
+ const end = Math.abs(half - textHalf);
86
+ const reach = Math.max(half, end);
87
+ const step = Math.max(SLIDE_STEP, reach / MAX_SLIDES);
88
+ const steps = Array.from({ length: Math.floor(reach / step) }, (_, i) => (i + 1) * step);
89
+ const all = [0, end, half, ...steps].flatMap((v) => [-v, v]).map((v) => Math.round(v * 1e6) / 1e6 + 0);
90
+ return [...new Set(all)];
91
+ }
92
+ function placesAround(part, clearance, turn) {
93
+ if (turn !== void 0) return sidePlaces(part, clearance, () => turn);
94
+ return [...sidePlaces(part, clearance, (flat) => flat ? 0 : 90), ...sidePlaces(part, clearance, (flat) => flat ? 90 : 0)];
95
+ }
96
+ function sidePlaces(part, clearance, turnFor) {
97
+ if (part.courtyard.length === 0) return [{ at: { x: part.x, y: part.y }, rotation: turnFor(true) }];
98
+ const box = boxOf(part.courtyard);
99
+ const [cx, cy] = [(box.minX + box.maxX) / 2, (box.minY + box.maxY) / 2];
100
+ const [halfW, halfH] = [(box.maxX - box.minX) / 2, (box.maxY - box.minY) / 2];
101
+ const long = textWidth(part.component, DESIGNATOR_HEIGHT) / 2 + SILK_WIDTH / 2;
102
+ const short = DESIGNATOR_HEIGHT / 2 + SILK_WIDTH / 2;
103
+ const found = [];
104
+ const along = { flat: slides(halfW, turnFor(true) === 0 ? long : short), upright: slides(halfH, turnFor(false) === 0 ? short : long) };
105
+ for (const ring2 of RINGS) {
106
+ const gap = clearance + ring2;
107
+ for (const side of ["top", "bottom", "left", "right"]) {
108
+ const flat = side === "top" || side === "bottom";
109
+ const rotation = turnFor(flat);
110
+ const [alongHalf, acrossHalf] = rotation === 0 === flat ? [long, short] : [short, long];
111
+ if (flat) {
112
+ const top = side === "top";
113
+ const y = top ? box.maxY + gap + acrossHalf : box.minY - gap - acrossHalf;
114
+ const [low, high] = top ? [box.maxY, y + acrossHalf] : [y - acrossHalf, box.minY];
115
+ for (const dx of along.flat) {
116
+ found.push({ at: { x: cx + dx, y }, rotation, reach: { minX: cx + dx - alongHalf, maxX: cx + dx + alongHalf, minY: low, maxY: high } });
117
+ }
118
+ } else {
119
+ const right = side === "right";
120
+ const x = right ? box.maxX + gap + acrossHalf : box.minX - gap - acrossHalf;
121
+ const [low, high] = right ? [box.maxX, x + acrossHalf] : [x - acrossHalf, box.minX];
122
+ for (const dy of along.upright) {
123
+ found.push({ at: { x, y: cy + dy }, rotation, reach: { minX: low, maxX: high, minY: cy + dy - alongHalf, maxY: cy + dy + alongHalf } });
124
+ }
125
+ }
126
+ }
127
+ }
128
+ const distance = (p) => Math.round(Math.hypot(p.at.x - cx, p.at.y - cy) * 1e3);
129
+ return found.map((place3, i) => ({ place: place3, i, d: distance(place3) })).sort((a, b) => a.d - b.d || a.i - b.i).map((entry) => entry.place);
130
+ }
131
+
132
+ // src/engine/fab/designators.ts
133
+ var DEFAULT_SILK_CLEARANCE = 0.15;
134
+ var designatorAnchor = (part) => part.nameAt ?? part.designatorAt ?? (placesAround(part, DEFAULT_SILK_CLEARANCE, 0).find((p) => p.at.y > part.y)?.at ?? { x: part.x, y: part.y });
135
+ var designatorTurn = (part) => (part.nameAt ? part.nameRotation : void 0) ?? part.designatorRotation ?? part.nameRotation ?? 0;
136
+
137
+ // studio/src/pcb/geometry.ts
138
+ var MIN_SCALE = 0.5;
139
+ var MAX_SCALE = 2e3;
140
+ function worldToScreen(camera, size, p) {
141
+ return { x: (p.x - camera.cx) * camera.scale + size.width / 2, y: -(p.y - camera.cy) * camera.scale + size.height / 2 };
142
+ }
143
+ function fitCamera(box, size, margin = 0.12) {
144
+ const width = Math.max(box.maxX - box.minX, 1);
145
+ const height = Math.max(box.maxY - box.minY, 1);
146
+ const scale = Math.min(size.width / width, size.height / height) * (1 - 2 * margin);
147
+ return { cx: (box.minX + box.maxX) / 2, cy: (box.minY + box.maxY) / 2, scale: clampScale(scale) };
148
+ }
149
+ function pointBounds(points) {
150
+ if (points.length === 0) return void 0;
151
+ const xs = points.map((p) => p.x);
152
+ const ys = points.map((p) => p.y);
153
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) };
154
+ }
155
+ function unionBoxes(boxes) {
156
+ return pointBounds(boxes.flatMap((b) => [{ x: b.minX, y: b.minY }, { x: b.maxX, y: b.maxY }]));
157
+ }
158
+ function clampScale(scale) {
159
+ return Math.min(MAX_SCALE, Math.max(MIN_SCALE, scale));
160
+ }
161
+
162
+ // studio/src/pcb/layers.ts
163
+ var LAYER_IDS = ["top", "bottom", "topSilk", "bottomSilk", "topAssembly", "bottomAssembly", "courtyard", "boardOutline", "multiLayer", "hole", "ratline", "keepout"];
164
+ var LAYER_ROWS = [
165
+ { id: "top", name: "Top Layer", group: "copper", color: PALETTE.topCopper },
166
+ { id: "bottom", name: "Bottom Layer", group: "copper", color: PALETTE.bottomCopper },
167
+ { id: "topSilk", name: "Top Silkscreen", group: "non-copper", color: PALETTE.topSilk },
168
+ { id: "bottomSilk", name: "Bottom Silkscreen", group: "non-copper", color: PALETTE.bottomSilk },
169
+ { id: "topAssembly", name: "Top Assembly", group: "non-copper", color: PALETTE.topAssembly },
170
+ { id: "bottomAssembly", name: "Bottom Assembly", group: "non-copper", color: PALETTE.bottomAssembly },
171
+ { id: "courtyard", name: "Courtyard", group: "non-copper", color: PALETTE.topAssembly, bottomColor: PALETTE.bottomAssembly },
172
+ { id: "boardOutline", name: "Board Outline", group: "non-copper", color: PALETTE.boardEdge },
173
+ { id: "multiLayer", name: "Multi-Layer", group: "copper", color: PALETTE.multiLayer },
174
+ { id: "hole", name: "Hole", group: "non-copper", color: PALETTE.drill },
175
+ { id: "ratline", name: "Ratline", group: "non-copper", color: PALETTE.ratsnest },
176
+ { id: "keepout", name: "Keepout", group: "non-copper", color: PALETTE.keepout }
177
+ ];
178
+ var DEFAULT_LAYERS = {
179
+ ...Object.fromEntries(LAYER_IDS.map((id) => [id, true])),
180
+ topAssembly: false,
181
+ bottomAssembly: false
182
+ };
183
+
184
+ // studio/src/selection.ts
185
+ var unique = (items) => [...new Set(items)];
186
+ var sameList = (a, b) => a.length === b.length && a.every((item, i) => item === b[i]);
187
+ var less = (items, taken) => items.filter((item) => !taken.includes(item));
188
+ var among = (items, kept) => {
189
+ const set = new Set(kept);
190
+ return items.filter((item) => set.has(item));
191
+ };
192
+ var sameEnd = (a, b) => a !== void 0 && a.x === b.x && a.y === b.y;
193
+ var sameSegment = (a, b) => a !== void 0 && a.id === b.id && a.index === b.index && sameEnd(a.from, b.from) && sameEnd(a.to, b.to);
194
+ function segmentFits(segment, points) {
195
+ return sameEnd(points[segment.index], segment.from) && sameEnd(points[segment.index + 1], segment.to);
196
+ }
197
+ var EMPTY = { names: [], wires: [], labels: [], drawings: [], copper: [], texts: [], board: [] };
198
+ var KEYS = ["names", "wires", "labels", "drawings", "copper", "texts", "board"];
199
+ var Selection = class _Selection {
200
+ /** Nothing selected. */
201
+ static none = new _Selection(EMPTY);
202
+ /** The part names, each once, oldest pick first. */
203
+ names;
204
+ /** The schematic wires, by their ids in the sheet's layout, each once, oldest pick first. */
205
+ wires;
206
+ /** The net labels and ground or power flags on the schematic, by their ids in the sheet's layout, oldest pick first. */
207
+ labels;
208
+ /** The schematic drawings (lines, shapes, texts and buses), by their ids in the sheet's layout, oldest pick first. */
209
+ drawings;
210
+ /** The PCB's tracks and vias, by their ids in the layout file (`t0001`, `v0001`), oldest pick first. */
211
+ copper;
212
+ /** Parts' names and values on the schematic and designators on the silkscreen, as "<part>:<prop>" ("R1:schNameAt"), oldest pick first. */
213
+ texts;
214
+ /** The PCB's copper pours and holes, by the ids the engine gives them (`copperpour:1`, `hole:1`), oldest pick first. */
215
+ board;
216
+ /** The segment of the track selected alone that a double click picked; undefined when the whole track (or anything else) is. */
217
+ segment;
218
+ constructor(lists, segment) {
219
+ this.names = Object.freeze([...lists.names]);
220
+ this.wires = Object.freeze([...lists.wires]);
221
+ this.labels = Object.freeze([...lists.labels]);
222
+ this.drawings = Object.freeze([...lists.drawings]);
223
+ this.copper = Object.freeze([...lists.copper]);
224
+ this.texts = Object.freeze([...lists.texts]);
225
+ this.board = Object.freeze([...lists.board]);
226
+ this.segment = segment && Object.freeze({ id: segment.id, index: segment.index, from: Object.freeze({ ...segment.from }), to: Object.freeze({ ...segment.to }) });
227
+ Object.freeze(this);
228
+ }
229
+ static from(lists) {
230
+ return KEYS.every((key) => lists[key].length === 0) ? _Selection.none : new _Selection(lists);
231
+ }
232
+ get lists() {
233
+ return { names: this.names, wires: this.wires, labels: this.labels, drawings: this.drawings, copper: this.copper, texts: this.texts, board: this.board };
234
+ }
235
+ /** This selection with some lists changed: itself when every list kept its length (lists are only ever shortened or kept here). */
236
+ with(changed) {
237
+ const next = { ...this.lists, ...changed };
238
+ return KEYS.every((key) => next[key].length === this[key].length) ? this : _Selection.from(next);
239
+ }
240
+ /** A new selection with some lists changed (grown). */
241
+ grown(changed) {
242
+ return new _Selection({ ...this.lists, ...changed });
243
+ }
244
+ /** The part picked last, or undefined when no part is selected. */
245
+ get primary() {
246
+ return this.names.at(-1);
247
+ }
248
+ /** How many parts are selected. */
249
+ get size() {
250
+ return this.names.length;
251
+ }
252
+ get wireCount() {
253
+ return this.wires.length;
254
+ }
255
+ get labelCount() {
256
+ return this.labels.length;
257
+ }
258
+ get drawingCount() {
259
+ return this.drawings.length;
260
+ }
261
+ get copperCount() {
262
+ return this.copper.length;
263
+ }
264
+ get textCount() {
265
+ return this.texts.length;
266
+ }
267
+ /** How many copper pours and holes are selected. */
268
+ get boardCount() {
269
+ return this.board.length;
270
+ }
271
+ /** Every object selected: the parts, the wires, the labels, the drawings, the copper, the names and values, the pours and holes. */
272
+ get total() {
273
+ return this.names.length + this.wires.length + this.labels.length + this.drawings.length + this.copper.length + this.texts.length + this.board.length;
274
+ }
275
+ /** The pour or hole when it is all that is selected: the one Properties shows and whose outline has handles. */
276
+ get soleBoard() {
277
+ return this.total === 1 ? this.board[0] : void 0;
278
+ }
279
+ /** The name, value or designator when it is all that is selected: the one Properties, the arrows and a drag move. */
280
+ get soleText() {
281
+ return this.total === 1 ? this.texts[0] : void 0;
282
+ }
283
+ /** The track or via when it is all that is selected: the one Properties shows the rows of. */
284
+ get soleCopper() {
285
+ return this.total === 1 ? this.copper[0] : void 0;
286
+ }
287
+ /** The wire when it is all that is selected (one wire, nothing else): the one its handles, reshaping and Wire section are for. */
288
+ get soleWire() {
289
+ return this.total === 1 ? this.wires[0] : void 0;
290
+ }
291
+ /** The label when it is all that is selected: the one Properties shows the rows of. */
292
+ get soleLabel() {
293
+ return this.total === 1 ? this.labels[0] : void 0;
294
+ }
295
+ /** The drawing when it is all that is selected: the one Properties shows the fields of. */
296
+ get soleDrawing() {
297
+ return this.total === 1 ? this.drawings[0] : void 0;
298
+ }
299
+ has(name) {
300
+ return this.names.includes(name);
301
+ }
302
+ hasWire(id) {
303
+ return this.wires.includes(id);
304
+ }
305
+ hasLabel(id) {
306
+ return this.labels.includes(id);
307
+ }
308
+ hasDrawing(id) {
309
+ return this.drawings.includes(id);
310
+ }
311
+ hasCopper(id) {
312
+ return this.copper.includes(id);
313
+ }
314
+ hasText(id) {
315
+ return this.texts.includes(id);
316
+ }
317
+ hasBoard(id) {
318
+ return this.board.includes(id);
319
+ }
320
+ /** Just this pour or hole. */
321
+ onlyBoard(id) {
322
+ return this.soleBoard === id ? this : new _Selection({ ...EMPTY, board: [id] });
323
+ }
324
+ /** The pour or hole taken out when it is in, else added after the others; the other kinds stay. */
325
+ toggleBoard(id) {
326
+ return this.hasBoard(id) ? this.withoutBoard([id]) : this.grown({ board: [...this.board, id] });
327
+ }
328
+ /** The pours and holes not in yet, added in order. */
329
+ addBoard(ids) {
330
+ const fresh = unique(ids).filter((id) => !this.hasBoard(id));
331
+ return fresh.length === 0 ? this : this.grown({ board: [...this.board, ...fresh] });
332
+ }
333
+ /** The selection less these pours and holes. */
334
+ withoutBoard(ids) {
335
+ return this.with({ board: less(this.board, ids) });
336
+ }
337
+ /** Only the selected pours and holes that are among these, such as those the board still has. */
338
+ keepBoard(ids) {
339
+ return this.with({ board: among(this.board, ids) });
340
+ }
341
+ /** Just this part. */
342
+ only(name) {
343
+ return this.total === 1 && this.names[0] === name ? this : new _Selection({ ...EMPTY, names: [name] });
344
+ }
345
+ /** Just this wire. */
346
+ onlyWire(id) {
347
+ return this.soleWire === id ? this : new _Selection({ ...EMPTY, wires: [id] });
348
+ }
349
+ /** Just this label. */
350
+ onlyLabel(id) {
351
+ return this.soleLabel === id ? this : new _Selection({ ...EMPTY, labels: [id] });
352
+ }
353
+ /** Just this drawing. */
354
+ onlyDrawing(id) {
355
+ return this.soleDrawing === id ? this : new _Selection({ ...EMPTY, drawings: [id] });
356
+ }
357
+ /** Just this name, value or designator. */
358
+ onlyText(id) {
359
+ return this.soleText === id ? this : new _Selection({ ...EMPTY, texts: [id] });
360
+ }
361
+ /** Just this track or via, the whole track even when one of its segments was selected. */
362
+ onlyCopper(id) {
363
+ return this.soleCopper === id && !this.segment ? this : new _Selection({ ...EMPTY, copper: [id] });
364
+ }
365
+ /** Just this segment of its track. */
366
+ onlySegment(segment) {
367
+ return sameSegment(this.segment, segment) ? this : new _Selection({ ...EMPTY, copper: [segment.id] }, segment);
368
+ }
369
+ /** The part taken out when it is in, else added as the primary; the other kinds stay. */
370
+ toggle(name) {
371
+ return this.has(name) ? this.without([name]) : this.grown({ names: [...this.names, name] });
372
+ }
373
+ /** The wire taken out when it is in, else added after the others; the other kinds stay. */
374
+ toggleWire(id) {
375
+ return this.hasWire(id) ? this.withoutWires([id]) : this.grown({ wires: [...this.wires, id] });
376
+ }
377
+ /** The label taken out when it is in, else added after the others; the other kinds stay. */
378
+ toggleLabel(id) {
379
+ return this.hasLabel(id) ? this.withoutLabels([id]) : this.grown({ labels: [...this.labels, id] });
380
+ }
381
+ /** The drawing taken out when it is in, else added after the others; the other kinds stay. */
382
+ toggleDrawing(id) {
383
+ return this.hasDrawing(id) ? this.withoutDrawings([id]) : this.grown({ drawings: [...this.drawings, id] });
384
+ }
385
+ /** The track or via taken out when it is in, else added after the others; the other kinds stay. */
386
+ toggleCopper(id) {
387
+ return this.hasCopper(id) ? this.withoutCopper([id]) : this.grown({ copper: [...this.copper, id] });
388
+ }
389
+ /** The name, value or designator taken out when it is in, else added after the others; the other kinds stay. */
390
+ toggleText(id) {
391
+ return this.hasText(id) ? this.with({ texts: less(this.texts, [id]) }) : this.grown({ texts: [...this.texts, id] });
392
+ }
393
+ /** The parts not in yet, added in order; the ones already in stay where they are. */
394
+ add(names) {
395
+ const fresh = unique(names).filter((name) => !this.has(name));
396
+ return fresh.length === 0 ? this : this.grown({ names: [...this.names, ...fresh] });
397
+ }
398
+ /** The wires not in yet, added in order. */
399
+ addWires(ids) {
400
+ const fresh = unique(ids).filter((id) => !this.hasWire(id));
401
+ return fresh.length === 0 ? this : this.grown({ wires: [...this.wires, ...fresh] });
402
+ }
403
+ /** The labels not in yet, added in order. */
404
+ addLabels(ids) {
405
+ const fresh = unique(ids).filter((id) => !this.hasLabel(id));
406
+ return fresh.length === 0 ? this : this.grown({ labels: [...this.labels, ...fresh] });
407
+ }
408
+ /** The drawings not in yet, added in order. */
409
+ addDrawings(ids) {
410
+ const fresh = unique(ids).filter((id) => !this.hasDrawing(id));
411
+ return fresh.length === 0 ? this : this.grown({ drawings: [...this.drawings, ...fresh] });
412
+ }
413
+ /** The tracks and vias not in yet, added in order. */
414
+ addCopper(ids) {
415
+ const fresh = unique(ids).filter((id) => !this.hasCopper(id));
416
+ return fresh.length === 0 ? this : this.grown({ copper: [...this.copper, ...fresh] });
417
+ }
418
+ clear() {
419
+ return _Selection.none;
420
+ }
421
+ /** Every one of these parts, wires, labels, drawings and tracks or vias, each once, and nothing else (no name or value). */
422
+ all(names, wires = [], labels = [], drawings = [], copper = []) {
423
+ const next = { names: unique(names), wires: unique(wires), labels: unique(labels), drawings: unique(drawings), copper: unique(copper), texts: [], board: [] };
424
+ return KEYS.every((key) => sameList(next[key], this[key])) ? this : _Selection.from(next);
425
+ }
426
+ /** The selection less these parts. */
427
+ without(names) {
428
+ return this.with({ names: less(this.names, names) });
429
+ }
430
+ /** The selection less these wires. */
431
+ withoutWires(ids) {
432
+ return this.with({ wires: less(this.wires, ids) });
433
+ }
434
+ /** The selection less these labels. */
435
+ withoutLabels(ids) {
436
+ return this.with({ labels: less(this.labels, ids) });
437
+ }
438
+ /** The selection less these drawings. */
439
+ withoutDrawings(ids) {
440
+ return this.with({ drawings: less(this.drawings, ids) });
441
+ }
442
+ /** The selection less these tracks and vias. */
443
+ withoutCopper(ids) {
444
+ return this.with({ copper: less(this.copper, ids) });
445
+ }
446
+ /** Only the selected parts that are among these, such as the parts the circuit still has. */
447
+ keep(names) {
448
+ return this.with({ names: among(this.names, names) });
449
+ }
450
+ /** Only the selected wires that are among these, such as the wires the sheet still draws (deleted or undone ones go). */
451
+ keepWires(ids) {
452
+ return this.with({ wires: among(this.wires, ids) });
453
+ }
454
+ /** Only the selected labels that are among these, such as the labels the sheet still draws. */
455
+ keepLabels(ids) {
456
+ return this.with({ labels: among(this.labels, ids) });
457
+ }
458
+ /** Only the selected drawings that are among these, such as the drawings the sheet still draws. */
459
+ keepDrawings(ids) {
460
+ return this.with({ drawings: among(this.drawings, ids) });
461
+ }
462
+ /** The selection less these names, values and designators. */
463
+ withoutTexts(ids) {
464
+ return this.with({ texts: less(this.texts, ids) });
465
+ }
466
+ /** Only the selected names, values and designators that are among these, such as those of the parts still drawn. */
467
+ keepTexts(ids) {
468
+ return this.with({ texts: among(this.texts, ids) });
469
+ }
470
+ /** Only the selected tracks and vias that are among these, such as those the layout file still has. */
471
+ keepCopper(ids) {
472
+ return this.with({ copper: among(this.copper, ids) });
473
+ }
474
+ };
475
+
476
+ // src/engine/symbols/types.ts
477
+ var TEXT_SIZE = { reference: 0.16, value: 0.16, "pin-name": 0.12, "pin-number": 0.1 };
478
+ var CHAR_WIDTH = 0.6;
479
+ var clean = (value) => Math.round(value * 1e6) / 1e6;
480
+ var pt = (x, y) => ({ x: clean(x), y: clean(y) });
481
+ var line = (...points) => ({ type: "polyline", points: points.map(([x, y]) => pt(x, y)) });
482
+ function text(value, at, anchor, role) {
483
+ return { type: "text", text: value, at, anchor, size: TEXT_SIZE[role], role };
484
+ }
485
+ function textExtent(shape) {
486
+ const width = CHAR_WIDTH * shape.size * shape.text.length;
487
+ const minX = shape.anchor === "left" ? shape.at.x : shape.anchor === "right" ? shape.at.x - width : shape.at.x - width / 2;
488
+ return { minX, maxX: minX + width, minY: shape.at.y - shape.size / 2, maxY: shape.at.y + shape.size / 2 };
489
+ }
490
+ function shapeExtent(shape) {
491
+ if (shape.type === "text") return textExtent(shape);
492
+ if (shape.type === "polyline") {
493
+ const xs = shape.points.map((p) => p.x);
494
+ const ys = shape.points.map((p) => p.y);
495
+ return { minX: Math.min(...xs), maxX: Math.max(...xs), minY: Math.min(...ys), maxY: Math.max(...ys) };
496
+ }
497
+ const { center, radius } = shape;
498
+ return { minX: center.x - radius, maxX: center.x + radius, minY: center.y - radius, maxY: center.y + radius };
499
+ }
500
+ function boundsOf(shapes, pins) {
501
+ const boxes = [...shapes.map(shapeExtent), ...pins.map((pin) => ({ minX: pin.end.x, maxX: pin.end.x, minY: pin.end.y, maxY: pin.end.y }))];
502
+ if (boxes.length === 0) return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
503
+ return {
504
+ minX: clean(Math.min(...boxes.map((b) => b.minX))),
505
+ minY: clean(Math.min(...boxes.map((b) => b.minY))),
506
+ maxX: clean(Math.max(...boxes.map((b) => b.maxX))),
507
+ maxY: clean(Math.max(...boxes.map((b) => b.maxY)))
508
+ };
509
+ }
510
+ var place = (x, y, side) => ({ end: pt(x, y), side });
511
+
512
+ // src/engine/symbols/passives.ts
513
+ var TWO_PIN = { 1: place(-0.5, 0, "left"), 2: place(0.5, 0, "right") };
514
+
515
+ // src/engine/symbols/semis.ts
516
+ var TWO_PIN2 = { 1: place(-0.5, 0, "left"), 2: place(0.5, 0, "right") };
517
+ var BASE_PLACES = { 1: place(-0.5, 0, "left"), 2: place(0.3, -0.5, "bottom"), 3: place(0.3, 0.5, "top") };
518
+
519
+ // src/engine/symbols/power.ts
520
+ function groundSymbol() {
521
+ return [line([0, 0], [0, -0.1]), line([-0.15, -0.1], [0.15, -0.1]), line([-0.1, -0.15], [0.1, -0.15]), line([-0.05, -0.2], [0.05, -0.2])];
522
+ }
523
+ function powerSymbol(name) {
524
+ return [line([0, 0], [0, 0.1]), line([-0.1, 0.1], [0.1, 0.1]), text(name, pt(0, 0.2), "center", "value")];
525
+ }
526
+
527
+ // studio/src/pcb/label-tag.ts
528
+ var NET_LABEL_TEXT = 0.16;
529
+ var TAG_THICKNESS = NET_LABEL_TEXT * 1.5;
530
+ var TAG_CHAR = 0.66;
531
+ var OUTWARD = { right: { x: 1, y: 0 }, left: { x: -1, y: 0 }, top: { x: 0, y: 1 }, bottom: { x: 0, y: -1 } };
532
+ function labelTag(label) {
533
+ const out = OUTWARD[label.side];
534
+ const length = label.text.length * NET_LABEL_TEXT * TAG_CHAR + TAG_THICKNESS;
535
+ const upright = out.x === 0;
536
+ const middle = { x: label.at.x + out.x * length / 2, y: label.at.y + out.y * length / 2 };
537
+ const [w, h] = upright ? [TAG_THICKNESS, length] : [length, TAG_THICKNESS];
538
+ return { middle, upright, box: { minX: middle.x - w / 2, minY: middle.y - h / 2, maxX: middle.x + w / 2, maxY: middle.y + h / 2 } };
539
+ }
540
+
541
+ // studio/src/pcb/markers.ts
542
+ var PCB_RINGS = { error: PALETTE.error, warning: PALETTE.warning };
543
+ var RING_PX = 6;
544
+ var RING_WIDTH_PX = 1.5;
545
+ var ACTIVE_WIDTH_PX = 3;
546
+ var HALO_PX = 1;
547
+ function drawViolationMarkers(ctx, view, markers, active, halo, colours = PCB_RINGS) {
548
+ if (markers.length === 0) return;
549
+ ctx.globalAlpha = 1;
550
+ ctx.setLineDash([]);
551
+ for (const marker of markers) {
552
+ const p = worldToScreen(view.camera, view.size, marker.at);
553
+ const width = marker.id === active ? ACTIVE_WIDTH_PX : RING_WIDTH_PX;
554
+ if (halo) ringHalos(ctx, p, width);
555
+ ctx.strokeStyle = marker.severity === "error" ? colours.error : colours.warning;
556
+ ring(ctx, p, RING_PX, width);
557
+ }
558
+ }
559
+ function ring(ctx, p, radius, width) {
560
+ ctx.lineWidth = width;
561
+ ctx.beginPath();
562
+ ctx.arc(p.x, p.y, radius, 0, Math.PI * 2);
563
+ ctx.stroke();
564
+ }
565
+ function ringHalos(ctx, p, width) {
566
+ const edge = (width + HALO_PX) / 2;
567
+ ctx.strokeStyle = PALETTE.ringHaloOuter;
568
+ ring(ctx, p, RING_PX + edge, HALO_PX);
569
+ ctx.strokeStyle = PALETTE.ringHaloInner;
570
+ ring(ctx, p, RING_PX - edge, HALO_PX);
571
+ }
572
+
573
+ // studio/src/pcb/schematic-theme.ts
574
+ var schematicTheme = {
575
+ background: "#FFFCF8",
576
+ grid: "#F0F0EB",
577
+ wire: "#008800",
578
+ bus: "#008800",
579
+ /** Lines, shapes and texts drawn on the sheet (Place → Polyline, Rectangle, …) unless they give their own colour. */
580
+ drawing: "#000080",
581
+ junction: "#CC0000",
582
+ /** Symbol outlines; symbols have no fill. */
583
+ symbolOutline: "#A00000",
584
+ pin: "#880000",
585
+ pinName: "#000000",
586
+ pinNumber: "#000000",
587
+ designator: "#0000FF",
588
+ netName: "#0000FF",
589
+ /** Values and other properties. */
590
+ value: "#000080",
591
+ noConnect: "#33CC33",
592
+ selection: "#FF0000",
593
+ highlight: "#FF9933",
594
+ border: "#A00000",
595
+ titleText: "#000080",
596
+ // Not in the table: they have to read on the light sheet.
597
+ /** The grid's dots, darker than its lines: lone dots in the line colour (about 1.1:1) look like no grid. */
598
+ gridDot: "#D9D9D2",
599
+ /** The flags are drawn in the symbol colour, the violation rings in the PCB's, and nothing glows. */
600
+ flag: "#A00000",
601
+ markerError: PALETTE.error,
602
+ markerWarning: PALETTE.warning,
603
+ selectionGlow: 0,
604
+ /** Outline of the part, label or wire under the pointer. */
605
+ hover: "rgb(255 0 0 / 45%)",
606
+ /** Fill of the square handles on a selected wire's corners; they are outlined in the selection colour. */
607
+ handleFill: "#FFFFFF",
608
+ /** Fill of the note box drawn with Place → Note box. */
609
+ selectionFill: "rgb(255 0 0 / 8%)",
610
+ /** The selection box dragged on the sheet: blue, as EasyEDA draws it, and its wash. */
611
+ selectionBox: "#0000FF",
612
+ selectionBoxFill: "rgb(0 0 255 / 8%)",
613
+ /** The lock badge's ground and its padlock. */
614
+ lockBadge: "#4f9a6c",
615
+ lockGlyph: "#ffffff",
616
+ /** A note for the agent: its pin and leader, the panel behind its text, and the text. */
617
+ notePin: "#e0a46a",
618
+ notePanel: "rgb(34 38 44 / 92%)",
619
+ noteText: "#e9e6df"
620
+ };
621
+ var darkSchematicTheme = {
622
+ background: "#141619",
623
+ grid: "#2B3038",
624
+ gridDot: "#2B3038",
625
+ gridFifth: "#3A4049",
626
+ wire: "#5BD3C7",
627
+ bus: "#8AB4FF",
628
+ drawing: "#9AA1A9",
629
+ junction: "#5BD3C7",
630
+ symbolOutline: "#D9DEE5",
631
+ pin: "#D9DEE5",
632
+ pinName: "#AEB6C0",
633
+ pinNumber: "#7E8792",
634
+ designator: "#E6E8EB",
635
+ netName: "#F2C66D",
636
+ value: "#AEB6C0",
637
+ noConnect: "#5BD3C7",
638
+ selection: "#4CC9F0",
639
+ /** A highlighted net, in the copper accent. */
640
+ highlight: "#E89A4F",
641
+ border: "#9AA1A9",
642
+ titleText: "#9AA1A9",
643
+ flag: "#FF9E80",
644
+ markerError: "#FF6B6B",
645
+ markerWarning: "#FFC857",
646
+ selectionGlow: 8,
647
+ hover: "#8BE0F5",
648
+ handleFill: "#141619",
649
+ selectionFill: "rgb(76 201 240 / 10%)",
650
+ selectionBox: "#4CC9F0",
651
+ selectionBoxFill: "rgb(76 201 240 / 8%)",
652
+ lockBadge: "#4f9a6c",
653
+ lockGlyph: "#ffffff",
654
+ notePin: "#e0a46a",
655
+ notePanel: "rgb(34 38 44 / 92%)",
656
+ noteText: "#e9e6df"
657
+ };
658
+ var schematicThemeFor = (theme) => theme === "dark" ? darkSchematicTheme : schematicTheme;
659
+ var current = schematicTheme;
660
+ var sheetPalette = () => current;
661
+ function setSheetPalette(palette) {
662
+ current = palette;
663
+ }
664
+ function resetSheetPalette() {
665
+ current = schematicTheme;
666
+ }
667
+ function glow(ctx, on, palette = current) {
668
+ const blur = on ? palette.selectionGlow : 0;
669
+ ctx.shadowBlur = blur;
670
+ ctx.shadowColor = blur > 0 ? palette.selection : "transparent";
671
+ }
672
+
673
+ // studio/src/pcb/drawing-style.ts
674
+ var WIRE_WIDTH = 0.02;
675
+ var BUS_WIDTH = 3 * WIRE_WIDTH;
676
+ var FILL_ALPHA_HEX = "33";
677
+ function strokeWidthOf(drawing) {
678
+ if (drawing.kind === "bus") return BUS_WIDTH;
679
+ return drawing.kind === "text" || drawing.kind === "junction" ? 0 : drawing.strokeWidth;
680
+ }
681
+ var drawnWidth = (width, devicePx) => Math.max(width, devicePx);
682
+ function dashOf(style, width) {
683
+ if (style === "dashed") return [4 * width, 3 * width];
684
+ return style === "dotted" ? [0, 2 * width] : [];
685
+ }
686
+ function lineStyleOf(drawing) {
687
+ return drawing.kind === "bus" || drawing.kind === "text" || drawing.kind === "junction" ? "solid" : drawing.lineStyle;
688
+ }
689
+ function colorOf(drawing) {
690
+ if (drawing.kind === "bus") return sheetPalette().bus;
691
+ if (drawing.kind === "junction") return drawing.color ?? sheetPalette().junction;
692
+ return drawing.color ?? sheetPalette().drawing;
693
+ }
694
+ var isFilled = (drawing) => (drawing.kind === "rect" || drawing.kind === "circle") && drawing.filled;
695
+ var fillOf = (color) => `${color}${FILL_ALPHA_HEX}`;
696
+
697
+ // src/engine/selectors.ts
698
+ var NET_NAME = /[\w-]+/;
699
+ var NET = new RegExp(String.raw`^net\.(${NET_NAME.source})$`);
700
+
701
+ // src/engine/drawing-kinds.ts
702
+ var JUNCTION_RADIUS = 0.04;
703
+ var PLAIN = new RegExp(String.raw`^${NET_NAME.source}$`);
704
+ var RANGE = new RegExp(String.raw`^(${NET_NAME.source})\[(\d+):(\d+)\]$`);
705
+ function pointsBox(points) {
706
+ const xs = points.map((p) => p.x);
707
+ const ys = points.map((p) => p.y);
708
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) };
709
+ }
710
+ function sweepOf(startAngle, endAngle) {
711
+ const turn = endAngle - startAngle;
712
+ return Math.abs(turn) >= 360 ? 360 : (turn % 360 + 360) % 360;
713
+ }
714
+ function arcBox(x, y, radius, startAngle, endAngle) {
715
+ const sweep = sweepOf(startAngle, endAngle);
716
+ const angles = [startAngle, startAngle + sweep];
717
+ for (let quarter = Math.ceil(startAngle / 90) * 90; quarter < startAngle + sweep; quarter += 90) angles.push(quarter);
718
+ const at = (degrees) => ({ x: x + radius * Math.cos(degrees * Math.PI / 180), y: y + radius * Math.sin(degrees * Math.PI / 180) });
719
+ return pointsBox(angles.map(at));
720
+ }
721
+ function textBox2(x, y, text2, fontSize, anchor) {
722
+ const width = CHAR_WIDTH * fontSize * text2.length;
723
+ const minX = anchor === "left" ? x : anchor === "right" ? x - width : x - width / 2;
724
+ return { minX, minY: y - fontSize / 2, maxX: minX + width, maxY: y + fontSize / 2 };
725
+ }
726
+ function rawBounds(drawing) {
727
+ switch (drawing.kind) {
728
+ case "path":
729
+ case "bus":
730
+ return pointsBox(drawing.points);
731
+ case "rect":
732
+ return { minX: drawing.x, minY: drawing.y, maxX: drawing.x + drawing.width, maxY: drawing.y + drawing.height };
733
+ case "circle":
734
+ return { minX: drawing.x - drawing.radius, minY: drawing.y - drawing.radius, maxX: drawing.x + drawing.radius, maxY: drawing.y + drawing.radius };
735
+ case "arc":
736
+ return arcBox(drawing.x, drawing.y, drawing.radius, drawing.startAngle, drawing.endAngle);
737
+ case "text":
738
+ return textBox2(drawing.x, drawing.y, drawing.text, drawing.fontSize, drawing.anchor);
739
+ case "junction":
740
+ return { minX: drawing.x - JUNCTION_RADIUS, minY: drawing.y - JUNCTION_RADIUS, maxX: drawing.x + JUNCTION_RADIUS, maxY: drawing.y + JUNCTION_RADIUS };
741
+ }
742
+ }
743
+ var tidy = (value) => clean(value) + 0;
744
+ function drawingBounds(drawing) {
745
+ const box = rawBounds(drawing);
746
+ return { minX: tidy(box.minX), minY: tidy(box.minY), maxX: tidy(box.maxX), maxY: tidy(box.maxY) };
747
+ }
748
+
749
+ // studio/src/pcb/crisp.ts
750
+ var squareAt = (v, ratio) => Math.round(v * ratio) / ratio;
751
+ var baselineAt = (v, ratio) => Math.round(v * ratio) / ratio;
752
+ var devicePixelIn = (cssPixel, ratio) => cssPixel / ratio;
753
+
754
+ // studio/src/pcb/text-level.ts
755
+ var TEXT_FROM = 7;
756
+ var ALL_TEXT_FROM = 9;
757
+ var PIN_NUMBERS_FROM = 11;
758
+ var OWN_TEXT_FROM = 5;
759
+ var SHEET_LEVEL_SIZE = 0.16;
760
+ function textLevel(devicePx) {
761
+ if (devicePx < TEXT_FROM) return "none";
762
+ return devicePx < ALL_TEXT_FROM ? "names" : "all";
763
+ }
764
+ function textShown(kind, levelPx, ownPx) {
765
+ if (ownPx < OWN_TEXT_FROM) return false;
766
+ const level = textLevel(levelPx);
767
+ if (kind === "name") return level !== "none";
768
+ if (kind === "pin-number") return levelPx >= PIN_NUMBERS_FROM;
769
+ return level === "all";
770
+ }
771
+ var devicePxFor = (worldSize, scale, ratio) => Math.max(1, Math.round(worldSize * scale * ratio));
772
+ var sheetLevelPx = (scale, ratio) => devicePxFor(SHEET_LEVEL_SIZE, scale, ratio);
773
+ var textAnchorAt = (p, ratio) => ({ x: squareAt(p.x, ratio), y: baselineAt(p.y, ratio) });
774
+ function sharpenText(ctx) {
775
+ if ("textRendering" in ctx) ctx.textRendering = "geometricPrecision";
776
+ }
777
+ var capToWidth = (devicePx, width, maxWidth) => width <= maxWidth || width <= 0 ? devicePx : Math.max(1, Math.floor(devicePx * maxWidth / width));
778
+
779
+ // studio/src/pcb/drawing-draw.ts
780
+ var rad = (degrees) => degrees * Math.PI / 180;
781
+ function shownDrawings(drawings, moving) {
782
+ if (!moving || moving.length === 0) return drawings;
783
+ const moved = new Map(moving.map((drawing) => [drawing.id, drawing]));
784
+ return drawings.map((drawing) => moved.get(drawing.id) ?? drawing);
785
+ }
786
+ function sweepOf2(startAngle, endAngle) {
787
+ const turn = endAngle - startAngle;
788
+ return Math.abs(turn) >= 360 ? 360 : (turn % 360 + 360) % 360;
789
+ }
790
+ function outline(ctx, drawing) {
791
+ ctx.beginPath();
792
+ if (drawing.kind === "path" || drawing.kind === "bus") {
793
+ drawing.points.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
794
+ return;
795
+ }
796
+ if (drawing.kind === "rect") {
797
+ const { x, y, width, height } = drawing;
798
+ ctx.moveTo(x, y);
799
+ ctx.lineTo(x + width, y);
800
+ ctx.lineTo(x + width, y + height);
801
+ ctx.lineTo(x, y + height);
802
+ ctx.closePath();
803
+ return;
804
+ }
805
+ if (drawing.kind === "circle") return ctx.arc(drawing.x, drawing.y, drawing.radius, 0, 2 * Math.PI);
806
+ const start = rad(drawing.startAngle);
807
+ ctx.arc(drawing.x, drawing.y, drawing.radius, start, start + rad(sweepOf2(drawing.startAngle, drawing.endAngle)));
808
+ }
809
+ function toneOf(drawing, paint) {
810
+ if (paint.selected?.includes(drawing.id)) return { color: sheetPalette().selection, alpha: 1 };
811
+ return { color: colorOf(drawing), alpha: paint.dim ? HIGHLIGHT_DIM : 1 };
812
+ }
813
+ function drawJunction(ctx, drawing, color, alpha, selected) {
814
+ ctx.globalAlpha = alpha;
815
+ ctx.fillStyle = color;
816
+ ctx.beginPath();
817
+ ctx.arc(drawing.x, drawing.y, JUNCTION_RADIUS, 0, 2 * Math.PI);
818
+ glow(ctx, selected);
819
+ ctx.fill();
820
+ glow(ctx, false);
821
+ }
822
+ function drawDrawings(ctx, drawings, devicePx, paint) {
823
+ for (const drawing of drawings) {
824
+ if (drawing.kind === "text") continue;
825
+ const { color, alpha } = toneOf(drawing, paint);
826
+ if (drawing.kind === "junction") {
827
+ drawJunction(ctx, drawing, color, alpha, paint.selected?.includes(drawing.id) ?? false);
828
+ continue;
829
+ }
830
+ const width = drawnWidth(strokeWidthOf(drawing), devicePx);
831
+ ctx.globalAlpha = alpha;
832
+ ctx.lineWidth = width;
833
+ ctx.strokeStyle = color;
834
+ ctx.setLineDash(dashOf(paint.pending ? "dashed" : lineStyleOf(drawing), width));
835
+ outline(ctx, drawing);
836
+ if (isFilled(drawing)) {
837
+ ctx.fillStyle = fillOf(color);
838
+ ctx.fill();
839
+ }
840
+ glow(ctx, paint.selected?.includes(drawing.id) ?? false);
841
+ ctx.stroke();
842
+ glow(ctx, false);
843
+ ctx.setLineDash([]);
844
+ }
845
+ ctx.globalAlpha = 1;
846
+ }
847
+ function drawDrawingTexts(ctx, drawings, camera, size, paint, ratio) {
848
+ for (const drawing of drawings) {
849
+ if (drawing.kind !== "text" || drawing.text === "") continue;
850
+ const devicePx = devicePxFor(drawing.fontSize, camera.scale, ratio);
851
+ if (!textShown("detail", sheetLevelPx(camera.scale, ratio), devicePx)) continue;
852
+ const fontPx = devicePx / ratio;
853
+ const { color, alpha } = toneOf(drawing, paint);
854
+ const at = textAnchorAt(worldToScreen(camera, size, drawing), ratio);
855
+ const [, horizontal] = anchorAlignment(drawing.anchor);
856
+ ctx.globalAlpha = alpha;
857
+ ctx.fillStyle = color;
858
+ ctx.font = `${fontPx}px ${CANVAS_FONT_FAMILY}`;
859
+ ctx.textAlign = horizontal;
860
+ ctx.textBaseline = "middle";
861
+ ctx.fillText(drawing.text, at.x, at.y);
862
+ }
863
+ ctx.globalAlpha = 1;
864
+ }
865
+
866
+ // studio/src/pcb/pin-name-fit.ts
867
+ var MIN_NAME_SCALE = 0.7;
868
+ var ELLIPSIS = "\u2026";
869
+ var MIN_CHARACTERS = 2;
870
+ function fitScaled(text2, scaleFor, least) {
871
+ const scale = scaleFor(text2);
872
+ if (scale >= 1) return { text: text2, scale: 1 };
873
+ if (scale >= least) return { text: text2, scale };
874
+ for (let keep = text2.length - 1; keep >= MIN_CHARACTERS; keep--) {
875
+ const short = text2.slice(0, keep) + ELLIPSIS;
876
+ if (scaleFor(short) >= least) return { text: short, scale: least };
877
+ }
878
+ return null;
879
+ }
880
+ function allot(room, mine, theirs) {
881
+ if (mine + theirs <= room) return mine;
882
+ const half = room / 2;
883
+ if (mine <= half) return mine;
884
+ return theirs <= half ? room - theirs : half;
885
+ }
886
+ var extentOn = (name, axis, text2, measure) => axis === "x" === name.quarter ? name.size : measure(text2);
887
+ var isSide = (name) => name.side === "left" || name.side === "right";
888
+ var inwardOf = (name) => isSide(name) ? "x" : "y";
889
+ var pitchOf = (name) => isSide(name) ? "y" : "x";
890
+ var reachShare = (name) => isSide(name) ? 1 : 0.5;
891
+ var OPPOSITE = { left: "right", right: "left", top: "bottom", bottom: "top" };
892
+ function inwardLimit(name, names, measure, gap) {
893
+ const [inward, pitch] = [inwardOf(name), pitchOf(name)];
894
+ const toward = name.side === "left" || name.side === "bottom" ? 1 : -1;
895
+ const reach = (n) => extentOn(n, inward, n.text, measure) * reachShare(n);
896
+ const sameLine = (other) => Math.abs(other.local[pitch] - name.local[pitch]) < (extentOn(name, pitch, name.text, measure) + extentOn(other, pitch, other.text, measure)) / 2;
897
+ const across = names.filter((other) => other.side === OPPOSITE[name.side] && sameLine(other) && (other.local[inward] - name.local[inward]) * toward > 0);
898
+ const nearest = across.sort((p, q) => Math.abs(p.local[inward] - name.local[inward]) - Math.abs(q.local[inward] - name.local[inward]))[0];
899
+ const room = Math.abs((nearest ? nearest.local[inward] : -name.local[inward]) - name.local[inward]) - gap;
900
+ return allot(room, reach(name), nearest ? reach(nearest) : 0) / reachShare(name);
901
+ }
902
+ function pitchLimit(name, names, gap) {
903
+ const pitch = pitchOf(name);
904
+ const pitches = names.filter((other) => other !== name && other.side === name.side).map((other) => Math.abs(other.local[pitch] - name.local[pitch]));
905
+ return pitches.length === 0 ? Infinity : Math.min(...pitches) - gap;
906
+ }
907
+ function fitBoth(name, names, measure, gap, least) {
908
+ const inward = inwardLimit(name, names, measure, gap);
909
+ const pitch = pitchLimit(name, names, gap);
910
+ const scaleFor = (text2) => Math.min(inward / extentOn(name, inwardOf(name), text2, measure), pitch / extentOn(name, pitchOf(name), text2, measure));
911
+ return fitScaled(name.text, scaleFor, least);
912
+ }
913
+ function spanOf(name, fit, measure) {
914
+ const width = measure(fit.text) * fit.scale;
915
+ const x0 = name.align === "left" ? name.x : name.align === "right" ? name.x - width : name.x - width / 2;
916
+ return { x0, x1: x0 + width, y0: name.y - name.ascent * fit.scale, y1: name.y + name.descent * fit.scale };
917
+ }
918
+ var overlap = (a, b) => a.x0 < b.x1 && b.x0 < a.x1 && a.y0 < b.y1 && b.y0 < a.y1;
919
+ function overlapping(spans, pair) {
920
+ const dropped = /* @__PURE__ */ new Set();
921
+ spans.forEach((a, i) => {
922
+ spans.forEach((b, j) => {
923
+ if (j > i && a && b && pair(i, j) && overlap(a, b)) dropped.add(i).add(j);
924
+ });
925
+ });
926
+ return dropped;
927
+ }
928
+ function fitPinNames(names, measure, gap, least = MIN_NAME_SCALE) {
929
+ const fitted = names.map((name) => fitBoth(name, names, measure, gap, least));
930
+ const spans = fitted.map((fit, i) => fit === null ? null : spanOf(names[i], fit, measure));
931
+ const sameSide = overlapping(spans, (i, j) => names[i]?.side === names[j]?.side);
932
+ const left = spans.map((span, i) => sameSide.has(i) ? null : span);
933
+ const crossing = overlapping(left, () => true);
934
+ return fitted.map((fit, i) => sameSide.has(i) || crossing.has(i) ? null : fit);
935
+ }
936
+
937
+ // studio/src/pcb/schematic-text.ts
938
+ var NAME_GAP = 0.25;
939
+ var FALLBACK_ASCENT = 0.8;
940
+ var FALLBACK_DESCENT = 0.2;
941
+ var BASELINE_DROP = { top: FALLBACK_ASCENT, middle: (FALLBACK_ASCENT - FALLBACK_DESCENT) / 2, bottom: -FALLBACK_DESCENT };
942
+ var fontOf = (label, devicePx, ratio) => canvasFont(label.strong ? TEXT_WEIGHT.strong : TEXT_WEIGHT.regular, devicePx / ratio, label.mono ? CANVAS_MONO_FAMILY : void 0);
943
+ function sizeOf(ctx, label, { camera, ratio }) {
944
+ const devicePx = devicePxFor(label.size, camera.scale, ratio);
945
+ if (label.maxWidth === void 0) return devicePx;
946
+ ctx.font = fontOf(label, devicePx, ratio);
947
+ return capToWidth(devicePx, ctx.measureText(label.text).width, label.maxWidth * camera.scale);
948
+ }
949
+ function inkOf(ctx, text2, baseline, size) {
950
+ ctx.textBaseline = baseline;
951
+ const metrics = ctx.measureText(text2);
952
+ const drop = (BASELINE_DROP[baseline] ?? 0) * size;
953
+ return {
954
+ ascent: metrics.actualBoundingBoxAscent ?? FALLBACK_ASCENT * size - drop,
955
+ descent: metrics.actualBoundingBoxDescent ?? FALLBACK_DESCENT * size + drop
956
+ };
957
+ }
958
+ function pinName(ctx, { label, devicePx }, paint) {
959
+ const pin = label.pinOf;
960
+ if (!pin) return null;
961
+ const size = devicePx / paint.ratio;
962
+ const p = worldToScreen(paint.camera, paint.size, label.at);
963
+ const [vertical, horizontal] = anchorAlignment(label.anchor);
964
+ const local = { x: pin.local.x * paint.camera.scale, y: pin.local.y * paint.camera.scale };
965
+ const ink = inkOf(ctx, label.text, vertical, size);
966
+ return { text: label.text, x: p.x, y: p.y, align: horizontal, size, ...ink, local, side: pin.side, quarter: pin.quarter };
967
+ }
968
+ function fitSymbol(ctx, names, paint) {
969
+ const first = names[0];
970
+ if (!first) return names;
971
+ ctx.font = fontOf(first.label, first.devicePx, paint.ratio);
972
+ const onScreen = names.map((sized) => pinName(ctx, sized, paint)).filter((name) => name !== null);
973
+ if (onScreen.length !== names.length) return names;
974
+ const least = Math.ceil(first.devicePx * MIN_NAME_SCALE) / first.devicePx;
975
+ const fits = fitPinNames(onScreen, (text2) => ctx.measureText(text2).width, first.devicePx / paint.ratio * NAME_GAP, least);
976
+ return names.flatMap((sized, i) => {
977
+ const fit = fits[i];
978
+ if (!fit) return [];
979
+ const devicePx = fit.scale < 1 ? Math.floor(sized.devicePx * fit.scale + 1e-9) : sized.devicePx;
980
+ return [{ label: { ...sized.label, text: fit.text }, devicePx }];
981
+ });
982
+ }
983
+ function arrange(ctx, labels, paint) {
984
+ const levelPx = sheetLevelPx(paint.camera.scale, paint.ratio);
985
+ const allowed = ({ label, devicePx }) => textShown(label.kind, levelPx, devicePx);
986
+ const shown = labels.filter((label) => label.text !== "").map((label) => ({ label, devicePx: sizeOf(ctx, label, paint) })).filter(allowed);
987
+ const bySymbol = /* @__PURE__ */ new Map();
988
+ for (const sized of shown) {
989
+ const symbol = sized.label.pinOf?.symbol;
990
+ if (symbol !== void 0) bySymbol.set(symbol, [...bySymbol.get(symbol) ?? [], sized]);
991
+ }
992
+ const fitted = [...bySymbol.values()].flatMap((names) => fitSymbol(ctx, names, paint));
993
+ return [...shown.filter(({ label }) => !label.pinOf), ...fitted.filter(allowed)];
994
+ }
995
+ function write(ctx, { label, devicePx }, paint) {
996
+ const p = textAnchorAt(worldToScreen(paint.camera, paint.size, label.at), paint.ratio);
997
+ const [vertical, horizontal] = anchorAlignment(label.anchor);
998
+ ctx.save();
999
+ ctx.translate(p.x, p.y);
1000
+ if (label.rotation) ctx.rotate(-label.rotation * Math.PI / 180);
1001
+ ctx.globalAlpha = label.alpha ?? 1;
1002
+ ctx.fillStyle = label.color;
1003
+ ctx.font = fontOf(label, devicePx, paint.ratio);
1004
+ ctx.textAlign = horizontal;
1005
+ ctx.textBaseline = vertical;
1006
+ ctx.fillText(label.text, 0, 0);
1007
+ ctx.restore();
1008
+ }
1009
+ function drawSheetTexts(ctx, labels, camera, size, ratio) {
1010
+ const paint = { camera, size, ratio };
1011
+ sharpenText(ctx);
1012
+ for (const sized of arrange(ctx, labels, paint)) write(ctx, sized, paint);
1013
+ }
1014
+
1015
+ // studio/src/pcb/no-connect-draw.ts
1016
+ var NO_CONNECT_HALF = 0.05;
1017
+ var NO_CONNECT_WIDTH = 0.015;
1018
+ function noConnectStrokes(at) {
1019
+ const h = NO_CONNECT_HALF;
1020
+ return [
1021
+ [{ x: at.x - h, y: at.y - h }, { x: at.x + h, y: at.y + h }],
1022
+ [{ x: at.x - h, y: at.y + h }, { x: at.x + h, y: at.y - h }]
1023
+ ];
1024
+ }
1025
+ function drawNoConnects(ctx, flags, line2, dim) {
1026
+ if (flags.length === 0) return;
1027
+ ctx.strokeStyle = sheetPalette().noConnect;
1028
+ ctx.lineWidth = line2(NO_CONNECT_WIDTH);
1029
+ ctx.globalAlpha = dim ? HIGHLIGHT_DIM : 1;
1030
+ for (const flag of flags) {
1031
+ for (const [a, b] of noConnectStrokes(flag.at)) {
1032
+ ctx.beginPath();
1033
+ ctx.moveTo(a.x, a.y);
1034
+ ctx.lineTo(b.x, b.y);
1035
+ ctx.stroke();
1036
+ }
1037
+ }
1038
+ ctx.globalAlpha = 1;
1039
+ }
1040
+
1041
+ // studio/src/pcb/schematic-draw.ts
1042
+ var NO_SHIFT = { x: 0, y: 0 };
1043
+ var SYMBOL_WIDTH = 0.02;
1044
+ var PIN_DOT_PX = 3.5;
1045
+ var LIT_PIN_WORLD = 0.06;
1046
+ var LIT_PIN_MIN_PX = 1.5;
1047
+ var ACTIVE_PIN_FACTOR = 1.6;
1048
+ var MIN_JUNCTION = 0.04;
1049
+ var JUNCTION_PX = 3;
1050
+ var DASH = [0.1, 0.06];
1051
+ var NUMBER_INSET = 0.1;
1052
+ var NUMBER_RISE = 0.07;
1053
+ var TWO_PIN_TEXT_LENGTHS = 2.5;
1054
+ var TEXT_KINDS = { reference: "name", value: "detail", "pin-name": "detail", "pin-number": "pin-number" };
1055
+ var TEXT_COLORS = {
1056
+ reference: "designator",
1057
+ value: "value",
1058
+ "pin-name": "pinName",
1059
+ "pin-number": "pinNumber"
1060
+ };
1061
+ var OUTWARD2 = { right: { x: 1, y: 0 }, left: { x: -1, y: 0 }, top: { x: 0, y: 1 }, bottom: { x: 0, y: -1 } };
1062
+ var rad2 = (degrees) => degrees * Math.PI / 180;
1063
+ function drawSchematic(ctx, layout, view, options) {
1064
+ const { camera, size } = view;
1065
+ const px = 1 / camera.scale;
1066
+ const line2 = (width) => Math.max(width, px / options.ratio);
1067
+ const texts = [];
1068
+ const shiftOf = (symbol) => options.moving?.components.includes(symbol.component) ? options.moving.by : NO_SHIFT;
1069
+ ctx.save();
1070
+ const s = camera.scale * options.ratio;
1071
+ ctx.setTransform(s, 0, 0, -s, (size.width / 2 - camera.cx * camera.scale) * options.ratio, (size.height / 2 + camera.cy * camera.scale) * options.ratio);
1072
+ ctx.lineCap = "round";
1073
+ ctx.lineJoin = "round";
1074
+ drawWires(ctx, layout, options, px, line2);
1075
+ const shown = shownDrawings(layout.drawings, options.movingDrawings);
1076
+ const pending = options.pendingDrawings ?? [];
1077
+ const drawings = [...shown, ...pending];
1078
+ const paint = { ...options.selectedDrawings ? { selected: options.selectedDrawings } : {}, dim: options.highlight !== void 0 };
1079
+ drawDrawings(ctx, shown, px / options.ratio, paint);
1080
+ drawDrawings(ctx, pending, px / options.ratio, { pending: true, dim: paint.dim });
1081
+ for (const symbol of layout.symbols) drawSymbol(ctx, symbol, shiftOf(symbol), { line: line2, px, fade: symbolFade(symbol, options.highlight) }, texts);
1082
+ for (const label of layout.labels) {
1083
+ const moving = options.movingLabels?.some((m) => m.id === label.id) ?? false;
1084
+ const selected = options.selectedLabels?.includes(label.id) ?? false;
1085
+ const tone = selected ? { color: sheetPalette().selection, alpha: 1 } : toneOf2(label.net, options.highlight);
1086
+ glow(ctx, selected);
1087
+ drawLabel(ctx, movedLabel(label, options), line2, texts, moving, tone);
1088
+ glow(ctx, false);
1089
+ }
1090
+ for (const ghost of options.ghostLabels ?? []) drawLabel(ctx, ghost, line2, texts, true, toneOf2(ghost.net, void 0));
1091
+ drawPins(ctx, layout, options, px, shiftOf);
1092
+ drawNoConnects(ctx, layout.noConnects ?? [], line2, options.highlight !== void 0);
1093
+ ctx.setTransform(options.ratio, 0, 0, options.ratio, 0, 0);
1094
+ drawSheetTexts(ctx, texts, camera, size, options.ratio);
1095
+ drawDrawingTexts(ctx, drawings, camera, size, paint, options.ratio);
1096
+ drawViolationMarkers(ctx, view, options.violations ?? [], options.activeViolation, false, { error: sheetPalette().markerError, warning: sheetPalette().markerWarning });
1097
+ ctx.restore();
1098
+ }
1099
+ function sheetBoxes(layout) {
1100
+ return layout.symbols.map((placed) => {
1101
+ const box = symbolBox(placed);
1102
+ return { name: placed.component, pcbComponentId: placed.component, center: { x: (box.minX + box.maxX) / 2, y: (box.minY + box.maxY) / 2 }, box };
1103
+ });
1104
+ }
1105
+ var isPartText = (shape) => shape.type === "text" && (shape.role === "reference" || shape.role === "value");
1106
+ function symbolBox(placed) {
1107
+ const { minX, minY, maxX, maxY } = boundsOf(placed.symbol.shapes.filter((shape) => !isPartText(shape)), placed.symbol.pins);
1108
+ const corners = [
1109
+ { x: minX, y: minY },
1110
+ { x: maxX, y: minY },
1111
+ { x: maxX, y: maxY },
1112
+ { x: minX, y: maxY }
1113
+ ].map((corner) => place2(corner, placed));
1114
+ const xs = corners.map((c) => c.x);
1115
+ const ys = corners.map((c) => c.y);
1116
+ return { minX: Math.min(...xs), minY: Math.min(...ys), maxX: Math.max(...xs), maxY: Math.max(...ys) };
1117
+ }
1118
+ function place2(p, frame) {
1119
+ const angle = rad2(frame.rotation);
1120
+ const cos = Math.cos(angle);
1121
+ const sin = Math.sin(angle);
1122
+ return { x: frame.x + p.x * cos - p.y * sin, y: frame.y + p.x * sin + p.y * cos };
1123
+ }
1124
+ function path(ctx, points) {
1125
+ ctx.beginPath();
1126
+ points.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
1127
+ }
1128
+ function dot(ctx, p, r) {
1129
+ ctx.beginPath();
1130
+ ctx.arc(p.x, p.y, Math.max(r, 0), 0, Math.PI * 2);
1131
+ }
1132
+ function toneOf2(net, highlight) {
1133
+ if (!highlight) return { color: void 0, alpha: 1 };
1134
+ return net === highlight.net || highlight.aliases?.includes(net) ? { color: sheetPalette().highlight, alpha: 1 } : { color: void 0, alpha: HIGHLIGHT_DIM };
1135
+ }
1136
+ function symbolFade(symbol, highlight) {
1137
+ if (!highlight) return 1;
1138
+ return highlight.pins?.some((pin) => pin in symbol.pinEnds) ? 1 : HIGHLIGHT_DIM;
1139
+ }
1140
+ var EPSILON = 1e-9;
1141
+ function onSegment(p, a, b) {
1142
+ const straight = Math.abs((b.x - a.x) * (p.y - a.y) - (b.y - a.y) * (p.x - a.x)) < EPSILON;
1143
+ const within = (v, lo, hi) => v >= Math.min(lo, hi) - EPSILON && v <= Math.max(lo, hi) + EPSILON;
1144
+ return straight && within(p.x, a.x, b.x) && within(p.y, a.y, b.y);
1145
+ }
1146
+ function junctionLit(layout, junction, highlight) {
1147
+ return layout.wires.some((wire) => toneOf2(wire.net, highlight).color !== void 0 && wire.points.some((b, i) => i > 0 && onSegment(junction, wire.points[i - 1] ?? b, b)));
1148
+ }
1149
+ function drawWires(ctx, layout, options, px, line2) {
1150
+ ctx.lineWidth = line2(WIRE_WIDTH);
1151
+ for (const wire of layout.wires) {
1152
+ if (options.movingLabels?.some((m) => m.hideWire === wire.id)) continue;
1153
+ const selected = options.selectedWires?.includes(wire.id) ?? false;
1154
+ const tone = selected ? { color: sheetPalette().selection, alpha: 1 } : toneOf2(wire.net, options.highlight);
1155
+ ctx.strokeStyle = tone.color ?? sheetPalette().wire;
1156
+ ctx.globalAlpha = tone.alpha;
1157
+ glow(ctx, selected);
1158
+ path(ctx, wire.points);
1159
+ ctx.stroke();
1160
+ }
1161
+ glow(ctx, false);
1162
+ for (const junction of layout.junctions) {
1163
+ const lit = options.highlight !== void 0 && junctionLit(layout, junction, options.highlight);
1164
+ ctx.fillStyle = lit ? sheetPalette().highlight : sheetPalette().junction;
1165
+ ctx.globalAlpha = options.highlight && !lit ? HIGHLIGHT_DIM : 1;
1166
+ dot(ctx, junction, Math.max(MIN_JUNCTION, JUNCTION_PX * px));
1167
+ ctx.fill();
1168
+ }
1169
+ ctx.globalAlpha = 1;
1170
+ ctx.strokeStyle = sheetPalette().wire;
1171
+ const pending = (options.pending ?? []).filter((points) => points.length >= 2);
1172
+ if (pending.length === 0) return;
1173
+ ctx.setLineDash(DASH);
1174
+ for (const points of pending) {
1175
+ path(ctx, points);
1176
+ ctx.stroke();
1177
+ }
1178
+ ctx.setLineDash([]);
1179
+ }
1180
+ function drawSymbol(ctx, placed, shift, pen, texts) {
1181
+ const frame = { x: placed.x + shift.x, y: placed.y + shift.y, rotation: placed.rotation };
1182
+ const alpha = pen.fade;
1183
+ const own = [];
1184
+ ctx.globalAlpha = alpha;
1185
+ ctx.lineWidth = pen.line(SYMBOL_WIDTH);
1186
+ drawShapes(ctx, placed.symbol.shapes, frame, sheetPalette().symbolOutline, own);
1187
+ ctx.globalAlpha = 1;
1188
+ const ownNumbers = placed.symbol.shapes.some((shape) => shape.type === "text" && shape.role === "pin-number");
1189
+ if (placed.symbol.kind !== "sheet" && !ownNumbers) own.push(...pinNumbers(placed.symbol, frame));
1190
+ texts.push(...own.map((label) => ({ ...label, alpha, ...textBounds(label, placed) })));
1191
+ }
1192
+ function textBounds(label, placed) {
1193
+ if (label.pinOf) return { pinOf: { ...label.pinOf, symbol: placed.component } };
1194
+ if (label.role !== "reference" && label.role !== "value" || placed.symbol.pins.length !== 2) return {};
1195
+ const [a, b] = placed.symbol.pins;
1196
+ return a && b ? { maxWidth: TWO_PIN_TEXT_LENGTHS * Math.hypot(a.end.x - b.end.x, a.end.y - b.end.y) } : {};
1197
+ }
1198
+ function pinNumbers(symbol, frame) {
1199
+ return symbol.pins.map((pin) => {
1200
+ const inward = OUTWARD2[pin.side];
1201
+ const local = { x: pin.end.x - inward.x * NUMBER_INSET, y: pin.end.y - inward.y * NUMBER_INSET };
1202
+ const alongLead = inward.x !== 0;
1203
+ const lifted = alongLead ? { x: local.x, y: local.y + NUMBER_RISE } : { x: local.x + NUMBER_RISE, y: local.y };
1204
+ return { text: String(pin.number), at: place2(lifted, frame), size: 0.1, anchor: "center", color: sheetPalette().pinNumber, mono: true, kind: "pin-number" };
1205
+ });
1206
+ }
1207
+ function drawShapes(ctx, shapes, frame, color, texts) {
1208
+ ctx.save();
1209
+ ctx.translate(frame.x, frame.y);
1210
+ if (frame.rotation) ctx.rotate(rad2(frame.rotation));
1211
+ ctx.strokeStyle = color;
1212
+ ctx.fillStyle = color;
1213
+ for (const shape of shapes) {
1214
+ if (shape.type === "text") texts.push(textLabel(shape, frame, color));
1215
+ else if (shape.type === "polyline" && shape.bus) busBar(ctx, shape);
1216
+ else paintShape(ctx, shape);
1217
+ }
1218
+ ctx.restore();
1219
+ }
1220
+ function busBar(ctx, shape) {
1221
+ const [stroke, fill] = [ctx.strokeStyle, ctx.fillStyle];
1222
+ ctx.strokeStyle = sheetPalette().bus;
1223
+ ctx.fillStyle = sheetPalette().bus;
1224
+ path(ctx, shape.points);
1225
+ ctx.closePath();
1226
+ ctx.fill();
1227
+ ctx.stroke();
1228
+ ctx.strokeStyle = stroke;
1229
+ ctx.fillStyle = fill;
1230
+ }
1231
+ function paintShape(ctx, shape) {
1232
+ if (shape.type === "polyline") {
1233
+ path(ctx, shape.points);
1234
+ if (shape.closed || shape.fill) ctx.closePath();
1235
+ if (shape.fill) ctx.fill();
1236
+ ctx.stroke();
1237
+ } else if (shape.type === "circle") {
1238
+ dot(ctx, shape.center, shape.radius);
1239
+ if (shape.fill) ctx.fill();
1240
+ ctx.stroke();
1241
+ } else {
1242
+ const end = shape.end < shape.start ? shape.end + 360 : shape.end;
1243
+ ctx.beginPath();
1244
+ ctx.arc(shape.center.x, shape.center.y, shape.radius, rad2(shape.start), rad2(end));
1245
+ ctx.stroke();
1246
+ }
1247
+ }
1248
+ function textLabel(shape, frame, fallback) {
1249
+ const along = shape.anchor === "left" ? 1 : shape.anchor === "right" ? -1 : 0;
1250
+ const angle = rad2(frame.rotation);
1251
+ const dx = along * Math.cos(angle);
1252
+ const dy = along * Math.sin(angle);
1253
+ const anchor = Math.abs(dx) > 0.5 ? dx > 0 ? "left" : "right" : Math.abs(dy) > 0.5 ? dy > 0 ? "bottom" : "top" : "center";
1254
+ const role = { role: shape.role, kind: TEXT_KINDS[shape.role], ...shape.role === "pin-name" ? { pinOf: pinFrame(shape, frame) } : {}, ...shape.role === "reference" ? { strong: true } : {}, ...shape.role === "pin-number" ? { mono: true } : {} };
1255
+ return { text: shape.text, at: place2(shape.at, frame), size: shape.size, anchor, color: sheetPalette()[TEXT_COLORS[shape.role]] ?? fallback, ...role };
1256
+ }
1257
+ function pinFrame(shape, frame) {
1258
+ const side = shape.anchor === "left" ? "left" : shape.anchor === "right" ? "right" : shape.at.y > 0 ? "top" : "bottom";
1259
+ return { symbol: "", local: shape.at, side, quarter: Math.abs(Math.sin(rad2(frame.rotation))) > 0.5 };
1260
+ }
1261
+ function movedLabel(label, options) {
1262
+ const moving = options.movingLabels?.find((m) => m.id === label.id);
1263
+ return moving ? { ...label, at: moving.at, side: moving.side } : label;
1264
+ }
1265
+ function drawLabel(ctx, label, line2, texts, moving, tone) {
1266
+ ctx.setLineDash(moving ? DASH : []);
1267
+ ctx.globalAlpha = tone.alpha;
1268
+ drawLabelShape(ctx, label, line2, texts, tone);
1269
+ ctx.globalAlpha = 1;
1270
+ ctx.setLineDash([]);
1271
+ }
1272
+ function drawLabelShape(ctx, label, line2, texts, tone) {
1273
+ if (label.style !== "label") {
1274
+ const shapes = label.style === "ground" ? groundSymbol() : powerSymbol(label.text);
1275
+ ctx.lineWidth = line2(SYMBOL_WIDTH);
1276
+ const first = texts.length;
1277
+ drawShapes(ctx, shapes, { x: label.at.x, y: label.at.y, rotation: 0 }, tone.color ?? sheetPalette().flag, texts);
1278
+ for (let i = first; i < texts.length; i++) texts[i] = { ...texts[i], strong: true, kind: "name", color: tone.color ?? sheetPalette().netName, alpha: tone.alpha };
1279
+ return;
1280
+ }
1281
+ const { middle, upright, box } = labelTag(label);
1282
+ texts.push({ text: label.text, at: middle, size: NET_LABEL_TEXT, anchor: "center", strong: true, kind: "name", color: tone.color ?? sheetPalette().netName, rotation: upright ? 90 : 0, alpha: tone.alpha });
1283
+ if (label.port) drawPortFlag(ctx, label, box, line2, tone);
1284
+ }
1285
+ function drawPortFlag(ctx, label, box, line2, tone) {
1286
+ ctx.strokeStyle = tone.color ?? sheetPalette().netName;
1287
+ ctx.lineWidth = line2(label.bus ? SYMBOL_WIDTH * 3 : SYMBOL_WIDTH);
1288
+ ctx.beginPath();
1289
+ ctx.moveTo(box.minX, box.minY);
1290
+ ctx.lineTo(box.maxX, box.minY);
1291
+ ctx.lineTo(box.maxX, box.maxY);
1292
+ ctx.lineTo(box.minX, box.maxY);
1293
+ ctx.closePath();
1294
+ ctx.stroke();
1295
+ }
1296
+ function drawPins(ctx, layout, options, px, shiftOf) {
1297
+ for (const symbol of layout.symbols) {
1298
+ const shift = shiftOf(symbol);
1299
+ for (const [id, end] of Object.entries(symbol.pinEnds)) {
1300
+ const lit = options.highlight?.pins?.includes(id) ?? false;
1301
+ const active = (options.activePins?.includes(id) ?? false) || lit;
1302
+ if (!active && !options.showPins) continue;
1303
+ ctx.fillStyle = active ? sheetPalette().highlight : sheetPalette().pin;
1304
+ const radius = lit ? Math.min(PIN_DOT_PX * px, Math.max(LIT_PIN_WORLD, LIT_PIN_MIN_PX * px)) : (active ? ACTIVE_PIN_FACTOR : 1) * PIN_DOT_PX * px;
1305
+ dot(ctx, { x: end.x + shift.x, y: end.y + shift.y }, radius);
1306
+ ctx.fill();
1307
+ }
1308
+ }
1309
+ }
1310
+
1311
+ // studio/src/pcb/wire-overlay.ts
1312
+ var sheetWireLookFor = (palette) => ({ hover: palette.hover, selected: palette.selection, handleFill: palette.handleFill });
1313
+ var SHEET_WIRE_LOOK = sheetWireLookFor(schematicTheme);
1314
+
1315
+ // studio/src/pcb/copper-hit.ts
1316
+ var stray = (item) => item.missingLayer === void 0 ? {} : { missingLayer: item.missingLayer };
1317
+ function copperShown(item, visible) {
1318
+ if (item.missingLayer !== void 0) return visible.keepout;
1319
+ if (item.kind === "via") return visible.multiLayer;
1320
+ return (item.layer === "top" || item.layer === "bottom") && visible[item.layer];
1321
+ }
1322
+
1323
+ // studio/src/pcb/copper-draw.ts
1324
+ var INACTIVE_COPPER_ALPHA = 0.4;
1325
+ var OUTLINE_PX = 1.5;
1326
+ var LAYER_COLORS = { top: PALETTE.topCopper, bottom: PALETTE.bottomCopper, inner1: PALETTE.topCopper, inner2: PALETTE.topCopper };
1327
+ var trackColor = (track) => track.missingLayer === void 0 ? LAYER_COLORS[track.layer] : PALETTE.keepout;
1328
+ var ringColor = (via) => via.missingLayer === void 0 ? PALETTE.viaRing : PALETTE.keepout;
1329
+ var trackShown = (track, layers) => copperShown({ kind: "track", layer: track.layer, ...stray(track) }, layers);
1330
+ var viaShown = (via, layers) => copperShown({ kind: "via", ...stray(via) }, layers);
1331
+ var litAlpha = (highlight, net) => highlight && (net === void 0 || !highlight.nets.includes(net)) ? PCB_DIM : 1;
1332
+ function strokePath(ctx, points, color, width) {
1333
+ ctx.strokeStyle = color;
1334
+ ctx.lineWidth = width;
1335
+ ctx.beginPath();
1336
+ points.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
1337
+ ctx.stroke();
1338
+ }
1339
+ function disc(ctx, at, radius, color) {
1340
+ ctx.fillStyle = color;
1341
+ ctx.beginPath();
1342
+ ctx.arc(at.x, at.y, Math.max(radius, 0), 0, Math.PI * 2);
1343
+ ctx.fill();
1344
+ }
1345
+ function drawTracks(ctx, scene, layers, highlight) {
1346
+ const active = scene.activeLayer ?? "top";
1347
+ const shown = scene.tracks.filter((track) => trackShown(track, layers));
1348
+ const isActive = (track) => track.layer === active || track.missingLayer !== void 0;
1349
+ const ordered = [...shown.filter((track) => !isActive(track)), ...shown.filter(isActive)];
1350
+ for (const track of ordered) {
1351
+ ctx.globalAlpha = (isActive(track) ? 1 : INACTIVE_COPPER_ALPHA) * litAlpha(highlight, track.net);
1352
+ strokePath(ctx, track.points, trackColor(track), track.width);
1353
+ }
1354
+ ctx.globalAlpha = 1;
1355
+ }
1356
+ function drawVias(ctx, scene, layers, highlight) {
1357
+ for (const via of scene.vias.filter((one) => viaShown(one, layers))) {
1358
+ ctx.globalAlpha = litAlpha(highlight, via.net);
1359
+ disc(ctx, via.at, via.diameter / 2, ringColor(via));
1360
+ if (layers.hole) disc(ctx, via.at, via.drill / 2, PALETTE.drill);
1361
+ }
1362
+ ctx.globalAlpha = 1;
1363
+ }
1364
+ function drawRoutes(ctx, scene, layers) {
1365
+ for (const { drawing, alpha } of scene.routes ?? []) {
1366
+ ctx.globalAlpha = alpha;
1367
+ for (const track of drawing.tracks) if (copperShown({ kind: "track", layer: track.layer }, layers)) strokePath(ctx, track.points, LAYER_COLORS[track.layer], track.width);
1368
+ if (!copperShown({ kind: "via" }, layers)) continue;
1369
+ for (const via of drawing.vias) {
1370
+ disc(ctx, via.at, via.diameter / 2, PALETTE.viaRing);
1371
+ if (layers.hole) disc(ctx, via.at, via.drill / 2, PALETTE.drill);
1372
+ }
1373
+ }
1374
+ ctx.globalAlpha = 1;
1375
+ }
1376
+ function markedPoints(scene, track, wash) {
1377
+ const { segment } = scene;
1378
+ return wash && segment?.id === track.id && segmentFits(segment, track.points) ? [segment.from, segment.to] : track.points;
1379
+ }
1380
+ function mark(ctx, scene, layers, id, color, wash, px) {
1381
+ const track = scene.tracks.find((one) => one.id === id);
1382
+ if (track && trackShown(track, layers)) {
1383
+ const points = markedPoints(scene, track, wash);
1384
+ strokePath(ctx, points, color, track.width + 2 * OUTLINE_PX * px);
1385
+ strokePath(ctx, points, trackColor(track), track.width);
1386
+ if (wash) strokePath(ctx, points, PALETTE.selectionFill, track.width);
1387
+ return;
1388
+ }
1389
+ const via = scene.vias.find((one) => one.id === id);
1390
+ if (!via || !viaShown(via, layers)) return;
1391
+ disc(ctx, via.at, via.diameter / 2 + OUTLINE_PX * px, color);
1392
+ disc(ctx, via.at, via.diameter / 2, ringColor(via));
1393
+ if (wash) disc(ctx, via.at, via.diameter / 2, PALETTE.selectionFill);
1394
+ if (layers.hole) disc(ctx, via.at, via.drill / 2, PALETTE.drill);
1395
+ }
1396
+ function drawCopperItems(ctx, scene, layers, highlight, px) {
1397
+ drawTracks(ctx, scene, layers, highlight);
1398
+ drawVias(ctx, scene, layers, highlight);
1399
+ drawRoutes(ctx, scene, layers);
1400
+ if (scene.hover !== void 0 && !scene.selected.has(scene.hover)) mark(ctx, scene, layers, scene.hover, PALETTE.hover, false, px);
1401
+ for (const id of scene.selected) mark(ctx, scene, layers, id, PALETTE.selection, true, px);
1402
+ }
1403
+
1404
+ // studio/src/pcb/pour-hit.ts
1405
+ function pourOutline(pour, board) {
1406
+ return pour.outline ?? board?.outline ?? [];
1407
+ }
1408
+ function pourShown(pour, visible, hidden) {
1409
+ if (hidden.has(pour.id)) return false;
1410
+ return pour.layer === "top" || pour.layer === "bottom" ? visible[pour.layer] : pour.layer === "inner1" || pour.layer === "inner2";
1411
+ }
1412
+
1413
+ // studio/src/pcb/pour-view.ts
1414
+ var POUR_FILL_ALPHA = 0.35;
1415
+
1416
+ // studio/src/pcb/pour-draw.ts
1417
+ var POUR_COLORS = { top: PALETTE.topCopper, bottom: PALETTE.bottomCopper, inner1: PALETTE.inner1Copper, inner2: PALETTE.inner2Copper };
1418
+ var LAYER_COLOR = POUR_COLORS;
1419
+ var HATCH_MM = 0.5;
1420
+ var MAX_HATCH = 400;
1421
+ var HANDLE_PX = 6;
1422
+ var OUTLINE_PX2 = 1;
1423
+ var SELECTED_PX = 1.5;
1424
+ function ringPath(ctx, ring2) {
1425
+ ring2.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
1426
+ ctx.closePath();
1427
+ }
1428
+ function fillPath(ctx, fill) {
1429
+ if (!(hasPath2D() && ctx instanceof Path2D)) ctx.beginPath();
1430
+ for (const polygon3 of fill.polygons) {
1431
+ ringPath(ctx, polygon3.outer);
1432
+ for (const hole of polygon3.holes) ringPath(ctx, hole);
1433
+ }
1434
+ }
1435
+ var HATCH_MIN_PX = 6;
1436
+ function pourHatch(fill, px = 0) {
1437
+ const points = fill.polygons.flatMap((polygon3) => polygon3.outer);
1438
+ if (points.length === 0) return [];
1439
+ const xs = points.map((p) => p.x);
1440
+ const ys = points.map((p) => p.y);
1441
+ const [minX, maxX, minY, maxY] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
1442
+ const height = maxY - minY;
1443
+ const start = minX - height;
1444
+ const span = maxX - start;
1445
+ const step = Math.max(HATCH_MM, HATCH_MIN_PX * px, span / (MAX_HATCH - 1));
1446
+ const count = Math.floor(span / step + 1e-9) + 1;
1447
+ return Array.from({ length: count }, (_, i) => [
1448
+ { x: start + i * step, y: minY },
1449
+ { x: start + i * step + height, y: maxY }
1450
+ ]);
1451
+ }
1452
+ var FILL_PATHS = /* @__PURE__ */ new WeakMap();
1453
+ var hasPath2D = () => typeof Path2D === "function";
1454
+ function pathsOf(fill) {
1455
+ const known = FILL_PATHS.get(fill);
1456
+ if (known) return known;
1457
+ const made = {};
1458
+ FILL_PATHS.set(fill, made);
1459
+ return made;
1460
+ }
1461
+ function ringsOf(fill) {
1462
+ if (!hasPath2D()) return void 0;
1463
+ const paths = pathsOf(fill);
1464
+ if (!paths.rings) {
1465
+ paths.rings = new Path2D();
1466
+ fillPath(paths.rings, fill);
1467
+ }
1468
+ return paths.rings;
1469
+ }
1470
+ function hatchOf(fill, px) {
1471
+ if (!hasPath2D()) return void 0;
1472
+ const paths = pathsOf(fill);
1473
+ if (paths.hatch?.px !== px) {
1474
+ const path2 = new Path2D();
1475
+ for (const [a, b] of pourHatch(fill, px)) {
1476
+ path2.moveTo(a.x, a.y);
1477
+ path2.lineTo(b.x, b.y);
1478
+ }
1479
+ paths.hatch = { px, path: path2 };
1480
+ }
1481
+ return paths.hatch.path;
1482
+ }
1483
+ function strokeRings(ctx, fill, width) {
1484
+ ctx.lineWidth = width;
1485
+ const rings = ringsOf(fill);
1486
+ if (rings) return ctx.stroke(rings);
1487
+ fillPath(ctx, fill);
1488
+ ctx.stroke();
1489
+ }
1490
+ function fillRings(ctx, fill, use) {
1491
+ const rings = ringsOf(fill);
1492
+ if (rings) return use === "fill" ? ctx.fill(rings, "evenodd") : ctx.clip(rings, "evenodd");
1493
+ fillPath(ctx, fill);
1494
+ if (use === "fill") ctx.fill("evenodd");
1495
+ else ctx.clip("evenodd");
1496
+ }
1497
+ function strokeHatch(ctx, fill, px) {
1498
+ const hatch = hatchOf(fill, px);
1499
+ if (hatch) return ctx.stroke(hatch);
1500
+ ctx.beginPath();
1501
+ for (const [a, b] of pourHatch(fill, px)) {
1502
+ ctx.moveTo(a.x, a.y);
1503
+ ctx.lineTo(b.x, b.y);
1504
+ }
1505
+ ctx.stroke();
1506
+ }
1507
+ function drawFill(ctx, fill, mode, px) {
1508
+ const color = LAYER_COLOR[fill.layer] ?? PALETTE.topCopper;
1509
+ ctx.fillStyle = color;
1510
+ ctx.strokeStyle = color;
1511
+ if (mode === "outline") {
1512
+ ctx.globalAlpha = 1;
1513
+ strokeRings(ctx, fill, OUTLINE_PX2 * px);
1514
+ return;
1515
+ }
1516
+ ctx.globalAlpha = POUR_FILL_ALPHA;
1517
+ if (mode === "solid") return fillRings(ctx, fill, "fill");
1518
+ ctx.save();
1519
+ fillRings(ctx, fill, "clip");
1520
+ ctx.lineWidth = OUTLINE_PX2 * px;
1521
+ ctx.globalAlpha = 1;
1522
+ strokeHatch(ctx, fill, px);
1523
+ ctx.restore();
1524
+ ctx.globalAlpha = 1;
1525
+ strokeRings(ctx, fill, OUTLINE_PX2 * px);
1526
+ }
1527
+ function drawPourFills(ctx, layout, scene, layers, px) {
1528
+ const shown = (layout.pours ?? []).filter((fill) => pourShown(fill, layers, scene.hidden));
1529
+ const ordered = [...shown.filter((fill) => fill.layer !== scene.activeLayer), ...shown.filter((fill) => fill.layer === scene.activeLayer)];
1530
+ for (const fill of ordered) drawFill(ctx, fill, scene.mode, px);
1531
+ ctx.globalAlpha = 1;
1532
+ }
1533
+ function square(ctx, at, size) {
1534
+ const half = size / 2;
1535
+ ctx.beginPath();
1536
+ ctx.moveTo(at.x - half, at.y - half);
1537
+ ctx.lineTo(at.x + half, at.y - half);
1538
+ ctx.lineTo(at.x + half, at.y + half);
1539
+ ctx.lineTo(at.x - half, at.y + half);
1540
+ ctx.closePath();
1541
+ }
1542
+ function drawSelectedOutline(ctx, outline2, handles, px) {
1543
+ ctx.strokeStyle = PALETTE.selection;
1544
+ ctx.lineWidth = SELECTED_PX * px;
1545
+ ctx.beginPath();
1546
+ ringPath(ctx, outline2);
1547
+ ctx.stroke();
1548
+ if (!handles) return;
1549
+ ctx.fillStyle = PALETTE.selection;
1550
+ for (const corner of outline2) {
1551
+ square(ctx, corner, HANDLE_PX * px);
1552
+ ctx.fill();
1553
+ }
1554
+ }
1555
+ function drawOutline(ctx, pour, outline2, scene, px, hair) {
1556
+ if (scene.selected.has(pour.id)) return drawSelectedOutline(ctx, outline2, pour.outline !== void 0, px);
1557
+ const hovered = scene.hover === pour.id;
1558
+ if (!hovered && pour.outline === void 0) return;
1559
+ ctx.strokeStyle = hovered ? PALETTE.hover : LAYER_COLOR[pour.layer] ?? PALETTE.topCopper;
1560
+ ctx.lineWidth = Math.max(hair, OUTLINE_PX2 * px);
1561
+ ctx.setLineDash([4 * px, 3 * px]);
1562
+ ctx.beginPath();
1563
+ ringPath(ctx, outline2);
1564
+ ctx.stroke();
1565
+ ctx.setLineDash([]);
1566
+ }
1567
+ function drawPreview(ctx, corners, px) {
1568
+ if (corners.length < 2) return;
1569
+ ctx.strokeStyle = PALETTE.selection;
1570
+ ctx.lineWidth = OUTLINE_PX2 * px;
1571
+ ctx.setLineDash([4 * px, 3 * px]);
1572
+ ctx.beginPath();
1573
+ ringPath(ctx, corners);
1574
+ ctx.stroke();
1575
+ ctx.setLineDash([]);
1576
+ }
1577
+ function drawPourOutlines(ctx, layout, scene, layers, px, hair) {
1578
+ for (const pour of layout.board?.pours ?? []) {
1579
+ if (!pourShown(pour, layers, scene.hidden)) continue;
1580
+ drawOutline(ctx, pour, scene.outlines?.get(pour.id) ?? pourOutline(pour, layout.board), scene, px, hair);
1581
+ }
1582
+ if (scene.preview) drawPreview(ctx, scene.preview, px);
1583
+ }
1584
+ function drawHoles(ctx, holes, scene, layers, px, hair) {
1585
+ if (!layers.hole) return;
1586
+ for (const hole of holes) {
1587
+ const r = hole.diameter / 2;
1588
+ ctx.fillStyle = PALETTE.drill;
1589
+ ctx.beginPath();
1590
+ ctx.arc(hole.x, hole.y, r, 0, Math.PI * 2);
1591
+ ctx.fill();
1592
+ const selected = scene.selected.has(hole.id);
1593
+ ctx.strokeStyle = selected ? PALETTE.selection : scene.hover === hole.id ? PALETTE.hover : PALETTE.multiLayer;
1594
+ ctx.lineWidth = selected ? SELECTED_PX * px : hair;
1595
+ ctx.stroke();
1596
+ }
1597
+ }
1598
+
1599
+ // src/engine/schematic-geometry.ts
1600
+ var tidy3 = (value) => clean(value) + 0;
1601
+ var turnsOf = (rotation) => Math.round((rotation % 360 + 360) % 360 / 90) % 4;
1602
+ function rotatePoint(p, rotation) {
1603
+ switch (turnsOf(rotation)) {
1604
+ case 1:
1605
+ return { x: tidy3(-p.y), y: tidy3(p.x) };
1606
+ case 2:
1607
+ return { x: tidy3(-p.x), y: tidy3(-p.y) };
1608
+ case 3:
1609
+ return { x: tidy3(p.y), y: tidy3(-p.x) };
1610
+ default:
1611
+ return { x: tidy3(p.x), y: tidy3(p.y) };
1612
+ }
1613
+ }
1614
+ function sheetPoint(p, at) {
1615
+ const turned = rotatePoint(p, at.rotation);
1616
+ return { x: tidy3(at.x + turned.x), y: tidy3(at.y + turned.y) };
1617
+ }
1618
+
1619
+ // src/engine/part-labels.ts
1620
+ var PROP_OF = { reference: "schNameAt", value: "schValueAt" };
1621
+ var partLabelId = (part, prop) => `${part}:${prop}`;
1622
+ function textBox3(at, size, length) {
1623
+ const half = CHAR_WIDTH * size * length / 2;
1624
+ return { minX: at.x - half, maxX: at.x + half, minY: at.y - size / 2, maxY: at.y + size / 2 };
1625
+ }
1626
+ function partLabels(placed) {
1627
+ return placed.symbol.shapes.flatMap((shape) => {
1628
+ if (shape.type !== "text" || shape.role !== "reference" && shape.role !== "value") return [];
1629
+ const at = sheetPoint(shape.at, placed);
1630
+ const prop = PROP_OF[shape.role];
1631
+ const offset = { x: tidy3(at.x - placed.x), y: tidy3(at.y - placed.y) };
1632
+ return [{ id: partLabelId(placed.component, prop), part: placed.component, prop, text: shape.text, at, offset, box: textBox3(at, shape.size, shape.text.length) }];
1633
+ });
1634
+ }
1635
+
1636
+ // studio/src/pcb/part-text.ts
1637
+ var DESIGNATOR_MM = 0.8;
1638
+ function sheetTexts(layout) {
1639
+ return layout.symbols.flatMap((placed) => partLabels(placed));
1640
+ }
1641
+
1642
+ // studio/src/pcb/pcb-draw.ts
1643
+ var PLAIN_POURS = { mode: "solid", hidden: /* @__PURE__ */ new Set(), selected: /* @__PURE__ */ new Set(), activeLayer: "top" };
1644
+ var NO_SHIFT2 = { x: 0, y: 0 };
1645
+ var AUTO_COURTYARD_PX = 1.5;
1646
+ var LIT_WASH_ALPHA = 0.35;
1647
+ var LIT_OUTLINE_PX = 1.5;
1648
+ var RATSNEST_ALPHA = 0.6;
1649
+ var SILK_WIDTH_MM = 0.12;
1650
+ var BOARD_EDGE_PX = 1.5;
1651
+ var KEEPOUT_ALPHA = 0.7;
1652
+ var KEEPOUT_HATCH_MM = 0.5;
1653
+ var MAX_HATCH_LINES = 400;
1654
+ var HATCH_SLACK = 1e-9;
1655
+ var DEFAULT_CORNER = 0.25;
1656
+ var AUTO_PLACED_ALPHA = 0.6;
1657
+ var rad3 = (degrees) => degrees * Math.PI / 180;
1658
+ var shownOn = (layers, part, kind) => layers[`${part.side === "top" ? "top" : "bottom"}${kind}`];
1659
+ var alphaOf = (part) => part.autoPlaced ? AUTO_PLACED_ALPHA : 1;
1660
+ var assemblyColor = (part) => part.side === "top" ? PALETTE.topAssembly : PALETTE.bottomAssembly;
1661
+ function drawPcb(ctx, layout, view, options) {
1662
+ const layers = { ...DEFAULT_LAYERS, ...options.layers };
1663
+ const { camera, size } = view;
1664
+ const px = 1 / camera.scale;
1665
+ const hair = devicePixelIn(px, options.ratio);
1666
+ const shiftOf = (part) => options.moving?.components.includes(part.component) ? options.moving.by : NO_SHIFT2;
1667
+ const each = (paint) => {
1668
+ for (const part of layout.parts) {
1669
+ framed(ctx, shiftOf(part).x, shiftOf(part).y, 0, () => {
1670
+ ctx.globalAlpha = alphaOf(part);
1671
+ paint(part);
1672
+ });
1673
+ }
1674
+ ctx.globalAlpha = 1;
1675
+ };
1676
+ ctx.save();
1677
+ ctx.setTransform(...worldMatrix(view, options.ratio));
1678
+ ctx.lineCap = "round";
1679
+ ctx.lineJoin = "round";
1680
+ if (layers.keepout) drawKeepouts(ctx, layout, px, hair);
1681
+ const pours = options.pours ?? PLAIN_POURS;
1682
+ drawPourFills(ctx, layout, pours, layers, px);
1683
+ drawCopper(ctx, layers, options.highlight, each, px);
1684
+ if (options.copper) drawCopperItems(ctx, options.copper, layers, options.highlight, px);
1685
+ if (layers.hole) drawDrills(ctx, each);
1686
+ drawHoles(ctx, layout.holes ?? [], pours, layers, px, hair);
1687
+ drawPourOutlines(ctx, layout, pours, layers, px, hair);
1688
+ each((part) => {
1689
+ if (shownOn(layers, part, "Silk")) drawPolylines(ctx, part.silkscreen, part.side === "top" ? PALETTE.topSilk : PALETTE.bottomSilk, Math.max(SILK_WIDTH_MM, hair), false);
1690
+ });
1691
+ if (layers.courtyard) drawCourtyards(ctx, each, px, hair);
1692
+ each((part) => {
1693
+ if (shownOn(layers, part, "Assembly")) drawPolylines(ctx, part.fabrication, assemblyColor(part), hair, false);
1694
+ });
1695
+ if (layers.boardOutline) {
1696
+ drawBoard(ctx, layout, () => {
1697
+ ctx.strokeStyle = PALETTE.boardEdge;
1698
+ ctx.lineWidth = BOARD_EDGE_PX * px;
1699
+ ctx.stroke();
1700
+ });
1701
+ }
1702
+ if (options.ratsnest !== false && layers.ratline) drawRatsnest(ctx, layout, options, hair);
1703
+ ctx.setTransform(options.ratio, 0, 0, options.ratio, 0, 0);
1704
+ sharpenText(ctx);
1705
+ for (const part of layout.parts) if (shownOn(layers, part, "Silk")) drawDesignator(ctx, part, camera, size, shiftOf(part), options.ratio);
1706
+ drawViolationMarkers(ctx, view, options.violations ?? [], options.activeViolation, true);
1707
+ ctx.restore();
1708
+ }
1709
+ function worldMatrix({ camera, size }, ratio) {
1710
+ const s = camera.scale * ratio;
1711
+ return [s, 0, 0, -s, (size.width / 2 - camera.cx * camera.scale) * ratio, (size.height / 2 + camera.cy * camera.scale) * ratio];
1712
+ }
1713
+ function framed(ctx, x, y, degrees, shape) {
1714
+ ctx.save();
1715
+ ctx.translate(x, y);
1716
+ if (degrees) ctx.rotate(rad3(degrees));
1717
+ shape();
1718
+ ctx.restore();
1719
+ }
1720
+ function polygon2(ctx, points) {
1721
+ ctx.beginPath();
1722
+ points.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
1723
+ ctx.closePath();
1724
+ }
1725
+ function circle2(ctx, x, y, r) {
1726
+ ctx.beginPath();
1727
+ ctx.arc(x, y, Math.max(r, 0), 0, Math.PI * 2);
1728
+ }
1729
+ function roundRect(ctx, w, h, r) {
1730
+ const radius = Math.max(0, Math.min(r, w / 2, h / 2));
1731
+ const x = -w / 2;
1732
+ const y = -h / 2;
1733
+ ctx.beginPath();
1734
+ ctx.moveTo(x + radius, y);
1735
+ ctx.arcTo(x + w, y, x + w, y + h, radius);
1736
+ ctx.arcTo(x + w, y + h, x, y + h, radius);
1737
+ ctx.arcTo(x, y + h, x, y, radius);
1738
+ ctx.arcTo(x, y, x + w, y, radius);
1739
+ ctx.closePath();
1740
+ }
1741
+ var stadium = (ctx, w, h) => roundRect(ctx, w, h, Math.min(w, h) / 2);
1742
+ function drawBoard(ctx, layout, paint) {
1743
+ const outline2 = layout.board?.outline;
1744
+ if (!outline2 || outline2.length < 3) return;
1745
+ polygon2(ctx, outline2);
1746
+ paint();
1747
+ }
1748
+ function drawKeepouts(ctx, layout, px, hair) {
1749
+ const keepouts = layout.board?.keepouts ?? [];
1750
+ if (keepouts.length === 0) return;
1751
+ ctx.strokeStyle = PALETTE.keepout;
1752
+ ctx.globalAlpha = KEEPOUT_ALPHA;
1753
+ for (const keepout of keepouts) {
1754
+ ctx.lineWidth = hair;
1755
+ ctx.setLineDash([4 * px, 3 * px]);
1756
+ polygon2(ctx, keepout.outline);
1757
+ ctx.stroke();
1758
+ ctx.setLineDash([]);
1759
+ ctx.save();
1760
+ polygon2(ctx, keepout.outline);
1761
+ ctx.clip();
1762
+ for (const [a, b] of hatchLines(keepout.outline)) drawLine(ctx, a, b);
1763
+ ctx.restore();
1764
+ }
1765
+ ctx.globalAlpha = 1;
1766
+ }
1767
+ function hatchLines(outline2) {
1768
+ const xs = outline2.map((p) => p.x);
1769
+ const ys = outline2.map((p) => p.y);
1770
+ const [minX, maxX, minY, maxY] = [Math.min(...xs), Math.max(...xs), Math.min(...ys), Math.max(...ys)];
1771
+ if (![minX, maxX, minY, maxY].every(Number.isFinite)) return [];
1772
+ const height = maxY - minY;
1773
+ const start = minX - height;
1774
+ const span = maxX - start;
1775
+ const step = Math.max(KEEPOUT_HATCH_MM, span / (MAX_HATCH_LINES - 1));
1776
+ const count = Math.floor(span / step + HATCH_SLACK) + 1;
1777
+ return Array.from({ length: count }, (_, i) => {
1778
+ const x = start + i * step;
1779
+ return [{ x, y: minY }, { x: x + height, y: maxY }];
1780
+ });
1781
+ }
1782
+ function padPath(ctx, pad) {
1783
+ framed(ctx, pad.x, pad.y, pad.rotation, () => {
1784
+ if (pad.shape === "circle") circle2(ctx, 0, 0, pad.width / 2);
1785
+ else if (pad.shape === "oval") stadium(ctx, pad.width, pad.height);
1786
+ else roundRect(ctx, pad.width, pad.height, pad.shape === "roundrect" ? pad.cornerRadius ?? DEFAULT_CORNER * Math.min(pad.width, pad.height) : 0);
1787
+ });
1788
+ }
1789
+ function padColor(pad) {
1790
+ if (pad.layers === "through") return PALETTE.multiLayer;
1791
+ return pad.layers === "bottom" ? PALETTE.bottomCopper : PALETTE.topCopper;
1792
+ }
1793
+ function drawCopper(ctx, layers, highlight, each, px) {
1794
+ const passes = [
1795
+ [layers.bottom, (pad) => pad.layers === "bottom"],
1796
+ [layers.top, (pad) => pad.layers === "top"],
1797
+ [layers.multiLayer, (pad) => pad.layers === "through"]
1798
+ ];
1799
+ for (const [visible, wanted] of passes) {
1800
+ if (!visible) continue;
1801
+ each((part) => {
1802
+ for (const pad of part.pads.filter(wanted)) {
1803
+ const lit = highlight !== void 0 && pad.net !== void 0 && highlight.nets.includes(pad.net);
1804
+ ctx.globalAlpha = (highlight && !lit ? PCB_DIM : 1) * alphaOf(part);
1805
+ ctx.fillStyle = padColor(pad);
1806
+ padPath(ctx, pad);
1807
+ ctx.fill();
1808
+ if (lit) lightPad(ctx, pad, px, alphaOf(part));
1809
+ }
1810
+ });
1811
+ }
1812
+ ctx.globalAlpha = 1;
1813
+ }
1814
+ function lightPad(ctx, pad, px, alpha) {
1815
+ ctx.globalAlpha = LIT_WASH_ALPHA * alpha;
1816
+ ctx.fillStyle = PALETTE.highlight;
1817
+ padPath(ctx, pad);
1818
+ ctx.fill();
1819
+ ctx.globalAlpha = alpha;
1820
+ ctx.strokeStyle = PALETTE.highlight;
1821
+ ctx.lineWidth = LIT_OUTLINE_PX * px;
1822
+ ctx.stroke();
1823
+ }
1824
+ function drawDrills(ctx, each) {
1825
+ ctx.fillStyle = PALETTE.drill;
1826
+ each((part) => {
1827
+ for (const pad of part.pads) {
1828
+ const { drill } = pad;
1829
+ if (!drill) continue;
1830
+ if (drill.width === drill.height) circle2(ctx, pad.x, pad.y, drill.width / 2);
1831
+ else framed(ctx, pad.x, pad.y, pad.rotation, () => stadium(ctx, drill.width, drill.height));
1832
+ ctx.fill();
1833
+ }
1834
+ });
1835
+ }
1836
+ function drawPolylines(ctx, lines, color, width, closed) {
1837
+ ctx.strokeStyle = color;
1838
+ ctx.lineWidth = width;
1839
+ for (const line2 of lines) {
1840
+ if (line2.length < 2) continue;
1841
+ ctx.beginPath();
1842
+ line2.forEach((p, i) => i === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y));
1843
+ if (closed) ctx.closePath();
1844
+ ctx.stroke();
1845
+ }
1846
+ }
1847
+ function drawCourtyards(ctx, each, px, hair) {
1848
+ ctx.setLineDash([4 * px, 3 * px]);
1849
+ each((part) => {
1850
+ ctx.globalAlpha = 1;
1851
+ drawPolylines(ctx, [part.courtyard], assemblyColor(part), part.autoPlaced ? AUTO_COURTYARD_PX * px : hair, true);
1852
+ });
1853
+ ctx.setLineDash([]);
1854
+ }
1855
+ function drawRatsnest(ctx, layout, options, hair) {
1856
+ const moving = options.moving;
1857
+ const movingPads = new Set(layout.parts.filter((p) => moving?.components.includes(p.component)).flatMap((p) => p.pads.map((pad) => pad.id)));
1858
+ const end = (point, pad) => moving && movingPads.has(pad) ? { x: point.x + moving.by.x, y: point.y + moving.by.y } : point;
1859
+ ctx.lineWidth = hair;
1860
+ for (const line2 of layout.ratsnest) {
1861
+ const lit = options.highlight?.nets.includes(line2.net) ?? false;
1862
+ ctx.strokeStyle = lit ? PALETTE.highlight : PALETTE.ratsnest;
1863
+ ctx.globalAlpha = lit ? 1 : options.highlight ? RATSNEST_ALPHA * PCB_DIM : RATSNEST_ALPHA;
1864
+ drawLine(ctx, end(line2.a, line2.from), end(line2.b, line2.to));
1865
+ }
1866
+ ctx.globalAlpha = 1;
1867
+ }
1868
+ function drawLine(ctx, a, b) {
1869
+ ctx.beginPath();
1870
+ ctx.moveTo(a.x, a.y);
1871
+ ctx.lineTo(b.x, b.y);
1872
+ ctx.stroke();
1873
+ }
1874
+ function drawDesignator(ctx, part, camera, size, shift, ratio) {
1875
+ const devicePx = devicePxFor(DESIGNATOR_MM, camera.scale, ratio);
1876
+ if (!textShown("name", devicePx, devicePx)) return;
1877
+ const spot = designatorAnchor(part);
1878
+ const p = textAnchorAt(worldToScreen(camera, size, { x: spot.x + shift.x, y: spot.y + shift.y }), ratio);
1879
+ ctx.fillStyle = part.side === "top" ? PALETTE.topSilk : PALETTE.bottomSilk;
1880
+ ctx.globalAlpha = alphaOf(part);
1881
+ ctx.font = canvasFont(TEXT_WEIGHT.strong, devicePx / ratio);
1882
+ ctx.textAlign = "center";
1883
+ ctx.textBaseline = "middle";
1884
+ if (designatorTurn(part) === 90) {
1885
+ ctx.save();
1886
+ ctx.translate(p.x, p.y);
1887
+ ctx.rotate(-Math.PI / 2);
1888
+ ctx.fillText(part.component, 0, 0);
1889
+ ctx.restore();
1890
+ } else ctx.fillText(part.component, p.x, p.y);
1891
+ ctx.globalAlpha = 1;
1892
+ }
1893
+
1894
+ // studio/src/pcb/label-drag.ts
1895
+ var LABEL_REACH = 0.1;
1896
+ function labelDrawnBox(label) {
1897
+ if (label.style === "label") return labelTag(label).box;
1898
+ const bounds = boundsOf(label.style === "ground" ? groundSymbol() : powerSymbol(label.text), []);
1899
+ return { minX: label.at.x + bounds.minX, minY: label.at.y + bounds.minY, maxX: label.at.x + bounds.maxX, maxY: label.at.y + bounds.maxY };
1900
+ }
1901
+ function labelHitBox(label) {
1902
+ const drawn = labelDrawnBox(label);
1903
+ if (label.style === "label") return drawn;
1904
+ return { minX: drawn.minX - LABEL_REACH, minY: drawn.minY - LABEL_REACH, maxX: drawn.maxX + LABEL_REACH, maxY: drawn.maxY + LABEL_REACH };
1905
+ }
1906
+
1907
+ // studio/src/pcb/drawing-extents.ts
1908
+ function drawingBox(drawing) {
1909
+ const box = drawingBounds(drawing);
1910
+ const half = "strokeWidth" in drawing ? drawing.strokeWidth / 2 : 0;
1911
+ return { minX: box.minX - half, minY: box.minY - half, maxX: box.maxX + half, maxY: box.maxY + half };
1912
+ }
1913
+ function drawingExtents(layout) {
1914
+ const boxes = [...sheetBoxes(layout).map((part) => part.box), ...sheetTexts(layout).map((text2) => text2.box)];
1915
+ boxes.push(...layout.labels.map(labelHitBox), ...layout.drawings.map(drawingBox));
1916
+ const points = [...layout.wires.flatMap((wire) => wire.points), ...layout.junctions];
1917
+ const pointBox = pointBounds(points);
1918
+ if (pointBox) boxes.push(pointBox);
1919
+ return unionBoxes(boxes);
1920
+ }
1921
+
1922
+ // src/engine/model.ts
1923
+ var MAIN_PAGE = "Main";
1924
+
1925
+ // studio/src/shell/schematic-pages.ts
1926
+ function pageNames(design) {
1927
+ const pages = design?.schematic.pages?.map((page) => page.name);
1928
+ return pages && pages.length > 0 ? pages : [MAIN_PAGE];
1929
+ }
1930
+ function designOnPage(design, page) {
1931
+ const pages = design.schematic.pages ?? [];
1932
+ const entry = pages.find((candidate) => candidate.name === page);
1933
+ if (pages.length <= 1 || !entry) return design;
1934
+ const keep = (list, ids, idOf) => {
1935
+ const wanted = new Set(ids);
1936
+ return list.filter((item) => wanted.has(idOf(item)));
1937
+ };
1938
+ const { schematic } = design;
1939
+ return {
1940
+ ...design,
1941
+ schematic: {
1942
+ ...schematic,
1943
+ symbols: keep(schematic.symbols, entry.parts, (s) => s.component),
1944
+ wires: keep(schematic.wires, entry.wires, (w) => w.id),
1945
+ labels: keep(schematic.labels, entry.labels, (l) => l.id),
1946
+ drawings: keep(schematic.drawings, entry.drawings, (d) => d.id),
1947
+ junctions: entry.junctions,
1948
+ ...schematic.noConnects ? { noConnects: keep(schematic.noConnects, entry.parts, (flag) => flag.component) } : {}
1949
+ }
1950
+ };
1951
+ }
1952
+
1953
+ // studio/src/render/render-frame.ts
1954
+ var MIN_WIDTH = 320;
1955
+ var MAX_WIDTH = 2e3;
1956
+ var DEFAULT_WIDTH = 1024;
1957
+ var WHOLE_MARGIN = 0.04;
1958
+ var PART_MARGIN = 0.25;
1959
+ var MIN_PART_MARGIN = 1.5;
1960
+ var MAX_ASPECT = 4;
1961
+ var round1 = (value) => Math.round(value * 10) / 10;
1962
+ function grown(box, share, least) {
1963
+ const pad = Math.max(Math.max(box.maxX - box.minX, box.maxY - box.minY) * share, least);
1964
+ return { minX: box.minX - pad, minY: box.minY - pad, maxX: box.maxX + pad, maxY: box.maxY + pad };
1965
+ }
1966
+ function partBoxes(names, boxes, where) {
1967
+ const missing = names.filter((name) => !boxes.has(name));
1968
+ if (missing.length > 0) throw new Error(`${missing.length === 1 ? "No part" : "No parts"} named ${missing.join(", ")} ${where}`);
1969
+ const box = unionBoxes(names.map((name) => boxes.get(name)));
1970
+ if (!box) throw new Error("No parts were named to zoom to");
1971
+ return box;
1972
+ }
1973
+ function pcbFrame(design, parts) {
1974
+ const pcb = design.pcb;
1975
+ if (parts && parts.length > 0) {
1976
+ const boxes = new Map(pcb.parts.flatMap((part) => {
1977
+ const box2 = pointBounds(part.courtyard);
1978
+ return box2 ? [[part.component, box2]] : [];
1979
+ }));
1980
+ return { box: grown(partBoxes(parts, boxes, "on the board"), PART_MARGIN, MIN_PART_MARGIN), what: `PCB, around ${parts.join(", ")}`, design };
1981
+ }
1982
+ const outline2 = pointBounds(pcb.board?.outline ?? []);
1983
+ const courtyards = pcb.parts.flatMap((part) => pointBounds(part.courtyard) ?? []);
1984
+ const board = outline2 ?? unionBoxes(courtyards);
1985
+ if (!board) throw new Error("The board is empty: it has no outline and no parts to draw");
1986
+ const size = `${round1(board.maxX - board.minX)} x ${round1(board.maxY - board.minY)} mm`;
1987
+ if (!outline2) return { box: grown(board, WHOLE_MARGIN, 0), what: `PCB, all parts ${size}`, design };
1988
+ const outside = courtyards.filter((yard) => yard.minX < outline2.minX || yard.maxX > outline2.maxX || yard.minY < outline2.minY || yard.maxY > outline2.maxY);
1989
+ const box = unionBoxes([outline2, ...outside]) ?? outline2;
1990
+ const also = outside.length === 0 ? "" : `, and ${outside.length} ${outside.length === 1 ? "part" : "parts"} outside it`;
1991
+ return { box: grown(box, WHOLE_MARGIN, 0), what: `PCB, whole board ${size}${also}`, design };
1992
+ }
1993
+ function schematicFrame(design, page, parts) {
1994
+ const pages = pageNames(design);
1995
+ const shown = page ?? pages[0] ?? "Main";
1996
+ if (!pages.includes(shown)) throw new Error(`No schematic page "${shown}"; the pages are ${pages.map((name) => `"${name}"`).join(", ")}`);
1997
+ const onPage = designOnPage(design, shown);
1998
+ const layout = onPage.schematic;
1999
+ const title = `Schematic page "${shown}"`;
2000
+ if (parts && parts.length > 0) {
2001
+ const boxes = new Map(sheetBoxes(layout).map((part) => [part.name, part.box]));
2002
+ return { box: grown(partBoxes(parts, boxes, `on page "${shown}"`), PART_MARGIN, MIN_PART_MARGIN), what: `${title}, around ${parts.join(", ")}`, page: shown, design: onPage };
2003
+ }
2004
+ const box = drawingExtents(layout);
2005
+ if (!box) throw new Error(`${title} is empty`);
2006
+ return { box: grown(box, WHOLE_MARGIN, 0), what: title, page: shown, design: onPage };
2007
+ }
2008
+ function frameFor(design, request) {
2009
+ if (request.view === "pcb") {
2010
+ if (request.page !== void 0) throw new Error("page is for the schematic only; the PCB has no pages");
2011
+ return pcbFrame(design, request.parts);
2012
+ }
2013
+ return schematicFrame(design, request.page, request.parts);
2014
+ }
2015
+ function widthOf(width) {
2016
+ const chosen = width ?? DEFAULT_WIDTH;
2017
+ if (!Number.isInteger(chosen) || chosen < MIN_WIDTH || chosen > MAX_WIDTH) throw new Error(`width must be a whole number of pixels from ${MIN_WIDTH} to ${MAX_WIDTH}`);
2018
+ return chosen;
2019
+ }
2020
+ function imageSize(box, width) {
2021
+ const across = Math.max(box.maxX - box.minX, 1e-6);
2022
+ const down = Math.max(box.maxY - box.minY, 1e-6);
2023
+ const aspect = Math.min(Math.max(down / across, 1 / MAX_ASPECT), MAX_ASPECT);
2024
+ return { width, height: Math.max(1, Math.round(width * aspect)) };
2025
+ }
2026
+ function cameraFor(box, size) {
2027
+ return fitCamera(box, size, 0);
2028
+ }
2029
+
2030
+ // studio/src/render/node-render.ts
2031
+ async function renderDesign(design, request) {
2032
+ const width = widthOf(request.width);
2033
+ const frame = frameFor(design, request);
2034
+ const size = imageSize(frame.box, width);
2035
+ const view = { camera: cameraFor(frame.box, size), size };
2036
+ const { createCanvas } = await import("@napi-rs/canvas");
2037
+ const canvas = createCanvas(size.width, size.height);
2038
+ const ctx = canvas.getContext("2d");
2039
+ if (request.view === "pcb") {
2040
+ ctx.fillStyle = PALETTE.background;
2041
+ ctx.fillRect(0, 0, size.width, size.height);
2042
+ const pcb = frame.design.pcb;
2043
+ drawPcb(ctx, pcb, view, { ratio: 1, copper: { tracks: pcb.tracks, vias: pcb.vias, selected: /* @__PURE__ */ new Set() } });
2044
+ } else {
2045
+ const colours = schematicThemeFor("light");
2046
+ ctx.fillStyle = colours.background;
2047
+ ctx.fillRect(0, 0, size.width, size.height);
2048
+ setSheetPalette(colours);
2049
+ try {
2050
+ drawSchematic(ctx, frame.design.schematic, view, { ratio: 1 });
2051
+ } finally {
2052
+ resetSheetPalette();
2053
+ }
2054
+ }
2055
+ const png = await canvas.encode("png");
2056
+ return { png: new Uint8Array(png), width: size.width, height: size.height, what: frame.what, ...frame.page !== void 0 ? { page: frame.page } : {} };
2057
+ }
2058
+ export {
2059
+ renderDesign
2060
+ };