altium monkey v2026.11.26 · gobblerito
On This Page (20)

PCB Layers & Layer Stacks

Altium Designer evolved across several file generations, so a single .PcbDoc can simultaneously carry legacy 1-byte layer numbers, 32-bit V7 saved layer IDs, runtime TV7_Layer mechanical-kind IDs, legacy LAYERnNEXT chains, V8 Layer Stack Manager rows, V9 Board6 stack/cache rows, and an embedded .stackupx XML payload.

This guide maps every layer and stack representation in altium-monkey, shows which API to use for reading vs. authoring, and documents the exact boundaries and gotchas.

Which API Should I Use?

TaskRecommended APIImport module
Read layers, names, substacks, regions, faces, mounts, drill pairs, or Z envelopes from a board or librarypcbdoc.layers(), pcblib.layers(), footprint.layers() (PcbLayerContext)altium_monkey.altium_pcb_layer_context
Pass a layer to a PCB primitive helper (add_track, add_region, …)PcbLayer (legacy) or PcbLayerRef (V7-aware)altium_monkey
Inspect source-aware stack topology, rigid-flex branches, bend lines, or impedance profilesAltiumLayerStackDocument.from_pcbdoc(pcbdoc)altium_monkey
Author a new rigid or rigid-flex board stackAltiumLayerStackDocument.from_rigid_layer_rows(...) (rigid) or multi-substack AltiumLayerStackDocument with board_regions (rigid-flex), plus builder.set_layer_stack_document(...)altium_monkey
Read or write .stackup / .stackupx interchange filesAltiumStackupDocument, AltiumStackupXDocumentaltium_monkey
Audit raw Board6 stack declaration keys without inflating embedded XMLpcbdoc.board_stack_declaration_evidence()altium_monkey.altium_layer_stack_document
Select layers for Gerber, IPC-2581, or PCB SVG outputFabView string layer keys ("TOP", "MID31", "MECHANICAL33", "PROFILE", "DRILLS")board.fab().view().layers()

Deprecated: ResolvedLayerStack (altium_monkey.altium_resolved_layer_stack, resolved_layer_stack_from_pcbdoc, AltiumLayerStackDocument.to_resolved_layer_stack) is deprecated and emits DeprecationWarning. Use pcbdoc.layers() (PcbLayerContext) instead.


1. Altium's Four Layer-Identity Schemes

Understanding which ID scheme a number belongs to prevents the most common PCB layer bugs.

A. Legacy PcbLayer (TV6_Layer, 1..75)

PcbLayer represents Altium's classic 1-byte layer enumeration:

RangePcbLayer values
1TOP
2..31MID1..MID30
32BOTTOM
33..38TOP_OVERLAY, BOTTOM_OVERLAY, TOP_PASTE, BOTTOM_PASTE, TOP_SOLDER, BOTTOM_SOLDER
39..54INTERNAL_PLANE_1..INTERNAL_PLANE_16
55..56DRILL_GUIDE, KEEPOUT
57..72MECHANICAL_1..MECHANICAL_16
73..75DRILL_DRAWING, MULTI_LAYER, CONNECT

Do not extrapolate PcbLayer linearly:

B. Serialized V7 Saved Layer IDs (32-bit)

Board6 stack/cache rows, configuration tables, and V7 primitive side fields (v7_layer_id, layer_v7_save_id, barcode_layer_v7) store 32-bit saved IDs (0x01000000 flag plus family and index):

FamilyFormula / Hex RangeExamples
Signal (Top, Mid1..Mid126)0x01000000 + ordinal0x01000001 = Top, 0x0100001F = Mid30, 0x01000020 = Mid31
Bottom sentinel0x0100FFFF (16842751)Bottom copper
Internal Plane (1..16)0x01010000 + n0x01010001 = Plane 1, 0x01010010 = Plane 16
Mechanical (1..65535)0x01020000 + n0x01020011 = Mech 17, 0x01020021 = Mech 33
Misc / System (TLayerPartition 6..26)0x01030000 + partition0x01030006 = Top Overlay, 0x0103000F = Multi-Layer, 0x01030000 = surface-finish stack row
Stack Dielectric (1..n)0x01040000 + nPhysical dielectric stack rows only (never primitive layers)

