summaryrefslogtreecommitdiff
path: root/gerbonara/gerber/apertures.py
blob: 872de9f311a3646caa5416e034106eb8400955a4 (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
import math
from dataclasses import dataclass, replace, fields, InitVar, KW_ONLY

from .aperture_macros.parse import GenericMacros
from .utils import MM, Inch

from . import graphic_primitives as gp


def _flash_hole(self, x, y, unit=None):
    if getattr(self, 'hole_rect_h', None) is not None:
        return [*self.primitives(x, y, unit),
                gp.Rectangle((x, y),
                    (self.unit.convert_to(unit, self.hole_dia), self.unit.convert_to(unit, self.hole_rect_h)),
                    rotation=self.rotation, polarity_dark=False)]
    elif self.hole_dia is not None:
        return [*self.primitives(x, y, unit),
                gp.Circle(x, y, self.unit.convert_to(unit, self.hole_dia/2), polarity_dark=False)]
    else:
        return self.primitives(x, y, unit)

def strip_right(*args):
    args = list(args)
    while args and args[-1] is None:
        args.pop()
    return args

def none_close(a, b):
    if a is None and b is None:
        return True
    elif a is not None and b is not None:
        return math.isclose(a, b)
    else:
        return False

class Length:
    def __init__(self, obj_type):
        self.type = obj_type

@dataclass
class Aperture:
    _ : KW_ONLY
    unit : str = None

    @property
    def hole_shape(self):
        if hasattr(self, 'hole_rect_h') and self.hole_rect_h is not None:
            return 'rect'
        else:
            return 'circle'

    def params(self, unit=None):
        out = []
        for f in fields(self):
            if f.kw_only:
                continue

            val = getattr(self, f.name)
            if isinstance(f.type, Length):
                val = self.unit.convert_to(unit, val)
            out.append(val)

        return out

    def flash(self, x, y, unit=None):
        return self.primitives(x, y, unit)

    def equivalent_width(self, unit=None):
        raise ValueError('Non-circular aperture used in interpolation statement, line width is not properly defined.')

    def to_gerber(self, settings=None):
        # Hack: The standard aperture shapes C, R, O do not have a rotation parameter. To make this API easier to use,
        # we emulate this parameter. Our circle, rectangle and oblong classes below have a rotation parameter. Only at
        # export time during to_gerber, this parameter is evaluated. 
        unit = settings.unit if settings else None
        #print(f'aperture to gerber {self.unit=} {settings=} {unit=}')
        actual_inst = self._rotated()
        params = 'X'.join(f'{float(par):.4}' for par in actual_inst.params(unit) if par is not None)
        return f'{actual_inst.gerber_shape_code},{params}'

    def __eq__(self, other):
        # We need to choose some unit here.
        return hasattr(other, to_gerber) and self.to_gerber(MM) == other.to_gerber(MM)

    def _rotate_hole_90(self):
        if self.hole_rect_h is None:
            return {'hole_dia': self.hole_dia, 'hole_rect_h': None}
        else:
            return {'hole_dia': self.hole_rect_h, 'hole_rect_h': self.hole_dia}

@dataclass(unsafe_hash=True)
class ExcellonTool(Aperture):
    human_readable_shape = 'drill'
    diameter : Length(float)
    plated : bool = None
    depth_offset : Length(float) = 0
    
    def primitives(self, x, y, unit=None):
        return [ gp.Circle(x, y, self.unit.convert_to(unit, self.diameter/2)) ]

    def to_xnc(self, settings):
        z_off = 'Z' + settings.write_excellon_value(self.depth_offset, self.unit) if self.depth_offset is not None else ''
        return 'C' + settings.write_excellon_value(self.diameter, self.unit) + z_off

    def __eq__(self, other):
        if not isinstance(other, ExcellonTool):
            return False

        if not self.plated == other.plated:
            return False

        if not none_close(self.depth_offset, self.unit(other.depth_offset, other.unit)):
            return False

        return none_close(self.diameter, self.unit(other.diameter, other.unit))

    def __str__(self):
        plated = '' if self.plated is None else (' plated' if self.plated else ' non-plated')
        z_off = '' if self.depth_offset is None else f' z_offset={self.depth_offset}'
        return f'<Excellon Tool d={self.diameter:.3f}{plated}{z_off} [{self.unit}]>'

    def equivalent_width(self, unit=MM):
        return unit(self.diameter, self.unit)

    def dilated(self, offset, unit=MM):
        offset = unit(offset, self.unit)
        return replace(self, diameter=self.diameter+2*offset)

    def _rotated(self):
        return self

    def to_macro(self):
        return ApertureMacroInstance(GenericMacros.circle, self.params(unit=MM))

    def params(self, unit=None):
        return [self.unit.convert_to(unit, self.diameter)]


@dataclass
class CircleAperture(Aperture):
    gerber_shape_code = 'C'
    human_readable_shape = 'circle'
    diameter : Length(float)
    hole_dia : Length(float) = None
    hole_rect_h : Length(float) = None
    rotation : float = 0 # radians; for rectangular hole; see hack in Aperture.to_gerber

    def primitives(self, x, y, unit=None):
        return [ gp.Circle(x, y, self.unit.convert_to(unit, self.diameter/2)) ]

    def __str__(self):
        return f'<circle aperture d={self.diameter:.3} [{self.unit}]>'

    flash = _flash_hole

    def equivalent_width(self, unit=None):
        return self.unit.convert_to(unit, self.diameter)

    def dilated(self, offset, unit=MM):
        offset = self.unit(offset, unit)
        return replace(self, diameter=self.diameter+2*offset, hole_dia=None, hole_rect_h=None)

    def _rotated(self):
        if math.isclose(self.rotation % (2*math.pi), 0) or self.hole_rect_h is None:
            return self
        else:
            return self.to_macro(self.rotation)

    def to_macro(self):
        return ApertureMacroInstance(GenericMacros.circle, self.params(unit=MM))

    def params(self, unit=None):
        return strip_right(
                self.unit.convert_to(unit, self.diameter),
                self.unit.convert_to(unit, self.hole_dia),
                self.unit.convert_to(unit, self.hole_rect_h))


@dataclass
class RectangleAperture(Aperture):
    gerber_shape_code = 'R'
    human_readable_shape = 'rect'
    w : Length(float)
    h : Length(float)
    hole_dia : Length(float) = None
    hole_rect_h : Length(float) = None
    rotation : float = 0 # radians

    def primitives(self, x, y, unit=None):
        return [ gp.Rectangle(x, y, self.unit.convert_to(unit, self.w), self.unit.convert_to(unit, self.h), rotation=self.rotation) ]

    def __str__(self):
        return f'<rect aperture {self.w:.3}x{self.h:.3} [{self.unit}]>'

    flash = _flash_hole

    def equivalent_width(self, unit=None):
        return self.unit.convert_to(unit, math.sqrt(self.w**2 + self.h**2))

    def dilated(self, offset, unit=MM):
        offset = self.unit(offset, unit)
        return replace(self, w=self.w+2*offset, h=self.h+2*offset, hole_dia=None, hole_rect_h=None)

    def _rotated(self):
        if math.isclose(self.rotation % math.pi, 0):
            return self
        elif math.isclose(self.rotation % math.pi, math.pi/2):
            return replace(self, w=self.h, h=self.w, **self._rotate_hole_90(), rotation=0)
        else: # odd angle
            return self.to_macro()

    def to_macro(self):
        return ApertureMacroInstance(GenericMacros.rect,
                [MM(self.w, self.unit),
                    MM(self.h, self.unit),
                    MM(self.hole_dia, self.unit) or 0,
                    MM(self.hole_rect_h, self.unit) or 0,
                    self.rotation])

    def params(self, unit=None):
        return strip_right(
                self.unit.convert_to(unit, self.w),
                self.unit.convert_to(unit, self.h),
                self.unit.convert_to(unit, self.hole_dia),
                self.unit.convert_to(unit, self.hole_rect_h))


@dataclass
class ObroundAperture(Aperture):
    gerber_shape_code = 'O'
    human_readable_shape = 'obround'
    w : Length(float)
    h : Length(float)
    hole_dia : Length(float) = None
    hole_rect_h : Length(float) = None
    rotation : float = 0

    def primitives(self, x, y, unit=None):
        return [ gp.Obround(x, y, self.unit.convert_to(unit, self.w), self.unit.convert_to(unit, self.h), rotation=self.rotation) ]

    def __str__(self):
        return f'<obround aperture {self.w:.3}x{self.h:.3} [{self.unit}]>'

    flash = _flash_hole

    def dilated(self, offset, unit=MM):
        offset = self.unit(offset, unit)
        return replace(self, w=self.w+2*offset, h=self.h+2*offset, hole_dia=None, hole_rect_h=None)

    def _rotated(self):
        if math.isclose(self.rotation % math.pi, 0):
            return self
        elif math.isclose(self.rotation % math.pi, math.pi/2):
            return replace(self, w=self.h, h=self.w, **self._rotate_hole_90(), rotation=0)
        else:
            return self.to_macro()

    def to_macro(self):
        # generic macro only supports w > h so flip x/y if h > w
        inst = self if self.w > self.h else replace(self, w=self.h, h=self.w, **_rotate_hole_90(self), rotation=self.rotation-90)
        return ApertureMacroInstance(GenericMacros.obround,
                [MM(inst.w, self.unit),
                 MM(ints.h, self.unit),
                 MM(inst.hole_dia, self.unit),
                 MM(inst.hole_rect_h, self.unit),
                 inst.rotation])

    def params(self, unit=None):
        return strip_right(
                self.unit.convert_to(unit, self.w),
                self.unit.convert_to(unit, self.h),
                self.unit.convert_to(unit, self.hole_dia),
                self.unit.convert_to(unit, self.hole_rect_h))


@dataclass
class PolygonAperture(Aperture):
    gerber_shape_code = 'P'
    diameter : Length(float)
    n_vertices : int
    rotation : float = 0
    hole_dia : Length(float) = None

    def __post_init__(self):
        self.n_vertices = int(self.n_vertices)

    def primitives(self, x, y, unit=None):
        return [ gp.RegularPolygon(x, y, self.unit.convert_to(unit, self.diameter)/2, self.n_vertices, rotation=self.rotation) ]

    def __str__(self):
        return f'<{self.n_vertices}-gon aperture d={self.diameter:.3} [{self.unit}]>'

    def dilated(self, offset, unit=MM):
        offset = self.unit(offset, unit)
        return replace(self, diameter=self.diameter+2*offset, hole_dia=None)

    flash = _flash_hole

    def _rotated(self):
        return self

    def to_macro(self):
        return ApertureMacroInstance(GenericMacros.polygon, self.params(MM))

    def params(self, unit=None):
        rotation = self.rotation % (2*math.pi / self.n_vertices) if self.rotation is not None else None
        if self.hole_dia is not None:
            return self.unit.convert_to(unit, self.diameter), self.n_vertices, rotation, self.unit.convert_to(unit, self.hole_dia)
        elif rotation is not None and not math.isclose(rotation, 0):
            return self.unit.convert_to(unit, self.diameter), self.n_vertices, rotation
        else:
            return self.unit.convert_to(unit, self.diameter), self.n_vertices

@dataclass
class ApertureMacroInstance(Aperture):
    macro : object
    parameters : [float]
    rotation : float = 0

    @property
    def gerber_shape_code(self):
        return self.macro.name

    def primitives(self, x, y, unit=None):
        return self.macro.to_graphic_primitives(
                offset=(x, y), rotation=self.rotation,
                parameters=self.parameters, unit=unit)

    def dilated(self, offset, unit=MM):
        return replace(self, macro=self.macro.dilated(offset, unit))

    def _rotated(self):
        if math.isclose(self.rotation % (2*math.pi), 0):
            return self
        else:
            return self.to_macro()

    def to_macro(self):
        return replace(self, macro=self.macro.rotated(self.rotation), rotation=0)

    def __eq__(self, other):
        return hasattr(other, 'macro') and self.macro == other.macro and \
                hasattr(other, 'params') and self.params == other.params and \
                hasattr(other, 'rotation') and self.rotation == other.rotation

    def params(self, unit=None):
        # We ignore "unit" here as we convert the actual macro, not this instantiation.
        # We do this because here we do not have information about which parameter has which physical units.
        return tuple(self.parameters)