-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathkicad_parser.py
More file actions
2067 lines (1709 loc) · 76.1 KB
/
kicad_parser.py
File metadata and controls
2067 lines (1709 loc) · 76.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
KiCad PCB Parser - Extracts pads, nets, tracks, vias, and board info from .kicad_pcb files.
"""
import re
import math
import json
from dataclasses import dataclass, field, asdict
from typing import Dict, List, Tuple, Optional
from pathlib import Path
# Position rounding precision for coordinate comparisons
# All position-based lookups must use this to ensure consistency
POSITION_DECIMALS = 3
# KiCad 10 removed numeric net IDs from the file format.
# Files with version >= this threshold use name-only nets: (net "name") instead of (net 29 "name").
# KiCad 9 uses version 20241229; KiCad 10 uses version 20260206.
KICAD_10_MIN_VERSION = 20250000
def detect_kicad_version(content: str) -> int:
"""Extract version number from (version YYYYMMDD) header."""
m = re.search(r'\(version\s+(\d+)\)', content)
return int(m.group(1)) if m else 0
def is_kicad_10(content: str) -> bool:
"""Check if file content is KiCad 10+ format (name-only nets)."""
return detect_kicad_version(content) >= KICAD_10_MIN_VERSION
@dataclass
class Pad:
"""Represents a component pad with global board coordinates."""
component_ref: str
pad_number: str
global_x: float
global_y: float
local_x: float
local_y: float
size_x: float
size_y: float
shape: str # circle, rect, roundrect, etc.
layers: List[str]
net_id: int
net_name: str
rotation: float = 0.0 # Total rotation in degrees (pad + footprint)
pinfunction: str = ""
drill: float = 0.0 # Drill size for through-hole pads (0 for SMD)
pintype: str = ""
roundrect_rratio: float = 0.0 # Corner radius ratio for roundrect pads
@dataclass
class Via:
"""Represents a via."""
x: float
y: float
size: float
drill: float
layers: List[str]
net_id: int
uuid: str = ""
free: bool = False # If True, KiCad won't auto-assign net based on overlapping tracks
@dataclass
class Segment:
"""Represents a track segment."""
start_x: float
start_y: float
end_x: float
end_y: float
width: float
layer: str
net_id: int
uuid: str = ""
# Original string representations for exact file matching
start_x_str: str = ""
start_y_str: str = ""
end_x_str: str = ""
end_y_str: str = ""
@dataclass
class Zone:
"""Represents a filled zone (power plane)."""
net_id: int
net_name: str
layer: str
polygon: List[Tuple[float, float]] # List of (x, y) vertices defining the zone outline
uuid: str = ""
@dataclass
class Footprint:
"""Represents a component footprint."""
reference: str
footprint_name: str
x: float
y: float
rotation: float
layer: str
pads: List[Pad] = field(default_factory=list)
value: str = "" # Component value (e.g., "MCF5213", "100nF", "10K")
@dataclass
class Net:
"""Represents a net (electrical connection)."""
net_id: int
name: str
pads: List[Pad] = field(default_factory=list)
@dataclass
class StackupLayer:
"""A layer in the board stackup."""
name: str
layer_type: str # 'copper', 'core', 'prepreg', etc.
thickness: float # in mm
epsilon_r: float = 0.0 # Dielectric constant (for dielectric layers)
loss_tangent: float = 0.0 # Loss tangent (for dielectric layers)
material: str = "" # Material name (e.g., "FR4", "S1000-2M")
@dataclass
class BoardInfo:
"""Board-level information."""
layers: Dict[int, str] # layer_id -> layer_name
copper_layers: List[str]
board_bounds: Optional[Tuple[float, float, float, float]] = None # min_x, min_y, max_x, max_y
stackup: List[StackupLayer] = field(default_factory=list) # ordered top to bottom
board_outline: List[Tuple[float, float]] = field(default_factory=list) # Polygon vertices for non-rectangular boards
board_cutouts: List[List[Tuple[float, float]]] = field(default_factory=list) # Interior cutout polygons
@dataclass
class PCBData:
"""Complete parsed PCB data."""
board_info: BoardInfo
nets: Dict[int, Net]
footprints: Dict[str, Footprint]
vias: List[Via]
segments: List[Segment]
pads_by_net: Dict[int, List[Pad]]
zones: List[Zone] = field(default_factory=list)
kicad_version: int = 0 # File format version (e.g., 20241229 for KiCad 9)
net_id_to_name: Dict[int, str] = field(default_factory=dict) # Synthetic ID -> net name (for KiCad 10 output)
def get_via_barrel_length(self, layer1: str, layer2: str) -> float:
"""Calculate the via barrel length between two copper layers.
Args:
layer1: First copper layer name (e.g., 'F.Cu', 'In2.Cu')
layer2: Second copper layer name
Returns:
Distance in mm through the board between the two layers
"""
stackup = self.board_info.stackup
if not stackup:
return 0.0
# Find indices of the two layers in stackup
idx1 = idx2 = -1
for i, layer in enumerate(stackup):
if layer.name == layer1:
idx1 = i
elif layer.name == layer2:
idx2 = i
if idx1 < 0 or idx2 < 0:
return 0.0
# Sum thicknesses between the two layers (exclusive of the layers themselves)
start_idx = min(idx1, idx2)
end_idx = max(idx1, idx2)
total = 0.0
for i in range(start_idx, end_idx + 1):
total += stackup[i].thickness
return total
def local_to_global(fp_x: float, fp_y: float, fp_rotation_deg: float,
pad_local_x: float, pad_local_y: float) -> Tuple[float, float]:
"""
Transform pad LOCAL coordinates to GLOBAL board coordinates.
CRITICAL: Negate the rotation angle! KiCad's rotation convention requires
negating the angle when applying the standard rotation matrix formula.
"""
rad = math.radians(-fp_rotation_deg) # CRITICAL: negate the angle
cos_r = math.cos(rad)
sin_r = math.sin(rad)
global_x = fp_x + (pad_local_x * cos_r - pad_local_y * sin_r)
global_y = fp_y + (pad_local_x * sin_r + pad_local_y * cos_r)
return global_x, global_y
def parse_s_expression(text: str) -> list:
"""
Simple S-expression parser - returns nested lists.
Not used for full file parsing (too slow), but useful for extracting specific elements.
"""
tokens = re.findall(r'"[^"]*"|\(|\)|[^\s()]+', text)
def parse_tokens(tokens, idx):
result = []
while idx < len(tokens):
token = tokens[idx]
if token == '(':
sublist, idx = parse_tokens(tokens, idx + 1)
result.append(sublist)
elif token == ')':
return result, idx
else:
# Remove quotes from strings
if token.startswith('"') and token.endswith('"'):
token = token[1:-1]
result.append(token)
idx += 1
return result, idx
result, _ = parse_tokens(tokens, 0)
return result
def extract_layers(content: str) -> BoardInfo:
"""Extract layer information from PCB file."""
layers = {}
copper_layers = []
# Find the layers section
layers_match = re.search(r'\(layers\s*((?:\([^)]+\)\s*)+)\)', content, re.DOTALL)
if layers_match:
layers_text = layers_match.group(1)
# Parse individual layer entries: (0 "F.Cu" signal)
layer_pattern = r'\((\d+)\s+"([^"]+)"\s+(\w+)'
for m in re.finditer(layer_pattern, layers_text):
layer_id = int(m.group(1))
layer_name = m.group(2)
layer_type = m.group(3)
layers[layer_id] = layer_name
if layer_type == 'signal' and '.Cu' in layer_name:
copper_layers.append(layer_name)
# Extract board bounds from Edge.Cuts
bounds = extract_board_bounds(content)
# Extract board outline polygon and cutouts for non-rectangular boards
outline, cutouts = extract_board_contours(content)
# Extract stackup information
stackup = extract_stackup(content)
return BoardInfo(layers=layers, copper_layers=copper_layers, board_bounds=bounds, stackup=stackup, board_outline=outline, board_cutouts=cutouts)
def extract_stackup(content: str) -> List[StackupLayer]:
"""Extract board stackup information for impedance calculation and via barrel length.
Extracts copper and dielectric layers with their electrical properties:
- thickness: layer thickness in mm
- epsilon_r: dielectric constant (for dielectric layers)
- loss_tangent: loss tangent (for dielectric layers)
- material: material name
"""
stackup = []
# Find the stackup section
stackup_match = re.search(r'\(stackup\s+(.*?)\n\s*\(copper_finish', content, re.DOTALL)
if not stackup_match:
# Try alternate pattern without copper_finish
stackup_match = re.search(r'\(stackup\s+(.*?)\n\s*\)\s*\n', content, re.DOTALL)
if not stackup_match:
return stackup
stackup_text = stackup_match.group(1)
# Parse each layer in stackup
# Pattern matches: (layer "name" (type "typename") (thickness value) ...)
# We need to handle multi-line layer definitions
layer_blocks = re.findall(r'\(layer\s+"([^"]+)"(.*?)(?=\(layer\s+"|$)', stackup_text, re.DOTALL)
for layer_name, layer_content in layer_blocks:
# Extract type
type_match = re.search(r'\(type\s+"([^"]+)"\)', layer_content)
layer_type = type_match.group(1) if type_match else 'unknown'
# Extract thickness (in mm)
thickness_match = re.search(r'\(thickness\s+([\d.]+)\)', layer_content)
thickness = float(thickness_match.group(1)) if thickness_match else 0.0
# Extract dielectric constant (epsilon_r)
epsilon_match = re.search(r'\(epsilon_r\s+([\d.]+)\)', layer_content)
epsilon_r = float(epsilon_match.group(1)) if epsilon_match else 0.0
# Extract loss tangent
loss_match = re.search(r'\(loss_tangent\s+([\d.]+)\)', layer_content)
loss_tangent = float(loss_match.group(1)) if loss_match else 0.0
# Extract material name
material_match = re.search(r'\(material\s+"([^"]+)"\)', layer_content)
material = material_match.group(1) if material_match else ""
# Only include copper and dielectric layers (skip mask, silk, paste)
if layer_type in ('copper', 'core', 'prepreg'):
stackup.append(StackupLayer(
name=layer_name,
layer_type=layer_type,
thickness=thickness,
epsilon_r=epsilon_r,
loss_tangent=loss_tangent,
material=material
))
return stackup
def _arc_to_segments(start: Tuple[float, float], mid: Tuple[float, float],
end: Tuple[float, float], num_segments: int = 16
) -> List[Tuple[Tuple[float, float], Tuple[float, float]]]:
"""Convert a 3-point arc to a polyline of straight segments.
Given start, mid (on arc), and end points, computes the circular arc
and returns it as a list of (start, end) line segment tuples.
"""
ax, ay = start
bx, by = mid
cx, cy = end
# Find circle center from 3 points using perpendicular bisector intersection
d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by))
if abs(d) < 1e-10:
# Degenerate (collinear points) - just return a straight line
return [(start, end)]
ux = ((ax * ax + ay * ay) * (by - cy) + (bx * bx + by * by) * (cy - ay) + (cx * cx + cy * cy) * (ay - by)) / d
uy = ((ax * ax + ay * ay) * (cx - bx) + (bx * bx + by * by) * (ax - cx) + (cx * cx + cy * cy) * (bx - ax)) / d
radius = math.hypot(ax - ux, ay - uy)
# Compute angles
angle_start = math.atan2(ay - uy, ax - ux)
angle_mid = math.atan2(by - uy, bx - ux)
angle_end = math.atan2(cy - uy, cx - ux)
# Determine arc direction: going from start to end, mid must be on the arc
# Normalize angles relative to start
def normalize(a, ref):
a = a - ref
while a < 0:
a += 2 * math.pi
while a >= 2 * math.pi:
a -= 2 * math.pi
return a
mid_ccw = normalize(angle_mid, angle_start)
end_ccw = normalize(angle_end, angle_start)
# If going CCW from start, mid should come before end
if mid_ccw <= end_ccw:
# CCW direction, sweep = end_ccw
sweep = end_ccw
else:
# CW direction, sweep is negative
sweep = end_ccw - 2 * math.pi
# Generate points along the arc, using exact start/end to preserve chaining
points = [start]
for i in range(1, num_segments):
t = i / num_segments
angle = angle_start + t * sweep
points.append((ux + radius * math.cos(angle), uy + radius * math.sin(angle)))
points.append(end)
# Build segments
segments = []
for i in range(len(points) - 1):
segments.append((points[i], points[i + 1]))
return segments
def extract_board_bounds(content: str) -> Optional[Tuple[float, float, float, float]]:
"""Extract board outline bounds from Edge.Cuts layer."""
min_x = min_y = float('inf')
max_x = max_y = float('-inf')
found = False
# Look for gr_rect on Edge.Cuts (multi-line format)
rect_pattern = r'\(gr_rect\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(rect_pattern, content, re.DOTALL):
x1, y1, x2, y2 = float(m.group(1)), float(m.group(2)), float(m.group(3)), float(m.group(4))
min_x = min(min_x, x1, x2)
min_y = min(min_y, y1, y2)
max_x = max(max_x, x1, x2)
max_y = max(max_y, y1, y2)
found = True
# Look for gr_line on Edge.Cuts (multi-line format)
line_pattern = r'\(gr_line\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(line_pattern, content, re.DOTALL):
x1, y1, x2, y2 = float(m.group(1)), float(m.group(2)), float(m.group(3)), float(m.group(4))
min_x = min(min_x, x1, x2)
min_y = min(min_y, y1, y2)
max_x = max(max_x, x1, x2)
max_y = max(max_y, y1, y2)
found = True
# Look for gr_arc on Edge.Cuts (multi-line format)
arc_pattern = r'\(gr_arc\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(mid\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(arc_pattern, content, re.DOTALL):
sx, sy = float(m.group(1)), float(m.group(2))
mx, my = float(m.group(3)), float(m.group(4))
ex, ey = float(m.group(5)), float(m.group(6))
# Use linearized arc points for accurate bounds
for seg in _arc_to_segments((sx, sy), (mx, my), (ex, ey)):
for px, py in seg:
min_x = min(min_x, px)
max_x = max(max_x, px)
min_y = min(min_y, py)
max_y = max(max_y, py)
found = True
if found:
return (min_x, min_y, max_x, max_y)
return None
def _collect_edge_cuts_segments(content: str) -> List[Tuple[Tuple[float, float], Tuple[float, float]]]:
"""Parse all gr_line, gr_arc, and gr_rect segments on Edge.Cuts from file content."""
segments = []
# gr_line
line_pattern = r'\(gr_line\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(line_pattern, content, re.DOTALL):
x1, y1, x2, y2 = float(m.group(1)), float(m.group(2)), float(m.group(3)), float(m.group(4))
segments.append(((x1, y1), (x2, y2)))
# gr_arc - approximate as polyline
arc_pattern = r'\(gr_arc\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(mid\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(arc_pattern, content, re.DOTALL):
sx, sy = float(m.group(1)), float(m.group(2))
mx, my = float(m.group(3)), float(m.group(4))
ex, ey = float(m.group(5)), float(m.group(6))
segments.extend(_arc_to_segments((sx, sy), (mx, my), (ex, ey)))
# gr_rect - expand to 4 line segments
rect_pattern = r'\(gr_rect\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\).*?\(layer\s+"Edge\.Cuts"\)'
for m in re.finditer(rect_pattern, content, re.DOTALL):
x1, y1, x2, y2 = float(m.group(1)), float(m.group(2)), float(m.group(3)), float(m.group(4))
segments.append(((x1, y1), (x2, y1)))
segments.append(((x2, y1), (x2, y2)))
segments.append(((x2, y2), (x1, y2)))
segments.append(((x1, y2), (x1, y1)))
return segments
def _chain_segments_into_contours(segments: List[Tuple[Tuple[float, float], Tuple[float, float]]],
tol: float = 0.01
) -> List[List[Tuple[float, float]]]:
"""Chain line segments into closed polygon contours.
Groups segments by connectivity (shared endpoints), chains each group
into a closed polygon. Returns list of polygons (each a list of vertices).
"""
if not segments:
return []
def approx_equal(p1, p2):
return abs(p1[0] - p2[0]) < tol and abs(p1[1] - p2[1]) < tol
# Build connected components using union-find
parent = list(range(len(segments)))
def find(x):
while parent[x] != x:
parent[x] = parent[parent[x]]
x = parent[x]
return x
def union(a, b):
a, b = find(a), find(b)
if a != b:
parent[a] = b
# Build spatial index: bucket endpoints for fast lookup
bucket_size = tol * 2
from collections import defaultdict
endpoint_buckets = defaultdict(list)
for i, seg in enumerate(segments):
for pt in [seg[0], seg[1]]:
bx = int(pt[0] / bucket_size)
by = int(pt[1] / bucket_size)
endpoint_buckets[(bx, by)].append(i)
# Union segments that share endpoints
for i, seg in enumerate(segments):
for pt in [seg[0], seg[1]]:
bx = int(pt[0] / bucket_size)
by = int(pt[1] / bucket_size)
# Check neighboring buckets
for dbx in [-1, 0, 1]:
for dby in [-1, 0, 1]:
for j in endpoint_buckets.get((bx + dbx, by + dby), []):
if j <= i:
continue
seg_j = segments[j]
if (approx_equal(pt, seg_j[0]) or approx_equal(pt, seg_j[1])):
union(i, j)
# Group segments by component
groups = defaultdict(list)
for i in range(len(segments)):
groups[find(i)].append(i)
# Chain each component into a polygon
contours = []
for group_indices in groups.values():
if len(group_indices) < 3:
continue
group_segs = [segments[idx] for idx in group_indices]
# Build spatial index for this group's segments
seg_buckets = defaultdict(list)
for i, seg in enumerate(group_segs):
for pt in [seg[0], seg[1]]:
bx = int(pt[0] / bucket_size)
by = int(pt[1] / bucket_size)
seg_buckets[(bx, by)].append(i)
polygon = [group_segs[0][0], group_segs[0][1]]
used = {0}
max_iterations = len(group_segs) * 2
for _ in range(max_iterations):
if len(used) >= len(group_segs):
break
current_end = polygon[-1]
bx = int(current_end[0] / bucket_size)
by = int(current_end[1] / bucket_size)
found_next = False
# Search nearby buckets for matching endpoint
for dbx in [-1, 0, 1]:
if found_next:
break
for dby in [-1, 0, 1]:
if found_next:
break
for i in seg_buckets.get((bx + dbx, by + dby), []):
if i in used:
continue
seg = group_segs[i]
if approx_equal(seg[0], current_end):
polygon.append(seg[1])
used.add(i)
found_next = True
break
elif approx_equal(seg[1], current_end):
polygon.append(seg[0])
used.add(i)
found_next = True
break
if not found_next:
break
# Remove duplicate closing point
if len(polygon) > 1 and approx_equal(polygon[0], polygon[-1]):
polygon = polygon[:-1]
if len(used) == len(group_segs) and len(polygon) >= 3:
contours.append(polygon)
return contours
def extract_board_outline(content: str) -> List[Tuple[float, float]]:
"""Extract board outline polygon from Edge.Cuts layer.
Parses gr_line, gr_arc, and gr_rect segments and assembles them into
closed polygons. Returns the largest contour as the board outline.
Returns an empty list if no outline is found or if it's a simple rectangle.
"""
outline, _ = extract_board_contours(content)
return outline
def extract_board_contours(content: str) -> Tuple[List[Tuple[float, float]], List[List[Tuple[float, float]]]]:
"""Extract board outline and cutout polygons from Edge.Cuts layer.
Returns:
(outline, cutouts) where outline is the outer boundary polygon vertices
and cutouts is a list of interior cutout polygons.
outline is empty if no outline found or if it's a simple axis-aligned rectangle.
"""
segments = _collect_edge_cuts_segments(content)
if len(segments) < 3:
return [], []
# Check if this is a simple 4-segment rectangle (no need for polygon handling)
if len(segments) == 4:
vertices = set()
for seg in segments:
vertices.add((round(seg[0][0], 3), round(seg[0][1], 3)))
vertices.add((round(seg[1][0], 3), round(seg[1][1], 3)))
if len(vertices) == 4:
all_axis_aligned = all(
abs(s[0][0] - s[1][0]) < 0.001 or abs(s[0][1] - s[1][1]) < 0.001
for s in segments
)
if all_axis_aligned:
return [], [] # Simple rectangle, use bounding box
contours = _chain_segments_into_contours(segments)
if not contours:
return [], []
# Find the largest contour by bounding box area (outer boundary)
def contour_bbox_area(contour):
xs = [p[0] for p in contour]
ys = [p[1] for p in contour]
return (max(xs) - min(xs)) * (max(ys) - min(ys))
contours.sort(key=contour_bbox_area, reverse=True)
outline = contours[0]
cutouts = contours[1:]
return outline, cutouts
def extract_nets(content: str, kicad_version: int = 0) -> Tuple[Dict[int, Net], Dict[str, int]]:
"""Extract all net definitions.
Returns:
Tuple of (nets dict keyed by net_id, name_to_id mapping).
For KiCad 9, net_id comes from the file. For KiCad 10, synthetic IDs are assigned.
"""
nets = {}
name_to_id: Dict[str, int] = {}
if kicad_version >= KICAD_10_MIN_VERSION:
# KiCad 10 removes the top-level net table entirely.
# Discover all net names from their usage in pads, segments, vias, and zones.
# Match (net "name") anywhere in the file — deduplicate to build the net list.
net_pattern = r'\(net\s+"([^"]*)"\)'
synthetic_id = 1
for m in re.finditer(net_pattern, content):
net_name = m.group(1)
if net_name in name_to_id:
continue # Already seen
nets[synthetic_id] = Net(net_id=synthetic_id, name=net_name)
name_to_id[net_name] = synthetic_id
synthetic_id += 1
else:
# KiCad 9: nets are (net <id> "name")
net_pattern = r'\(net\s+(\d+)\s+"([^"]*)"\)'
for m in re.finditer(net_pattern, content):
net_id = int(m.group(1))
net_name = m.group(2)
nets[net_id] = Net(net_id=net_id, name=net_name)
name_to_id[net_name] = net_id
return nets, name_to_id
def extract_footprints_and_pads(content: str, nets: Dict[int, Net], name_to_id: Dict[str, int] = None) -> Tuple[Dict[str, Footprint], Dict[int, List[Pad]]]:
"""Extract footprints and their pads with global coordinates."""
footprints = {}
pads_by_net: Dict[int, List[Pad]] = {}
# Find all footprints - need to handle nested parentheses properly
# Strategy: find (footprint and then match balanced parens
footprint_starts = [m.start() for m in re.finditer(r'\(footprint\s+"', content)]
for start in footprint_starts:
# Find the matching end parenthesis
depth = 0
end = start
for i, char in enumerate(content[start:], start):
if char == '(':
depth += 1
elif char == ')':
depth -= 1
if depth == 0:
end = i + 1
break
fp_text = content[start:end]
# Extract footprint name
fp_name_match = re.search(r'\(footprint\s+"([^"]+)"', fp_text)
if not fp_name_match:
continue
fp_name = fp_name_match.group(1)
# Extract position and rotation
at_match = re.search(r'\(at\s+([\d.-]+)\s+([\d.-]+)(?:\s+([\d.-]+))?\)', fp_text)
if not at_match:
continue
fp_x = float(at_match.group(1))
fp_y = float(at_match.group(2))
fp_rotation = float(at_match.group(3)) if at_match.group(3) else 0.0
# Extract layer
layer_match = re.search(r'\(layer\s+"([^"]+)"\)', fp_text)
fp_layer = layer_match.group(1) if layer_match else "F.Cu"
# Extract reference
ref_match = re.search(r'\(property\s+"Reference"\s+"([^"]+)"', fp_text)
reference = ref_match.group(1) if ref_match else "?"
# Extract value (component part number or value)
value_match = re.search(r'\(property\s+"Value"\s+"([^"]+)"', fp_text)
value = value_match.group(1) if value_match else ""
footprint = Footprint(
reference=reference,
footprint_name=fp_name,
x=fp_x,
y=fp_y,
rotation=fp_rotation,
layer=fp_layer,
value=value
)
# Extract pads
# Pattern for pad: (pad "num" type shape ... (at x y [rot]) ... (size sx sy) ... (net id "name") ...)
pad_pattern = r'\(pad\s+"([^"]+)"\s+(\w+)\s+(\w+)(.*?)\)\s*(?=\(pad|\(model|\(zone|\Z|$)'
# Simpler approach: find pad starts and extract info
# Note: pad number can be empty string (pad "") so use [^"]* not [^"]+
for pad_match in re.finditer(r'\(pad\s+"([^"]*)"\s+(\w+)\s+(\w+)', fp_text):
pad_start = pad_match.start()
# Find end of this pad block
depth = 0
pad_end = pad_start
for i, char in enumerate(fp_text[pad_start:], pad_start):
if char == '(':
depth += 1
elif char == ')':
depth -= 1
if depth == 0:
pad_end = i + 1
break
pad_text = fp_text[pad_start:pad_end]
pad_num = pad_match.group(1)
pad_type = pad_match.group(2) # smd, thru_hole, etc.
pad_shape = pad_match.group(3) # circle, rect, roundrect, etc.
# Extract pad local position and rotation
pad_at_match = re.search(r'\(at\s+([\d.-]+)\s+([\d.-]+)(?:\s+([\d.-]+))?\)', pad_text)
if not pad_at_match:
continue
local_x = float(pad_at_match.group(1))
local_y = float(pad_at_match.group(2))
pad_rotation = float(pad_at_match.group(3)) if pad_at_match.group(3) else 0.0
# Total rotation = pad rotation + footprint rotation
total_rotation = (pad_rotation + fp_rotation) % 360
# Extract size
size_match = re.search(r'\(size\s+([\d.-]+)\s+([\d.-]+)\)', pad_text)
if size_match:
size_x = float(size_match.group(1))
size_y = float(size_match.group(2))
else:
size_x = size_y = 0.5 # default
# Apply only pad rotation to get board-space dimensions
# The pad rotation already accounts for orientation relative to footprint,
# and footprint rotation transforms coordinates but the size in local
# footprint space after pad rotation gives the board-space dimensions
pad_rot_normalized = pad_rotation % 180
if 45 < pad_rot_normalized < 135: # Close to 90°
size_x, size_y = size_y, size_x
# Extract layers - use findall to get all quoted layer names
layers_section = re.search(r'\(layers\s+([^)]+)\)', pad_text)
pad_layers = []
if layers_section:
pad_layers = re.findall(r'"([^"]+)"', layers_section.group(1))
# Extract net - try KiCad 9 format first, then KiCad 10
net_match = re.search(r'\(net\s+(\d+)\s+"([^"]*)"\)', pad_text)
if net_match:
net_id = int(net_match.group(1))
net_name = net_match.group(2)
else:
# KiCad 10: (net "name") with no numeric ID
net_match_v10 = re.search(r'\(net\s+"([^"]*)"\)', pad_text)
if net_match_v10 and name_to_id:
net_name = net_match_v10.group(1)
net_id = name_to_id.get(net_name, 0)
else:
net_id = 0
net_name = ""
# Extract pinfunction
pinfunc_match = re.search(r'\(pinfunction\s+"([^"]*)"\)', pad_text)
pinfunction = pinfunc_match.group(1) if pinfunc_match else ""
# Extract pintype
pintype_match = re.search(r'\(pintype\s+"([^"]*)"\)', pad_text)
pintype = pintype_match.group(1) if pintype_match else ""
# Extract drill size for through-hole pads
drill_match = re.search(r'\(drill\s+([\d.]+)', pad_text)
drill_size = float(drill_match.group(1)) if drill_match else 0.0
# Extract roundrect_rratio for roundrect pads
rratio_match = re.search(r'\(roundrect_rratio\s+([\d.]+)\)', pad_text)
roundrect_rratio = float(rratio_match.group(1)) if rratio_match else 0.0
# Calculate global coordinates
global_x, global_y = local_to_global(fp_x, fp_y, fp_rotation, local_x, local_y)
pad = Pad(
component_ref=reference,
pad_number=pad_num,
global_x=global_x,
global_y=global_y,
local_x=local_x,
local_y=local_y,
size_x=size_x,
size_y=size_y,
shape=pad_shape,
layers=pad_layers,
net_id=net_id,
net_name=net_name,
rotation=total_rotation,
pinfunction=pinfunction,
pintype=pintype,
drill=drill_size,
roundrect_rratio=roundrect_rratio
)
footprint.pads.append(pad)
# Add to pads_by_net
if net_id not in pads_by_net:
pads_by_net[net_id] = []
pads_by_net[net_id].append(pad)
# Also add to Net object
if net_id in nets:
nets[net_id].pads.append(pad)
footprints[reference] = footprint
return footprints, pads_by_net
def extract_vias(content: str, name_to_id: Dict[str, int] = None) -> List[Via]:
"""Extract all vias from PCB file."""
vias = []
# Try KiCad 9 format first: (net <id>)
# Strict field ordering: at → size → drill → layers → (free?) → net → uuid
via_pattern = r'\(via\s+\(at\s+([\d.-]+)\s+([\d.-]+)\)\s+\(size\s+([\d.-]+)\)\s+\(drill\s+([\d.-]+)\)\s+\(layers\s+"([^"]+)"\s+"([^"]+)"\)\s+(?:\(free\s+(yes|no)\)\s+)?\(net\s+(\d+)\)\s+\(uuid\s+"([^"]+)"\)'
for m in re.finditer(via_pattern, content, re.DOTALL):
free_value = m.group(7) # "yes", "no", or None
via = Via(
x=float(m.group(1)),
y=float(m.group(2)),
size=float(m.group(3)),
drill=float(m.group(4)),
layers=[m.group(5), m.group(6)],
net_id=int(m.group(8)),
uuid=m.group(9),
free=(free_value == "yes")
)
vias.append(via)
if not vias and name_to_id:
# KiCad 10 format: (net "name")
# Use flexible matching between layers and net to handle new v10 fields
# (tenting, covering, plugging, capping, filling) that appear after layers.
via_pattern_v10 = r'\(via\s+\(at\s+([\d.-]+)\s+([\d.-]+)\)\s+\(size\s+([\d.-]+)\)\s+\(drill\s+([\d.-]+)\)\s+\(layers\s+"([^"]+)"\s+"([^"]+)"\).*?\(net\s+"([^"]*)"\)\s+\(uuid\s+"([^"]+)"\)'
for m in re.finditer(via_pattern_v10, content, re.DOTALL):
net_name = m.group(7)
via = Via(
x=float(m.group(1)),
y=float(m.group(2)),
size=float(m.group(3)),
drill=float(m.group(4)),
layers=[m.group(5), m.group(6)],
net_id=name_to_id.get(net_name, 0),
uuid=m.group(8),
free=False # Parse free from content if present
)
vias.append(via)
# Check for free flag in matched vias
if vias:
free_pattern = r'\(via\s+\(at\s+[\d.-]+\s+[\d.-]+\).*?\(free\s+yes\).*?\(uuid\s+"([^"]+)"\)'
free_uuids = {m.group(1) for m in re.finditer(free_pattern, content, re.DOTALL)}
for via in vias:
if via.uuid in free_uuids:
via.free = True
return vias
def extract_segments(content: str, name_to_id: Dict[str, int] = None) -> List[Segment]:
"""Extract all track segments from PCB file."""
segments = []
# Try KiCad 9 format first: (net <id>)
segment_pattern = r'\(segment\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\)\s+\(width\s+([\d.-]+)\)\s+\(layer\s+"([^"]+)"\)\s+\(net\s+(\d+)\)\s+\(uuid\s+"([^"]+)"\)'
for m in re.finditer(segment_pattern, content, re.DOTALL):
segment = Segment(
start_x=float(m.group(1)),
start_y=float(m.group(2)),
end_x=float(m.group(3)),
end_y=float(m.group(4)),
width=float(m.group(5)),
layer=m.group(6),
net_id=int(m.group(7)),
uuid=m.group(8),
# Store original strings for exact file matching
start_x_str=m.group(1),
start_y_str=m.group(2),
end_x_str=m.group(3),
end_y_str=m.group(4)
)
segments.append(segment)
if not segments and name_to_id:
# KiCad 10 format: (net "name")
segment_pattern_v10 = r'\(segment\s+\(start\s+([\d.-]+)\s+([\d.-]+)\)\s+\(end\s+([\d.-]+)\s+([\d.-]+)\)\s+\(width\s+([\d.-]+)\)\s+\(layer\s+"([^"]+)"\)\s+\(net\s+"([^"]*)"\)\s+\(uuid\s+"([^"]+)"\)'
for m in re.finditer(segment_pattern_v10, content, re.DOTALL):
net_name = m.group(7)
segment = Segment(
start_x=float(m.group(1)),
start_y=float(m.group(2)),
end_x=float(m.group(3)),
end_y=float(m.group(4)),
width=float(m.group(5)),
layer=m.group(6),
net_id=name_to_id.get(net_name, 0),
uuid=m.group(8),
start_x_str=m.group(1),
start_y_str=m.group(2),
end_x_str=m.group(3),
end_y_str=m.group(4)
)
segments.append(segment)
return segments
def extract_zones(content: str, name_to_id: Dict[str, int] = None) -> List[Zone]:
"""Extract all filled zones from PCB file.
Parses zone definitions including their net assignment, layer, and polygon outline.
These are used for power planes and other filled copper areas.
"""
zones = []
# Find each zone block start - zones are at the top level, indented with single tab
# Use \r?\n to handle both Unix and Windows line endings
zone_start_pattern = r'\r?\n\t\(zone\s*\r?\n'
for start_match in re.finditer(zone_start_pattern, content):
# Find the matching closing paren by counting balanced parens
start_pos = start_match.start() + len(start_match.group()) - 1 # Position after opening (
paren_count = 1
pos = start_match.end()
zone_end = None
while pos < len(content) and paren_count > 0:
char = content[pos]
if char == '(':
paren_count += 1
elif char == ')':
paren_count -= 1
if paren_count == 0:
zone_end = pos
pos += 1
if zone_end is None:
continue