Reserved mechanical numbers in Altium include 32767 (route guide) and 64530 + 2*k / 64530 + 2*k + 1 (top and bottom coverlay outlines for substack index k).

Legacy placeholder clamping: When Altium writes a primitive on an extended V7 layer, the legacy 1-byte layer field is clamped to a placeholder (Mid31+ → 31, Plane17+ → 54, Mech17+ → 72, coverlay outlines → 0), while the exact layer is stored in the V7 side field. On read, nonzero v7_layer_id / layer_v7_save_id, positive barcode_layer_v7, or textual V7_LAYER takes precedence over the legacy byte.

Collision warning: Stripping the 0x01000000 prefix from Mid31 (0x01000020) yields 0x20 (32), which collides with PcbLayer.BOTTOM. Never pass raw 32-bit V7 saved IDs as layer=; construct a PcbLayerRef instead (PcbLayerRef.from_v7_saved_layer_id(0x01000020)).

C. Runtime TV7_Layer IDs in LayerKindMapping/Data

LayerKindMapping/Data (mechanical layer semantic kinds such as 3D Body, Assembly, Courtyard) uses Altium's runtime TV7_Layer encoding rather than serialized V7 saved IDs:

text
Mechanical 1..16  -> 57..72                          (classic V6 byte)
Mechanical 17..32 -> 0x04000000 | mechanical_number  (runtime TV7_Layer family 4)

For example, Mechanical 17 is 0x04000011 in LayerKindMapping/Data but 0x01020011 as a serialized V7 saved layer ID. Python's mechanical-kind codec currently supports Mechanical 1..32.

D. FabView Layer Keys

board.fab().view() and Fab SVG (to_svg, to_layer_svgs) address layers by canonical uppercase string keys:


2. How Altium Stores Layer Stacks (And How altium-monkey Unifies Them)

A single .PcbDoc may contain up to four overlapping stack encodings inside Board6/Data plus BoardRegions/Data, and Altium also exchanges standalone stacks as .stackup or .stackupx files:

  1. Legacy LAYERnNEXT chain (Board6/Data): A singly linked list of conductive layers from Top (1) to Bottom (32) including Internal Planes (39..54), with predecessor-owned dielectric fields (LAYERnDIELTYPE, LAYERnDIELCONST, LAYERnDIELHEIGHT, LAYERnDIELMATERIAL). A cut chain keeps only the layers reached before the break; if a legacy-only chain is cyclic or yields no layers, AltiumBoard.from_record() falls back to the default board stackup (and AltiumLayerStackDocument uses board.layer_stackup only when the chain walk is empty).
  2. V8 Layer Stack Manager rows (Board6/Data and .stackup): LAYERMASTERSTACK_V8*, LAYERSUBSTACK_V8_{N}*, LAYER_V8_{N}* (with saved V7 LAYERID, TYPEID GUIDs, $LSM$* properties, and per-substack _{GUID}CONTEXT), plus VIASPAN_V8_*, DRILLPAIR_V8_*, DRILLSPAN_V8_*, IMPEDANCEPROFILE_V8_*, TRACEIMPEDANCE_V8_*, and BRANCH_V8_*.
  3. V9 Board6 stack/cache rows (Board6/Data): V9_MASTERSTACK_*, V9_SUBSTACK{N}_*, V9_STACK_LAYER{N}_* (per-substack _{GUID}CONTEXT: 0 = enabled, nonzero = disabled), and flat layer-registry rows V9_CACHE_LAYER{N}_* (display names, MECHENABLED, MECHKIND, extended mechanical/signal entries).
  4. Embedded V9_STACKCUSTOMDATA (Board6/Data): Base64 + zlib compressed StackupX XML embedded inside V9 boards. When present, Board6 provides the base stack and V9_STACKCUSTOMDATA merges richer metadata over it (custom properties, adhesive kind over native prepreg, surface-finish rows, impedance profiles with CustomName, feature flags, rigid-flex branches, and per-substack enablement).

Native Board6 Family Precedence

