summaryrefslogtreecommitdiff
path: root/gerbonara/cad/kicad/footprints.py
blob: a95f36ee2fa547fd7486a379937b8eee00b6c9d7 (plain)
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
1001
1002
1003
1004
1005
1006
"""
Library for handling KiCad's footprint files (`*.kicad_mod`).
"""

import re
import copy
import enum
import string
import datetime
import math
import time
import fnmatch
from itertools import chain
from pathlib import Path
from dataclasses import field, replace

from .sexp import *
from .base_types import *
from .primitives import *
from . import graphical_primitives as gr

from ..primitives import Positioned

from ... import graphic_primitives as gp
from ... import graphic_objects as go
from ... import apertures as ap
from ...layers import LayerStack
from ...newstroke import Newstroke
from ...utils import MM, rotate_point, offset_bounds, sum_bounds
from ...aperture_macros.parse import GenericMacros, ApertureMacro
from ...aperture_macros import primitive as amp


class _MISSING:
    pass

def angle_difference(a, b):
    return (b - a + math.pi) % (2*math.pi) - math.pi

@sexp_type('attr')
class Attribute:
    type: AtomChoice(Atom.smd, Atom.through_hole) = None
    board_only: Flag() = False
    virtual: Flag() = False # prior to 20208026
    exclude_from_pos_files: Flag() = False
    exclude_from_bom: Flag() = False
    allow_missing_courtyard: Flag() = False
    allow_soldermask_bridges: Flag() = False
    dnp: Flag() = False


@sexp_type('fp_text')
class Text:
    type: AtomChoice(Atom.reference, Atom.value, Atom.user) = Atom.user
    text: str = ""
    at: AtPos = field(default_factory=AtPos)
    unlocked: Flag() = False
    layer: Named(str) = None
    hide: Flag() = False
    effects: TextEffect = field(default_factory=TextEffect)
    tstamp: Timestamp = None

    def render(self, variables={}, cache=None):
        if self.hide: # why
            return

        yield from gr.Text.render(self, variables=variables)


@sexp_type('fp_text_box')
class TextBox:
    locked: Flag() = False
    text: str = None
    start: Rename(XYCoord) = None
    end: Named(XYCoord) = None
    pts: PointList = None
    angle: Named(float) = 0.0
    layer: Named(str) = None
    tstamp: Timestamp = None
    effects: TextEffect = field(default_factory=TextEffect)
    stroke: Stroke = field(default_factory=Stroke)
    render_cache: RenderCache = None

    def render(self, variables={}, cache=None):
        yield from gr.TextBox.render(self, variables=variables)


@sexp_type('fp_line')
class Line:
    start: Rename(XYCoord) = None
    end: Rename(XYCoord) = None
    layer: Named(str) = None
    width: Named(float) = None
    stroke: Stroke = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def to_graphical_primitive(self, flip=False):
        # FIXME flip
        return gr.Line(self.start, self.end, self.layer, self.width, self.stroke, self.tstamp)

    def render(self, variables=None, cache=None):
        dasher = Dasher(self)
        dasher.move(self.start.x, self.start.y)
        dasher.line(self.end.x, self.end.y)

        for x1, y1, x2, y2 in dasher:
            yield go.Line(x1, y1, x2, y2, aperture=ap.CircleAperture(dasher.width, unit=MM), unit=MM)


@sexp_type('fp_rect')
class Rectangle:
    start: Rename(XYCoord) = None
    end: Rename(XYCoord) = None
    layer: Named(str) = None
    width: Named(float) = None
    stroke: Stroke = None
    fill: Named(AtomChoice(Atom.solid, Atom.none)) = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def render(self, variables=None, cache=None):
        x1, y1 = self.start.x, self.start.y
        x2, y2 = self.end.x, self.end.y
        x1, x2 = min(x1, x2), max(x1, x2)
        y1, y2 = min(y1, y2), max(y1, y2)
        w, h = x2-x1, y2-y1

        if self.fill == Atom.solid:
            yield go.Region.from_rectangle(x1, y1, w, h, unit=MM)

        dasher = Dasher(self)
        dasher.move(x1, y1)
        dasher.line(x1, y2)
        dasher.line(x2, y2)
        dasher.line(x2, y1)
        dasher.close()

        aperture = ap.CircleAperture(dasher.width, unit=MM)
        for x1, y1, x2, y2 in dasher:
            yield go.Line(x1, y1, x2, y2, aperture=aperture, unit=MM)


