"""Data model for a Gerber X2/X3 fabrication data set.
Coordinates and sizes are millimeters; the emitters put them on the 1 nm
grid (`units`). Rotations are degrees counter-clockwise, the Gerber
convention. Object order within a file is the image order: a clear object
erases everything emitted before it, so the order a caller builds is the
order that reaches the file.
"""
from __future__ import annotations
from .compat import DEFAULT as DEFAULT_COMPAT
from .compat import Compat
from dataclasses import dataclass, field
from enum import StrEnum
from hashlib import sha256
from typing import TypeAlias
from .units import quantize
# --------------------------------------------------------------------------
# attributes
Attribute: TypeAlias = "tuple[str, tuple[str, ...]]"
AttrSet: TypeAlias = "tuple[Attribute, ...]"
"""Attribute names (with their leading dot for standard names) and values.
A tuple rather than a mapping so it can take part in an aperture key. An
empty value tuple emits a bare `%TO.Name*%`; a single empty string emits the
reserved empty value `%TO.N,*%`.
"""
[docs]
def attr(name: str, *values: str) -> Attribute:
"""One attribute for an `AttrSet`."""
return (name, tuple(values))
_ESCAPED = {",", "*", "%", "\\"}
[docs]
def escape_field(value: str) -> str:
"""Escape a string for use as an attribute field.
Reserved characters and everything outside printable ASCII become
`\\uXXXX` (or `\\UXXXXXXXX` above the BMP), so the whole file stays
7-bit printable ASCII and a user net name cannot break the syntax.
"""
out: list[str] = []
for char in value:
point = ord(char)
if char in _ESCAPED or point < 0x20 or point > 0x7E:
out.append(f"\\u{point:04X}" if point <= 0xFFFF else f"\\U{point:08X}")
else:
out.append(char)
return "".join(out)
# --------------------------------------------------------------------------
# file functions
[docs]
class FileKind(StrEnum):
"""The primary branch a naming scheme and the overwrite guard key on."""
COPPER = "copper"
SOLDERMASK = "soldermask"
LEGEND = "legend"
PASTE = "paste"
PROFILE = "profile"
DRILL = "drill"
COMPONENT = "component"
JOB = "job"
[docs]
class Side(StrEnum):
TOP = "Top"
INNER = "Inr"
BOTTOM = "Bot"
[docs]
class CopperType(StrEnum):
SIGNAL = "Signal"
PLANE = "Plane"
MIXED = "Mixed"
[docs]
class HoleType(StrEnum):
PTH = "PTH"
NPTH = "NPTH"
BLIND = "Blind"
BURIED = "Buried"
[docs]
class DrillContent(StrEnum):
DRILL = "Drill"
ROUT = "Rout"
MIXED = "Mixed"
[docs]
class Polarity(StrEnum):
"""Object polarity: dark adds to the image, clear erases from it."""
DARK = "D"
CLEAR = "C"
[docs]
class FilePolarity(StrEnum):
POSITIVE = "Positive"
NEGATIVE = "Negative"
[docs]
@dataclass(frozen=True)
class Copper:
"""`Copper,L<index>,<side>[,<type>]`.
Args:
index: 1-based conductor index, counted from the top.
side: Top for index 1, Bot for the last conductor, Inr otherwise.
conductors: total conductor count, for naming schemes that vary with
board size. Not part of the rendered attribute.
type: emitted only when set; a plain signal layer leaves it off.
"""
index: int
side: Side
conductors: int
type: CopperType | None = None
kind = FileKind.COPPER
[docs]
def render(self) -> str:
tail = f",{self.type}" if self.type is not None else ""
return f"Copper,L{self.index},{self.side}{tail}"
[docs]
@dataclass(frozen=True)
class Soldermask:
"""`Soldermask,<side>`. Images the openings, so the file is negative."""
side: Side
kind = FileKind.SOLDERMASK
[docs]
def render(self) -> str:
return f"Soldermask,{self.side}"
[docs]
@dataclass(frozen=True)
class Legend:
"""`Legend,<side>`."""
side: Side
kind = FileKind.LEGEND
[docs]
def render(self) -> str:
return f"Legend,{self.side}"
[docs]
@dataclass(frozen=True)
class Paste:
"""`Paste,<side>`."""
side: Side
kind = FileKind.PASTE
[docs]
def render(self) -> str:
return f"Paste,{self.side}"
[docs]
@dataclass(frozen=True)
class Profile:
"""`Profile,(P|NP)`. JITX has no edge plating, so NP in practice."""
plated: bool = False
kind = FileKind.PROFILE
[docs]
def render(self) -> str:
return f"Profile,{'P' if self.plated else 'NP'}"
[docs]
@dataclass(frozen=True)
class Drill:
"""`(Plated|NonPlated),<from>,<to>,<hole type>[,<content>]`.
Args:
first: 1-based conductor index the span starts at.
last: 1-based conductor index the span ends at.
hole: PTH/NPTH for a span crossing the whole board, Blind or Buried
otherwise.
plated: selects the `Plated` or `NonPlated` keyword. Plating is a
file attribute by design, which is why plated and non-plated
hits cannot share a file.
content: Drill, Rout or Mixed; omitted when the file is plain hits.
format: which format the file is written in. Not part of the
rendered attribute - it decides the file's extension and its
gbrjob `FileFormat`, so naming and the job writer branch on it
rather than on an extension they would otherwise have to guess.
"""
first: int
last: int
hole: HoleType
plated: bool = True
content: DrillContent | None = None
format: DrillFormat = DrillFormat.GERBER
kind = FileKind.DRILL
[docs]
def render(self) -> str:
head = "Plated" if self.plated else "NonPlated"
tail = f",{self.content}" if self.content is not None else ""
return f"{head},{self.first},{self.last},{self.hole}{tail}"
[docs]
@dataclass(frozen=True)
class Component:
"""`Component,L<index>,<side>`, the X3 assembly layer for one side."""
index: int
side: Side
kind = FileKind.COMPONENT
[docs]
def render(self) -> str:
return f"Component,L{self.index},{self.side}"
[docs]
@dataclass(frozen=True)
class Job:
"""The `.gbrjob` file.
It is not a Gerber file and carries no `TF.FileFunction`, but it is part
of the written set, so naming and the overwrite guard need a handle for
it.
"""
kind = FileKind.JOB
[docs]
def render(self) -> str:
raise TypeError("the job file has no TF.FileFunction")
FileFunction: TypeAlias = (
"Copper | Soldermask | Legend | Paste | Profile | Drill | Component | Job"
)
# --------------------------------------------------------------------------
# apertures
# The two tables §6.5 calls for are value semantics rather than registries.
# A Macro is keyed by its rendered body, so one macro serves every rotation
# of a shape (the rotation is an AD argument, not macro content) while a
# mirrored shape - whose vertex list differs - is a different macro on its
# own. An Aperture is keyed by template identity, every AD modifier
# including the rotation argument, and its attributes, so one function means
# one aperture. Both quantize on construction, so 45.0 and 45.00000001
# cannot become two D-codes.
[docs]
@dataclass(frozen=True)
class Macro:
"""An `AM` template, named from its content.
Args:
body: primitive and variable lines without their trailing `*`,
already rendered with `$1` wherever the rotation belongs.
"""
body: tuple[str, ...]
@property
def name(self) -> str:
"""The generated `JITX<hash>` template name."""
digest = sha256("\n".join(self.body).encode("ascii")).hexdigest()
return f"JITX{digest[:12].upper()}"
[docs]
@dataclass(frozen=True)
class Aperture:
"""An `AD` instantiation of a standard template or a macro.
Args:
template: a standard template letter (`C`, `R`, `O`, `P`) or the
macro to instantiate.
params: the `AD` modifiers in order, joined with `X` on emission.
For a macro this includes the rotation argument.
attrs: aperture attributes, applied to this aperture alone.
"""
template: str | Macro
params: tuple[float, ...] = ()
attrs: AttrSet = ()
def __post_init__(self) -> None:
object.__setattr__(self, "params", tuple(quantize(p) for p in self.params))
@property
def template_name(self) -> str:
return self.template if isinstance(self.template, str) else self.template.name
@property
def macro(self) -> Macro | None:
return self.template if isinstance(self.template, Macro) else None
# --------------------------------------------------------------------------
# graphic objects
[docs]
@dataclass(frozen=True)
class Flash:
"""A `D03`: one aperture stamped at a point.
Every pad is a flash and every flash is a pad (spec 4.10), so nothing
else may use this.
"""
x: float
y: float
aperture: Aperture
attrs: AttrSet = ()
[docs]
@dataclass(frozen=True)
class Draw:
"""A `D01` in linear mode: a straight stroke with round caps."""
x1: float
y1: float
x2: float
y2: float
aperture: Aperture
attrs: AttrSet = ()
[docs]
@dataclass(frozen=True)
class ArcObj:
"""A `D01` in circular mode, stroked from (x1, y1) to (x2, y2).
The center is absolute; the emitter derives the signed `I`/`J` offsets.
`ccw` selects `G03` over `G02`. A sweep over 180 degrees is split by the
emitter, and a coincident start and end is a full circle, which the
emitter also splits rather than emitting as the spec's zero-length form.
"""
x1: float
y1: float
x2: float
y2: float
cx: float
cy: float
ccw: bool
aperture: Aperture
attrs: AttrSet = ()
[docs]
@dataclass(frozen=True)
class Seg:
"""A straight contour segment ending at (x, y)."""
x: float
y: float
[docs]
@dataclass(frozen=True)
class CurveSeg:
"""An arc contour segment ending at (x, y) around an absolute center."""
x: float
y: float
cx: float
cy: float
ccw: bool
[docs]
@dataclass(frozen=True)
class Contour:
"""One closed contour of a region.
Args:
start: the `D02` point the contour opens on.
segments: must return to `start`; the emitter closes nothing
implicitly, it only checks that the closure holds on the output
grid.
"""
start: tuple[float, float]
segments: tuple[Seg | CurveSeg, ...]
[docs]
@dataclass(frozen=True)
class Region:
"""A `G36`/`G37` statement: the union of its contours' filled areas.
All contours share one polarity, since polarity is a property of a
graphic object. Holes are separate clear regions, not contours here.
Args:
aper_attrs: aperture attributes. A region has no aperture, so it
takes these from the attribute dictionary as it stands at `G36`
(5.3.1); this is how a pour carries `Conductor` and a net tie
carries `EtchedComponent`.
"""
contours: tuple[Contour, ...]
polarity: Polarity = Polarity.DARK
attrs: AttrSet = ()
aper_attrs: AttrSet = ()
[docs]
@dataclass(frozen=True)
class Surface:
"""An island with the holes that belong to it, kept together.
The grouping is the unit any ordering moves, so an island can never be
separated from a hole that would erase it. The emitter expands it into a
dark region followed by one clear region per hole; `island` is also the
outer ring a containment ordering sorts on.
"""
island: Contour
holes: tuple[Contour, ...] = ()
attrs: AttrSet = ()
aper_attrs: AttrSet = ()
GraphicObject: TypeAlias = "Flash | Draw | ArcObj | Region | Surface"
# --------------------------------------------------------------------------
# files
[docs]
@dataclass(frozen=True)
class GenerationSoftware:
"""`TF.GenerationSoftware` and the gbrjob `Header` object of the same
name, which spells the same three fields as JSON."""
vendor: str
application: str
version: str
[docs]
@dataclass(frozen=True)
class ProjectId:
"""`TF.ProjectId`: a name, an RFC 4122 GUID and a revision.
`revision` is `rev?` when the design carries none.
"""
name: str
guid: str
revision: str = "rev?"
[docs]
@dataclass
class GerberFile:
"""One Gerber image: its file function, polarity and object list.
There is no aperture table here on purpose. Every object carries the
aperture it uses, apertures are values rather than registry entries, and
§7 assigns D-codes by sorted key once the set is complete - so the table
is derived at emission and cannot drift out of step with the objects.
"""
function: FileFunction
polarity: FilePolarity = FilePolarity.POSITIVE
objects: list[GraphicObject] = field(default_factory=list)
[docs]
def add(self, obj: GraphicObject) -> None:
"""Append an object to the image."""
self.objects.append(obj)
[docs]
@dataclass(frozen=True)
class Hit:
"""A drill hit of the selected tool."""
x: float
y: float
tool: Tool
attrs: AttrSet = ()
[docs]
@dataclass(frozen=True)
class Slot:
"""A rout path: tool down at `start`, one segment per step, tool up.
Arc segments span at most 180 degrees; XNC carries a radius rather than
a center, so the emitter derives it and the direction comes from `ccw`.
"""
start: tuple[float, float]
segments: tuple[Seg | CurveSeg, ...]
tool: Tool
attrs: AttrSet = ()
[docs]
@dataclass
class DrillFile:
"""One XNC file: one plating, one span.
Hits and slots are emitted in the order added, grouped into the drill
and rout sections the XNC grammar requires.
"""
function: Drill
hits: list[Hit] = field(default_factory=list)
slots: list[Slot] = field(default_factory=list)
@property
def tools(self) -> list[Tool]:
"""Every distinct tool used, in sorted emission order."""
seen = dict.fromkeys([h.tool for h in self.hits] + [s.tool for s in self.slots])
return sorted(seen, key=lambda t: (t.diameter, render_attrs(t.attrs)))
[docs]
def render_attrs(attrs: AttrSet) -> str:
"""A stable text rendering of an attribute set, for sorting and keying."""
return "|".join(
name + "".join("," + escape_field(v) for v in values) for name, values in attrs
)