When reading a .PcbDoc, altium-monkey selects the native Board6 stack family by the first present non-blank master key — with no per-field fall-through between families:

text
V9_MASTERSTACK_ID  ──►  LAYERMASTERSTACK_V8ID  ──►  LAYER1NAME
     (V9)                      (V8)                   (Legacy)

V8 master electrical attributes (such as roughness model parameters, which have no V9 key) are read across all families.

Unified Model Pipeline

text
Board6/Data + BoardRegions/Data (+ V9_STACKCUSTOMDATA)
  or .stackup  (AltiumStackupDocument)
  or .stackupx (AltiumStackupXDocument)
      │
      ▼
AltiumLayerStackDocument   (source-aware stack model, authoring, .stackup/.stackupx I/O)
      │
      └─► PcbLayerContext  (pcbdoc.layers() / pcblib.layers() / footprint.layers():
                            canonical read API for layers, substacks, regions,
                            faces, mounts, drill pairs, via spans, and nm Z envelopes)

3. Canonical Read API: PcbLayerContext

Call pcbdoc.layers() (or pcblib.layers() / footprint.layers()) for all normal layer and stack queries. The context is cached per document and invalidates automatically when high-level authoring helpers mutate the document (call pcbdoc.mark_modified() if you mutate raw record lists directly).

python
from altium_monkey import AltiumPcbDoc, PcbLayerRef
from altium_monkey.altium_pcb_layer_context import PcbLayerFace

board = AltiumPcbDoc.from_file("board.PcbDoc")
ctx = board.layers()

# Resolve any layer ref or token to a context layer entry
lookup = ctx.resolve(PcbLayerRef.top())
if lookup.found is not None:
    layer = ctx.layer(lookup.found)
    print(layer.ref.token, layer.name, layer.kind, layer.order)

# Physical Z envelope for the primary substack (integer nanometres, z=0 at top, downward negative)
if ctx.primary is not None:
    env = ctx.envelope(ctx.primary)
    for entry in env.rows:
        print(f"{entry.row.name}: z=[{entry.z_top_nm}, {entry.z_bottom_nm}] nm (thick={entry.row.thickness_nm} nm)")

# Rigid-flex spatial lookup (board coordinates in mils)
region_id = ctx.region_at(1500.0, 800.0)
if region_id is not None:
    substack_id = ctx.substack_of_region(region_id).found
    if substack_id is not None:
        top_surfaces = ctx.surface_layers(substack_id, PcbLayerFace.TOP)
        print("Top copper:", top_surfaces.copper, "overlay:", top_surfaces.overlay)

# Component mounting
for comp in board.components[:5]:
    mount = ctx.component_mount(comp)
    if mount.found is not None:
        print(comp.designator, mount.found.face, mount.found.substack)

Key capabilities on PcbLayerContext:

Via-span nuance: Altium's Vias6 stream stores only legacy 1-byte start and end layers (not V7 saved IDs). When a via's start or end byte is a legacy placeholder (such as 31 for Mid31+), ctx.via_span(...) provisionally resolves it against ctx.drill_pairs (provisional=True); if multiple drill pairs clamp to the same placeholder byte (for example, Mid31..Bottom and Mid35..Bottom), the lookup returns PcbLayerLookupStatus.AMBIGUOUS.


4. AltiumLayerStackDocument: Inspection & Authoring

Use AltiumLayerStackDocument when you need source-aware stack inspection, .stackup / .stackupx conversion, or new-board stack synthesis.

Inspecting Rigid-Flex & Multi-Stack Boards

GUIDs across Board6/Data, BoardRegions/Data, and .stackupx vary in case and braces. AltiumLayerStackDocument join helpers normalize both automatically:

python
from altium_monkey import AltiumLayerStackDocument, AltiumPcbDoc

board = AltiumPcbDoc.from_file("rigid_flex.PcbDoc")
stack_doc = AltiumLayerStackDocument.from_pcbdoc(board)

for region in stack_doc.board_regions:
    substack = stack_doc.substack_by_source_ref(region.layerstack_id)
    layers = stack_doc.layers_for_board_region(region)
    print(region.name, "->", substack.name if substack else None, len(layers), "layers")