@sexp_type('fp_circle')
class Circle:
    center: Rename(XYCoord) = None
    end: Rename(XYCoord) = None
    layer: Named(str) = None
    width: Named(float) = None
    stroke: Stroke = None
    fill: Named(AtomChoice(Atom.solid, Atom.none)) = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def render(self, variables=None, cache=None):
        x, y = self.center.x, self.center.y
        r = math.dist((x, y), (self.end.x, self.end.y)) # insane

        dasher = Dasher(self)
        aperture = ap.CircleAperture(dasher.width or 0, unit=MM)

        circle = go.Arc.from_circle(x, y, r, aperture=aperture, unit=MM)

        if self.fill == Atom.solid:
            yield circle.to_region()

        if dasher.solid:
            yield circle

        else: # pain
            for line in circle.approximate(): # TODO precision settings
                dasher.segments.append((line.x1, line.y1, line.x2, line.y2))

            aperture = ap.CircleAperture(dasher.width, unit=MM)
            for x1, y1, x2, y2 in dasher:
                yield go.Line(x1, y1, x2, y2, aperture=aperture, unit=MM)


@sexp_type('fp_arc')
class Arc:
    start: Rename(XYCoord) = None
    mid: Rename(XYCoord) = None
    end: Rename(XYCoord) = None
    width: Named(float) = None
    stroke: Stroke = None
    layer: Named(str) = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def to_graphical_primitive(self, flip=False):
        # FIXME flip
        return gr.Arc(self.start, self.mid, self.end, self.layer, self.width, self.stroke, self.tstamp)

    def render(self, variables=None, cache=None):
        mx, my = self.mid.x, self.mid.y
        x1, y1 = self.start.x, self.start.y
        x2, y2 = self.end.x, self.end.y
        dasher = Dasher(self)
        aperture = ap.CircleAperture(dasher.width, unit=MM)

        if math.isclose(x1, x2, abs_tol=1e-6) and math.isclose(y1, y2, abs_tol=1e-6):
            cx = (x1 + mx) / 2
            cy = (y1 + my) / 2
            arc = go.Arc(x1, y1, x2, y2, cx-x1, cy-y1, clockwise=True, aperture=aperture, unit=MM)
            if dasher.solid:
                yield arc

            else:
                # use approximation from graphic object arc class 
                for line in arc.approximate():
                    dasher.segments.append((line.x1, line.y1, line.x2, line.y2))
                
                for line in dasher:
                    yield go.Line(x1, y1, x2, y2, aperture=ap.CircleAperture(dasher.width, unit=MM), unit=MM)

        else:
            # https://stackoverflow.com/questions/56224824/how-do-i-find-the-circumcenter-of-the-triangle-using-python-without-external-lib
            d = 2 * (x1 * (y2 - my) + x2 * (my - y1) + mx * (y1 - y2))
            cx = ((x1 * x1 + y1 * y1) * (y2 - my) + (x2 * x2 + y2 * y2) * (my - y1) + (mx * mx + my * my) * (y1 - y2)) / d
            cy = ((x1 * x1 + y1 * y1) * (mx - x2) + (x2 * x2 + y2 * y2) * (x1 - mx) + (mx * mx + my * my) * (x2 - x1)) / d

        # KiCad only has clockwise arcs.
        arc = go.Arc(x1, y1, x2, y2, cx-x1, cy-y1, clockwise=False, aperture=aperture, unit=MM)
        if dasher.solid:
            yield arc

        else:
            # use approximation from graphic object arc class 
            for line in arc.approximate():
                dasher.segments.append((line.x1, line.y1, line.x2, line.y2))
            
            for line in dasher:
                yield go.Line(x1, y1, x2, y2, aperture=ap.CircleAperture(dasher.width, unit=MM), unit=MM)


@sexp_type('fp_poly')
class Polygon:
    pts: PointList = field(default_factory=PointList)
    layer: Named(str) = None
    width: Named(float) = None
    stroke: Stroke = None
    fill: Named(AtomChoice(Atom.solid, Atom.none)) = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def render(self, variables=None, cache=None):
        if len(self.pts.xy) < 2:
            return

        dasher = Dasher(self)
        start = self.pts.xy[0]
        dasher.move(start.x, start.y)
        for point in self.pts.xy[1:]:
            dasher.line(point.x, point.y)

        aperture = ap.CircleAperture(dasher.width, unit=MM)
        for x1, y1, x2, y2 in dasher:
            yield go.Line(x1, y1, x2, y2, aperture=aperture, unit=MM)

        if self.fill == Atom.solid:
            yield go.Region([(pt.x, pt.y) for pt in self.pts.xy], unit=MM)


