Files
kicad-action-scripts/ViaStitching/FillAreaAction.py
T
Zdeněk bb6815b9b2 ViaStitching 1.3: checks against poured copper, snap grid, skip markers
- clearances checked with exact shapes (round via) against pads, tracks,
  vias, copper drawings, other zones' poured copper and keepouts;
  Rectangular no longer uses square box tests
- Outline follows the poured copper edge, vias on the grid
- same-net pads: only thermal relief gap and hole-to-hole spacing
- optional zone refill before placing vias
- snap grid option (disables Grid Origin choice)
- via group mode: per net, per net and pattern, new group per run
- optional markers of skipped vias on User.Drawings with reason letter
- option to keep vias out of footprint references
- warning when "Only under selected Zone" has no zone of the net selected
- dialog: options in two columns, narrower window
2026-11-16 18:42:58 +01:00

220 lines
8.8 KiB
Python

#
# FillAreaAction.py
#
# Copyright 2017 JS Reynaud <js.reynaud@gmail.com>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
from __future__ import print_function
import pcbnew
import wx
from . import FillArea
from . import FillAreaDialog
import os
import json
def PopulateNets(anet, dlg):
"""Fill the net list with nets that have a zone (GND first).
Preselects GND; if the board has no GND zone, falls back to anet
(last used net), then to the first net in the list.
"""
netnames = sorted(set(zone.GetNetname() for zone in pcbnew.GetBoard().Zones()) - {""})
if "GND" in netnames:
netnames.remove("GND")
netnames.insert(0, "GND")
dlg.m_cbNet.Set(netnames)
for name in ("GND", anet):
if name:
index = dlg.m_cbNet.FindString(name)
if index != wx.NOT_FOUND:
dlg.m_cbNet.SetSelection(index)
return
if netnames:
dlg.m_cbNet.SetSelection(0)
#
def SettingsFile():
"""Path to the JSON file with the last used dialog values."""
try:
base = pcbnew.SETTINGS_MANAGER.GetUserSettingsPath()
except Exception:
base = os.path.dirname(os.path.realpath(__file__))
return os.path.join(base, "ViaStitching.json")
def LoadSettings():
try:
with open(SettingsFile(), "r") as f:
data = json.load(f)
return data if isinstance(data, dict) else {}
except Exception:
return {}
def SaveSettings(dlg):
data = {
"size": dlg.m_SizeMM.GetValue(),
"drill": dlg.m_DrillMM.GetValue(),
"clearance": dlg.m_ClearanceMM.GetValue(),
"step": dlg.m_StepMM.GetValue(),
"net": dlg.m_cbNet.GetStringSelection(),
"fill_type": dlg.m_cbFillType.GetStringSelection(),
"grid_type": dlg.m_cbGridType.GetStringSelection(),
"snap": dlg.m_SnapMM.GetValue(),
"group_mode": dlg.m_cbGroupMode.GetStringSelection(),
"random": dlg.m_Random.IsChecked(),
"only_selected": dlg.m_only_selected.IsChecked(),
"via_through_areas": dlg.m_viaThroughAreas.IsChecked(),
"same_net_tracks": dlg.m_sameNetTracks.IsChecked(),
"refill_zones": dlg.m_refillZones.IsChecked(),
"mark_skipped": dlg.m_markSkipped.IsChecked(),
"skip_reference": dlg.m_skipReference.IsChecked(),
}
try:
with open(SettingsFile(), "w") as f:
json.dump(data, f, indent=2)
except Exception as e:
wx.LogMessage("ViaStitching: cannot save settings: {}".format(e))
def ApplySettings(dlg, data):
for key, ctrl in (("size", dlg.m_SizeMM), ("drill", dlg.m_DrillMM),
("clearance", dlg.m_ClearanceMM), ("step", dlg.m_StepMM),
("snap", dlg.m_SnapMM)):
if isinstance(data.get(key), str) and data[key].strip():
ctrl.SetValue(data[key])
for key, ctrl in (("random", dlg.m_Random), ("only_selected", dlg.m_only_selected),
("via_through_areas", dlg.m_viaThroughAreas),
("same_net_tracks", dlg.m_sameNetTracks),
("refill_zones", dlg.m_refillZones),
("mark_skipped", dlg.m_markSkipped),
("skip_reference", dlg.m_skipReference)):
if isinstance(data.get(key), bool):
ctrl.SetValue(data[key])
for key, ctrl in (("fill_type", dlg.m_cbFillType), ("grid_type", dlg.m_cbGridType),
("group_mode", dlg.m_cbGroupMode)):
if isinstance(data.get(key), str):
index = ctrl.FindString(data[key])
if index != wx.NOT_FOUND:
ctrl.SetSelection(index)
def ParseSnap(text):
"""Snap grid in mm from the dialog; empty / invalid / <= 0 means off."""
try:
value = float(text.replace(',', '.'))
except ValueError:
return 0.0
return value if value > 0 else 0.0
class FillAreaDialogEx(FillAreaDialog.FillAreaDialog):
def onSnapChanged(self, event):
self.UpdateGridTypeState()
def UpdateGridTypeState(self):
# Snap grid always starts at the board grid origin => the origin choice does not apply
self.m_cbGridType.Enable(ParseSnap(self.m_SnapMM.GetValue()) == 0)
def onDeleteClick(self, event):
return self.EndModal(wx.ID_DELETE)
class FillAreaAction(pcbnew.ActionPlugin):
def defaults(self):
self.name = "Via Stitching Generator 1.3"
self.category = "Modify PCB"
self.description = "Via Stitching for PCB Zone"
self.icon_file_name = os.path.join(os.path.dirname(__file__), "./stitching-vias.png")
self.show_toolbar_button = True
def Run(self):
a = FillAreaDialogEx(None)
# a.m_SizeMM.SetValue("0.8")
a.m_StepMM.SetValue("2.5")
# a.m_DrillMM.SetValue("0.3")
# a.m_Netname.SetValue("GND")
# a.m_ClearanceMM.SetValue("0.2")
a.m_bitmapStitching.SetBitmap(wx.Bitmap(os.path.join(os.path.dirname(os.path.realpath(__file__)), "stitching-vias-help.png")))
self.board = pcbnew.GetBoard()
self.boardDesignSettings = self.board.GetDesignSettings()
a.m_SizeMM.SetValue(str(pcbnew.ToMM(self.boardDesignSettings.GetCurrentViaSize())))
a.m_DrillMM.SetValue(str(pcbnew.ToMM(self.boardDesignSettings.GetCurrentViaDrill())))
a.m_ClearanceMM.SetValue(str(pcbnew.ToMM(self.boardDesignSettings.GetSmallestClearanceValue())))
# Grow the default size only if the content needs more (fonts / DPI differ between systems)
best = a.GetBestSize()
a.SetSize(wx.Size(max(a.GetSize().x, best.x), max(a.GetSize().y, best.y)))
a.SetMinSize(best)
settings = LoadSettings()
ApplySettings(a, settings)
last_net = settings.get("net")
PopulateNets(last_net if isinstance(last_net, str) else None, a)
a.UpdateGridTypeState()
modal_result = a.ShowModal()
if modal_result == wx.ID_OK:
SaveSettings(a)
if 1: # try:
fill = FillArea.FillArea()
fill.SetStepMM(float(a.m_StepMM.GetValue().replace(',', '.')))
fill.SetSizeMM(float(a.m_SizeMM.GetValue().replace(',', '.')))
fill.SetDrillMM(float(a.m_DrillMM.GetValue().replace(',', '.')))
fill.SetClearanceMM(float(a.m_ClearanceMM.GetValue().replace(',', '.')))
# fill.SetNetname(a.m_Netname.GetValue())
netname = a.m_cbNet.GetStringSelection()
fill.SetNetname(netname)
if a.m_Debug.IsChecked():
fill.SetDebug()
fill.SetRandom(a.m_Random.IsChecked())
fill.SetViaThroughAreas(a.m_viaThroughAreas.IsChecked())
fill.SetGridType(a.m_cbGridType.GetStringSelection())
fill.SetSnapMM(ParseSnap(a.m_SnapMM.GetValue()))
fill.SetFillType(a.m_cbFillType.GetStringSelection())
fill.SetGroupMode(a.m_cbGroupMode.GetStringSelection())
fill.SetSameNetTracks(a.m_sameNetTracks.IsChecked())
fill.SetRefillZones(a.m_refillZones.IsChecked())
fill.SetMarkSkipped(a.m_markSkipped.IsChecked())
fill.SetSkipReference(a.m_skipReference.IsChecked())
if a.m_only_selected.IsChecked():
fill.OnlyOnSelectedArea()
if not fill.CheckSelectedZone():
a.Destroy()
return # warning shown, nothing logged => no extra log window
wx.LogMessage('Via Stitching')
fill.Run()
else: # except Exception:
wx.MessageDialog(None, "Invalid parameter")
elif modal_result == wx.ID_DELETE:
if 1: # try:
fill = FillArea.FillArea()
fill.SetNetname(a.m_cbNet.GetStringSelection()) # a.m_Netname.GetValue())
if a.m_Debug.IsChecked():
fill.SetDebug()
fill.DeleteVias()
fill.Run()
else: # except Exception:
wx.MessageDialog(None, "Invalid parameter for delete")
else:
print("Cancel")
a.Destroy()
FillAreaAction().register()