Note that read-only inspection types (AltiumPhysicalStack, AltiumStackLayer, AltiumStackSubstack, AltiumStackRegion, AltiumStackBendLine, AltiumStackBranch, AltiumImpedanceProfile, AltiumTransmissionLine) live in altium_monkey.altium_layer_stack_document rather than the root package.

Authoring New Board Stacks

For new boards (PcbDocBuilder), choose the constructor that matches your control level:

Hard gates enforced by PcbDocBuilder.set_layer_stack_document(...) for semantic writes:

  1. Exactly one physical_stacks entry.
  2. Between 2 and 128 copper layers.
  3. At least one dielectric row between every adjacent pair of copper layers.
  4. Every present board_regions entry must have at least 3 outline vertices; if multiple substacks are present, board_regions must also be non-empty.
  5. For stackupx-origin documents, every non-empty stack_ref and source_record_id must be a valid GUID string.

Arbitrary in-place stack rewriting of already-loaded .PcbDoc files is not yet part of the public writer contract; use set_layer_stack_document(...) when synthesizing new boards via PcbDocBuilder.


5. .stackup And .stackupx Interchange

.stackup (Pipe-Delimited V8 LSM Text)

AltiumStackupDocument parses and writes Altium's pipe-delimited .stackup format (STACKUPVERSION, FEATURE_*, LAYER_V8_*, VIASPAN_V8_*, IMPEDANCEPROFILE_V8_*, BRANCH_V8_*).

python
from altium_monkey import AltiumStackupDocument

text_doc = AltiumStackupDocument.from_file("vendor.stackup")
stack_doc = text_doc.to_layer_stack_document()
stack_doc.to_stackup().write("out.stackup")

Export limitations: to_stackup() / AltiumStackupDocument.from_layer_stack_document(...) requires exactly one physical stack, rejects flex stacks (is_flex=True), requires copper layers, silently drops paste rows, and allows only {overlay, solder_mask, copper, dielectric, surface_finish, plating, misc, marking} row families.

.stackupx (Altium Layer Stack Manager XML)

AltiumStackupXDocument handles Altium's XML stackup format (http://altium.com/ns/LayerStackManager), including typed StackupXLayerType (27 well-known TypeId GUIDs), StackupXFeatureId (5 feature GUIDs: STANDARD_STACKUP, IMPEDANCE_CALCULATOR, RIGID_FLEX, RIGID_FLEX_ADVANCED, BACK_DRILLS), rigid-flex multi-stacks, impedance profiles, and branches.

python
from altium_monkey import AltiumStackupXDocument, PcbDocBuilder

xml_doc = AltiumStackupXDocument.from_file("rigid_stack.stackupx")
stack_doc = xml_doc.to_layer_stack_document()

# Author a new PcbDoc directly from a single-stack rigid .stackupx (including Mid31..Mid126)
builder = PcbDocBuilder()
builder.set_layer_stack_document(stack_doc)
builder.save("from_stackupx.PcbDoc")

Important .stackupx rules:


6. Board Stack Declaration Evidence

pcbdoc.board_stack_declaration_evidence() is a lightweight, read-only audit of the raw Board6/Data scalar keys for six stack-feature families (embedded_stackup, substack_context, branch, split_line, bend_line, feature). It never inflates V9_STACKCUSTOMDATA, never re-serializes the board, and never inspects BoardRegions:

python
evidence = board.board_stack_declaration_evidence()
if evidence.status == "current":
    for decl in evidence.declarations:
        print(decl.family, decl.source_key, decl.state)
else:
    print("Unresolved:", evidence.unresolved_reason)

Treat negative states ("absent" / "empty") as authoritative only when evidence.status == "current". Authored builders, modified board.raw_record maps, non-standard Board6 framing, or projected fallback boards report status == "unresolved" with a specific unresolved_reason (authored_source, unretained_source, board_text_unaccounted, projected_board, or changed_board).


7. Authoring Matrix & Hard Gates