@sexp_type('fp_curve')
class Curve:
    pts: PointList = field(default_factory=PointList)
    layer: Named(str) = None
    width: Named(float) = None
    stroke: Stroke = None
    locked: Flag() = False
    tstamp: Timestamp = None

    def render(self, variables=None, cache=None):
        raise NotImplementedError('Bezier rendering is not yet supported. Please raise an issue and provide an example file.')


@sexp_type('format')
class DimensionFormat:
    prefix: Named(str) = None
    suffix: Named(str) = None
    units: Named(int) = 3
    units_format: Named(int) = 0
    precision: Named(int) = 3
    override_value: Named(str) = None
    suppress_zeros: Flag() = False


@sexp_type('style')
class DimensionStyle:
    thickness: Named(float) = None
    arrow_length: Named(float) = None
    text_position_mode: Named(int) = 0
    extension_height: Named(float) = None
    text_frame: Named(int) = 0
    extension_offset: Named(str) = None
    keep_text_aligned: Flag() = False


@sexp_type('dimension')
class Dimension:
    locked: Flag() = False
    type: AtomChoice(Atom.aligned, Atom.leader, Atom.center, Atom.orthogonal, Atom.radial) = None
    layer: Named(str) = None
    tstamp: Timestamp = None
    pts: PointList = field(default_factory=PointList)
    height: Named(float) = None
    orientation: Named(int) = 0
    leader_length: Named(float) = None
    gr_text: Named(Text) = None
    format: DimensionFormat = field(default_factory=DimensionFormat)
    style: DimensionStyle = field(default_factory=DimensionStyle)

    def render(self, variables=None, cache=None):
        raise NotImplementedError()


@sexp_type('drill')
class Drill:
    oval: Flag() = False
    diameter: float = 0
    width: float = None
    offset: Rename(XYCoord) = None


@sexp_type('net')
class NetDef:
    number: int = None
    name: str = None


@sexp_type('options')
class CustomPadOptions:
    clearance: Named(AtomChoice(Atom.outline, Atom.convexhull)) = Atom.outline
    anchor: Named(AtomChoice(Atom.rect, Atom.circle)) = Atom.rect


@sexp_type('primitives')
class CustomPadPrimitives:
    annotation_bboxes: List(gr.AnnotationBBox) = field(default_factory=list)
    lines: List(gr.Line) = field(default_factory=list)
    rectangles: List(gr.Rectangle) = field(default_factory=list)
    circles: List(gr.Circle) = field(default_factory=list)
    arcs: List(gr.Arc) = field(default_factory=list)
    polygons: List(gr.Polygon) = field(default_factory=list)
    curves: List(gr.Curve) = field(default_factory=list)
    width: Named(float) = None
    fill: Named(YesNoAtom()) = True

    def all(self):
        yield from self.lines
        yield from self.rectangles
        yield from self.circles
        yield from self.arcs
        yield from self.polygons
        yield from self.curves


@sexp_type('chamfer')
class Chamfer:
    top_left: Flag() = False
    top_right: Flag() = False
    bottom_left: Flag() = False
    bottom_right: Flag() = False


