"""Soldermask, legend and paste files.
The queried shapes are the content directly: the transformer layer already
synthesizes mask openings from untented vias and pad soldermask definitions,
so there is no board-minus-openings subtraction anywhere.
A feature's side is relative to its placement - `Bottom` means the opposite
side from where the owning landpattern sits - so the side comes off the
composed transform like every other side question here.
Soldermask files image the openings and are therefore `TF.FilePolarity,
Negative` with their objects drawn dark. Legend and paste are positive.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from logging import getLogger
from jitx.feature import Courtyard, Paste, Silkscreen, Soldermask, SurfaceFeature
from jitx.run.runtime import RuntimeDesign
from jitx.shapes import Shape
from jitx.transform import Transform
from ..format.apertures import circle_aperture
from ..format.model import (
AttrSet,
FileFunction,
FilePolarity,
GerberFile,
Legend,
Paste as PasteFunction,
Side,
Soldermask as MaskFunction,
Surface,
attr,
)
from . import geometry
from .components import ComponentIndex
logger = getLogger(__name__)
MATERIAL = attr(".AperFunction", "Material")
"""5.6.10's function for openings on the extra layers. The reference export
omits it, so it is not a guide here; the spec is."""
LEGEND_TEXT = attr(".AperFunction", "NonMaterial")
"""5.6.10: drawing elements rather than physical material.
Stroked legend text is a drawing element on a layer that is otherwise
material, which is exactly the case the value exists for.
"""
_KINDS: list[tuple[type[SurfaceFeature], str]] = [
(Soldermask, "mask"),
(Silkscreen, "legend"),
(Paste, "paste"),
]
[docs]
@dataclass
class Features:
"""The mask, legend and paste files a design actually needs.
Files are created only where content exists, which is the same
content-driven policy the ODB++ exporter uses: a design with no paste
features gets no paste file rather than an empty one.
"""
files: dict[tuple[str, Side], GerberFile] = field(default_factory=dict)
[docs]
def ordered(self) -> list[GerberFile]:
order = {"mask": 0, "legend": 1, "paste": 2}
return [
self.files[key]
for key in sorted(
self.files, key=lambda k: (order[k[0]], k[1] is not Side.TOP)
)
]
[docs]
def build(design: RuntimeDesign, components: ComponentIndex) -> Features:
"""Walk the surface features into per-side files.
Args:
components: the component index, for the `TO.C` a mask opening,
paste deposit or legend mark carries when it belongs to a
component. CAM uses it, and it costs nothing once the index that
the component layers need already exists.
"""
out = Features()
skipped: dict[str, int] = {}
for kind, label in _KINDS:
for trace, feature in design.query(kind):
side = geometry.surface_side(trace.transform, feature.side)
file = _file(out, label, side)
owner = components.component_attribute(str(trace.path))
attrs: AttrSet = () if owner is None else (owner,)
if geometry.is_filled(feature.shape):
for island in geometry.to_islands(feature.shape, trace.transform):
file.add(
Surface(
island.outer,
island.holes,
attrs,
aper_attrs=(MATERIAL,),
)
)
elif geometry.is_stroked(feature.shape):
aperture = circle_aperture(
geometry.stroke_width(feature.shape, trace.transform),
attrs=(MATERIAL,),
)
for stroke in geometry.to_strokes(
feature.shape, aperture, trace.transform, attrs
):
file.add(stroke)
elif label == "legend" and geometry.is_text(feature.shape):
_text(
file,
feature.shape,
trace.transform,
attrs,
components.labels_for(str(trace.path)),
)
else:
key = f"{label}_{side}"
skipped[key] = skipped.get(key, 0) + 1
_report_unsupported(design, components)
for key, count in sorted(skipped.items()):
logger.warning(
"Skipped %d features Gerber has no native form for on %s", count, key
)
return out
def _text(
file: GerberFile,
shape: Shape,
transform: Transform | None,
attrs: AttrSet,
labels: dict[str, str],
) -> None:
"""One text feature, stroked into draws on the legend.
Text on mask or paste is not stroked. A string in a mask file would be an
opening shaped like a word, which is a thing a design can mean but is not
what a `Text` on those layers has ever meant here, so it stays counted
and skipped rather than silently becoming copper-bare board.
Args:
labels: the `>REF` and `>VALUE` substitutions of the component that
owns this feature, empty when none does.
"""
string = _resolve(shape, labels)
if string is None:
return
width = geometry.text_stroke_width(shape, transform)
if width <= 0:
logger.warning("Legend text with a non-positive stroke width was skipped")
return
aperture = circle_aperture(width, attrs=(LEGEND_TEXT,))
for stroke in geometry.to_text_strokes(shape, aperture, transform, attrs, string):
file.add(stroke)
def _resolve(shape: Shape, labels: dict[str, str]) -> str | None:
"""The string to write for a text shape, with a label placeholder
resolved against its owning component.
Returns None for a placeholder nothing resolves, which drops the text.
Silkscreening the literal `>REF` would be worse than dropping it: it
reaches the board as ink that says nothing, and a missing designator is
at least visibly missing.
"""
string = geometry.text_string(shape)
if string is None or not string.startswith(">"):
return string
resolved = labels.get(string)
if resolved is None:
logger.warning("Dropping unresolved legend label %s", string)
return resolved
def _file(out: Features, label: str, side: Side) -> GerberFile:
found = out.files.get((label, side))
if found is None:
function, polarity = _function(label, side)
found = GerberFile(function, polarity)
out.files[(label, side)] = found
return found
def _function(label: str, side: Side) -> tuple[FileFunction, FilePolarity]:
match label:
case "mask":
return MaskFunction(side), FilePolarity.NEGATIVE
case "legend":
return Legend(side), FilePolarity.POSITIVE
case _:
return PasteFunction(side), FilePolarity.POSITIVE
def _report_unsupported(design: RuntimeDesign, components: ComponentIndex) -> None:
"""Count the surface features that get no file at all.
`Glue`, `Finish`, `Courtyard` outside a component and `Custom` have no
output here. `Custom` is a deferral rather than a rejection - it carries
assorted things that do need to reach fabrication - and `Glue` has a file
function (`Glue,(Top|Bot)`) that would be cheap if a design ever had one.
Until then a dropped feature should be visible in the run log rather than
silent.
A courtyard belonging to a component is not dropped - it is the primary
source for that component's `ComponentOutline` - so it is not counted
here. Reporting it would say a feature was discarded that in fact reached
the output through another file.
"""
counts: dict[str, int] = {}
for trace, feature in design.query(SurfaceFeature):
name = type(feature).__name__
if isinstance(feature, (Soldermask, Silkscreen, Paste)):
continue
if isinstance(feature, Courtyard) and components.owner(str(trace.path)):
continue
counts[name] = counts.get(name, 0) + 1
for name, count in sorted(counts.items()):
logger.info(
"Skipped %d %s features; they have no Gerber file here", count, name
)