Helper / TargetLegacy / Planes (Plane1..16)V7 Mech (17+)V7 Signal (Mid31+)
PcbDoc / PcbDocBuilder: add_track, add_arc, add_fill, add_text, add_regionSupportedMech17..53 auto-register (legacy byte 72); Mech54+ rejected¹Supported with matching enabled stack evidence² (legacy byte 31)
PcbDoc / PcbDocBuilder: add_component_body³SupportedMech17..53 supported; Mech54+ rejectedRejected
AltiumPcbFootprint: add_track, add_arc, add_fill, add_text, add_region, add_component_bodySupportedMech17..53 supported; Mech54+ rejected¹Rejected (no board stack context)
add_pad (PcbDoc & PcbLib)SupportedRejectedRejected
add_via (PcbDoc & PcbLib: layer_start, layer_end)Signal + Planes (1..32, 39..54)RejectedRejected
set_mechanical_layer / set_mechanical_layer_pairMechanical 1..16Mech17..53 supported; Mech54+ rejectedN/A
get_mechanical_layer_kind / set_mechanical_layer_kindMechanical 1..16Mech17..32 supported; Mech33+ rejectedN/A

¹ Exception: add_region on both PcbDoc / PcbDocBuilder and AltiumPcbFootprint allows coverlay-outline replay with layer=0 and MECHANICAL64530..65535. ² Stack evidence comes either from a loaded .PcbDoc's enabled stack layers or from PcbDocBuilder.set_layer_stack_document(...). ³ PcbDocBuilder.add_component_body(body) accepts a prebuilt AltiumPcbComponentBody record rather than a layer= keyword; the layer gate applies to body.layer / body.v7_layer_id.


8. Common Gotchas

  1. PcbLayerRef == PcbLayer is always False: PcbLayerRef.top() == PcbLayer.TOP evaluates to False. Use ref.matches(PcbLayer.TOP) or normalize both sides with coerce_pcb_layer_ref(...).
  2. AltiumDielectricLayerKind.CORE (0) vs. readback dielectric_type (1): The authoring enum defines CORE = 0, PREPREG = 2, COVERLAY = 4, whereas parsed AltiumStackLayer.dielectric_type and PcbDielectricType expose Altium's native TDielectricType (0 = NO_DIELECTRIC, 1 = CORE, 2 = PREPREG, 3 = SURFACE_MATERIAL, 4 = FILM). Never compare layer.dielectric_type == AltiumDielectricLayerKind.CORE.
  3. Different layer conventions on set_mechanical_layer* vs. add_*: Primitive helpers accept PcbLayerRef and treat any bare int as a legacy TV6_Layer ID (1 = Top, 13 = Mid12, 57 = Mech 1). By contrast, set_mechanical_layer, set_mechanical_layer_pair, get_mechanical_layer_kind, and set_mechanical_layer_kind do not accept PcbLayerRef objects (pass ref.token, e.g. "MECHANICAL13") and treat bare int 1..53 (1..32 for kinds) as a mechanical layer number while 57..72 remain legacy TV6 IDs (54..56 raise ValueError on set_mechanical_layer*, and 33..56 raise ValueError on get/set_mechanical_layer_kind).
  4. Transient dense IDs on PcbLayerContext: layer.id, substack.id, and region.id are per-context dense integers that reset when the context rebuilds. Persist PcbLayerRef tokens and substack source_ref GUIDs instead.
  5. Units and Z origin differ by API: PcbLayerContext.envelope() uses integer nanometres with z = 0 at the substack top surface going negative downward (while region_at(x_mils, y_mils) is in mils); AltiumLayerStackDocument uses mils (or thickness_mm= on row factories); deprecated ResolvedStackEnvelope used mils with z = 0 at the midplane.
  6. Never infer layer side or family from English names: A board can rename an inner copper layer to "Bottom Layer" or Top Solder to "F.Mask". Always inspect layer.kind, layer.ref.family, or ctx.face(layer_id, substack_id).
  7. Direct record mutations require pcbdoc.mark_modified(): Editing pcbdoc.tracks or pcbdoc.board in place does not automatically invalidate the cached pcbdoc.layers() context; call pcbdoc.mark_modified() afterward.
altium-monkey v2026.11.26 · gobblerito·Docs updated 2026.11.29 17:55 UTC (0665053)