@sexp_type('pad')
class Pad:
    number: str = None
    type: AtomChoice(Atom.thru_hole, Atom.smd, Atom.connect, Atom.np_thru_hole) = None
    shape: AtomChoice(Atom.circle, Atom.rect, Atom.oval, Atom.trapezoid, Atom.roundrect, Atom.custom) = None
    at: AtPos = field(default_factory=AtPos)
    locked: Flag() = False
    size: Rename(XYCoord) = field(default_factory=XYCoord)
    drill: Drill = None
    layers: Named(Array(str)) = field(default_factory=list)
    properties: List(Property) = field(default_factory=list)
    remove_unused_layers: Wrap(Flag()) = False
    keep_end_layers: Wrap(Flag()) = False
    rect_delta: Rename(XYCoord) = None
    roundrect_rratio: Named(float) = None
    thermal_bridge_angle: Named(int) = 45
    thermal_bridge_width: Named(float) = 0.5
    chamfer_ratio: Named(float) = None
    chamfer: Chamfer = None
    net: NetDef = None
    tstamp: Timestamp = None
    pin_function: Named(str) = None
    pintype: Named(str) = None
    pinfunction: Named(str) = None
    die_length: Named(float) = None
    solder_mask_margin: Named(float) = None
    solder_paste_margin: Named(float) = None
    solder_paste_margin_ratio: Named(float) = None
    clearance: Named(float) = None
    zone_connect: Named(int) = None
    thermal_width: Named(float) = None
    thermal_gap: Named(float) = None
    options: OmitDefault(CustomPadOptions) = None
    primitives: OmitDefault(CustomPadPrimitives) = None
    _: SEXP_END = None
    footprint: object = None

    def __after_parse__(self, parent=None):
        self.layers = unfuck_layers(self.layers)

    def __before_sexp__(self):
        self.layers = fuck_layers(self.layers)

    @property
    def abs_pos(self):
        if self.footprint:
            px, py, pr = self.footprint.at.x, self.footprint.at.y, self.footprint.at.rotation
        else:
            px, py, pr = 0, 0, 0

        x, y = rotate_point(self.at.x, self.at.y, math.radians(pr))
        return x+px, y+py, self.at.rotation, False

    @property
    def layer_mask(self):
        return layer_mask(self.layers)

    def offset(self, x=0, y=0):
        self.at = self.at.with_offset(x, y)

    def find_connected_footprints(self, **filters):
        """ Find footprints connected to the same net as this pad """
        return self.footprint.board.find_footprints(net=self.net.name, **filters)

    def find_same_net(self, include_vias=True):
        """ Find traces and vias of the same net as this pad. """ 
        return self.footprint.board.find_traces(self.net.name, include_vias=include_vias)

    def render(self, variables=None, margin=None, cache=None):
        #if self.type in (Atom.connect, Atom.np_thru_hole):
        #    return
        if self.drill and self.drill.offset:
            ox, oy = rotate_point(self.drill.offset.x, self.drill.offset.y, math.radians(self.at.rotation))
        else:
            ox, oy = 0, 0

        cache_key = id(self), margin
        if cache and cache_key in cache:
            aperture = cache[cache_key]

        elif cache is not None:
            aperture = cache[cache_key] = self.aperture(margin)

        else:
            aperture = self.aperture(margin)

        yield go.Flash(self.at.x+ox, self.at.y+oy, aperture, unit=MM)

    def aperture(self, margin=None):
        rotation = math.radians(self.at.rotation)
        margin = margin or 0

        if self.shape == Atom.circle:
            return ap.CircleAperture(self.size.x+2*margin, unit=MM)

        elif self.shape == Atom.rect:
            if margin > 0:
                return ap.ApertureMacroInstance(GenericMacros.rounded_rect,
                        (self.size.x+2*margin, self.size.y+2*margin,
                         margin,
                         0, 0, # no hole
                         rotation), unit=MM)
            else:
                return ap.RectangleAperture(self.size.x+2*margin, self.size.y+2*margin, unit=MM).rotated(rotation)

        elif self.shape == Atom.oval:
            return ap.ObroundAperture(self.size.x+2*margin, self.size.y+2*margin, unit=MM).rotated(rotation)

        elif self.shape == Atom.trapezoid:
            # KiCad's trapezoid aperture "rect_delta" param is just weird to the point that I think it's probably
            # bugged. If you have a size of 2mm by 2mm, and set this param to 1mm, the resulting pad extends past the
            # original bounding box, and the trapezoid's base and tip length are 3mm and 1mm.

            x, y = self.size.x, self.size.y
            if self.rect_delta:
                dx, dy = self.rect_delta.x, self.rect_delta.y
            else: # RF_Antenna/Pulse_W3011 has trapezoid pads w/o rect_delta, which KiCad renders as plain rects.
                dx, dy = 0, 0

            if dx != 0:
                x, y = y, x
                dy = dx
                rotation += math.pi/2

            if margin <= 0:
                # Note: KiCad already uses MM units, so no conversion needed here.

                alpha = math.atan(y / dy) if dy > 0 else 0
                return ap.ApertureMacroInstance(GenericMacros.isosceles_trapezoid,
                        (x+dy+2*margin*math.cos(alpha), y+2*margin,
                         2*dy,
                         0, 0, # no hole
                         rotation), unit=MM)

            else:
                return ap.ApertureMacroInstance(GenericMacros.rounded_isosceles_trapezoid,
                        (x+dy, y,
                         2*dy, margin,
                         0, 0, # no hole
                         rotation), unit=MM)

        elif self.shape == Atom.roundrect:
            x, y = self.size.x, self.size.y
            r = min(x, y) * self.roundrect_rratio
            if margin > -r:
                return ap.ApertureMacroInstance(GenericMacros.rounded_rect,
                        (x+2*margin, y+2*margin,
                         r+margin,
                         0, 0, # no hole
                         rotation), unit=MM)
            else:
                return ap.RectangleAperture(x+margin, y+margin, unit=MM).rotated(rotation)

        elif self.shape == Atom.custom:
            primitives = []

            # One round trip through the Gerbonara APIs, please!
            for obj in self.primitives.all():
                for gn_obj in obj.render():
                    if margin and isinstance(gn_obj, (go.Line, go.Arc)):
                        gn_obj = replace(gn_obj, aperture=gn_obj.aperture.dilated(margin))

                    if isinstance(gn_obj, go.Region) and margin > 0:
                        for line in gn_obj.outline_objects(ap.CircleAperture(2*margin, unit=MM)):
                            primitives += line._aperture_macro_primitives()

                    new_primitives = list(gn_obj._aperture_macro_primitives()) # todo: precision params
                    primitives += new_primitives

                    # inexact, only works with convex shapes. But whatever, the only other way to do this would require
                    # an entire polygon clipping/offsetting library. Probably a bad choice to put something this complex
                    # into a file format.
                    if isinstance(gn_obj, go.Region) and margin < 0:
                        for line in gn_obj.outline_objects(ap.CircleAperture(2*margin, unit=MM)):
                            line.polarity_dark = False
                            primitives += line._aperture_macro_primitives()

            if self.options:
                if self.options.anchor == Atom.rect and self.size.x > 0 and self.size.y > 0:
                    if margin <= 0:
                        primitives.append(amp.CenterLine(MM, 1, self.size.x+2*margin, self.size.y+2*margin, 0, 0, 0))

                    else: # margin > 0
                        primitives.append(amp.CenterLine(MM, 1, self.size.x+2*margin, self.size.y, 0, 0, 0))
                        primitives.append(amp.CenterLine(MM, 1, self.size.x, self.size.y+2*margin, 0, 0, 0))
                        primitives.append(amp.Circle(MM, 1, 2*margin, -self.size.x/2, -self.size.y/2))
                        primitives.append(amp.Circle(MM, 1, 2*margin, -self.size.x/2, +self.size.y/2))
                        primitives.append(amp.Circle(MM, 1, 2*margin, +self.size.x/2, -self.size.y/2))
                        primitives.append(amp.Circle(MM, 1, 2*margin, +self.size.x/2, +self.size.y/2))

                elif self.options.anchor == Atom.circle and self.size.x > 0:
                    primitives.append(amp.Circle(MM, 1, self.size.x+2*margin, 0, 0, 0))

            macro = ApertureMacro(primitives=tuple(primitives)).rotated(rotation)
            return ap.ApertureMacroInstance(macro, unit=MM)

    def render_drill(self):
        if not self.drill:
            return

        plated = self.type != Atom.np_thru_hole
        if self.drill.oval:
            dia = self.drill.diameter
            w = self.drill.width

            if self.drill.offset:
                ox, oy = self.drill.offset.x, self.drill.offset.y
            else:
                ox, oy = 0, 0
            
            if w > dia:
                dx = 0
                dy = (w-dia)/2
            else:
                dx = (dia-w)/2
                dy = 0

            aperture = ap.ExcellonTool(min(dia, w), plated=plated, unit=MM)
            l = go.Line(ox-dx, oy-dy, ox+dx, oy+dy, aperture=aperture, unit=MM) 
            l.rotate(math.radians(self.at.rotation))
            l.offset(self.at.x, self.at.y)
            yield l

        else:
            aperture = ap.ExcellonTool(self.drill.diameter, plated=plated, unit=MM)
            yield go.Flash(self.at.x, self.at.y, aperture=aperture, unit=MM) 


