diff --git a/README.md b/README.md index 3021b1d..6beca0e 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,23 @@ ViaStitching.json in the KiCad user settings directory (~/.config/kicad/10.0/ on Linux); delete this file to get the defaults back (via drill and clearance from the board design settings). +Options (1.3): + +- Vias are checked against the poured copper (not the zone outline) and + the exact shapes of pads, tracks, vias, other zones and keepouts. + "Refill zones" refills all zones before placing vias. +- Pads of the target net only need to keep their thermal relief gap. +- "Snap grid" (mm, 0 = off) puts every via on that grid, counted from + the board Grid Origin. +- "Via group": one group per net, per net and pattern, or a new group + for every run. +- "Mark skipped vias" draws a circle with a letter on User.Drawings + where a via could not be placed: P pad, T track, Z other zone, + K keepout, D copper drawing, F no poured copper, E board edge, + R reference. +- "Skip references" keeps vias out of visible footprint references. +- "Only under selected Zone" warns when no zone of the net is selected. + Then the result should be: ![The result](images/via2.png) diff --git a/ViaStitching/FillArea.py b/ViaStitching/FillArea.py index 937c383..a00791c 100644 --- a/ViaStitching/FillArea.py +++ b/ViaStitching/FillArea.py @@ -28,6 +28,7 @@ import tempfile import shutil import os import random +import math import pprint import wx from inspect import currentframe, getframeinfo @@ -54,6 +55,14 @@ def ViaWidth(via): return via.GetWidth() +def Unfracture(poly): + """Split outlines back into outline + holes (fractured polygons join holes by slits).""" + try: + poly.Unfracture() + except TypeError: + poly.Unfracture(SHAPE_POLY_SET.PM_FAST) # KiCad 8 and older + + def PadCollidesShape(pad, shape): """Test pad copper polygon vs. shape; KiCad 10+ needs a layer argument.""" try: @@ -137,6 +146,21 @@ class FillArea: REASON_PAD = 5 REASON_DRAWING = 6 REASON_STEP = 7 + REASON_NO_FILL = 8 + REASON_BOARD_EDGE = 9 + REASON_REFERENCE = 10 + + # Letters drawn into the "skipped via" markers + SKIP_LABELS = { + REASON_OTHER_SIGNAL: "Z", + REASON_KEEPOUT: "K", + REASON_TRACK: "T", + REASON_PAD: "P", + REASON_DRAWING: "D", + REASON_NO_FILL: "F", + REASON_BOARD_EDGE: "E", + REASON_REFERENCE: "R", + } GRID_TYPE_BOARD_BOUNDS = "Board Bounds" GRID_TYPE_ABSOLUTE = "Absolute (0, 0)" @@ -147,6 +171,9 @@ class FillArea: FILL_TYPE_CONCENTRIC = "Concentric" FILL_TYPE_OUTLINE = "Outline" FILL_TYPE_OUTLINE_NO_HOLES = "Outline (No Holes)" + GROUP_MODE_PER_NET = "Per net" + GROUP_MODE_PER_PATTERN = "Per net and pattern" + GROUP_MODE_PER_RUN = "New group per run" def __init__(self, filename=None): self.filename = None @@ -168,6 +195,16 @@ class FillArea: self.delete_vias = False self.via_through_areas = False self.same_net_tracks = False + self.refill_zones = False + self.mark_skipped = False + self.skip_reference = False + self.ref_shapes = [] + self.pad_gap_cache = {} + self.area_fill_cache = {} + self.snap = 0 + self.grid_origin = VECTOR2I(0, 0) + self.skipped = {} # (x, y) -> reason, drawn by DrawSkippedMarkers() + self.unfilled_zones = [] if self.pcb is not None: for lnet in ["GND", "/GND"]: if self.pcb.FindNet(lnet) is not None: @@ -178,6 +215,7 @@ class FillArea: self.random = False self.grid_type = self.GRID_TYPE_BOARD_BOUNDS self.fill_type = self.FILL_TYPE_RECTANGULAR + self.group_mode = self.GROUP_MODE_PER_NET if self.netname is None: self.SetNetname("GND") @@ -209,11 +247,117 @@ class FillArea: self.same_net_tracks = r return self + def SetSkipReference(self, r): + self.skip_reference = r + return self + + def SetMarkSkipped(self, r): + self.mark_skipped = r + return self + + def AddSkipped(self, p, reason): + if self.mark_skipped and reason in self.SKIP_LABELS: + self.skipped.setdefault((int(p.x), int(p.y)), reason) + + def DrawSkippedMarkers(self, group_name): + """Draw a circle with the reason letter on User.Drawings for every skipped via position.""" + if not self.mark_skipped or not self.skipped: + return 0 + # A position rejected for one zone may still have got a via from another zone (other layer) + placed = [via.GetPosition() for via in self.pcb_group.GetItems() if via.GetClass() == "PCB_VIA"] if self.pcb_group else [] + group = PCB_GROUP(None) + group.SetName(group_name + " skipped") + self.pcb.Add(group) + radius = int(self.size / 2) + count = 0 + for (x, y), reason in sorted(self.skipped.items()): + p = VECTOR2I(x, y) + if any((p - v).EuclideanNorm() < radius for v in placed): + continue + circle = PCB_SHAPE(self.pcb) + circle.SetShape(SHAPE_T_CIRCLE) + circle.SetLayer(Dwgs_User) + circle.SetWidth(FromMM(0.05)) + circle.SetCenter(p) + circle.SetEnd(VECTOR2I(x + radius, y)) + self.pcb.Add(circle) + group.AddItem(circle) + + text = PCB_TEXT(self.pcb) + text.SetLayer(Dwgs_User) + text.SetText(self.SKIP_LABELS[reason]) + h = max(int(radius * 1.2), FromMM(0.2)) + text.SetTextSize(VECTOR2I(h, h)) + text.SetTextThickness(max(h // 8, FromMM(0.02))) + text.SetHorizJustify(GR_TEXT_H_ALIGN_CENTER) + text.SetVertJustify(GR_TEXT_V_ALIGN_CENTER) + text.SetPosition(p) + self.pcb.Add(text) + group.AddItem(text) + count += 1 + wxPrint("{} skipped via positions marked on User.Drawings (group '{}'): " + "P=pad T=track Z=other zone K=keepout D=copper drawing F=no poured copper E=board edge R=reference".format(count, group.GetName())) + return count + + def SetRefillZones(self, r): + self.refill_zones = r + return self + + def GetZoneFill(self, zone): + """Filled copper of the zone, one SHAPE_POLY_SET per copper layer. + + Only the via centre has to lie on poured copper: the fill edge already keeps + the zone clearance, so the via copper may reach slightly past it; clearance to + the surrounding objects is checked separately (CheckViaPosition / pads / tracks). + Returns None when the zone is not filled (fill check is then skipped). + """ + polys = [] + for layer in zone.GetLayerSet().CuStack(): + try: + fill = zone.GetFilledPolysList(layer) + except Exception: + fill = None + if fill is None or fill.OutlineCount() == 0: + continue + polys.append(SHAPE_POLY_SET(fill)) + if polys: + return polys + self.unfilled_zones.append("{} ({})".format(zone.GetNetname(), zone.GetLayerName())) + return None + + @staticmethod + def IsOnZoneFill(zone_fill, p): + return zone_fill is None or any(poly.Contains(p) for poly in zone_fill) + + def ReportUnfilledZones(self): + if self.unfilled_zones: + wxPrint("WARNING: zone(s) not filled, vias were not checked against the poured copper: {}.\n" + "Fill all zones (B) before running the plugin.".format(", ".join(self.unfilled_zones))) + def SetGridType(self, grid_type): self.grid_type = grid_type return self + def SetSnapMM(self, s): + """Snap every via to a fine grid (grid origin of the board + n * s); 0 = off.""" + self.snap = int(FromMM(s)) if s and s > 0 else 0 + return self + + def SnapCandidates(self, p): + """The 4 snap grid points around p, nearest first (just p when snap is off).""" + if not self.snap: + return [p] + o = self.grid_origin + fx = int(math.floor((p.x - o.x) / float(self.snap))) + fy = int(math.floor((p.y - o.y) / float(self.snap))) + pts = [VECTOR2I(o.x + (fx + i) * self.snap, o.y + (fy + j) * self.snap) for i in (0, 1) for j in (0, 1)] + pts.sort(key=lambda q: (q - p).EuclideanNorm()) + return pts + def GetGridOrig(self, lboard): + if self.snap: + # Snap grid follows the editor grid, which starts at the board grid origin + return self.pcb.GetDesignSettings().GetGridOrigin() if self.grid_type == self.GRID_TYPE_ABSOLUTE: return VECTOR2I(0, 0) elif self.grid_type == self.GRID_TYPE_GRID_ORIGIN: @@ -225,6 +369,25 @@ class FillArea: self.fill_type = fill_type return self + def SetGroupMode(self, group_mode): + self.group_mode = group_mode + return self + + def GetGroupName(self): + """Name of the group the new vias go to (depends on group_mode).""" + base = "ViaStitching {}".format(self.netname) + if self.group_mode == self.GROUP_MODE_PER_NET: + return base + base = "{} {}".format(base, self.fill_type) + if self.group_mode == self.GROUP_MODE_PER_PATTERN: + return base + # New group per run: first free " #N" + names = set(g.GetName() for g in self.pcb.Groups()) + n = 1 + while "{} #{}".format(base, n) in names: + n += 1 + return "{} #{}".format(base, n) + def SetPCB(self, pcb): self.pcb = pcb if self.pcb is not None: @@ -336,69 +499,64 @@ STEP = '-' # filler = ZONE_FILLER(self.pcb) # filler.Fill(self.pcb.Zones()) + def AreaFillCached(self, area): + """Poured copper of a zone, one SHAPE_POLY_SET per copper layer (cached per run). + None when the zone is not filled.""" + key = area.m_Uuid.AsString() + if key not in self.area_fill_cache: + polys = [] + for layer in area.GetLayerSet().CuStack(): + try: + fill = area.GetFilledPolysList(layer) + except Exception: + fill = None + if fill is not None and fill.OutlineCount() > 0: + polys.append(SHAPE_POLY_SET(fill)) + self.area_fill_cache[key] = polys if (polys or area.IsFilled()) else None + return self.area_fill_cache[key] + def CheckViaInAllAreas(self, via, all_areas): """ - Checks if an existing Via collides with another area + Checks a via (round, through all layers) against keepouts and zones of other nets. + + - Rule area forbidding vias: the via must not touch its outline. + - Copper zone of another net (unless "Ignore other areas"): the via copper plus + clearance must not touch its poured copper, otherwise the via would punch a hole + into it. An unfilled zone is checked against its outline instead, where a target + net zone with higher priority on the same layer wins. + Rule areas without via restriction and zones of the target net are ignored. """ - # Enum all area + p = VECTOR2I(int(via.PosX), int(via.PosY)) + radius = int(self.size / 2) for area in all_areas: - area_layer = area.GetLayer() - area_clearance = area.GetLocalClearance() - area_priority = area.GetAssignedPriority() - is_rules_area = area.GetIsRuleArea() - is_rule_exclude_via_area = area.GetIsRuleArea() and area.GetDoNotAllowVias() - is_target_net = area.GetNetname() == self.netname # (area.GetNetname().upper() == self.netname) - # wx.LogMessage(area.GetNetname()) #wx.LogMessage(area.GetNetname().upper()) + if area.GetIsRuleArea(): + if area.GetDoNotAllowVias() and area.Outline().Collide(p, radius): + return self.REASON_KEEPOUT + continue + if area.GetNetname() == self.netname or self.via_through_areas: + continue - if not is_target_net or is_rule_exclude_via_area: # Only process areas that are not in the target net or is a rule area that could exlude vias - # print("Process...") - # Offset is half the size of the via plus the clearance of the via or the area - offset = max(self.clearance, area_clearance) + self.size / 2 - for dx in [-offset, offset]: - # All 4 corners of the via are testet (upper, lower, left, right) but not the center - for dy in [-offset, offset]: - point_to_test = VECTOR2I(int(via.PosX + dx), int(via.PosY + dy)) + clr = int(max(self.clearance, area.GetLocalClearance() or 0)) + radius + fill = self.AreaFillCached(area) + if fill is not None: + if any(poly.Collide(p, clr) for poly in fill): + return self.REASON_OTHER_SIGNAL + continue - hit_test_area = False - if KicadMajorVersion() < 7: - # below 7.0.0 - for layer_id in area.GetLayerSet().CuStack(): - hit_test_area = hit_test_area or area.HitTestFilledArea(layer_id, point_to_test) # Collides with a filled area - else: - # 7.0.0 and above - for layer_id in area.GetLayerSet().CuStack(): - for i in range(0, area.Outline().OutlineCount()): - area_outline = area.Outline().Outline(i) - if area.GetLayerSet().Contains(layer_id) and (layer_id != Edge_Cuts): - hit_test_area = hit_test_area or area_outline.PointInside(point_to_test) - hit_test_edge = area.HitTestForEdge(point_to_test, 1) # Collides with an edge/corner - try: - hit_test_zone = area.HitTestInsideZone(point_to_test) # Is inside a zone (e.g. KeepOut/Rules) - except: - hit_test_zone = False - # wxPrint('exception: missing HitTestInsideZone: To Be Fixed (not available in kicad 7.0)') - # hit_test_zone = area.HitTest(point_to_test) - - # Is inside a zone (e.g. KeepOut/Rules with via exlusion) kicad - if is_rule_exclude_via_area and (hit_test_area or hit_test_edge or hit_test_zone): - return self.REASON_KEEPOUT # Collides with keepout/rules - - elif (not self.via_through_areas) and (hit_test_area or hit_test_edge) and not is_rules_area: - # Collides with another signal (e.g. on another layer) but not a rule zone - return self.REASON_OTHER_SIGNAL - - elif (not self.via_through_areas) and hit_test_zone and not is_rules_area: - # Check if the zone is higher priority than other zones of the target net in the same point - # target_areas_on_same_layer = filter(lambda x: ((x.GetPriority() > area_priority) and (x.GetLayer() == area_layer) and (x.GetNetname().upper() == self.netname)), all_areas) - target_areas_on_same_layer = filter( - lambda x: ((x.GetPriority() > area_priority) and (x.GetLayer() == area_layer) and (x.GetNetname() == self.netname)), all_areas - ) - for area_with_higher_priority in target_areas_on_same_layer: - if area_with_higher_priority.HitTestInsideZone(point_to_test): - break # Area of target net has higher priority on this layer - else: - # Collides with another signal (e.g. on another layer) - return self.REASON_OTHER_SIGNAL + # Not filled: use the drawn outline + if not area.Outline().Collide(p, clr): + continue + area_layers = set(area.GetLayerSet().CuStack()) + covered = any( + other.GetNetname() == self.netname + and not other.GetIsRuleArea() + and other.GetAssignedPriority() > area.GetAssignedPriority() + and area_layers.issubset(set(other.GetLayerSet().CuStack())) + and other.Outline().Contains(p) + for other in all_areas + ) + if not covered: + return self.REASON_OTHER_SIGNAL return self.REASON_OK @@ -461,22 +619,261 @@ STEP = '-' Avoid placing vias to close to via present in all_vias """ - def AddViasAlongOutline(self, outline, outline_parent, all_vias, offset=0): - via_placed = 0 - step = max(self.step, self.size + self.clearance) - len = int(outline.Length()) - steps = len // step - steps = 1 if steps == 0 else steps - stepsize = int(len // steps) - for l in range(int(stepsize * offset), len, stepsize): - p = outline.PointAlong(l) + def GetBoardEdge(self): + """Board outline shrunk so that a via centre inside it keeps the edge clearance.""" + board_edge = SHAPE_POLY_SET() + try: + # KiCad 10+: aInferOutlineIfNecessary is a required argument + self.pcb.GetBoardPolygonOutlines(board_edge, True) + except TypeError: + # KiCad 9 and older + self.pcb.GetBoardPolygonOutlines(board_edge) + b_clearance = max(self.pcb.GetDesignSettings().m_CopperEdgeClearance, self.clearance) + self.size / 2 + board_edge.Deflate(int(b_clearance), CORNER_STRATEGY_ROUND_ALL_CORNERS, FromMM(0.01)) + return board_edge - if all(self.CheckViaDistance(p, via, outline_parent) for via in all_vias): + def PrepareObstacles(self, include_net_vias=False): + """Collect everything a via must keep clear of. Existing vias of the target net are + included only on request (outline/concentric check their spacing by CheckViaDistance).""" + self.obs_board_edge = self.GetBoardEdge() + self.obs_areas = [self.pcb.GetArea(i) for i in xrange(self.pcb.GetAreaCount())] + + # Each obstacle: (inflated bounding box for a quick reject, item, kind) + reach = int(self.size / 2 + self.clearance) + FromMM(1) # generous margin for the bbox prefilter + self.obstacles = [] + + def add(item, kind): + bbox = item.GetBoundingBox() + bbox.Inflate(reach + int(item.GetOwnClearance(UNDEFINED_LAYER, "") if kind != "drawing" else 0)) + self.obstacles.append((bbox, item, kind)) + + for pad in self.pcb.GetPads(): + add(pad, "pad") + for track in self.pcb.GetTracks(): + if track.GetNetname() == self.netname: + if track.GetClass() == "PCB_VIA": + if include_net_vias: + add(track, "track") + continue + if self.same_net_tracks: + continue + add(track, "track") + try: + drawings = list(self.pcb.Drawings()) + except Exception: + drawings = list(self.pcb.DrawingsList()) + for draw in drawings: + if IsCopperLayer(draw.GetLayer()): + add(draw, "drawing") + + # Visible footprint references: a via must not cut through the reference text + self.ref_shapes = [] + if self.skip_reference: + for fp in self.pcb.GetFootprints(): + ref = fp.Reference() + if ref.IsVisible() and ref.GetText(): + self.ref_shapes.append(self.TextBoxPoly(ref)) + + @staticmethod + def TextBoxPoly(text): + """Text box of a (possibly rotated) text as a polygon.""" + box = text.GetTextBox(None) + c = text.GetDrawPos() + a = text.GetDrawRotation().AsRadians() + cos_a, sin_a = math.cos(a), math.sin(a) + poly = SHAPE_POLY_SET() + poly.NewOutline() + for x, y in ((box.GetLeft(), box.GetTop()), (box.GetRight(), box.GetTop()), + (box.GetRight(), box.GetBottom()), (box.GetLeft(), box.GetBottom())): + dx, dy = x - c.x, y - c.y + poly.Append(int(c.x + dx * cos_a + dy * sin_a), int(c.y - dx * sin_a + dy * cos_a)) + return poly + + def IsSameNetPad(self, pad): + """Pads of the target net need no clearance to the via, only no overlap + and hole-to-hole spacing.""" + return pad.GetNetname() == self.netname + + def SameNetPadGap(self, pad): + """Copper gap a via must keep to a pad of the target net: the thermal relief gap + when the pad is connected to a target zone by a thermal relief, otherwise 0.""" + key = pad.m_Uuid.AsString() + if key in self.pad_gap_cache: + return self.pad_gap_cache[key] + conn = pad.GetLocalZoneConnection() + fp = pad.GetParentFootprint() + if conn == ZONE_CONNECTION_INHERITED and fp is not None: + conn = fp.GetLocalZoneConnection() + try: + pad_gap = pad.GetLocalThermalGapOverride() + except Exception: + pad_gap = None + gap = 0 + pad_layers = list(pad.GetLayerSet().CuStack()) + for zone in self.pcb.Zones(): + if zone.GetNetname() != self.netname or zone.GetIsRuleArea(): + continue + if not any(zone.IsOnLayer(layer) for layer in pad_layers): + continue + c = conn if conn != ZONE_CONNECTION_INHERITED else zone.GetPadConnection() + if c == ZONE_CONNECTION_THERMAL or (c == ZONE_CONNECTION_THT_THERMAL and pad.GetAttribute() == PAD_ATTRIB_PTH): + gap = max(gap, pad_gap if pad_gap else zone.GetThermalReliefGap()) + self.pad_gap_cache[key] = gap + return gap + + def SameNetPadBlocksVia(self, pad, p): + """Pad of the target net: no clearance needed, only keep the via out of the pad + (no via-in-pad / solder wicking) and out of its thermal relief gap, and keep + the minimum hole-to-hole distance.""" + radius = int(self.size / 2) + int(self.SameNetPadGap(pad)) + for layer in pad.GetLayerSet().CuStack(): + if pad.GetEffectiveShape(layer).Collide(p, radius): + return True + if pad.HasHole(): + hole_gap = int(self.drill / 2) + int(self.pcb.GetDesignSettings().m_HoleToHoleMin) + if pad.GetEffectiveHoleShape().Collide(p, hole_gap): + return True + return False + + def CheckViaPosition(self, p, zone_clearance=0): + """Return REASON_OK if a via at p keeps clearance to all obstacles.""" + if not self.obs_board_edge.Collide(p): + return self.REASON_BOARD_EDGE + + reason = self.CheckViaInAllAreas(ViaObject(x=0, y=0, pos_x=p.x, pos_y=p.y), self.obs_areas) + if reason != self.REASON_OK: + return reason + + base = max(self.clearance, zone_clearance) + radius = int(self.size / 2) + for poly in self.ref_shapes: + if poly.Collide(p, radius): + return self.REASON_REFERENCE + for bbox, item, kind in self.obstacles: + if not bbox.Contains(p): + continue + if kind == "pad" and self.IsSameNetPad(item): + if self.SameNetPadBlocksVia(item, p): + return self.REASON_PAD + elif kind == "pad": + clr = int(max(base, item.GetOwnClearance(UNDEFINED_LAYER, ""))) + radius + for layer in item.GetLayerSet().CuStack(): + if item.GetEffectiveShape(layer).Collide(p, clr): + return self.REASON_PAD + if item.HasHole() and item.GetEffectiveHoleShape().Collide(p, clr): + return self.REASON_PAD + elif kind == "track": + clr = int(max(base, item.GetOwnClearance(UNDEFINED_LAYER, ""))) + radius + if item.GetEffectiveShape().Collide(p, clr): + return self.REASON_TRACK + else: # copper text or graphic shape + clr = int(base) + radius + try: + hit = item.GetEffectiveShape(item.GetLayer()).Collide(p, clr) + except Exception: + bbox_d = item.GetBoundingBox() + bbox_d.Inflate(clr) + hit = bbox_d.Contains(p) + if hit: + return self.REASON_DRAWING + return self.REASON_OK + + def OutlineCandidates(self, outline, offset=0): + """Via positions along a closed outline. + + Straight horizontal / vertical parts get their vias on the via grid (grid origin + + n * pitch, same grid as the rectangular fill), so stitching along straight edges + lines up. Slanted parts and arcs are walked at a regular pitch along the length. + """ + step = int(max(self.step, self.size + self.clearance)) + origin = self.grid_origin + tol = FromMM(0.005) + points = [] + carry = step * offset # distance to the next via on slanted parts + for i in range(outline.SegmentCount()): + seg = outline.CSegment(i) + a, b = seg.A, seg.B + dx, dy = b.x - a.x, b.y - a.y + length = math.hypot(dx, dy) + if length == 0: + continue + horizontal = abs(dy) <= tol + vertical = abs(dx) <= tol + if horizontal or vertical: + start, delta, o = (a.x, dx, origin.x) if horizontal else (a.y, dy, origin.y) + lo, hi = min(start, start + delta), max(start, start + delta) + ts = [] + k = int(math.ceil((lo - o) / float(step))) + while o + k * step <= hi: + ts.append((o + k * step - start) / float(delta)) + k += 1 + ts.sort() + for t in ts: + points.append(VECTOR2I(int(round(a.x + t * dx)), int(round(a.y + t * dy)))) + carry = max(step - (1 - ts[-1]) * length, 0) if ts else max(carry - length, 0) + else: + d = carry + while d <= length: + points.append(VECTOR2I(int(round(a.x + dx * d / length)), int(round(a.y + dy * d / length)))) + d += step + carry = d - length + return points + + def AddViasAlongOutline(self, outline, outline_parent, all_vias, offset=0, zone_clearance=0, zone_fill=None): + via_placed = 0 + for candidate in self.OutlineCandidates(outline, offset): + # With snap on, try the nearest snap grid points and take the first one that fits + first_reason = None + p = None + for q in self.SnapCandidates(candidate): + if not all(self.CheckViaDistance(q, via, outline_parent) for via in all_vias): + continue # regular spacing to other vias, not worth a marker + reason = self.CheckViaPosition(q, zone_clearance) + if reason == self.REASON_OK and not self.IsOnZoneFill(zone_fill, q): + reason = self.REASON_NO_FILL + if reason == self.REASON_OK: + p = q + break + if first_reason is None: + first_reason = (q, reason) + if p is None: + if first_reason is not None: + self.AddSkipped(first_reason[0], first_reason[1]) + else: via = self.AddVia(p, 0, 0) all_vias.append(via) via_placed += 1 return via_placed + def GetZoneOutlinePoly(self, zone): + """Copy of the drawn zone outline (used when the zone is not filled).""" + # For KiCad >= 7, zone.Outline() may return an empty SHAPE_POLY_SET for inner-layer + # zones. We therefore try to build the polygon from points directly. + zone_poly = SHAPE_POLY_SET() + if KicadMajorVersion() < 7: + for layer_id in zone.GetLayerSet().CuStack(): + z = zone.RawPolysList(layer_id) + if z.OutlineCount() > 0: + zone_poly.Append(z) + break + else: + src = zone.Outline() + if src is not None and src.OutlineCount() > 0: + # Manually copy each outline to avoid SWIG aliasing issues + for oi in range(src.OutlineCount()): + chain = src.Outline(oi) + zone_poly.NewOutline() + for pi in range(chain.PointCount()): + pt = chain.CPoint(pi) + zone_poly.Append(pt.x, pt.y) + for hi in range(src.HoleCount(oi)): + hchain = src.Hole(oi, hi) + zone_poly.NewHole(oi) + for pi in range(hchain.PointCount()): + pt = hchain.CPoint(pi) + zone_poly.Append(pt.x, pt.y, oi, zone_poly.HoleCount(oi) - 1) + return zone_poly + def ConcentricFillVias(self): wxPrint("Calculate placement areas") @@ -497,6 +894,9 @@ STEP = '-' # Global list also grows so we avoid absolute overlaps between zones. all_new_vias = [] + self.PrepareObstacles() + self.grid_origin = self.GetGridOrig(self.pcb.ComputeBoundingBox(False)) + wxPrint("Generating via placement") off = 0 via_placed = 0 @@ -508,85 +908,92 @@ STEP = '-' if self.only_selected_area and not zone.IsSelected(): continue - # Build the polygon for this zone. - # For KiCad >= 7, zone.Outline() may return an empty SHAPE_POLY_SET for inner-layer - # zones. We therefore try to build the polygon from points directly. - zone_poly = SHAPE_POLY_SET() - if KicadMajorVersion() < 7: - for layer_id in zone.GetLayerSet().CuStack(): - z = zone.RawPolysList(layer_id) - if z.OutlineCount() > 0: - zone_poly.Append(z) - break - else: - src = zone.Outline() - if src is not None and src.OutlineCount() > 0: - # Manually copy each outline to avoid SWIG aliasing issues - for oi in range(src.OutlineCount()): - chain = src.Outline(oi) - zone_poly.NewOutline() - for pi in range(chain.PointCount()): - pt = chain.CPoint(pi) - zone_poly.Append(pt.x, pt.y) - - if self.debug: - wxPrint(" Zone layer={} outline_pts={} outline_count={}".format( - zone.GetLayerName(), zone_poly.TotalVertices() if hasattr(zone_poly, 'TotalVertices') else '?', - zone_poly.OutlineCount())) - - if zone_poly.OutlineCount() == 0: - if self.debug: - wxPrint(" -> Skipped (empty outline)") - continue - - processed_any = True - - # Shrink slightly so vias fit inside the zone boundary. - # Use ALLOW_ACUTE_CORNERS (no chamfering) to preserve complex polygon topology. - inflate_amount = int(-(1 * self.clearance + 0.5 * self.size)) - zone_poly.Inflate(inflate_amount, CORNER_STRATEGY_ALLOW_ACUTE_CORNERS, FromMM(0.01)) - - if self.debug: - wxPrint(" -> After inflate: outline_count={}".format(zone_poly.OutlineCount())) - - if zone_poly.OutlineCount() == 0: - if self.debug: - wxPrint(" -> Skipped (empty after inflate)") - continue # Zone too small after shrink - - # For this zone, only use pre-existing vias + already-placed-this-run vias - # for spacing checks – NOT vias placed on other zones' perimeters. - zone_vias = existing_vias + all_new_vias - - # Place vias along outlines and holes of this zone - current_poly = zone_poly - while current_poly.OutlineCount() > 0: - for i in range(0, current_poly.OutlineCount()): - outline = current_poly.Outline(i) - n = self.AddViasAlongOutline(outline, outline, zone_vias, off) - via_placed += n + zone_clearance = zone.GetLocalClearance() or 0 + zone_fill = self.GetZoneFill(zone) + # Vias follow the outer edge of the poured copper (one polygon per copper layer): + # the fill edge already keeps the clearances to the board edge and to anything + # touching the zone border. Clearance cut-outs inside the fill (around pads, + # tracks...) are ignored here - those are handled by CheckViaPosition. Holes drawn + # in the zone outline (cut-outs) are kept for the "Outline" / "Concentric" types. + # Without a fill fall back to the drawn zone outline. + outline_poly = self.GetZoneOutlinePoly(zone) + if zone_fill: + sources = [] + for fill in zone_fill: + filled = SHAPE_POLY_SET(fill) + Unfracture(filled) + poly = SHAPE_POLY_SET() + for oi in range(filled.OutlineCount()): + poly.AddOutline(filled.Outline(oi)) if self.fill_type != self.FILL_TYPE_OUTLINE_NO_HOLES: - for k in range(0, current_poly.HoleCount(i)): - hole = current_poly.Hole(i, k) - n = self.AddViasAlongOutline(hole, outline, zone_vias, off) - via_placed += n + for oi in range(outline_poly.OutlineCount()): + for hi in range(outline_poly.HoleCount(oi)): + cutout = SHAPE_POLY_SET() + cutout.AddOutline(outline_poly.Hole(oi, hi)) + poly.BooleanSubtract(cutout) + Unfracture(poly) + sources.append(poly) + # The fill edge already keeps the clearances: the via copper may be flush with it + inflate_amount = -int(0.5 * self.size + FromMM(0.001)) + else: + sources = [outline_poly] + # Drawn zone outline: keep the via clearance from it + inflate_amount = -int(self.clearance + 0.5 * self.size) - # Concentric: shrink inward for next ring; Outline: single pass - if self.fill_type == self.FILL_TYPE_CONCENTRIC: - current_poly.Inflate(int(-max(self.step, self.size + self.clearance)), CORNER_STRATEGY_CHAMFER_ALL_CORNERS, FromMM(0.01)) - off = 0.5 if off == 0 else 0 - else: - current_poly = SHAPE_POLY_SET() # exit while loop + for zone_poly in sources: + if zone_poly.OutlineCount() == 0: + if self.debug: + wxPrint(" -> Skipped (empty outline)") + continue + processed_any = True - # Record vias placed for this zone to prevent global overlaps - all_new_vias = zone_vias[len(existing_vias):] + # Shrink so the via fits inside the copper (or keeps clearance to the zone outline). + # Use ALLOW_ACUTE_CORNERS (no chamfering) to preserve complex polygon topology. + zone_poly.Inflate(inflate_amount, CORNER_STRATEGY_ALLOW_ACUTE_CORNERS, FromMM(0.01)) + Unfracture(zone_poly) # Inflate may return holes joined to the outline by slits + + if zone_poly.OutlineCount() == 0: + if self.debug: + wxPrint(" -> Skipped (empty after inflate)") + continue # Zone too small after shrink + + # For this zone, only use pre-existing vias + already-placed-this-run vias + # for spacing checks – NOT vias placed on other zones' perimeters. + zone_vias = existing_vias + all_new_vias + + # Place vias along outlines and holes of this zone + current_poly = zone_poly + while current_poly.OutlineCount() > 0: + for i in range(0, current_poly.OutlineCount()): + outline = current_poly.Outline(i) + n = self.AddViasAlongOutline(outline, outline, zone_vias, off, zone_clearance, zone_fill) + via_placed += n + + if self.fill_type != self.FILL_TYPE_OUTLINE_NO_HOLES: + for k in range(0, current_poly.HoleCount(i)): + hole = current_poly.Hole(i, k) + n = self.AddViasAlongOutline(hole, outline, zone_vias, off, zone_clearance, zone_fill) + via_placed += n + + # Concentric: shrink inward for next ring; Outline: single pass + if self.fill_type == self.FILL_TYPE_CONCENTRIC: + current_poly.Inflate(int(-max(self.step, self.size + self.clearance)), CORNER_STRATEGY_CHAMFER_ALL_CORNERS, FromMM(0.01)) + Unfracture(current_poly) + off = 0.5 if off == 0 else 0 + else: + current_poly = SHAPE_POLY_SET() # exit while loop + + # Record vias placed for this zone to prevent global overlaps + all_new_vias = zone_vias[len(existing_vias):] if not processed_any: wxPrint("No areas to fill") return self.RefillBoardAreas() + self.ReportUnfilledZones() + self.DrawSkippedMarkers(self.pcb_group.GetName()) msg = "Done. {:d} vias placed. You have to refill all your pcb's areas/zones !!!".format(via_placed) wxPrint(msg) return via_placed @@ -595,25 +1002,36 @@ STEP = '-' Main function which does the via placement or deletion """ + def CheckSelectedZone(self): + """With "Only under selected Zone" a zone of the target net must be selected. + Tell the user why nothing would happen instead of silently placing 0 vias.""" + selected = [zone for zone in self.pcb.Zones() if zone.IsSelected() and not zone.GetIsRuleArea()] + if any(zone.GetNetname() == self.netname for zone in selected): + return True + msg = "\"Only under selected Zone\" is checked, but no zone of net {} is selected.\n\n".format(self.netname) + if selected: + msg += "Selected zone(s) belong to other nets: {}.\n\n".format( + ", ".join(sorted(set("{} ({})".format(zone.GetNetname() or "", zone.GetLayerName()) for zone in selected)))) + msg += "Select a {} zone (click its outline) and run the plugin again, or uncheck the option.".format(self.netname) + try: + wx.MessageBox(msg, "Via Stitching", wx.OK | wx.ICON_WARNING) + except Exception: + print("WARNING: " + msg.replace("\n\n", " ")) # no GUI (command line use) + return False + def Run(self): - VIA_GROUP_NAME = "ViaStitching {}".format(self.netname) - - if self.debug: - print("Enumerate groups") - for i in self.pcb.Groups(): - if i.GetName() == VIA_GROUP_NAME: - if self.debug: - print("Group {} Found !".format(VIA_GROUP_NAME)) - self.pcb_group = i - """ Launch the process """ if self.delete_vias: # Do not perform a real delete since exposed function in python are not safe for deletion + prefix = "ViaStitching {}".format(self.netname) + groups = sorted(g.GetName() for g in self.pcb.Groups() + if g.GetName() == prefix or g.GetName().startswith(prefix + " ")) + listing = "\n".join(" " + name for name in groups) if groups else " (none found)" wx.MessageBox( - "To delete vias:\n - select one of the generated via to select the group of vias named {}\n - hit delete key\n - That's all !".format(VIA_GROUP_NAME), "Information" + "To delete vias:\n - select one of the generated vias to select its group\n - hit delete key\n - That's all !\n\nVia groups for net {}:\n{}".format(self.netname, listing), "Information" ) """ @@ -626,6 +1044,24 @@ STEP = '-' """ return # no need to run the rest of logic + if self.only_selected_area and not self.CheckSelectedZone(): + return + + if self.refill_zones: + wxPrint("Refilling all zones...") + ZONE_FILLER(self.pcb).Fill(self.pcb.Zones()) + self.area_fill_cache = {} + + VIA_GROUP_NAME = self.GetGroupName() + + if self.debug: + print("Enumerate groups") + for i in self.pcb.Groups(): + if i.GetName() == VIA_GROUP_NAME: + if self.debug: + print("Group {} Found !".format(VIA_GROUP_NAME)) + self.pcb_group = i + if self.pcb_group is None: self.pcb_group = PCB_GROUP(None) self.pcb_group.SetName(VIA_GROUP_NAME) @@ -656,6 +1092,9 @@ STEP = '-' l_clearance = self.clearance + self.size if l_clearance < self.step: l_clearance = self.step + if self.snap: + # Pitch a multiple of the snap grid => all grid points lie on the snap grid + l_clearance = int(math.ceil(l_clearance / float(self.snap))) * self.snap # Calculate grid extents relative to origin (support negative offsets) board_min_x = lboard.GetPosition().x @@ -696,18 +1135,10 @@ STEP = '-' # KeepOuts are filtered because they have no name target_areas = filter(lambda x: (x.GetNetname() == self.netname), all_areas) - # Get the board outline and size with - board_edge = SHAPE_POLY_SET() - try: - # KiCad 10+: aInferOutlineIfNecessary is a required argument - self.pcb.GetBoardPolygonOutlines(board_edge, True) - except TypeError: - # KiCad 9 and older - self.pcb.GetBoardPolygonOutlines(board_edge) - b_clearance = max(self.pcb.GetDesignSettings().m_CopperEdgeClearance, self.clearance) + self.size - board_edge.Deflate(int(b_clearance), CORNER_STRATEGY_ROUND_ALL_CORNERS, FromMM(0.01)) + board_edge = self.GetBoardEdge() via_list = [] # Create a list of existing vias => faster than scanning through the whole rectangle + no_fill_cells = [] # inside a target area outline, but not on its poured copper max_target_area_clearance = 0 # Enum all target areas (Search possible positions for vias on the target net) @@ -723,6 +1154,7 @@ STEP = '-' max_target_area_clearance = area_clearance if (not self.only_selected_area) or (self.only_selected_area and is_selected_area): # All areas or only the selected area + area_fill = self.GetZoneFill(area) # Check every possible point in the virtual coordinate system if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) @@ -756,6 +1188,9 @@ STEP = '-' test_result = hit_test_area and not hit_test_edge test_result = test_result and board_edge.Collide(point_to_test) # check if inside board outline + if test_result and not self.IsOnZoneFill(area_fill, point_to_test): # on poured copper + test_result = False + no_fill_cells.append((x, y, point_to_test)) if test_result: # Create a via object with information about the via and place it in the rectangle @@ -767,135 +1202,28 @@ STEP = '-' print("\nPost target areas:") self.PrintRect(rectangle) - # Enum all vias - if self.debug: - print("%s: Line %u" % (time.time(), currentframe().f_lineno)) - wxPrint("Processing all vias of target area...") + # Check every candidate against pads, tracks, existing vias, copper drawings, keepouts + # and the board edge with the exact copper shapes (round via, real track/pad outline). + wxPrint("Checking clearances of {} candidate positions...".format(len(via_list))) + self.PrepareObstacles(include_net_vias=True) for via in via_list: - reason = self.CheckViaInAllAreas(via, all_areas) + reason = self.CheckViaPosition(VECTOR2I(int(via.PosX), int(via.PosY)), max_target_area_clearance) if reason != self.REASON_OK: rectangle[via.X][via.Y] = reason if self.debug: - print("\nPost areas:") + print("\nPost obstacles:") self.PrintRect(rectangle) - # Same job with all pads => all pads on all layers - wxPrint("Processing all pads...") - if self.debug: - print("%s: Line %u" % (time.time(), currentframe().f_lineno)) - for pad in all_pads: - local_offset = max(pad.GetOwnClearance(UNDEFINED_LAYER, ""), self.clearance, max_target_area_clearance) + (self.size / 2) - max_size = max(pad.GetSize().x, pad.GetSize().y) - - start_x = int(floor(((pad.GetPosition().x - (max_size / 2.0 + local_offset)) - origin.x) / l_clearance)) - x_min - stop_x = int(ceil(((pad.GetPosition().x + (max_size / 2.0 + local_offset)) - origin.x) / l_clearance)) - x_min - - start_y = int(floor(((pad.GetPosition().y - (max_size / 2.0 + local_offset)) - origin.y) / l_clearance)) - y_min - stop_y = int(ceil(((pad.GetPosition().y + (max_size / 2.0 + local_offset)) - origin.y) / l_clearance)) - y_min - - for x in range(start_x, stop_x + 1): - for y in range(start_y, stop_y + 1): - try: - if isinstance(rectangle[x][y], ViaObject): - size_rect = VECTOR2I(int(2 * local_offset), int(2 * local_offset)) - start_rect = VECTOR2I(int(origin.x + ((x + x_min) * l_clearance) - local_offset), int(origin.y + ((y + y_min) * l_clearance) - local_offset)) - if pad.HitTest(BOX2I(start_rect, size_rect), False): - rectangle[x][y] = self.REASON_PAD - else: - # Hit test doesn't handle large pads. This following should fix that. - m = PCB_VIA(self.parent_area) - m.SetPosition(VECTOR2I(int(origin.x + ((x + x_min) * l_clearance)), int(origin.y + ((y + y_min) * l_clearance)))) - m.SetNet(self.target_net) - m.SetViaType(VIATYPE_THROUGH) - m.SetDrill(int(self.drill)) - m.SetWidth(int(self.size)) - if PadCollidesShape(pad, m.GetEffectiveShape()): - rectangle[x][y] = self.REASON_PAD - - except: - wxPrint("exception on Processing all pads...") - if self.debug: - print("\nPost pads:") - self.PrintRect(rectangle) - - # Same job with tracks => all tracks on all layers - wxPrint("Processing all tracks...") - if self.debug: - print("%s: Line %u" % (time.time(), currentframe().f_lineno)) - for track in all_tracks: - if self.same_net_tracks: - if not isinstance(track, PCB_VIA) and track.GetNetname() == self.netname: - continue - start_x = track.GetStart().x - start_y = track.GetStart().y - - stop_x = track.GetEnd().x - stop_y = track.GetEnd().y - - if start_x > stop_x: - d = stop_x - stop_x = start_x - start_x = d - - if start_y > stop_y: - d = stop_y - stop_y = start_y - start_y = d - - osx = start_x - osy = start_y - opx = stop_x - opy = stop_y - - clearance = max(track.GetOwnClearance(UNDEFINED_LAYER, ""), self.clearance, max_target_area_clearance) + (self.size / 2) + (track.GetWidth() / 2) - - start_x = int(floor(((start_x - clearance) - origin.x) / l_clearance)) - x_min - stop_x = int(ceil(((stop_x + clearance) - origin.x) / l_clearance)) - x_min - - start_y = int(floor(((start_y - clearance) - origin.y) / l_clearance)) - y_min - stop_y = int(ceil(((stop_y + clearance) - origin.y) / l_clearance)) - y_min - - for x in range(start_x, stop_x + 1): - for y in range(start_y, stop_y + 1): - try: - if isinstance(rectangle[x][y], ViaObject): - start_rect = VECTOR2I(int(origin.x + ((x + x_min) * l_clearance) - clearance), int(origin.y + ((y + y_min) * l_clearance) - clearance)) - size_rect = VECTOR2I(int(2 * clearance), int(2 * clearance)) - if track.HitTest(BOX2I(start_rect, size_rect), False): - rectangle[x][y] = self.REASON_TRACK - except: - wxPrint("exception on Processing all tracks...") - - if self.debug: - print("\nPost tracks:") - self.PrintRect(rectangle) - - # Same job with existing text - wxPrint("Processing all existing drawings...") - if self.debug: - print("%s: Line %u" % (time.time(), currentframe().f_lineno)) - for draw in all_drawings: - inter = float(self.clearance + self.size) / 2 - bbox = draw.GetBoundingBox() - - start_x = int(floor(((bbox.GetPosition().x - inter) - origin.x) / l_clearance)) - x_min - stop_x = int(ceil(((bbox.GetPosition().x + (bbox.GetSize().x + inter)) - origin.x) / l_clearance)) - x_min - - start_y = int(floor(((bbox.GetPosition().y - inter) - origin.y) / l_clearance)) - y_min - stop_y = int(ceil(((bbox.GetPosition().y + (bbox.GetSize().y + inter)) - origin.y) / l_clearance)) - y_min - - for x in range(start_x, stop_x): - if x < 0 or x >= len(rectangle): - continue - for y in range(start_y, stop_y): - if y < 0 or y >= len(rectangle[0]): - continue - rectangle[x][y] = self.REASON_DRAWING - - if self.debug: - print("Post Drawnings:") - self.PrintRect(rectangle) + # Candidate positions rejected by an obstacle (cells outside any target area are not marked) + candidates = set() + for via in via_list: + candidates.add((via.X, via.Y)) + if not isinstance(rectangle[via.X][via.Y], ViaObject): + self.AddSkipped(VECTOR2I(int(via.PosX), int(via.PosY)), rectangle[via.X][via.Y]) + for x, y, p in no_fill_cells: + if (x, y) not in candidates: + self.AddSkipped(p, self.REASON_NO_FILL) clear_distance = 0 if self.step != 0.0 and self.fill_type == self.FILL_TYPE_STAR: @@ -917,6 +1245,12 @@ STEP = '-' max_offset = max(self.step - (self.clearance + self.size), 0) / 2.0 ran_x = (random.random() * max_offset) - (max_offset / 2.0) ran_y = (random.random() * max_offset) - (max_offset / 2.0) + if self.snap: + # Round towards zero so the offset stays within max_offset + ran_x = int(ran_x / self.snap) * self.snap + ran_y = int(ran_y / self.snap) * self.snap + if self.CheckViaPosition(VECTOR2I(int(via.PosX + ran_x), int(via.PosY + ran_y)), max_target_area_clearance) != self.REASON_OK: + ran_x = ran_y = 0 # the shifted position violates a clearance => keep the checked one self.AddVia(VECTOR2I(int(via.PosX + ran_x), int(via.PosY + ran_y)), via.X, via.Y) via_placed += 1 @@ -928,6 +1262,8 @@ STEP = '-' if self.debug: print("%s: Line %u" % (time.time(), currentframe().f_lineno)) self.RefillBoardAreas() + self.ReportUnfilledZones() + self.DrawSkippedMarkers(self.pcb_group.GetName()) if self.filename: self.pcb.Save(self.filename) diff --git a/ViaStitching/FillAreaAction.py b/ViaStitching/FillAreaAction.py index e37a165..55fb0c1 100644 --- a/ViaStitching/FillAreaAction.py +++ b/ViaStitching/FillAreaAction.py @@ -75,10 +75,15 @@ def SaveSettings(dlg): "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: @@ -89,23 +94,44 @@ def SaveSettings(dlg): def ApplySettings(dlg, data): for key, ctrl in (("size", dlg.m_SizeMM), ("drill", dlg.m_DrillMM), - ("clearance", dlg.m_ClearanceMM), ("step", dlg.m_StepMM)): + ("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)): + ("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)): + 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) @@ -113,7 +139,7 @@ class FillAreaDialogEx(FillAreaDialog.FillAreaDialog): class FillAreaAction(pcbnew.ActionPlugin): def defaults(self): - self.name = "Via Stitching Generator 1.2" + 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") @@ -132,15 +158,18 @@ class FillAreaAction(pcbnew.ActionPlugin): 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()))) - a.SetMinSize(a.GetSize()) + # 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: - wx.LogMessage('Via Stitching') SaveSettings(a) if 1: # try: fill = FillArea.FillArea() @@ -156,10 +185,19 @@ class FillAreaAction(pcbnew.ActionPlugin): 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") diff --git a/ViaStitching/FillAreaDialog.py b/ViaStitching/FillAreaDialog.py index 7ae2b6f..5e012e4 100644 --- a/ViaStitching/FillAreaDialog.py +++ b/ViaStitching/FillAreaDialog.py @@ -17,13 +17,14 @@ import wx.xrc class FillAreaDialog ( wx.Dialog ): def __init__( self, parent ): - wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = u"Fill Area parameters", pos = wx.DefaultPosition, size = wx.Size( 402,663 ), style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER ) + wx.Dialog.__init__ ( self, parent, id = wx.ID_ANY, title = u"Fill Area parameters", pos = wx.DefaultPosition, size = wx.Size( 350,663 ), style = wx.DEFAULT_DIALOG_STYLE|wx.RESIZE_BORDER ) self.SetSizeHints( wx.DefaultSize, wx.DefaultSize ) bSizer3 = wx.BoxSizer( wx.VERTICAL ) fgSizer1 = wx.FlexGridSizer( 0, 2, 0, 0 ) + fgSizer1.AddGrowableCol( 1 ) fgSizer1.SetFlexibleDirection( wx.BOTH ) fgSizer1.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) @@ -33,8 +34,6 @@ class FillAreaDialog ( wx.Dialog ): fgSizer1.Add( self.m_staticText3, 1, wx.ALL|wx.EXPAND, 5 ) self.m_SizeMM = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - self.m_SizeMM.SetMinSize( wx.Size( 1000,-1 ) ) - fgSizer1.Add( self.m_SizeMM, 1, wx.ALL|wx.EXPAND, 5 ) self.m_staticText9 = wx.StaticText( self, wx.ID_ANY, u"Via drill size (mm)", wx.DefaultPosition, wx.DefaultSize, 0 ) @@ -61,6 +60,14 @@ class FillAreaDialog ( wx.Dialog ): self.m_StepMM = wx.TextCtrl( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) fgSizer1.Add( self.m_StepMM, 1, wx.ALL|wx.EXPAND, 5 ) + self.m_staticTextSnap = wx.StaticText( self, wx.ID_ANY, u"Snap grid (mm, 0 = off)", wx.DefaultPosition, wx.DefaultSize, 0 ) + self.m_staticTextSnap.Wrap( -1 ) + + fgSizer1.Add( self.m_staticTextSnap, 0, wx.ALL, 5 ) + + self.m_SnapMM = wx.TextCtrl( self, wx.ID_ANY, u"0", wx.DefaultPosition, wx.DefaultSize, 0 ) + fgSizer1.Add( self.m_SnapMM, 1, wx.ALL|wx.EXPAND, 5 ) + self.m_staticTextGridType = wx.StaticText( self, wx.ID_ANY, u"Grid Origin", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticTextGridType.Wrap( -1 ) @@ -96,48 +103,88 @@ class FillAreaDialog ( wx.Dialog ): self.m_cbFillType.SetSelection( 3 ) fgSizer1.Add( self.m_cbFillType, 0, wx.ALL, 5 ) + self.m_staticTextGroupMode = wx.StaticText( self, wx.ID_ANY, u"Via group", wx.DefaultPosition, wx.DefaultSize, 0 ) + self.m_staticTextGroupMode.Wrap( -1 ) + + fgSizer1.Add( self.m_staticTextGroupMode, 0, wx.ALL, 5 ) + + m_cbGroupModeChoices = [ u"Per net", u"Per net and pattern", u"New group per run" ] + self.m_cbGroupMode = wx.ComboBox( self, wx.ID_ANY, u"Per net", wx.DefaultPosition, wx.DefaultSize, m_cbGroupModeChoices, wx.CB_READONLY ) + self.m_cbGroupMode.SetSelection( 0 ) + fgSizer1.Add( self.m_cbGroupMode, 0, wx.ALL, 5 ) + + bSizer3.Add( fgSizer1, 1, wx.EXPAND, 5 ) + + fgSizerOpts = wx.FlexGridSizer( 0, 4, 0, 0 ) + fgSizerOpts.SetFlexibleDirection( wx.BOTH ) + fgSizerOpts.SetNonFlexibleGrowMode( wx.FLEX_GROWMODE_SPECIFIED ) + self.m_staticText8 = wx.StaticText( self, wx.ID_ANY, u"Random it", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText8.Wrap( -1 ) - fgSizer1.Add( self.m_staticText8, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_staticText8, 0, wx.ALL, 5 ) self.m_Random = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - fgSizer1.Add( self.m_Random, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_Random, 0, wx.ALL, 5 ) self.m_staticText81 = wx.StaticText( self, wx.ID_ANY, u"Only under selected Zone", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText81.Wrap( -1 ) - fgSizer1.Add( self.m_staticText81, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_staticText81, 0, wx.ALL, 5 ) self.m_only_selected = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - fgSizer1.Add( self.m_only_selected, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_only_selected, 0, wx.ALL, 5 ) self.m_staticText71 = wx.StaticText( self, wx.ID_ANY, u"Ignore areas on other layers", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText71.Wrap( -1 ) - fgSizer1.Add( self.m_staticText71, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_staticText71, 0, wx.ALL, 5 ) self.m_viaThroughAreas = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - fgSizer1.Add( self.m_viaThroughAreas, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_viaThroughAreas, 0, wx.ALL, 5 ) self.m_staticText72 = wx.StaticText( self, wx.ID_ANY, u"Also on tracks with same net", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText72.Wrap( -1 ) - fgSizer1.Add( self.m_staticText72, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_staticText72, 0, wx.ALL, 5 ) self.m_sameNetTracks = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - fgSizer1.Add( self.m_sameNetTracks, 0, wx.ALL, 5 ) + fgSizerOpts.Add( self.m_sameNetTracks, 0, wx.ALL, 5 ) + + self.m_staticTextRefill = wx.StaticText( self, wx.ID_ANY, u"Refill zones before run", wx.DefaultPosition, wx.DefaultSize, 0 ) + self.m_staticTextRefill.Wrap( -1 ) + + fgSizerOpts.Add( self.m_staticTextRefill, 0, wx.ALL, 5 ) + + self.m_refillZones = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) + fgSizerOpts.Add( self.m_refillZones, 0, wx.ALL, 5 ) + + self.m_staticTextMarkSkipped = wx.StaticText( self, wx.ID_ANY, u"Mark skipped vias (User.Drawings)", wx.DefaultPosition, wx.DefaultSize, 0 ) + self.m_staticTextMarkSkipped.Wrap( -1 ) + + fgSizerOpts.Add( self.m_staticTextMarkSkipped, 0, wx.ALL, 5 ) + + self.m_markSkipped = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) + fgSizerOpts.Add( self.m_markSkipped, 0, wx.ALL, 5 ) + + self.m_staticTextSkipRef = wx.StaticText( self, wx.ID_ANY, u"Skip references (silkscreen)", wx.DefaultPosition, wx.DefaultSize, 0 ) + self.m_staticTextSkipRef.Wrap( -1 ) + + fgSizerOpts.Add( self.m_staticTextSkipRef, 0, wx.ALL, 5 ) + + self.m_skipReference = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) + fgSizerOpts.Add( self.m_skipReference, 0, wx.ALL, 5 ) self.m_staticText7 = wx.StaticText( self, wx.ID_ANY, u"Debug mode", wx.DefaultPosition, wx.DefaultSize, 0 ) self.m_staticText7.Wrap( -1 ) - fgSizer1.Add( self.m_staticText7, 1, wx.ALL|wx.EXPAND, 5 ) + fgSizerOpts.Add( self.m_staticText7, 0, wx.ALL, 5 ) self.m_Debug = wx.CheckBox( self, wx.ID_ANY, wx.EmptyString, wx.DefaultPosition, wx.DefaultSize, 0 ) - fgSizer1.Add( self.m_Debug, 1, wx.ALL|wx.EXPAND, 5 ) + fgSizerOpts.Add( self.m_Debug, 0, wx.ALL, 5 ) - bSizer3.Add( fgSizer1, 1, wx.EXPAND, 5 ) + bSizer3.Add( fgSizerOpts, 0, wx.EXPAND, 5 ) bSizer1 = wx.BoxSizer( wx.HORIZONTAL ) @@ -158,7 +205,7 @@ class FillAreaDialog ( wx.Dialog ): bSizer1.Add( self.m_button3_delete, 0, wx.ALL, 5 ) - bSizer3.Add( bSizer1, 0, wx.EXPAND|wx.ALIGN_RIGHT, 5 ) + bSizer3.Add( bSizer1, 0, wx.EXPAND, 5 ) self.SetSizer( bSizer3 ) @@ -167,6 +214,7 @@ class FillAreaDialog ( wx.Dialog ): self.Centre( wx.BOTH ) # Connect Events + self.m_SnapMM.Bind( wx.EVT_TEXT, self.onSnapChanged ) self.m_button3_delete.Bind( wx.EVT_BUTTON, self.onDeleteClick ) def __del__( self ): @@ -174,6 +222,9 @@ class FillAreaDialog ( wx.Dialog ): # Virtual event handlers, override them in your derived class + def onSnapChanged( self, event ): + event.Skip() + def onDeleteClick( self, event ): event.Skip() diff --git a/ViaStitching/FillAreaTpl.fbp b/ViaStitching/FillAreaTpl.fbp index 776d7fb..68cf9d7 100644 --- a/ViaStitching/FillAreaTpl.fbp +++ b/ViaStitching/FillAreaTpl.fbp @@ -50,7 +50,7 @@ FillAreaDialog - 402,663 + 350,663 wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER Fill Area parameters @@ -71,7 +71,7 @@ 2 wxBOTH - + 1 0 @@ -181,7 +181,7 @@ 0 0 - 1000,-1 + 1 m_SizeMM 1 @@ -588,6 +588,134 @@ + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + Snap grid (mm, 0 = off) + 0 + + 0 + + + 0 + + 1 + m_staticTextSnap + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + 5 + wxALL|wxEXPAND + 1 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + 0 + + 0 + + 1 + m_SnapMM + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + 0 + + + + onSnapChanged + + 5 wxALL @@ -1041,6 +1169,152 @@ + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + Via group + 0 + + 0 + + + 0 + + 1 + m_staticTextGroupMode + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + "Per net" "Per net and pattern" "New group per run" + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + + 0 + + + 0 + + 1 + m_cbGroupMode + 1 + + + protected + 1 + + Resizable + 0 + 1 + + wxCB_READONLY + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + Per net + + + + + + + + + 5 + wxEXPAND + 0 + + 4 + wxBOTH + + + 0 + + fgSizerOpts + wxFLEX_GROWMODE_SPECIFIED + none + 0 + 0 5 wxALL @@ -1549,10 +1823,391 @@ + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + Refill zones before run + 0 + + 0 + + + 0 + + 1 + m_staticTextRefill + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + m_refillZones + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + Mark skipped vias (User.Drawings) + 0 + + 0 + + + 0 + + 1 + m_staticTextMarkSkipped + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + m_markSkipped + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + Skip references (silkscreen) + 0 + + 0 + + + 0 + + 1 + m_staticTextSkipRef + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + + + -1 + + + + 5 + wxALL + 0 + + 1 + 1 + 1 + 1 + 0 + + 0 + 0 + + + + 1 + 0 + 0 + 1 + + 1 + 0 + Dock + 0 + Left + 0 + 1 + + 1 + + 0 + 0 + wxID_ANY + + + 0 + + + 0 + + 1 + m_skipReference + 1 + + + protected + 1 + + Resizable + 1 + + + + 0 + + + wxFILTER_NONE + wxDefaultValidator + + + + + + 5 - wxALL|wxEXPAND - 1 + wxALL + 0 1 1 @@ -1613,8 +2268,8 @@ 5 - wxALL|wxEXPAND - 1 + wxALL + 0 1 1 @@ -1680,7 +2335,7 @@ 5 - wxEXPAND|wxALIGN_RIGHT + wxEXPAND 0 diff --git a/ViaStitching/metadata.json b/ViaStitching/metadata.json index 8bd7b7a..3dd35ad 100644 --- a/ViaStitching/metadata.json +++ b/ViaStitching/metadata.json @@ -28,7 +28,7 @@ ], "versions": [ { - "version": "1.2.0", + "version": "1.3.0", "status": "stable", "kicad_version": "9.0" }