summaryrefslogtreecommitdiff
path: root/gerbonara/gerber
diff options
context:
space:
mode:
Diffstat (limited to 'gerbonara/gerber')
-rw-r--r--gerbonara/gerber/aperture_macros/parse.py153
-rw-r--r--gerbonara/gerber/gerber_primitives.py14
-rw-r--r--gerbonara/gerber/graphic_objects.py165
3 files changed, 332 insertions, 0 deletions
diff --git a/gerbonara/gerber/aperture_macros/parse.py b/gerbonara/gerber/aperture_macros/parse.py
new file mode 100644
index 0000000..47f45d1
--- /dev/null
+++ b/gerbonara/gerber/aperture_macros/parse.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+# Copyright 2021 Jan Götte <gerbonara@jaseg.de>
+
+import operator
+import re
+import ast
+import copy
+import math
+
+import primitive as ap
+from expression import *
+
+from .. import apertures
+
+def rad_to_deg(x):
+ return (x / math.pi) * 180
+
+def _map_expression(node):
+ if isinstance(node, ast.Num):
+ return ConstantExpression(node.n)
+
+ elif isinstance(node, ast.BinOp):
+ op_map = {ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.truediv}
+ return OperatorExpression(op_map[type(node.op)], _map_expression(node.left), _map_expression(node.right))
+
+ elif isinstance(node, ast.UnaryOp):
+ if type(node.op) == ast.UAdd:
+ return _map_expression(node.operand)
+ else:
+ return OperatorExpression(operator.sub, ConstantExpression(0), _map_expression(node.operand))
+
+ elif isinstance(node, ast.Name):
+ return VariableExpression(int(node.id[3:])) # node.id has format var[0-9]+
+
+ else:
+ raise SyntaxError('Invalid aperture macro expression')
+
+def _parse_expression(expr):
+ expr = expr.lower().replace('x', '*')
+ expr = re.sub(r'\$([0-9]+)', r'var\1', expr)
+ try:
+ parsed = ast.parse(expr, mode='eval').body
+ except SyntaxError as e:
+ raise SyntaxError('Invalid aperture macro expression') from e
+ return _map_expression(parsed)
+
+class ApertureMacro:
+ def __init__(self, name=None, primitives=None, variables=None):
+ self._name = name
+ self.comments = []
+ self.variables = variables or {}
+ self.primitives = primitives or []
+
+ @classmethod
+ def parse_macro(cls, name, macro, unit):
+ macro = cls(name)
+
+ blocks = re.sub(r'\s', '', macro).split('*')
+ for block in blocks:
+ if not (block := block.strip()): # empty block
+ continue
+
+ if block[0:1] == '0 ': # comment
+ macro.comments.append(Comment(block[2:]))
+
+ if block[0] == '$': # variable definition
+ name, expr = block.partition('=')
+ number = int(name[1:])
+ if number in macro.variables:
+ raise SyntaxError(f'Re-definition of aperture macro variable {number} inside macro')
+ macro.variables[number] = _parse_expression(expr)
+
+ else: # primitive
+ primitive, *args = block.split(',')
+ args = [_parse_expression(arg) for arg in args]
+ primitive = ap.PRIMITIVE_CLASSES[int(primitive)](unit=unit, args=args
+ macro.primitives.append(primitive)
+
+ @property
+ def name(self):
+ if self.name is not None:
+ return self.name
+ else:
+ return f'gn_{hash(self)}'
+
+ def __str__(self):
+ return f'<Aperture macro, variables {str(self.variables)}, primitives {self.primitives}>'
+
+ def __eq__(self, other):
+ return hasattr(other, to_gerber) and self.to_gerber() == other.to_gerber()
+
+ def __hash__(self):
+ return hash(self.to_gerber())
+
+ def to_gerber(self, unit=None):
+ comments = [ c.to_gerber() for c in self.comments ]
+ variable_defs = [ f'${var.to_gerber(unit)}={expr}' for var, expr in self.variables.items() ]
+ primitive_defs = [ prim.to_gerber(unit) for prim in self.primitives ]
+ return '*\n'.join(comments + variable_defs + primitive_defs)
+
+ def to_graphic_primitives(self, offset, rotation:'radians', parameters : [float], unit=None):
+ variables = dict(self.variables)
+ for number, value in enumerate(parameters):
+ if i in variables:
+ raise SyntaxError(f'Re-definition of aperture macro variable {i} through parameter {value}')
+ variables[i] = value
+
+ return [ primitive.to_graphic_primitives(offset, rotation, variables, unit) for primitive in self.primitives ]
+
+ def rotated(self, angle):
+ copy = copy.deepcopy(self)
+ for primitive in copy.primitives:
+ primitive.rotation += rad_to_deg(angle)
+ return copy
+
+
+class GenericMacros:
+ deg_per_rad = 180 / math.pi
+ cons, var = VariableExpression
+ _generic_hole = lambda n: [
+ ap.Circle(exposure=0, diameter=var(n), x=0, y=0),
+ ap.Rectangle(exposure=0, w=var(n), h=var(n+1), x=0, y=0, rotation=var(n+2) * deg_per_rad)]
+
+ circle = ApertureMacro([
+ ap.Circle(exposure=1, diameter=var(1), x=0, y=0, rotation=var(4) * deg_per_rad),
+ *_generic_hole(2)])
+
+ rect = ApertureMacro([
+ ap.Rectangle(exposure=1, w=var(1), h=var(2), x=0, y=0, rotation=var(5) * deg_per_rad),
+ *_generic_hole(3) ])
+
+ # w must be larger than h
+ obround = ApertureMacro([
+ ap.Rectangle(exposure=1, w=var(1), h=var(2), x=0, y=0, rotation=var(5) * deg_per_rad),
+ ap.Circle(exposure=1, diameter=var(2), x=+var(1)/2, y=0, rotation=var(5) * deg_per_rad),
+ ap.Circle(exposure=1, diameter=var(2), x=-var(1)/2, y=0, rotation=var(5) * deg_per_rad),
+ *_generic_hole(3) ])
+
+ polygon = ApertureMacro([
+ ap.Polygon(exposure=1, n_vertices=var(2), x=0, y=0, diameter=var(1), rotation=var(3) * deg_per_rad),
+ pa.Circle(exposure=0, diameter=var(4), x=0, y=0)])
+
+
+if __name__ == '__main__':
+ import sys
+ #for line in sys.stdin:
+ #expr = _parse_expression(line.strip())
+ #print(expr, '->', expr.optimized())
+
+ for primitive in parse_macro(sys.stdin.read(), 'mm'):
+ print(primitive)
diff --git a/gerbonara/gerber/gerber_primitives.py b/gerbonara/gerber/gerber_primitives.py
new file mode 100644
index 0000000..1a40948
--- /dev/null
+++ b/gerbonara/gerber/gerber_primitives.py
@@ -0,0 +1,14 @@
+
+from apertures import *
+
+class GerberPrimitive:
+ pass
+
+ def to_graphic_primitives(self):
+ pass
+
+class Line(GerberPrimitive):
+ pass
+
+class Arc(GerberPrimitive):
+ pass
diff --git a/gerbonara/gerber/graphic_objects.py b/gerbonara/gerber/graphic_objects.py
new file mode 100644
index 0000000..55d1b9c
--- /dev/null
+++ b/gerbonara/gerber/graphic_objects.py
@@ -0,0 +1,165 @@
+
+import graphic_primitives as gp
+
+class GerberObject:
+ _ : KW_ONLY
+ polarity_dark : bool = True
+
+ def to_primitives(self):
+ raise NotImplementedError()
+
+@dataclass
+class Flash(GerberObject):
+ x : float
+ y : float
+ aperture : object
+
+ def with_offset(self, dx, dy):
+ return replace(self, x=self.x+dx, y=self.y+dy)
+
+ def rotate(self, rotation, cx=None, cy=None):
+ self.x, self.y = gp.rotate_point(self.x, self.y, rotation, cx, cy)
+
+ def to_primitives(self):
+ yield from self.aperture.flash(self.x, self.y)
+
+ def to_statements(self, gs):
+ yield from gs.set_polarity(self.polarity_dark)
+ yield from gs.set_aperture(self.aperture)
+ yield FlashStmt(self.x, self.y)
+
+class Region(GerberObject):
+ def __init__(self, outline=[], arc_centers=None, *, polarity_dark):
+ super().__init__(self, polarity_dark=polarity_dark)
+ self.poly = gp.ArcPoly()
+
+ def with_offset(self, dx, dy):
+ return Region([ (x+dx, y+dy) for x, y in outline ], radii, polarity_dark=self.polarity_dark)
+
+ def rotate(self, angle, cx=0, cy=0):
+ self.poly.outline = [ gp.rotate_point(x, y, angle, cx, cy) for x, y in self.poly.outline ]
+ self.poly.arc_centers = [ gp.rotate_point(x, y, angle, cx, cy) for x, y in self.poly.arc_centers ]
+
+ def append(self, obj):
+ if not self.outline:
+ self.poly.outline.append(obj.p1)
+ self.poly.outline.append(obj.p2)
+
+ if isinstance(obj, Arc):
+ self.poly.arc_centers.append(obj.center)
+ else:
+ self.poly.arc_centers.append(None)
+
+ def to_primitives(self):
+ self.poly.polarity_dark = polarity_dark
+ yield self.poly
+
+ def to_statements(self, gs):
+ yield RegionStartStmt()
+
+ yield from gs.set_current_point(self.poly.outline[0])
+
+ for point, arc_center in zip(self.poly.outline, self.poly.arc_centers):
+ if arc_center is None:
+ yield from gs.set_interpolation_mode(LinearModeStmt)
+ yield InterpolateStmt(*point)
+
+ else:
+ cx, cy = arc_center
+ x2, y2 = point
+ yield from gs.set_interpolation_mode(CircularCCWModeStmt)
+ yield InterpolateStmt(x2, y2, cx-x2, cy-y2)
+
+ yield RegionEndStmt()
+
+
+class Line(GerberObject):
+ # Line with *round* end caps.
+ x1 : float
+ y1 : float
+ x2 : float
+ y2 : float
+ aperture : object
+
+ def with_offset(self, dx, dy):
+ return replace(self, x1=self.x1+dx, y1=self.y1+dy, x2=self.x2+dx, y2=self.y2+dy)
+
+ def rotate(self, rotation, cx=None, cy=None):
+ if cx is None:
+ cx = (self.x1 + self.x2) / 2
+ cy = (self.y1 + self.y2) / 2
+ self.x1, self.y1 = gp.rotate_point(self.x1, self.y1, rotation, cx, cy)
+ self.x2, self.y2 = gp.rotate_point(self.x2, self.y2, rotation, cx, cy)
+
+ @property
+ def p1(self):
+ return self.x1, self.y1
+
+ @property
+ def p2(self):
+ return self.x2, self.y2
+
+ def to_primitives(self):
+ yield gp.Line(*self.p1, *self.p2, self.aperture.equivalent_width, polarity_dark=self.polarity_dark)
+
+ def to_statements(self, gs):
+ yield from gs.set_aperture(self.aperture)
+ yield from gs.set_interpolation_mode(LinearModeStmt)
+ yield from gs.set_current_point(self.p1)
+ yield InterpolateStmt(*self.p2)
+
+
+class Arc(GerberObject):
+ x : float
+ y : float
+ r : float
+ angle1 : float # radians!
+ angle2 : float # radians!
+ aperture : object
+
+ @classmethod
+ def from_coords(kls, start, end, center_delta, aperture, flipped=False, polarity_dark=True):
+ x0, y0 = start
+ x1, y1 = end
+ dx, dy = center_delta
+ cx, cy = x0+dx, y0+dy
+ angle1 = math.atan2(y0-cy, x0-cx)
+ angle2 = math.atan2(y1-cy, x1-cx)
+ aperture = self.aperture
+ if flipped:
+ angle1, angle2 = angle2, angle1
+ r = math.sqrt(dx**2 + dy**2)
+ # r should be approximately (depending on coordinate resolution) equal for center->start and center->end
+ return kls(cx, cy, r, angle1, angle2, polarity_dark=polarity_dark)
+
+ def with_offset(self, dx, dy):
+ return replace(self, x=self.x+dx, y=self.y+dy)
+
+ @property
+ def p1(self):
+ return self.x + self.r*sin(self.angle1), self.y + self.r*cos(self.angle1)
+
+ @property
+ def p2(self):
+ return self.x + self.r*sin(self.angle2), self.y + self.r*cos(self.angle2)
+
+ @property
+ def center(self):
+ return (self.x, self.y)
+
+ def rotate(self, rotation, cx=None, cy=None):
+ self.x, self.y = gp.rotate_point(self.x, self.y, rotation, cx, cy)
+ self.angle1 = (self.angle1+rotation) % (2*math.pi)
+ self.angle2 = (self.angle2+rotation) % (2*math.pi)
+
+ def to_primitives(self):
+ yield gp.Arc(self.x, self.y, self.r, self.angle1, self.angle2, self.aperture.equivalent_width, polarity_dark=self.polarity_dark)
+
+ def to_statements(self, gs):
+ yield from gs.set_aperture(self.aperture)
+ yield from gs.set_interpolation_mode(CircularCCWModeStmt)
+ yield from gs.set_current_point(self.p1)
+ x2, y2 = self.p2
+ yield InterpolateStmt(x2, y2, self.x-x2, self.y-y2)
+
+