@sexp_type('model')
class Model:
    name: str = ''
    at: Named(XYZCoord) = field(default_factory=XYZCoord)
    offset: Named(XYZCoord) = field(default_factory=XYZCoord)
    scale: Named(XYZCoord) = field(default_factory=XYZCoord)
    rotate: Named(XYZCoord) = field(default_factory=XYZCoord)


SUPPORTED_FILE_FORMAT_VERSIONS = [20210108, 20211014, 20221018, 20230517]
@sexp_type('footprint')
class Footprint:
    name: str = None
    _version: Named(int, name='version') = 20221018
    generator: Named(Atom) = Atom.gerbonara
    locked: Flag() = False
    placed: Flag() = False
    layer: Named(str) = 'F.Cu'
    tedit: EditTime = field(default_factory=EditTime)
    tstamp: Timestamp = None
    at: AtPos = field(default_factory=AtPos)
    descr: Named(str) = None
    tags: Named(str) = None
    properties: List(DrawnProperty) = field(default_factory=list)
    path: Named(str) = None
    sheetname: Named(str) = None
    sheetfile: Named(str) = None
    autoplace_cost90: Named(float) = None
    autoplace_cost180: Named(float) = None
    solder_mask_margin: Named(float) = None
    solder_paste_margin: Named(float) = None
    solder_paste_ratio: Named(float) = None
    clearance: Named(float) = None
    zone_connect: Named(int) = None
    thermal_width: Named(float) = None
    thermal_gap: Named(float) = None
    attributes: Attribute = field(default_factory=Attribute)
    private_layers: Named(str) = None
    net_tie_pad_groups: Named(Array(str)) = None
    texts: List(Text) = field(default_factory=list)
    text_boxes: List(TextBox) = field(default_factory=list)
    lines: List(Line) = field(default_factory=list)
    rectangles: List(Rectangle) = field(default_factory=list)
    circles: List(Circle) = field(default_factory=list)
    arcs: List(Arc) = field(default_factory=list)
    polygons: List(Polygon) = field(default_factory=list)
    curves: List(Curve) = field(default_factory=list)
    dimensions: List(Dimension) = field(default_factory=list)
    pads: List(Pad) = field(default_factory=list)
    zones: List(Zone) = field(default_factory=list)
    groups: List(Group) = field(default_factory=list)
    models: List(Model) = field(default_factory=list)
    _ : SEXP_END = None
    original_filename: str = None
    _bounding_box: tuple = None
    board: object = None

    def __after_parse__(self, parent):
        for pad in self.pads:
            pad.footprint = self

    def property_value(self, key, default=_MISSING):
        for prop in self.properties:
            if prop.key == key:
                return prop.value

        if default is not _MISSING:
            return default

        raise IndexError(f'Footprint has no property named "{key}"')

    def set_property(self, key, value, x=0, y=0, rotation=0, layer='F.Fab', hide=True, effects=None):
        for prop in self.properties:
            if prop.key == key:
                old_value, prop.value = prop.value, value
                return old_value

        if effects is None:
            effects = TextEffect()

        self.properties.append(DrawnProperty(key, value, 
                                             at=AtPos(x, y, rotation, unlocked=True),
                                             layer=layer,
                                             hide=hide,
                                             effects=effects))

    def make_standard_properties(self):
        if not self.property_value('Reference', None):
            self.set_property('Reference', 'REF**', 0, 0, 0, 'F.SilkS')

        if not self.property_value('Value', None):
            self.set_property('Value', self.name or 'VAL**', 0, 0, 0, hide=False)

        if not self.property_value('Footprint', None):
            self.set_property('Footprint', '', 0, 0, 0)

        if not self.property_value('Datasheet', None):
            self.set_property('Datasheet', '', 0, 0, 0)

        if not self.property_value('Description', None):
            self.set_property('Description', self.descr or '', 0, 0, 0)

    @property
    def pads_by_number(self):
        return {(int(pad.number) if pad.number.isnumeric() else pad.number): pad for pad in self.pads if pad.number}

    def find_pads(self, number=None, net=None):
        for pad in self.pads:
            if number is not None and pad.number == str(number):
                yield pad
            elif isinstance(net, str) and fnmatch.fnmatch(pad.net.name, net):
                yield pad
            elif net is not None and pad.net.number == net:
                yield pad

    def pad(self, number=None, net=None):
        candidates = list(self.find_pads(number=number, net=net))
        if not candidates:
            raise IndexError(f'No such pad "{number or net}"')

        if len(candidates) > 1:
            raise IndexError(f'Ambiguous pad "{number or net}", {len(candidates)} matching pads.')

        return candidates[0]

    def offset(self, x=0, y=0):
        self.at = self.at.with_offset(x, y)

    @property
    def version(self):
        return self._version

    @version.setter
    def version(self, value):
        if value not in SUPPORTED_FILE_FORMAT_VERSIONS:
            raise FormatError(f'File format version {value} is not supported. Supported versions are {", ".join(map(str, SUPPORTED_FILE_FORMAT_VERSIONS))}.')

    @property
    def reference(self):
        return self.property_value('Reference')

    @reference.setter
    def reference(self, value):
        self.set_property('Reference', value)

    @property
    def parsed_reference(self):
        ref = self.reference
        if (m := re.match(r'^.*[^0-9]([0-9]+)$', ref)):
            return m.group(0), int(m.group(1))
        else:
            return ref

    @property
    def value(self):
        return self.property_value('Value')

    @value.setter
    def value(self, value):
        self.set_property('Value', value)

    def write(self, filename=None):
        with open(filename or self.original_filename, 'w') as f:
            f.write(self.serialize())

    def serialize(self):
        return build_sexp(sexp(type(self), self)[0])

    @classmethod
    def open_pretty(kls, pretty_dir, fp_name, *args, **kwargs):
        pretty_dir = Path(pretty_dir) / f'{fp_name}.kicad_mod'
        return kls.open_mod(pretty_dir / mod_name, *args, **kwargs)

    @classmethod
    def open_mod(kls, mod_file, *args, **kwargs):
        return kls.load(Path(mod_file).read_text(), *args, **kwargs, original_filename=mod_file)

    @classmethod
    def open_system(kls, fp_path):
        raise NotImplementedError()

    @classmethod
    def open_download(kls, fp_path):
        raise NotImplementedError()

    @classmethod
    def load(kls, data, *args, **kwargs):
        return kls.parse(data, *args, **kwargs)

    @property
    def side(self):
        return 'front' if self.layer == 'F.Cu' else 'back'

    @side.setter
    def side(self, value):
        if value not in ('front', 'back'):
            raise ValueError(f'side must be either "front" or "back", not {side!r}')
        
        if self.side != value:
            self.flip()

    def flip(self):
        def flip_layer(name):
            if name.startswith('F.'):
                return f'B.{name[2:]}'
            elif name.startswith('B.'):
                return f'F.{name[2:]}'
            else:
                return name

        self.layer = flip_layer(self.layer)
        for obj in self.objects():
            if hasattr(obj, 'layer'):
                obj.layer = flip_layer(obj.layer)

            if hasattr(obj, 'layers'):
                obj.layers = [flip_layer(name) for name in obj.layers]

        for obj in chain(self.texts, self.text_boxes):
            obj.effects.justify.mirror = not obj.effects.justify.mirror

        for obj in self.properties:
            obj.effects.justify.mirror = not obj.effects.justify.mirror
            obj.layer = flip_layer(obj.layer)

    @property
    def single_sided(self):
        raise NotImplementedError()
    
    def face(self, direction, pad=None, net=None):
        if not net and not pad:
            pad = '1'

        candidates = list(self.find_pads(net=net, number=pad))
        if len(candidates) == 0:
            raise KeyError(f'Reference pad "{net or pad}" not found.')

        if len(candidates) > 1:
            raise KeyError(f'Reference pad "{net or pad}" is ambiguous, {len(candidates)} matching pads found.')

        pad = candidates[0]
        pad_angle = math.atan2(pad.at.y, pad.at.x)

        target_angle = {
                'right': 0,
                'top right': math.pi/4,
                'top': math.pi/2,
                'top left': 3*math.pi/4,
                'left': math.pi,
                'bottom left': -3*math.pi/4,
                'bottom': -math.pi/2,
                'bottom right': -math.pi/4}.get(direction, direction)
        
        delta = angle_difference(target_angle, pad_angle)
        adj = round(delta / (math.pi/2)) * math.pi/2
        self.set_rotation(adj)
        
    def rotate(self, angle=None, cx=None, cy=None, **reference_pad):
        """ Rotate this footprint by the given angle in radians, counter-clockwise. When (cx, cy) are given, rotate
        around the given coordinates in the global coordinate space. Otherwise rotate around the footprint's origin. """
        if (cx, cy) != (None, None):
            x, y = self.at.x-cx, self.at.y-cy
            self.at.x = math.cos(angle)*x - math.sin(angle)*y + cx
            self.at.y = math.sin(angle)*x + math.cos(angle)*y + cy

        self.at.rotation = (self.at.rotation - math.degrees(angle)) % 360

        for pad in self.pads:
            pad.at.rotation = (pad.at.rotation - math.degrees(angle)) % 360

        for prop in self.properties:
            prop.at.rotation = (prop.at.rotation - math.degrees(angle)) % 360

        for text in self.texts:
            text.at.rotation = (text.at.rotation - math.degrees(angle)) % 360

    def set_rotation(self, angle):
        old_deg = self.at.rotation
        new_deg = self.at.rotation = -math.degrees(angle)
        delta = new_deg - old_deg

        for pad in self.pads:
            pad.at.rotation = (pad.at.rotation + delta) % 360

        for prop in self.properties:
            prop.at.rotation = (prop.at.rotation + delta) % 360

        for text in self.texts:
            text.at.rotation = (text.at.rotation + delta) % 360

    def objects(self, text=False, pads=True, groups=True):
        return chain(
                (self.texts if text else []),
                (self.text_boxes if text else []),
                self.lines,
                self.rectangles,
                self.circles,
                self.arcs,
                self.polygons,
                self.curves,
                (self.dimensions if text else []),
                (self.pads if pads else []),
                self.zones,
                self.groups if groups else [])

    def render(self, layer_stack, layer_map, x=0, y=0, rotation=0, text=False, flip=False, variables={}, cache=None):
        x += self.at.x
        y += self.at.y
        rotation += math.radians(self.at.rotation)

        for obj in self.objects(pads=False, text=text):
            if not (layer := layer_map.get(obj.layer)):
                continue

            for fe in obj.render(variables=variables):
                fe.rotate(rotation)
                fe.offset(x, y, MM)
                layer_stack[layer].objects.append(fe)

        for obj in self.pads:
            if self.solder_mask_margin is not None:
                solder_mask_margin = self.solder_mask_margin
            elif obj.solder_mask_margin is not None:
                solder_mask_margin = obj.solder_mask_margin
            else:
                solder_mask_margin = None

            if self.solder_paste_margin is not None:
                solder_paste_margin = self.solder_paste_margin
            elif obj.solder_paste_margin_ratio is not None:
                solder_paste_margin = max(obj.size.x, obj.size.y) * obj.solder_paste_margin_ratio
            elif obj.solder_paste_margin is not None:
                solder_paste_margin = obj.solder_paste_margin
            else:
                solder_paste_margin = None

            for glob in obj.layers or []:
                for layer in fnmatch.filter(layer_map, glob):

                    if layer.endswith('.Mask'):
                        margin = solder_mask_margin
                    elif layer.endswith('.Paste'):
                        margin = solder_paste_margin
                    else:
                        margin = None

                    for fe in obj.render(margin=margin, cache=cache):
                        fe.rotate(rotation)
                        fe.offset(x, y, MM)
                        if isinstance(fe, go.Flash) and fe.aperture:
                            fe.aperture = fe.aperture.rotated(rotation)
                        layer_stack[layer_map[layer]].objects.append(fe)

        for obj in self.pads:
            for fe in obj.render_drill():
                fe.rotate(rotation)
                fe.offset(x, y, MM)

                if obj.type == Atom.np_thru_hole:
                    layer_stack.drill_npth.append(fe)
                else:
                    layer_stack.drill_pth.append(fe)
    
    def bounding_box(self, unit=MM):
        if not self._bounding_box:
            stack = LayerStack()
            layer_map = {kc_id: gn_id for kc_id, gn_id in LAYER_MAP_K2G.items() if gn_id in stack}
            self.render(stack, layer_map, x=0, y=0, rotation=0, flip=False, text=False, variables={})
            self._bounding_box = stack.bounding_box(unit)
        return self._bounding_box

        
