From 3b423af5b5e951072d6a867e55a50e78739ca282 Mon Sep 17 00:00:00 2001 From: cpu Date: Mon, 8 Jun 2026 08:50:54 +0200 Subject: [PATCH] clean up --- scripts/Readme.md | 160 +++-------- scripts/export_for_cnc.sh | 37 +++ scripts/{export.sh => export_for_msla.sh} | 6 +- scripts/gerber_to_pm4n.py | 327 +++++++++++++--------- scripts/millproject | 12 +- 5 files changed, 278 insertions(+), 264 deletions(-) create mode 100755 scripts/export_for_cnc.sh rename scripts/{export.sh => export_for_msla.sh} (94%) diff --git a/scripts/Readme.md b/scripts/Readme.md index 3fbca1b..ee80ed5 100644 --- a/scripts/Readme.md +++ b/scripts/Readme.md @@ -1,30 +1,26 @@ +TODO: Add table of content +# KiKit Fixture Processor +Processing script for KiKit panelizes PCBs and draws a fixture sketch and positions the whole panel for easy CNC and MSLA processing. + +The script: + +- Panelizes the board +- Moves the finished panel to the origin `(0, 0)` +- Adds alignment holes +- Adds silskcreen text +- Extends the copper layers + +The resulting output is intended for repeatable CNC/MSLA processing. + ![Panel](../images/Flow_Controller_Panel.png) -# Install kikit +## Install kikit Install `kikit`: ```bash pipx install --system-site-packages kikit ``` -# KiKit Fixture Processor -Processing script for KiKit panelizes PCBs and draws a fixture sketch and positions the whole panel for easy CNC processing. - -The script: - -- Draws fixture reference geometry -- Centres the finished panel inside a predefined fixture frame -- Adds mechanical alignment pin holes -- Moves the finished panel to the origin `(0, 0)` - -The resulting output is intended for repeatable CNC manufacturing workflows -where drilling, routing, and UV exposure all share the same physical fixture -and alignment holes. - -Check the kikit panelization [examples](https://yaqwsx.github.io/KiKit/latest/panelization/examples/). - ---- - -# Usage +## Usage ```bash # Panelize the PCB using the preset defined in `myPreset.json`. @@ -46,7 +42,13 @@ The new `panel/Flow_Controller_Panel.kicad_pcb` file will contain the panelized } ``` See all values in [default.json](https://raw.githubusercontent.com/yaqwsx/KiKit/refs/heads/master/kikit/resources/panelizePresets/default.json) -## Exporting gcode files from KiCad + +Check the kikit panelization [examples](https://yaqwsx.github.io/KiKit/latest/panelization/examples/). + +# Exporting gcode for CNC + +## pcb2gcode +Use CNC for drilling holes and milling board outlines. You can also use CNC for isolation traces milling. However, the best result will give you MSLA PCB exposure. TODO: Add link to the section Adapt milling and drilling parameters in `millproject`. Look up [pcb2gcode/wiki](https://github.com/pcb2gcode/pcb2gcode/wiki) for help. ```bash @@ -54,22 +56,15 @@ nano millproject ``` *Make sure to set `mirror-axis` in the `millproject` to half of your board width!!!* -Run the export by providing the `.kicad_pcb` file as a first argument: - ```bash -# Input layers/filenames and all milling/drilling parameters are taken from the config file: 'millproject'. -docker run --rm -i -t \ - -u "$(id -u):$(id -g)" \ - -v "$(pwd):/data" \ - ptodorov/pcb2gcode +./export_for_cnc.sh panel/Flow_Controller_Panel.kicad_pcb ``` -The script will first generate gerber files in the `gerbers` directory and then generate gcode files in the `gcode` directory. Launch the `gSender` program. -* Load the `gcode/drill.ngc` file for drilling holes. -* Load the `gcode/outline.ngc` file for milling the board outlines. -* Load the `gcode/back.ngc` file if you want to mill the isolation traces. -* Load the `gcode/front.ngc` file if you want to mill the isolation traces. +* Load the `output/gcode/drill.ngc` file for drilling holes. +* Load the `output/gcode/outline.ngc` file for milling the board outlines. +* Load the `output/gcode/back.ngc` file if you want to mill the isolation traces. +* Load the `output/gcode/front.ngc` file if you want to mill the isolation traces. ## Milling tip: Increase the thermal spoke and trace width When routing for milling, use the widest traces possible. 1mm, 2mm and wider, the machine doesn't care, but later you won't be soldering leads to small fragile strips of copper. You can use copper pours for routing too. @@ -85,21 +80,11 @@ Convert KiCad PCB layers to `.pm4n` files for direct UV exposure on an **Anycubi --- -## Files - -| File | Purpose | -|---|---| -| `export.sh` | Main entry point — exports Gerbers from KiCad, converts to `.pm4n` | -| `gerber_to_pm4n.py` | Python converter (Gerber → RLE → pm4n binary surgery) | -| `Dummy.pm4n` | Template file for your specific printer. | - ---- - ## Setup ### 1. Create the Dummy.pm4n -Open **CHITUBOX_Basic** slicer, select printer **Anycubic Photon Mono 4**, slice any tiny STL (a 1×1×0.05 mm box), and save as `Dummy.pm4n` in the same directory as `export.sh`. +Open **CHITUBOX Basic** slicer, select printer **Anycubic Photon Mono 4**, slice any tiny STL (a 1×1×0.05 mm box), and save as `Dummy.pm4n` in the same directory as `export_for_msla.sh`. This file is reused for every job — it carries the correct LCD resolution metadata. @@ -113,64 +98,18 @@ pip install pygerber Pillow numpy Or activate the venv once and put `source .venv/bin/activate` in your shell profile. ---- - -## Usage - -``` -./export.sh [OPTIONS] -``` - -### Options - -| Option | Default | Description | -|---|---|---| -| `--layers L,L,...` | `Front,F.Mask` | KiCad layer names to process | -| `--invert L,L,...` | *(none)* | Layers to invert the image for | -| `--mirror L,L,...` | *(none)* | Layers to mirror X for | -| `--exposure N` | `60` | Exposure time in seconds | -| `--dummy FILE` | `./Dummy.pm4n` | Path to dummy template | -| `--out DIR` | `./output` | Output directory | -| `--dpmm N` | `58.824` | Render resolution (native = 17 µm/px) | -| `--pos X,Y` | centred | Board position in mm from top-left | - ---- - -## Examples - -### Typical: top copper, positive-working resist (Bungard standard) +### 3. Export multiple layers (e.g. copper + soldermask) ```bash -./export.sh \ - --layers Front \ - --invert Front \ - --mirror Front \ +./export_for_msla.sh \ + --layers Front,Back,F.Mask,B.Mask,F.SilkS,B.SilkS \ + --invert Front,Back,F.Mask,B.Mask,F.SilkS,B.SilkS \ + --mirror Front,F.Mask,F.SilkS \ --exposure 60 \ panel/Flow_Controller_Panel.kicad_pcb ``` -`--invert`: Bungard presensitized is positive-working — UV removes resist, so the background must be exposed (white) and traces must block UV (dark). The Gerber is positive (copper=white), so inversion is needed. - -`--mirror`: the board sits copper-side-down on the FEP, so the image must be flipped so the pattern reads correctly through the board. - -### Multiple layers (e.g. copper + soldermask) - -```bash -./export.sh \ - --layers Front,F.Mask \ - --invert Front,F.Mask \ - --mirror Front,F.Mask \ - --exposure 60 \ - panel/Flow_Controller_Panel.kicad_pcb -``` - -### Quick test at lower resolution (faster render) - -```bash -./export.sh --dpmm 30 --layers Front --invert Front --mirror Front panel/Flow_Controller_Panel.kicad_pcb -``` - -### Using gerber_to_pm4n.py directly +#### Using gerber_to_pm4n.py directly ```bash python3 gerber_to_pm4n.py Dummy.pm4n output/gerbers/Flow_Controller_Panel-Front.gbr \ @@ -195,29 +134,6 @@ output/ --- -## Invert and mirror logic - -| Setting | When to use | -|---|---| -| `--invert` | Positive-working resist (standard Bungard): UV removes resist → background must be white (exposed), traces black (masked) | -| no `--invert` | Negative-working resist: UV hardens resist → traces must be white | -| `--mirror` | Board placed **copper-side down** on FEP (normal for this workflow) | -| no `--mirror` | Board placed copper-side up | - -When in doubt: check the `.preview.png` before printing. Traces should appear **dark** on a white background for standard Bungard positive-working boards. - ---- - -## Exposure calibration - -Start at **60 s** and bracket in ±15 s steps. Typical range for Bungard presensitized at 405 nm is 30–120 s depending on board age and storage conditions. - -A correctly exposed board after development will show: -- Clear copper traces (resist intact, blue/green tint) -- Bare copper in etched areas (resist removed, shiny copper) - ---- - ## Troubleshooting **`kicad-cli: command not found`** — add KiCad to PATH: @@ -239,14 +155,10 @@ alias kicad-cli='flatpak run --command=kicad-cli org.kicad.KiCad' | `B.Mask` | `B_Mask` | | `F.SilkS` | `F_Silkscreen` | -**Image looks wrong in preview** — check invert/mirror flags. Open `.preview.png`: for positive-working resist, traces = dark, background = white. - -**UVtools PCB Exposure freezes on per-item invert checkbox** — known v6 bug at 46 MP. Use the global invert checkbox at the bottom of the dialog instead, or use this script pipeline entirely. - --- First print checklist -Open the `.pm4n` in Chitubox to visually verify before printing. +Open the `.pm4n` in `Chitubox Basic` slicer to visually verify before printing. Check the `.preview.png` — traces should appear black on white background (background = UV exposed = resist removed = etched away; traces = dark = resist kept = copper stays) Start with `--exposure 60` and bracket from there — Bungard presensitized at 405nm typically lands between 30–120s depending on board vintage and storage. diff --git a/scripts/export_for_cnc.sh b/scripts/export_for_cnc.sh new file mode 100755 index 0000000..473b771 --- /dev/null +++ b/scripts/export_for_cnc.sh @@ -0,0 +1,37 @@ +#!/bin/bash + +set -euo pipefail + +GERBERS_DIR="output/gerbers" +GCODE_DIR="output/gcode" + +usage() { + echo "Usage: $0 " + exit 1 +} + +PCB_FILE="$1" + +mkdir -p "$GERBERS_DIR" +mkdir -p "$GCODE_DIR" + +# Export drill, front and back layers as gerber files. +echo "Exporting gerbers..." +kicad-cli pcb export drill -o "$GERBERS_DIR" "$PCB_FILE" +kicad-cli pcb export gerbers -o "$GERBERS_DIR" -l Front "$PCB_FILE" +kicad-cli pcb export gerbers -o "$GERBERS_DIR" -l Back "$PCB_FILE" +kicad-cli pcb export gerbers -o "$GERBERS_DIR" -l Edge.Cuts "$PCB_FILE" + +# Export outlines of the penelized board i.e. use the layer 'User.Eco1'. +# echo "Exporting panelized outlines from layer 'User.Eco1'..." +# python3 export_panel_outlines_gerber.py \ +# --layers User.Eco1 \ +# --output "$GERBERS_DIR" \ +# "$PCB_FILE" + +# Input layers/filenames and all milling/drilling parameters are taken from the config file: 'millproject'. +echo "Exporting Gcode..." +docker run --rm -i -t \ + -u "$(id -u):$(id -g)" \ + -v "$(pwd):/data" \ + ptodorov/pcb2gcode diff --git a/scripts/export.sh b/scripts/export_for_msla.sh similarity index 94% rename from scripts/export.sh rename to scripts/export_for_msla.sh index 3155a18..9dd5fa3 100755 --- a/scripts/export.sh +++ b/scripts/export_for_msla.sh @@ -1,8 +1,8 @@ #!/usr/bin/env bash -# export.sh — KiCad Gerber export + pm4n generation for Anycubic Photon Mono 4 +# export_for_msla.sh — KiCad Gerber export + pm4n generation for Anycubic Photon Mono 4 # # Usage: -# ./export.sh [OPTIONS] +# ./export_for_msla.sh [OPTIONS] # # Options: # --layers LAYER,LAYER,... KiCad layer names to export (default: F.Cu) @@ -16,7 +16,7 @@ # -h, --help Show this help # # Example: -# ./export.sh --invert F.Cu,B.Mask --mirror F.Cu,F.Mask panel/Flow_Controller_Panel.kicad_pcb +# ./export_for_msla.sh --invert F.Cu,B.Mask --mirror F.Cu,F.Mask panel/Flow_Controller_Panel.kicad_pcb # # Layer name → Gerber filename mapping (KiCad default): # F.Cu → -F_Cu.gbr diff --git a/scripts/gerber_to_pm4n.py b/scripts/gerber_to_pm4n.py index de536c0..fccf134 100755 --- a/scripts/gerber_to_pm4n.py +++ b/scripts/gerber_to_pm4n.py @@ -1,6 +1,6 @@ #!/usr/bin/env python3 """ -gerber_to_pm4n.py - Anycubic Photon Mono 4 PCB exposure file generator +gerber_to_pm4n.py – Anycubic Photon Mono 4 PCB exposure file generator Usage: python3 gerber_to_pm4n.py [options] @@ -12,9 +12,8 @@ Options: --exposure SEC Layer exposure time in seconds [default: 60] --dpmm N Render resolution in dots/mm [default: 58.824, native 17µm/px] --pos X,Y Place board at X,Y mm from top-left (default: centred on LCD) - --help Show this message -Photon Mono 4 specs: 9024 x 5120 px | 153.408 x 87.040 mm | 17.001 µm/px +Photon Mono 4 specs: 9024 × 5120 px | 153.408 × 87.040 mm | 17.001 µm/px """ import argparse @@ -34,97 +33,140 @@ LCD_H_MM = 87.040 NATIVE_DPMM = LCD_W_PX / LCD_W_MM # 58.824 dpmm (1 px ≈ 17.001 µm) # --------------------------------------------------------------------------- -# Photon Workshop RLE (BW — 2 bytes per run) +# pm4n / ANYCUBIC file format constants (reverse-engineered from Dummy.pm4n) # -# Byte0 [7:4] = colour nibble (0x0 = black, 0xF = white) -# Byte0 [3:0] = high 4 bits of run length (bits 11:8) -# Byte1 = low 8 bits of run length (bits 7:0) -# Run length encodes (n-1): 0x000 = 1 pixel, 0xFFF = 4096 pixels +# File layout: +# 0x00 ANYCUBIC magic (8 bytes) +# 0x08 unknown u32 (0) +# 0x0C version u32 (0x00000206) +# 0x10 section_count u32 (5) +# 0x14 header_size u32 (0x40 = 64) +# 0x18 section table: 5 × (length:u32, offset:u32) +# entry 0: PREV preview images +# entry 1: LAYE layer definitions +# entry 2: MACH machine params +# entry 3: Mode layer image data (header + RLE blocks) +# entry 4: HEAD printer config +# +# Sections located by scanning for 4-byte tags from known offsets. +# Tags: HEAD(0x40), PREV(0xB0), LAYE(0x0126D4), MACH(0x0127F0), Mode(0x012974) +# Note: actual offsets vary per dummy file — we scan for tags. +# +# LAYE section layout (at its offset): +# +0x00 'LAYE' tag +# +0x04 'REDF' sub-tag +# +0x08 u32=0 +# +0x0C u32 payload_size +# +0x10 u32 (AA level or mode) +# +0x14 u32 composite_image_offset (absolute file offset of block 0) +# +0x18 u32 image_block_size (size of EACH block, all identical) +# +0x1C layer entries begin (N entries × 32 bytes): +# +0x00 f32 bottom_exposure +# +0x04 f32 normal_exposure ← patched with --exposure value +# +0x08 f32 lift_mm +# +0x0C f32 layer_height +# +0x10 u32 unknown +# +0x14 u32 unknown +# +0x18 u32 image_data_offset (absolute file offset for this layer) +# +0x1C u32 image_data_size (patched when RLE size changes) +# +# Mode section layout: +# +0x00 'Model\0\0\0' tag (8 bytes) +# +0x04 u32 sub-header size (108) +# +0x08..+0x2B bounding box / Z params as floats +# +0x2C 'SUBIMGS\0\0\0\0\0' sub-tag (12 bytes) +# +0x38 u32 SUBIMGS table size +# +0x3C u32 layer_count (N) +# +0x40 u32 bytes_per_pixel (1) +# +0x44 u32 first_image_offset (= composite_image_offset, same as LAYE+0x14) +# +0x48 u32 first_image_size (= image_block_size, same as LAYE+0x18) +# +0x4C u32 unknown +# then N RLE image blocks follow (at offsets stored in LAYE entries) +# --------------------------------------------------------------------------- + +LAYE_TAG = b'LAYE' +MODE_TAG = b'Mode' +ENTRY_STRIDE = 0x20 # 32 bytes per layer entry in LAYE +LAYE_HDR_SIZE = 0x1C # bytes before first entry + + +def find_tag(data: bytes, tag: bytes, start: int = 0) -> int: + """Return file offset of first occurrence of tag (exact 4-byte match at 4-byte boundary).""" + i = start + while i + 4 <= len(data): + if data[i:i+4] == tag: + return i + i += 4 + # Fall back to unaligned search + pos = data.find(tag, start) + if pos < 0: + raise ValueError(f"Tag {tag!r} not found in file") + return pos + + +def count_laye_entries(data: bytes, laye_off: int) -> int: + """Count layer entries by scanning until we hit the 'EXTR' sub-section or end of section.""" + entry_start = laye_off + LAYE_HDR_SIZE + n = 0 + while True: + pos = entry_start + n * ENTRY_STRIDE + if pos + 4 > len(data): + break + word = data[pos:pos+4] + # Stop if we hit a known sub-tag marker + if word in (b'EXTR', b'MACH', b'Mode', b'HEAD', b'PREV'): + break + # Stop if the f32 at this position is not a plausible exposure time + v = struct.unpack_from(' bytes: + return struct.pack(' bytes: + return struct.pack(' int: + return struct.unpack_from(' bytes: - """Encode flat 0x00/0xFF bytes → Photon Workshop BW RLE.""" out = bytearray() - i = 0 - n = len(pixels) + i, n = 0, len(pixels) while i < n: - colour = pixels[i] - nibble = 0xF if colour >= 0x80 else 0x0 + colour = pixels[i] + nibble = 0xF if colour >= 0x80 else 0x0 j = i + 1 while j < n and pixels[j] == colour and (j - i) < MAX_RUN: j += 1 - run = j - i - encoded = run - 1 - out.append((nibble << 4) | ((encoded >> 8) & 0x0F)) - out.append(encoded & 0xFF) + run = j - i + enc = run - 1 + out.append((nibble << 4) | ((enc >> 8) & 0x0F)) + out.append(enc & 0xFF) i = j return bytes(out) -def decode_rle(data: bytes, expected_pixels: int) -> bytes: - """Decode PW RLE → raw pixel bytes (used for verification).""" - out = bytearray() - i = 0 - while i + 1 < len(data): - b0, b1 = data[i], data[i + 1] - nibble = (b0 >> 4) & 0x0F - colour = 0xFF if nibble == 0xF else 0x00 - run = (((b0 & 0x0F) << 8) | b1) + 1 - out.extend([colour] * run) - i += 2 - return bytes(out[:expected_pixels]) - - # --------------------------------------------------------------------------- -# pm4n binary surgery -# -# Photon Workshop file = sequence of tagged sections: -# tag:4 length:4 payload:length -# -# Sections we care about: -# HEAD – contains exposure time as a float somewhere in a packed struct -# LAYE – layer definition table: count:u32 then N × entry(28 bytes) -# entry[0:4] = absolute file offset of RLE blob -# entry[4:8] = RLE blob length in bytes -# After the sections: raw RLE layer image blobs (referenced by LAYE offsets) -# --------------------------------------------------------------------------- -SECTION_HDR = 8 # 4-byte tag + 4-byte length - -def read_sections(data: bytes) -> list: - sections = [] - i = 0 - while i + SECTION_HDR <= len(data): - tag = data[i:i+4] - length = struct.unpack_from(' tuple: - for t, off, ln in read_sections(data): - if t == tag: - return off, ln - raise ValueError(f"Section {tag!r} not found in file") - -def patch_u32(data: bytearray, offset: int, value: int): - struct.pack_into(' Image.Image: - """ - Render a Gerber file to a binary PIL image sized to the Photon Mono 4 LCD. - copper = white on black background before any transforms. - """ try: from pygerber.gerberx3.api.v2 import ( GerberFile, ColorScheme, PixelFormatEnum, ImageFormatEnum @@ -132,93 +174,117 @@ def render_gerber(gbr_path: Path, dpmm: float, except ImportError: sys.exit( "ERROR: pygerber not found.\n" - "Activate the venv first: source .venv/bin/activate\n" - "Or install: pip install pygerber Pillow numpy" + "Activate the venv: source .venv/bin/activate\n" + "Or install: pip install pygerber Pillow" ) buf = io.BytesIO() - (GerberFile - .from_file(str(gbr_path)) - .parse() - .render_raster( - buf, - dpmm=int(round(dpmm)), - color_scheme=ColorScheme.DEFAULT_GRAYSCALE, - pixel_format=PixelFormatEnum.RGB, - image_format=ImageFormatEnum.PNG, - ) + GerberFile.from_file(str(gbr_path)).parse().render_raster( + buf, + dpmm=int(round(dpmm)), + color_scheme=ColorScheme.DEFAULT_GRAYSCALE, + pixel_format=PixelFormatEnum.RGB, + image_format=ImageFormatEnum.PNG, ) buf.seek(0) layer_img = Image.open(buf).convert('L') - # Place onto full LCD canvas - cw, ch = layer_img.size + cw, ch = layer_img.size canvas = Image.new('L', (LCD_W_PX, LCD_H_PX), 0) if pos_mm is not None: - px = int(round(pos_mm[0] * dpmm)) - py = int(round(pos_mm[1] * dpmm)) + px = max(0, int(round(pos_mm[0] * dpmm))) + py = max(0, int(round(pos_mm[1] * dpmm))) else: px = (LCD_W_PX - cw) // 2 py = (LCD_H_PX - ch) // 2 - canvas.paste(layer_img, (max(0, px), max(0, py))) + canvas.paste(layer_img, (px, py)) if mirror: canvas = ImageOps.mirror(canvas) if invert: canvas = ImageOps.invert(canvas) - # Hard-binarise: no antialiasing artefacts in the RLE stream + # Hard-binarise to strict 0/255 canvas = canvas.point(lambda v: 255 if v >= 128 else 0) - return canvas # --------------------------------------------------------------------------- -# pm4n surgery +# pm4n surgery — rewrite with exact format knowledge # --------------------------------------------------------------------------- def patch_pm4n(dummy_path: Path, image: Image.Image, exposure_sec: float, output_path: Path): - """Replace layer RLE + exposure time in a dummy .pm4n, write output.""" + raw = bytearray(dummy_path.read_bytes()) - # Encode new layer image - pixels = image.convert('L').tobytes() - new_rle = encode_rle(pixels) + # --- encode new RLE --- + new_rle = encode_rle(image.convert('L').tobytes()) + new_rle_size = len(new_rle) - # Patch exposure time: scan HEAD for any float in 0.5–600 s range - hdr_off, hdr_len = find_section(raw, b'HEAD') - for off in range(hdr_off, hdr_off + hdr_len - 3): - val = struct.unpack_from('