Examples Showcase / fab_virtual_layers_to_mechanical
Bake FabView virtual layers onto Altium mechanical layers
Bake all 9 top FabView virtual layers (CUTOUTS, PIN1_TOP, DIODES_TOP, CAPACITORS_TOP, INDUCTORS_TOP, RESISTORS_TOP, ASSEMBLY_OUTLINES_TOP, ASSEMBLY_DESIGNATORS_TOP, PAD_LABELS_TOP) onto Mechanical 11–19 on virtual_fab_layers.PcbDoc via bake_virtual_layers_to_pcbdoc(), verify save/reload persistence, and render an unclipped colour-coded SVG preview.
Output Previews
Compute all 9 top board-derived FabView virtual layers (CUTOUTS, PIN1_TOP, DIODES_TOP, CAPACITORS_TOP, INDUCTORS_TOP, RESISTORS_TOP, ASSEMBLY_OUTLINES_TOP, ASSEMBLY_DESIGNATORS_TOP, PAD_LABELS_TOP) on the virtual_fab_layers.PcbDoc showcase board and bake them directly onto cleared Altium mechanical layers (Mechanical 11–19) using bake_virtual_layers_to_pcbdoc(...).
What It Shows
- Loading
virtual_fab_layers.PcbDocfrom shared showcase assets (never mutating tracked asset files), featuring 7 cutouts (including crossing+slots), diodes/LEDs, polarized and non-polarized capacitors and inductors, a resistor, BGA/QFP ICs, and edge connectors - Configuring
VirtualLayerOptionswithCutoutLayerOptions,Pin1LayerOptions,DiodeLayerOptions,CapacitorLayerOptions,InductorLayerOptions,ResistorLayerOptions,AssemblyOutlineLayerOptions,AssemblyDesignatorLayerOptions, andPadLabelLayerOptions - Baking all 9 virtual layers onto
MECHANICAL11–MECHANICAL19in a single call tobake_virtual_layers_to_pcbdoc(...)with component ownership, Cutouts union grouping, and idempotent re-bake cleanup - Saving the modified
.PcbDoc, reloading it from disk to verify persistence, and rendering a colour-coded SVG preview directly from the baked mechanical layers
Mechanical Layer Assignment
| Virtual Layer | Target Mechanical Layer | Display Name |
|---|---|---|
CUTOUTS | MECHANICAL11 | Virtual Cutouts |
PIN1_TOP | MECHANICAL12 | Virtual Pin 1 Top |
DIODES_TOP | MECHANICAL13 | Virtual Diodes Top |
CAPACITORS_TOP | MECHANICAL14 | Virtual Capacitors Top |
INDUCTORS_TOP | MECHANICAL15 | Virtual Inductors Top |
RESISTORS_TOP | MECHANICAL16 | Virtual Resistors Top |
ASSEMBLY_OUTLINES_TOP | MECHANICAL17 | Virtual Assembly Outlines Top |
ASSEMBLY_DESIGNATORS_TOP | MECHANICAL18 | Virtual Assembly Designators Top |
PAD_LABELS_TOP | MECHANICAL19 | Virtual Pad Labels Top |
Run
From the repository root:
uv run python examples\fab_virtual_layers_to_mechanical\fab_virtual_layers_to_mechanical.pyOutput
The script writes:
examples/fab_virtual_layers_to_mechanical/output/virtual_fab_layers_baked_mechanicals.PcbDoc
examples/fab_virtual_layers_to_mechanical/output/virtual_mechanical_layers_preview.svg
examples/fab_virtual_layers_to_mechanical/output/virtual_mechanical_layers_preview_dark.svg
examples/fab_virtual_layers_to_mechanical/output/virtual_layers_to_mechanical_manifest.jsonSource Code
from __future__ import annotations
import json
import shutil
from pathlib import Path
from altium_monkey import AltiumPcbDoc
from altium_monkey.fab import (
AssemblyDesignatorLayerOptions,
AssemblyOutlineLayerOptions,
BakeVirtualLayersOptions,
CapacitorLayerOptions,
ComponentVisibilityPolicy,
CutoutLayerOptions,
DiodeLayerOptions,
InductorLayerOptions,
MechanicalLayerTarget,
PadLabelLayerOptions,
Pin1LayerOptions,
ResistorLayerOptions,
VirtualLayerOptions,
bake_virtual_layers_to_pcbdoc,
)
from altium_monkey.fab.svg import SvgWriterOptions, svg_frame, write_svg_board
SAMPLE_DIR = Path(__file__).resolve().parent
EXAMPLES_DIR = SAMPLE_DIR.parent
PCBDOC_FILE = (
EXAMPLES_DIR
/ "assets"
/ "projects"
/ "virtual_fab_layers"
/ "virtual_fab_layers.PcbDoc"
)
OUTPUT_DIR = SAMPLE_DIR / "output"
SAVED_PCBDOC_PATH = OUTPUT_DIR / "virtual_fab_layers_baked_mechanicals.PcbDoc"
PREVIEW_SVG_PATH = OUTPUT_DIR / "virtual_mechanical_layers_preview.svg"
PREVIEW_DARK_SVG_PATH = OUTPUT_DIR / "virtual_mechanical_layers_preview_dark.svg"
MANIFEST_PATH = OUTPUT_DIR / "virtual_layers_to_mechanical_manifest.json"
# Map all 9 top virtual FabView layers to dedicated Altium mechanical layers (11..19).
VIRTUAL_TO_MECHANICAL: dict[str, MechanicalLayerTarget] = {
"CUTOUTS": MechanicalLayerTarget("MECHANICAL11", name="Virtual Cutouts"),
"PIN1_TOP": MechanicalLayerTarget("MECHANICAL12", name="Virtual Pin 1 Top"),
"DIODES_TOP": MechanicalLayerTarget("MECHANICAL13", name="Virtual Diodes Top"),
"CAPACITORS_TOP": MechanicalLayerTarget("MECHANICAL14", name="Virtual Capacitors Top"),
"INDUCTORS_TOP": MechanicalLayerTarget("MECHANICAL15", name="Virtual Inductors Top"),
"RESISTORS_TOP": MechanicalLayerTarget("MECHANICAL16", name="Virtual Resistors Top"),
"ASSEMBLY_OUTLINES_TOP": MechanicalLayerTarget(
"MECHANICAL17", name="Virtual Assembly Outlines Top"
),
"ASSEMBLY_DESIGNATORS_TOP": MechanicalLayerTarget(
"MECHANICAL18", name="Virtual Assembly Designators Top"
),
"PAD_LABELS_TOP": MechanicalLayerTarget("MECHANICAL19", name="Virtual Pad Labels Top"),
}
def _all_geometry_frame_nm(
view: object,
layer_keys: tuple[str, ...],
*,
margin_nm: float = 2_500_000.0,
) -> tuple[float, float, float, float]:
"""Return a padded nanometre frame enclosing the board profile and overhanging layers."""
x0, y0, x1, y1 = svg_frame(view, layer_keys) # type: ignore[arg-type]
for key in layer_keys:
if key in ("PROFILE", "DRILLS"):
continue
items = view.layer(key) # type: ignore[attr-defined]
for stroke in items.strokes or ():
half = float(stroke.shape.width) / 2.0
for pt in stroke.shape.path.points:
x0 = min(x0, float(pt.x) - half)
y0 = min(y0, float(pt.y) - half)
x1 = max(x1, float(pt.x) + half)
y1 = max(y1, float(pt.y) + half)
for area in items.areas or ():
outer = getattr(area.shape, "outer", None)
if outer is not None:
for pt in getattr(outer, "points", ()):
x0 = min(x0, float(pt.x))
y0 = min(y0, float(pt.y))
x1 = max(x1, float(pt.x))
y1 = max(y1, float(pt.y))
return (x0 - margin_nm, y0 - margin_nm, x1 + margin_nm, y1 + margin_nm)
def _examples_relative(path: Path) -> str:
return path.relative_to(EXAMPLES_DIR).as_posix()
def _sample_relative(path: Path) -> str:
return path.relative_to(SAMPLE_DIR).as_posix()
def build_virtual_layers_to_mechanical(
output_dir: Path = OUTPUT_DIR,
) -> dict[str, object]:
if output_dir.exists():
shutil.rmtree(output_dir)
output_dir.mkdir(parents=True, exist_ok=True)
# 1. Load the virtual_fab_layers showcase board (read-only; never mutated on disk).
pcbdoc = AltiumPcbDoc.from_file(PCBDOC_FILE)
# 2. Configure VirtualLayerOptions matching the virtual-layers guide.
virtual_options = VirtualLayerOptions(
font_mode="stroke",
stroke_font="sans_serif",
visibility=ComponentVisibilityPolicy(exclude_kinds=("graphical", "net_tie")),
cutouts=CutoutLayerOptions(
scope="interior",
hatch=True,
hatch_angle_deg=45.0,
hatch_pitch_mm=1.0,
label="CUTOUT",
),
pin1=Pin1LayerOptions(
pad_parameter="PIN1_PAD",
exclude_designator_prefixes=("R", "C", "L"),
diode_ak_labels=True,
cap_polarity_labels=True,
inductor_polarity_markers=True,
),
diodes=DiodeLayerOptions(default_cathode_pad="2", color_mode="shaded"),
capacitors=CapacitorLayerOptions(visibility_mode="all"),
inductors=InductorLayerOptions(visibility_mode="all"),
resistors=ResistorLayerOptions(visibility_mode="all", style="zigzag"),
assembly_outlines=AssemblyOutlineLayerOptions(detail="simple"),
assembly_designators=AssemblyDesignatorLayerOptions(
min_font_size_mm=0.08,
max_font_size_mm=2.40,
fill_ratio=0.78,
),
pad_labels=PadLabelLayerOptions(font_mode="stroke", knockout=False),
)
# 3. Bake all 9 virtual layers onto Mechanical 11..19 with component ownership
# and Cutouts union tracking via the built-in bake_virtual_layers_to_pcbdoc() API.
bake_report = bake_virtual_layers_to_pcbdoc(
pcbdoc,
options=BakeVirtualLayersOptions(
layer_map=VIRTUAL_TO_MECHANICAL,
virtual_options=virtual_options,
clear_existing=True,
set_layer_names=True,
set_layer_pairs=True,
),
)
# 4. Save the modified .PcbDoc, reload it from disk to verify persistence,
# and render a colour-coded SVG preview directly from the baked mechanical layers.
saved_pcbdoc_path = output_dir / SAVED_PCBDOC_PATH.name
pcbdoc.save(saved_pcbdoc_path)
reloaded = AltiumPcbDoc.from_file(saved_pcbdoc_path)
reloaded_fab = reloaded.fab()
reloaded_view = reloaded_fab.view()
baked_layers: list[dict[str, object]] = []
for layer_rep in bake_report.layers:
reloaded_items = reloaded_view.layer(layer_rep.mechanical_layer)
reloaded_count = (
len(reloaded_items.strokes or ())
+ len(reloaded_items.areas or ())
+ len(reloaded_items.lands or ())
)
if reloaded_count == 0:
raise RuntimeError(
f"Expected populated mechanical layer {layer_rep.mechanical_layer} after save/reload"
)
baked_layers.append(
{
"virtual_key": layer_rep.virtual_key,
"mechanical_layer": layer_rep.mechanical_layer,
"display_name": VIRTUAL_TO_MECHANICAL[layer_rep.virtual_key].name,
"cleared_existing_primitives": layer_rep.cleared,
"tracks": layer_rep.tracks,
"arcs": layer_rep.arcs,
"regions": layer_rep.regions,
"texts": layer_rep.texts,
"unions_created": layer_rep.unions_created,
"reloaded_item_count": reloaded_count,
}
)
paper_layers: tuple[tuple[str, str], ...] = (
("PROFILE", "#ECEEE9"),
("TOP", "#D6D8D4"),
("DRILLS", "#ADD8E6"),
("MECHANICAL11", "rgba(136, 0, 0, 0.45)"), # Virtual Cutouts
("MECHANICAL17", "rgba(0, 158, 255, 0.78)"), # Virtual Assembly Outlines Top
("MECHANICAL18", "rgba(0, 148, 255, 0.65)"), # Virtual Assembly Designators Top
("MECHANICAL12", "rgba(255, 0, 0, 0.78)"), # Virtual Pin 1 Top
("MECHANICAL13", "#DC2626"), # Virtual Diodes Top
("MECHANICAL14", "#0F766E"), # Virtual Capacitors Top
("MECHANICAL15", "#5B21B6"), # Virtual Inductors Top
("MECHANICAL16", "#047857"), # Virtual Resistors Top
("MECHANICAL19", "#C2410C"), # Virtual Pad Labels Top (always on top)
)
dark_layers: tuple[tuple[str, str], ...] = (
("PROFILE", "#1B2330"),
("TOP", "#3B4A5E"),
("DRILLS", "#7DD3FC"),
("MECHANICAL11", "rgba(248, 113, 113, 0.72)"), # Virtual Cutouts
("MECHANICAL17", "rgba(56, 189, 248, 0.80)"), # Virtual Assembly Outlines Top
("MECHANICAL18", "rgba(147, 197, 253, 0.72)"), # Virtual Assembly Designators Top
("MECHANICAL12", "#F43F5E"), # Virtual Pin 1 Top
("MECHANICAL13", "#FB923C"), # Virtual Diodes Top
("MECHANICAL14", "#2DD4BF"), # Virtual Capacitors Top
("MECHANICAL15", "#C084FC"), # Virtual Inductors Top
("MECHANICAL16", "#34D399"), # Virtual Resistors Top
("MECHANICAL19", "#FBBF24"), # Virtual Pad Labels Top (always on top)
)
frame_nm = _all_geometry_frame_nm(
reloaded_view,
tuple(key for key, _ in paper_layers),
margin_nm=2_500_000.0,
)
writer_opts = SvgWriterOptions(frame_nm=frame_nm, scale=8.0, annotate=True)
paper_svg = write_svg_board(reloaded_view, paper_layers, writer_opts, holes=None)
dark_svg = write_svg_board(reloaded_view, dark_layers, writer_opts, holes=None)
preview_svg_path = output_dir / PREVIEW_SVG_PATH.name
preview_svg_path.write_text(paper_svg.text, encoding="utf-8", newline="\n")
preview_dark_svg_path = output_dir / PREVIEW_DARK_SVG_PATH.name
preview_dark_svg_path.write_text(dark_svg.text, encoding="utf-8", newline="\n")
manifest: dict[str, object] = {
"source_pcbdoc": _examples_relative(PCBDOC_FILE),
"saved_pcbdoc": _sample_relative(saved_pcbdoc_path),
"preview_svg": _sample_relative(preview_svg_path),
"preview_dark_svg": _sample_relative(preview_dark_svg_path),
"baked_layers": baked_layers,
}
manifest_path = output_dir / MANIFEST_PATH.name
manifest_path.write_text(
json.dumps(manifest, indent=2) + "\n",
encoding="utf-8",
newline="\n",
)
return manifest
def main() -> None:
manifest = build_virtual_layers_to_mechanical()
baked = manifest["baked_layers"]
assert isinstance(baked, list)
print(f"Source PcbDoc: {manifest['source_pcbdoc']}")
for row in baked:
assert isinstance(row, dict)
print(
f" {row['virtual_key']:26s} -> {row['mechanical_layer']:12s} "
f"(tracks={row['tracks']}, arcs={row['arcs']}, "
f"regions={row['regions']}, reloaded={row['reloaded_item_count']})"
)
print(f"Saved PcbDoc: {manifest['saved_pcbdoc']}")
print(f"Preview SVG: {manifest['preview_svg']}")
if __name__ == "__main__":
main()