@dataclass
class FootprintInstance(Positioned):
    sexp: Footprint = None
    hide_text: bool = True 
    reference: str = 'REF**'
    value: str = None
    variables: dict = field(default_factory=lambda: {})

    def render(self, layer_stack, cache=None):
        x, y, rotation, flip= self.abs_pos
        x, y = MM(x, self.unit), MM(y, self.unit)

        variables = dict(self.variables)

        if self.reference is not None:
            variables['REFERENCE'] = str(self.reference)

        if self.value is not None:
            variables['VALUE'] = str(self.value)

        layer_map = {kc_id: gn_id for kc_id, gn_id in LAYER_MAP_K2G.items() if gn_id in layer_stack}

        self.sexp.render(layer_stack, layer_map,
                         x=x, y=y, rotation=rotation,
                         flip=flip,
                         text=(not self.hide_text),
                         variables=variables, cache=cache)
    
    def bounding_box(self, unit=MM):
        return offset_bounds(self.sexp.bounding_box(unit), unit(self.x, self.unit), unit(self.y, self.unit))


if __name__ == '__main__':
    import sys
    from ...layers import LayerStack
    fp = Footprint.open_mod(sys.argv[1])
    stack = LayerStack()
    FootprintInstance(0, 0, fp, unit=MM).render(stack)
    print(stack.to_pretty_svg())
    stack.save_to_directory('/tmp/testdir')