"""Convert JITX shapes into Gerber graphic objects and apertures.
Three targets, and which one a shape gets is a property of what the shape is
for rather than of its geometry:
- a **pad** becomes an aperture that is flashed, always. 4.10 requires that
all pads are flashed and all flashes are pads, so a shape a macro cannot
express exactly is composed from primitives or linearized, never turned
into a region.
- a **stroked** shape (a routed trace, a legend outline) becomes draws and
arcs with a circular aperture, which is what Gerber's round caps and joins
already mean.
- a **filled** shape becomes region contours, an island with its holes.
Mirroring is read off the composed transform and nowhere else. A transform
composes as translate * rotate * scale, so a point maps to `t + R(r)·S(s)·p`;
an aperture flashed at `t` with rotation `r` therefore holds `S(s)·p`, which
is the whole of the mirror handling and why none of it is hand-rolled here.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from logging import getLogger
from jitx.layerindex import Side as JitxSide
from jitx.placement import Placement
from jitx.shapes import Shape
from jitx.shapes.composites import capsule_from_polyline, rectangle_from_polygon
from jitx.shapes.primitive import (
Primitive,
Arc,
ArcPolygon,
ArcPolyline,
Circle,
Empty,
Polygon,
PolygonSet,
Polyline,
Text,
)
from jitx.shapes.shapely import ShapelyGeometry
from jitx.transform import IDENTITY, Transform
from ..format import apertures, font
from ..format.contours import closed_ring, signed_area
from ..format.model import (
ArcObj,
Aperture,
AttrSet,
Contour,
CurveSeg,
Draw,
Seg,
Side,
)
from ..format.compat import DEFAULT as DEFAULT_COMPAT
from ..format.compat import Compat
from ..format.units import HALF_STEP, grid
logger = getLogger(__name__)
TOLERANCE = 1e-4
"""Arc linearization tolerance in mm, for the paths that must linearize.
Two orders of magnitude tighter than `from_primitive`'s 1e-2 default and two
above the 1 nm coordinate grid, which leaves room on both sides: a linearized
pad stays well inside the outline primitive's vertex budget, and the error is
invisible at the output resolution.
"""
Point = tuple[float, float]
[docs]
class GeometryError(ValueError):
"""A shape cannot be expressed in the Gerber model."""
[docs]
class Placer:
"""A shape's composed transform, decomposed once.
Args:
total: the full transform from the shape's own frame to the board,
already composed. Nothing here adds a side flip of its own: a
bottom-side `Placement` carries its mirror already, and applying
another composes two mirrors into none.
Raises:
GeometryError: the transform scales x and y differently, which
neither an aperture nor an arc can express.
"""
def __init__(self, total: Transform) -> None:
_, rotation, (sx, sy) = total.trs
if abs(abs(sx) - abs(sy)) > 1e-12:
raise GeometryError(f"Non-uniform scale is not supported: {(sx, sy)}")
self.transform = total
self.rotation = rotation
self.scale = abs(sx)
self.axes = (sx, sy)
self.mirrored = (sx * sy) < 0
[docs]
def point(self, x: float, y: float) -> Point:
"""A point in the shape's frame, placed on the board."""
return self.transform * (x, y)
[docs]
def length(self, value: float) -> float:
"""A length in the shape's frame, scaled."""
return value * self.scale
[docs]
def aperture_point(self, x: float, y: float) -> Point:
"""A point in the aperture's own frame.
The aperture carries the scale and the mirror; the flash carries the
translation and the `AD` carries the rotation, so what is left for
the vertex list is exactly `S(s)·p`.
"""
sx, sy = self.axes
return (x * sx, y * sy)
[docs]
def placer(shape: Shape, transform: Transform | None = IDENTITY) -> Placer:
"""The placer for a shape under an accumulated transform."""
prim = shape.to_primitive()
return Placer((transform or IDENTITY) * prim.transform)
[docs]
def surface_side(transform: Transform | None, side: JitxSide) -> Side:
"""Which side of the board a surface feature ends up on.
A `SurfaceFeature`'s side is relative to its placement - `Bottom` means
the opposite side from where the owning landpattern sits - so the answer
comes off the composed transform, like every other side question here.
"""
flip = Placement(transform).side if transform is not None else JitxSide.Top
resolved = side if flip == JitxSide.Top else side.flip()
return Side.TOP if resolved == JitxSide.Top else Side.BOTTOM
[docs]
def geometry_of(shape: Shape) -> object:
"""A shape's primitive geometry, with its own transform stripped off."""
return shape.to_primitive().geometry
[docs]
def is_stroked(shape: Shape) -> bool:
"""Whether the shape is a polyline, which Gerber strokes rather than fills."""
return isinstance(geometry_of(shape), (Polyline, ArcPolyline))
[docs]
def is_filled(shape: Shape) -> bool:
"""Whether the shape encloses an area, so it images as regions."""
return isinstance(geometry_of(shape), (Circle, ArcPolygon, Polygon, PolygonSet))
[docs]
def is_text(shape: Shape) -> bool:
"""Whether the shape is text, which Gerber has no native form for."""
return isinstance(geometry_of(shape), Text)
# --------------------------------------------------------------------------
# filled shapes
[docs]
@dataclass(frozen=True)
class Island:
"""One filled area: its outer ring and the holes inside it.
The grouping is what any ordering moves, so an island can never be
separated from a hole that would erase it.
"""
outer: Contour
holes: tuple[Contour, ...] = ()
[docs]
def to_islands(shape: Shape, transform: Transform | None = IDENTITY) -> list[Island]:
"""Convert a filled shape to islands with their holes, arcs intact.
Raises:
GeometryError: the geometry is not a filled shape.
"""
prim = shape.to_primitive()
place = Placer((transform or IDENTITY) * prim.transform)
geom = prim.geometry
match geom:
case Empty():
return []
case Circle():
return [Island(_circle_contour(geom.radius, place, ccw=True))]
case ArcPolygon():
return [Island(_oriented(_arc_polygon(geom, place), ccw=True))]
case Polygon():
return [_polygon_island(geom, place)]
case PolygonSet():
return [_polygon_island(poly, place) for poly in geom.polygons]
case _:
raise GeometryError(f"Not a filled shape: {type(geom).__name__}")
def _polygon_island(poly: Polygon, place: Placer) -> Island:
outer = _oriented(_ring([(p[0], p[1]) for p in poly.elements], place), ccw=True)
holes = tuple(
_oriented(_ring([(p[0], p[1]) for p in hole], place), ccw=False)
for hole in poly.holes
)
return Island(outer, holes)
def _ring(points: list[Point], place: Placer) -> Contour:
return closed_ring([place.point(x, y) for x, y in points])
def _circle_contour(radius: float, place: Placer, *, ccw: bool) -> Contour:
"""A full circle as two half arcs.
The spec's zero-length full-circle form is legal but is the construct it
also calls numerically unstable, and it is forbidden inside a contour, so
this package never writes one.
"""
left = place.point(-radius, 0.0)
right = place.point(radius, 0.0)
center = place.point(0.0, 0.0)
return Contour(
start=left,
segments=(
CurveSeg(*right, *center, ccw),
CurveSeg(*left, *center, ccw),
),
)
def _arc_point(arc: Arc, angle: float) -> Point:
radians = math.radians(angle)
return (
arc.center[0] + arc.radius * math.cos(radians),
arc.center[1] + arc.radius * math.sin(radians),
)
def _arc_polygon(poly: ArcPolygon, place: Placer) -> Contour:
"""An arc polygon as a contour, keeping its arcs exact."""
start: Point | None = None
segments: list[Seg | CurveSeg] = []
def vertex(point: Point) -> None:
nonlocal start
if start is None:
start = point
else:
segments.append(Seg(*point))
for element in poly.elements:
if not isinstance(element, Arc):
vertex(place.point(element[0], element[1]))
continue
first = place.point(*_arc_point(element, element.start))
if element.radius == 0 or element.arc == 0:
vertex(first)
continue
center = place.point(*element.center)
ccw = (element.arc > 0) != place.mirrored
if start is None:
start = first
elif (segments and (segments[-1].x, segments[-1].y) != first) or not segments:
segments.append(Seg(*first))
end = place.point(*_arc_point(element, element.start + element.arc))
# a 360 degree element would close on itself; the emitter splits any
# sweep over 180 degrees, so one segment to the end point is enough
segments.append(CurveSeg(*end, *center, ccw))
if start is None:
raise GeometryError("Arc polygon has no elements")
if not segments or (segments[-1].x, segments[-1].y) != start:
segments.append(Seg(*start))
return Contour(start=start, segments=tuple(segments))
[docs]
def reverse(contour: Contour) -> Contour:
"""Run a contour the other way round, flipping its arcs with it."""
points = [contour.start] + [(s.x, s.y) for s in contour.segments]
segments: list[Seg | CurveSeg] = []
for index in range(len(contour.segments) - 1, -1, -1):
segment = contour.segments[index]
target = points[index]
if isinstance(segment, Seg):
segments.append(Seg(*target))
else:
segments.append(CurveSeg(*target, segment.cx, segment.cy, not segment.ccw))
return Contour(start=points[-1], segments=tuple(segments))
def _oriented(contour: Contour, *, ccw: bool) -> Contour:
"""Force the winding convention this package fixes: outer contours
counter-clockwise, holes clockwise.
The spec leaves winding open, but §8's polarity simulator needs a
convention to interpret, so one is chosen and enforced here rather than
inherited from whatever the design happened to author. Arc bulges do not
enter the area, which is sound for deciding a sign and not for measuring.
"""
area = signed_area(contour)
if area == 0 or (area > 0) == ccw:
return contour
return reverse(contour)
# --------------------------------------------------------------------------
# stroked shapes
[docs]
def to_path(
shape: Shape, transform: Transform | None = IDENTITY
) -> tuple[Point, tuple[Seg | CurveSeg, ...]] | None:
"""Convert a polyline to a placed start point and its segments.
The open-path counterpart of `to_islands`. `to_strokes` images the path
with an aperture; a drill rout needs the same walk as bare geometry,
since XNC states a path and a tool rather than an image.
Returns:
None when the polyline images nothing - no elements, or a single
point with no segment leaving it.
Raises:
GeometryError: the shape is not a polyline.
"""
prim = shape.to_primitive()
place = Placer((transform or IDENTITY) * prim.transform)
geom = prim.geometry
if not isinstance(geom, (Polyline, ArcPolyline)):
raise GeometryError(f"Not a stroked shape: {type(geom).__name__}")
start: Point | None = None
out: list[Seg | CurveSeg] = []
here: Point | None = None
for element in geom.elements:
if not isinstance(element, Arc):
point = place.point(element[0], element[1])
if here is not None:
out.append(Seg(*point))
here = point
start = start if start is not None else point
continue
begin = place.point(*_arc_point(element, element.start))
if here is not None and here != begin:
out.append(Seg(*begin))
start = start if start is not None else begin
if element.radius == 0 or element.arc == 0:
here = begin
continue
end = place.point(*_arc_point(element, element.start + element.arc))
center = place.point(*element.center)
ccw = (element.arc > 0) != place.mirrored
out.append(CurveSeg(*end, *center, ccw))
here = end
if start is None or not out:
return None
return start, tuple(out)
[docs]
def to_strokes(
shape: Shape,
aperture: Aperture,
transform: Transform | None = IDENTITY,
attrs: AttrSet = (),
) -> list[Draw | ArcObj]:
"""Convert a polyline to the draws and arcs that stroke it.
Args:
aperture: the circular aperture to stroke with; its diameter is the
polyline width, which the caller has already placed.
Raises:
GeometryError: the shape is not a polyline.
"""
path = to_path(shape, transform)
if path is None:
return []
start, segments = path
out: list[Draw | ArcObj] = []
here = start
for segment in segments:
end = (segment.x, segment.y)
if isinstance(segment, Seg):
out.append(Draw(*here, *end, aperture, attrs))
else:
out.append(
ArcObj(
*here, *end, segment.cx, segment.cy, segment.ccw, aperture, attrs
)
)
here = end
return out
[docs]
def text_string(shape: Shape) -> str | None:
"""The string a text shape carries, or None when it is not text.
A query rather than a raise, because the caller's next question is
usually whether the string is a label placeholder, and a shape that is
not text simply has no string to inspect.
"""
geom = shape.to_primitive().geometry
return geom.string if isinstance(geom, Text) else None
[docs]
def text_stroke_width(shape: Shape, transform: Transform | None = IDENTITY) -> float:
"""The placed stroke diameter legend text of this shape is drawn with.
Separate from `to_text_strokes` for the same reason `stroke_width` is
separate from `to_strokes`: the aperture carries `TA.AperFunction` as
well as a diameter, and what function it has is the caller's decision.
Raises:
GeometryError: the shape is not text.
"""
return _text_placer(shape, transform)[0].length(
font.stroke_width(_text_geometry(shape).size)
)
[docs]
def to_text_strokes(
shape: Shape,
aperture: Aperture,
transform: Transform | None = IDENTITY,
attrs: AttrSet = (),
string: str | None = None,
) -> list[Draw]:
"""Stroke a text shape into the draws that write it.
Args:
string: what to write instead of the shape's own string. This is how
a resolved `>REF` or `>VALUE` reaches the legend: the size, the
anchor and the placement stay the shape's, only the characters
change.
Gerber has no native text (5.7), so a legend string is a run of `D01`
draws with a small circular aperture. The glyphs come from `format.font`
and the anchor is resolved against that font's own metrics, so the box
the anchor names is the box the ink actually fills.
A glyph that is a dot comes out as a zero-length draw, which is what the
spec's note under 4.8 describes and the only correct object for it: the
same image as a flash, but not a flash, because every flash is a pad.
Raises:
GeometryError: the shape is not text.
"""
place, origin = _text_placer(shape, transform, string)
geom = _text_geometry(shape)
text = geom.string if string is None else string
out: list[Draw] = []
# placing the glyph points through the composed transform is also what
# makes bottom-side legend text read correctly from the bottom: the
# placement carries the mirror, and nothing here adds one
for stroke in font.strokes(text, geom.size, origin):
placed = [place.point(x, y) for x, y in stroke]
for start, end in zip(placed, placed[1:], strict=False):
out.append(Draw(*start, *end, aperture, attrs))
if len(placed) == 1:
out.append(Draw(*placed[0], *placed[0], aperture, attrs))
return out
def _text_geometry(shape: Shape) -> Text:
geom = shape.to_primitive().geometry
if not isinstance(geom, Text):
raise GeometryError(f"Not a text shape: {type(geom).__name__}")
return geom
def _text_placer(
shape: Shape, transform: Transform | None, string: str | None = None
) -> tuple[Placer, Point]:
"""The placer for a text shape and the lower-left corner of its box.
The anchor names a point on the text box; the font lays glyphs out from
the box's lower-left corner, so the anchor becomes an offset in the
shape's own frame and the transform does the rest.
The box is measured against `string` when one is given, not against the
shape's own. A substituted label has to anchor as what it will actually
write: a centred `>REF` measured as five glyphs and drawn as `U1` would
sit half a placeholder to the right of where the design put it.
"""
prim = shape.to_primitive()
geom = _text_geometry(shape)
place = Placer((transform or IDENTITY) * prim.transform)
width, height = font.extents(geom.string if string is None else string, geom.size)
anchor = geom.anchor.value
dx = -width / 2 if anchor in ("N", "C", "S") else -width if "E" in anchor else 0.0
dy = -height / 2 if anchor in ("W", "C", "E") else -height if "N" in anchor else 0.0
return place, (dx, dy)
[docs]
def stroke_width(shape: Shape, transform: Transform | None = IDENTITY) -> float:
"""The placed stroke width of a polyline shape."""
prim = shape.to_primitive()
geom = prim.geometry
if not isinstance(geom, (Polyline, ArcPolyline)):
raise GeometryError(f"Not a stroked shape: {type(geom).__name__}")
return Placer((transform or IDENTITY) * prim.transform).length(geom.width)
# --------------------------------------------------------------------------
# pads
[docs]
def pad_aperture(
shape: Shape,
transform: Transform | None = IDENTITY,
attrs: AttrSet = (),
compat: Compat = DEFAULT_COMPAT,
) -> tuple[Aperture, Point] | None:
"""The aperture and flash point for a pad shape, or None when empty.
The result always flashes. Standard templates serve the shapes they can
express exactly, a macro composition serves rotated rectangles, capsules,
rounded rectangles and annular pads, and only a genuinely free-form
outline is linearized - at `TOLERANCE`, which is chosen against the
outline primitive's vertex budget rather than independently.
Args:
compat: output adjustments; `bake_macro_rotation` writes rotated
macros with the rotation in their coordinates.
Raises:
GeometryError: the shape cannot be expressed as an aperture.
ApertureError: the shape needs more outline vertices than one
primitive holds.
"""
prim = shape.to_primitive()
total = (transform or IDENTITY) * prim.transform
place = Placer(total)
geom = prim.geometry
baked = compat.bake_macro_rotation
match geom:
case Empty():
return None
case Circle():
diameter = place.length(2 * geom.radius)
return apertures.circle_aperture(diameter, attrs=attrs), place.point(0, 0)
case Polyline() if len(list(geom.elements)) == 2:
return _capsule_aperture(geom, total, attrs, baked)
case Polygon() if not geom.holes:
return _rect_or_outline(geom, total, place, attrs, baked)
case Polygon():
return _holed_aperture(geom, place, attrs, baked)
case _:
return _linearized_aperture(geom, place, attrs, baked)
def _snapped(rotation: float, reach: float) -> float:
"""The rotation, or the nearest quarter turn when the difference cannot
show on the output grid.
Args:
rotation: degrees.
reach: the largest distance in mm from the flash point to any point
of the shape.
"""
# Placements can arrive as float32 (a half turn as -179.99998474), so
# a fixed angular tolerance either misses them or, for a large enough
# pad, snaps a visible rotation. Bounding the displacement instead
# makes the snap exactly as invisible as coordinate rounding.
nearest = round(rotation / 90.0) * 90.0
if math.radians(abs(rotation - nearest)) * reach < HALF_STEP:
return nearest
return rotation
def _axis_angle(rotation: float, reach: float) -> tuple[float, bool]:
"""Fold a two-fold symmetric shape's angle into [-90, 90).
Returns the folded angle, exactly 0 when the shape is axis-aligned, and
whether the shape's own width and height swap, which is what a quarter
turn does to an axis-aligned template.
"""
folded = (_snapped(rotation, reach) + 90.0) % 180.0 - 90.0
if folded == -90.0:
return 0.0, True
return folded, False
def _ring_reach(rings: list[list[Point]]) -> float:
return max((math.hypot(x, y) for ring in rings for x, y in ring), default=0.0)
def _capsule_aperture(
geom: Polyline, total: Transform, attrs: AttrSet, baked: bool
) -> tuple[Aperture, Point]:
try:
(width, height), place_at = capsule_from_polyline(geom)
except ValueError as error:
raise GeometryError(f"Capsule pad shape not recognized: {error}") from error
composed = Placer(total * place_at)
width, height = composed.length(width), composed.length(height)
angle, swapped = _axis_angle(composed.rotation, max(width, height) / 2)
if swapped:
width, height = height, width
point = composed.point(0.0, 0.0)
if angle == 0.0:
return apertures.obround_aperture(width, height, attrs=attrs), point
return apertures.rotated_capsule(width, height, angle, attrs, baked=baked), point
def _rect_or_outline(
geom: Polygon, total: Transform, place: Placer, attrs: AttrSet, baked: bool
) -> tuple[Aperture, Point]:
try:
(width, height), place_at = rectangle_from_polygon(geom)
except ValueError:
ring = [place.aperture_point(p[0], p[1]) for p in geom.elements]
return _outlines([(ring, [])], place, attrs, "outline", baked)
composed = Placer(total * place_at)
width, height = composed.length(width), composed.length(height)
angle, swapped = _axis_angle(composed.rotation, math.hypot(width, height) / 2)
if swapped:
width, height = height, width
point = composed.point(0.0, 0.0)
if angle == 0.0:
return apertures.rect_aperture(width, height, attrs=attrs), point
return apertures.rotated_rect(width, height, angle, attrs, baked=baked), point
_Rings = tuple[list[Point], list[list[Point]]]
def _outlines(
islands: list[_Rings], place: Placer, attrs: AttrSet, label: str, baked: bool
) -> tuple[Aperture, Point]:
reach = _ring_reach([outer for outer, _ in islands])
rotation = _snapped(place.rotation, reach)
aperture = apertures.outlines_aperture(
islands, rotation, attrs, label=label, baked=baked
)
return aperture, place.point(0.0, 0.0)
def _rings(outer: list[Point], holes: list[list[Point]], place: Placer) -> _Rings:
return (
[place.aperture_point(p[0], p[1]) for p in outer],
[[place.aperture_point(p[0], p[1]) for p in hole] for hole in holes],
)
def _holed_aperture(
geom: Polygon, place: Placer, attrs: AttrSet, baked: bool
) -> tuple[Aperture, Point]:
"""A pad with holes, as one macro with exposure-off primitives.
Never a region with `LPC`: an aperture hole is transparent (4.4.6, "holes
do not clear the objects under them"), while a clear region erases the
image plane. A donut pad over a same-net pour has to leave the pour
showing through the middle, which only the aperture form does.
"""
island = _rings(list(geom.elements), [list(h) for h in geom.holes], place)
return _outlines([island], place, attrs, "outline with holes", baked)
def _linearized_aperture(
geom: Primitive, place: Placer, attrs: AttrSet, baked: bool
) -> tuple[Aperture, Point]:
"""The fallback for a free-form outline: linearize and flash it.
Not a region. 4.10 is explicit that all pads are flashed and all flashes
are pads, so a pad emitted as a `G36` surface is not a pad as far as CAM
is concerned whatever it looks like on screen.
"""
shapely_geom = ShapelyGeometry.from_primitive(geom, TOLERANCE).to_primitive()
polygons: list[Polygon]
match shapely_geom:
case Polygon():
polygons = [shapely_geom]
case PolygonSet():
polygons = list(shapely_geom.polygons)
case _: # pragma: no cover - from_primitive returns one of the two
raise GeometryError(f"Cannot flash shape: {type(geom).__name__}")
islands = [
_rings(list(poly.elements), [list(h) for h in poly.holes], place)
for poly in polygons
]
return _outlines(islands, place, attrs, "linearized outline", baked)
# --------------------------------------------------------------------------
# shapely
[docs]
def to_shapely(shape: Shape, transform: Transform | None = IDENTITY) -> ShapelyGeometry:
"""A filled shape as shapely geometry on the output grid.
Snapping happens here rather than at the union, because shapely's
predicates are float-exact: two rectangles abutting at a shared edge
intersect, the same pair with a 1e-12 gap do not, and the two answers
give different connected components. Deciding adjacency on the grid the
file is written on is the only definition that matches the output.
"""
import shapely
prim = shape.to_primitive()
geom = ShapelyGeometry.from_primitive(prim.geometry, TOLERANCE)
placed = geom.apply((transform or IDENTITY) * prim.transform)
return ShapelyGeometry(shapely.set_precision(placed.g, 1e-6))
[docs]
def snap(value: float) -> float:
"""A millimeter value on the 1 nm output grid."""
return grid(value)
[docs]
def ring_contour(points: list[Point], *, ccw: bool) -> Contour:
"""A closed contour from a point ring, wound to the convention.
The ring is expected already placed; this is the entry point for
geometry that arrives from shapely rather than from a JITX primitive.
"""
return _oriented(closed_ring(points), ccw=ccw)
[docs]
def stroke_contour(
contour: Contour, aperture: Aperture, attrs: AttrSet = ()
) -> list[Draw | ArcObj]:
"""Draw a closed contour as a connected run of strokes.
The board profile is a stroked path rather than a region: the profile
file images the board edge, not the board.
"""
out: list[Draw | ArcObj] = []
here = contour.start
for segment in contour.segments:
end = (segment.x, segment.y)
if isinstance(segment, Seg):
out.append(Draw(*here, *end, aperture, attrs))
else:
out.append(
ArcObj(
*here, *end, segment.cx, segment.cy, segment.ccw, aperture, attrs
)
)
here = end
return out