kicad monkey v2026.11.30
On This Page (5)

Examples Showcase / pcb_3d_model_embedding

KiCad 10 Embedded 3D STEP Extraction & Re-Packing

Inspect board-scope kicad-embed:// 3D models, decode Zstandard + Base64 STEP bytes, verify MMH3-128 checksums, and re-pack into a fresh portable KiCad 10 PCB with byte-exact round-trip verification.

pcbfootprint3d3dstepkicad-embedzstdextraction

Demonstrate the complete KiCad 10 native embedded 3D STEP (kicad-embed://) workflow on hlr_test.kicad_pcb: inspect KiCadPcb.embedded_files, decode Zstandard + Base64 STEP payloads with decode_embedded_file(), verify MMH3-128 checksums and ISO-10303-21 headers, and re-pack extracted .STEP bytes into a fresh self-contained .kicad_pcb using EmbeddedFile.from_kicad_bytes().

What It Shows

  1. Inspecting board-scope embedded 3D models via KiCadPcb.embedded_files
  2. Decoding KiCad 10 Zstandard + Base64 payloads with decode_embedded_file()
  3. Verifying ISO-10303-21 STEP headers and KiCad 10 MMH3-128 checksums
  4. Re-packing raw STEP bytes into a portable board with EmbeddedFile.from_kicad_bytes() and proving byte-exact round-trip after KiCadPcb.save() / KiCadPcb.from_file()

Input

text
examples/assets/projects/hlr_sot23/hlr_test.kicad_pcb

Run

From the repository root:

sh
uv run python examples/pcb_3d_model_embedding/pcb_3d_model_embedding.py

Output

text
examples/pcb_3d_model_embedding/output/extracted_models/SOT23-5.STEP
examples/pcb_3d_model_embedding/output/repacked_portable.kicad_pcb
examples/pcb_3d_model_embedding/output/embedded_3d_report.json

Source Code

examples/pcb_3d_model_embedding/pcb_3d_model_embedding.py
"""KiCad 10 native embedded 3D STEP round-trip: inspect, decode, extract, and re-pack."""

from __future__ import annotations

import json
from pathlib import Path

from kicad_monkey import KiCadPcb, decode_embedded_file
from kicad_monkey.kicad_embedded_resources import EmbeddedFile

HERE = Path(__file__).resolve().parent
INPUT_PCB = HERE.parent / "assets" / "projects" / "hlr_sot23" / "hlr_test.kicad_pcb"
OUT_DIR = HERE / "output"
STEP_DIR = OUT_DIR / "extracted_models"


def main() -> None:
    OUT_DIR.mkdir(parents=True, exist_ok=True)
    STEP_DIR.mkdir(parents=True, exist_ok=True)

    # 1. Load board with KiCad 10 embedded 3D STEP payload(s)
    pcb = KiCadPcb.from_file(INPUT_PCB)
    extracted_records: list[dict[str, object]] = []

    # 2. Inspect, decode (Base64 + Zstandard), and extract every board-level embedded file
    for ef in pcb.embedded_files:
        raw_bytes = decode_embedded_file(ef)
        assert raw_bytes is not None, f"Failed to decode embedded file {ef.name}"
        out_step = STEP_DIR / ef.name
        out_step.write_bytes(raw_bytes)

        # Re-encode via KiCad 10 native packer (zstd L15 + MMH3-128 checksum) to verify checksum parity
        repacked_check = EmbeddedFile.from_kicad_bytes(ef.name, ef.file_type, raw_bytes)
        extracted_records.append(
            {
                "name": ef.name,
                "file_type": ef.file_type,
                "encoded_chars": len(ef.data),
                "decoded_bytes": len(raw_bytes),
                "stored_checksum_mmh3": ef.checksum,
                "repacked_checksum_mmh3": repacked_check.checksum,
                "checksum_matches": ef.checksum.upper() == repacked_check.checksum.upper(),
                "starts_with_iso_step": raw_bytes.lstrip().startswith(b"ISO-10303-21;"),
            }
        )

    # 3. Re-pack the extracted STEP bytes into a fresh portable KiCad 10 board
    repacked_pcb = KiCadPcb.new(paper="A4")
    for rec in extracted_records:
        step_name = str(rec["name"])
        step_bytes = (STEP_DIR / step_name).read_bytes()
        repacked_pcb.embedded_files.append(
            EmbeddedFile.from_kicad_bytes(step_name, "model", step_bytes)
        )

    repacked_path = OUT_DIR / "repacked_portable.kicad_pcb"
    repacked_pcb.save(repacked_path)

    # 4. Reload the saved board and verify byte-exact round-trip decoding
    verified = KiCadPcb.from_file(repacked_path)
    repacked_entries: list[dict[str, object]] = []
    for ef in verified.embedded_files:
        roundtrip_bytes = decode_embedded_file(ef)
        orig_bytes = (STEP_DIR / ef.name).read_bytes()
        assert roundtrip_bytes == orig_bytes, f"Round-trip mismatch for {ef.name}"
        repacked_entries.append(
            {
                "name": ef.name,
                "encoded_chars": len(ef.data),
                "checksum_mmh3": ef.checksum,
                "byte_exact_roundtrip": True,
            }
        )

    report = {
        "source_board": INPUT_PCB.name,
        "extracted": extracted_records,
        "repacked_board": repacked_path.name,
        "repacked_verified": repacked_entries,
    }
    (OUT_DIR / "embedded_3d_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")

    for rec in extracted_records:
        print(
            f"Decoded {rec['name']}: {rec['decoded_bytes']:,} STEP bytes "
            f"(zstd+b64={rec['encoded_chars']:,} chars, ISO-10303-21={rec['starts_with_iso_step']}, "
            f"mmh3_match={rec['checksum_matches']})"
        )
    print(f"Re-packed and verified byte-exact round-trip in {repacked_path.name}")


if __name__ == "__main__":
    main()
kicad-monkey v2026.11.30·Docs updated 2026.12.01 15:43 UTC (fd9b75b)