kcaa 0.2.7__tar.gz → 0.2.9__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. {kcaa-0.2.7 → kcaa-0.2.9}/PKG-INFO +4 -1
  2. {kcaa-0.2.7 → kcaa-0.2.9}/README.md +3 -0
  3. {kcaa-0.2.7 → kcaa-0.2.9}/README_CN.md +2 -0
  4. kcaa-0.2.9/kcaa/router/__init__.py +20 -0
  5. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/router/grid_a_star.py +152 -23
  6. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/router/path_postprocess.py +48 -1
  7. kcaa-0.2.9/kcaa/router/pns/__init__.py +15 -0
  8. kcaa-0.2.9/kcaa/router/pns/direction45.py +417 -0
  9. kcaa-0.2.9/kcaa/router/pns/node.py +118 -0
  10. kcaa-0.2.9/kcaa/router/pns/shove.py +792 -0
  11. kcaa-0.2.9/kcaa/router/pns/walkaround.py +485 -0
  12. kcaa-0.2.9/kcaa/router/route_engine.py +2662 -0
  13. kcaa-0.2.9/kcaa/router/router.py +4712 -0
  14. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/router/visibility_graph.py +118 -37
  15. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/router/world_model.py +198 -36
  16. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_group_tools.py +1 -1
  17. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_library_tools.py +643 -3
  18. kcaa-0.2.9/kcaa/tools/pcb_routing_tools.py +1571 -0
  19. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/render_board_tools.py +117 -14
  20. kcaa-0.2.9/kcaa/tools/render_route_state.py +234 -0
  21. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/skill_tools.py +23 -4
  22. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/symbol_tools.py +31 -59
  23. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/config.py +60 -0
  24. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pcb_footprint_utils.py +100 -3
  25. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_extractor.py +1 -1
  26. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_library_utils.py +4 -4
  27. {kcaa-0.2.7 → kcaa-0.2.9}/pyproject.toml +1 -1
  28. kcaa-0.2.7/kcaa/router/__init__.py +0 -16
  29. kcaa-0.2.7/kcaa/router/a_star.py +0 -166
  30. kcaa-0.2.7/kcaa/router/router.py +0 -2107
  31. kcaa-0.2.7/kcaa/tools/pcb_routing_tools.py +0 -605
  32. {kcaa-0.2.7 → kcaa-0.2.9}/.gitignore +0 -0
  33. {kcaa-0.2.7 → kcaa-0.2.9}/LICENSE +0 -0
  34. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/__init__.py +0 -0
  35. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/context.py +0 -0
  36. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/prompts/__init__.py +0 -0
  37. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/prompts/bom_prompts.py +0 -0
  38. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/prompts/drc_prompt.py +0 -0
  39. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/prompts/pattern_prompts.py +0 -0
  40. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/prompts/templates.py +0 -0
  41. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/__init__.py +0 -0
  42. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/bom_resources.py +0 -0
  43. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/drc_resources.py +0 -0
  44. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/files.py +0 -0
  45. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/netlist_resources.py +0 -0
  46. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/pattern_resources.py +0 -0
  47. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/resources/projects.py +0 -0
  48. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/router/via_check.py +0 -0
  49. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/server.py +0 -0
  50. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/__init__.py +0 -0
  51. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/analysis_tools.py +0 -0
  52. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/bom_tools.py +0 -0
  53. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/drc_tools.py +0 -0
  54. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/erc_tools.py +0 -0
  55. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/export_tools.py +0 -0
  56. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/kipy_tools.py +0 -0
  57. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/netlist_tools.py +0 -0
  58. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/no_connect_tools.py +0 -0
  59. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pattern_tools.py +0 -0
  60. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_edit_tools.py +0 -0
  61. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_placement_helpers.py +0 -0
  62. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_placement_tools.py +0 -0
  63. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_query_tools.py +0 -0
  64. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/pcb_zone_tools.py +0 -0
  65. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/placement_helpers.py +0 -0
  66. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/project_tools.py +0 -0
  67. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/schematic_group_tools.py +0 -0
  68. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/sheet_tools.py +0 -0
  69. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/symbol_edit_tools.py +0 -0
  70. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/validation_tools.py +0 -0
  71. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/version_tools.py +0 -0
  72. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/tools/wire_edit_tools.py +0 -0
  73. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/__init__.py +0 -0
  74. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/boundary_validator.py +0 -0
  75. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/component_utils.py +0 -0
  76. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/file_utils.py +0 -0
  77. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/footprint_database.py +0 -0
  78. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/footprint_index_manager.py +0 -0
  79. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/fp_lib_table_utils.py +0 -0
  80. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/ipc_drc.py +0 -0
  81. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/kicad_api_detection.py +0 -0
  82. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/kicad_cli.py +0 -0
  83. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/kicad_utils.py +0 -0
  84. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/kipy_reload.py +0 -0
  85. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/net_settings.py +0 -0
  86. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/netlist_parser.py +0 -0
  87. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/path_validator.py +0 -0
  88. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pattern_recognition.py +0 -0
  89. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pcb_board_utils.py +0 -0
  90. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pcb_design_rules.py +0 -0
  91. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pcb_library_utils.py +0 -0
  92. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/pcb_sexp_utils.py +0 -0
  93. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/schematic_sexp_utils.py +0 -0
  94. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/secure_subprocess.py +0 -0
  95. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/skip_compat.py +0 -0
  96. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/skip_helpers.py +0 -0
  97. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/sym_lib_table_utils.py +0 -0
  98. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_database.py +0 -0
  99. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_geometry.py +0 -0
  100. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_index_manager.py +0 -0
  101. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/symbol_index_reader.py +0 -0
  102. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/temp_dir_manager.py +0 -0
  103. {kcaa-0.2.7 → kcaa-0.2.9}/kcaa/utils/version_manager.py +0 -0
  104. {kcaa-0.2.7 → kcaa-0.2.9}/kicad_plugin/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: kcaa
3
- Version: 0.2.7
3
+ Version: 0.2.9
4
4
  Summary: Model Context Protocol (MCP) server for KiCad electronic design automation (EDA) files
5
5
  Project-URL: Homepage, https://github.com/paul356/KiCad-AI-Assistant
6
6
  Project-URL: Bug Tracker, https://github.com/paul356/KiCad-AI-Assistant/issues
@@ -46,6 +46,8 @@ Tested on **KiCad 10.0 / Linux & Windows**.
46
46
 
47
47
  [![CI](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml/badge.svg)](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml)
48
48
 
49
+ **Contributions welcome!** Bug reports, feature ideas, and pull requests are all appreciated — see [Contributing](#contributing) for how to get started.
50
+
49
51
  ## Table of Contents
50
52
 
51
53
  - [KiCad AI Assistant](#kicad-ai-assistant)
@@ -197,6 +199,7 @@ All settings can be changed through **Options → Settings** in the plugin panel
197
199
  | `llm_aws_secret_access_key` | AWS secret access key for SigV4 auth | *(empty)* |
198
200
  | `llm_aws_session_token` | Optional STS session token for temporary AWS credentials | *(empty)* |
199
201
  | `server_port` | Fixed port for the built-in MCP server (`0` = auto) | `0` |
202
+ | `mcp_tool_timeout_seconds` | Per-call deadline (s) for MCP tool calls (e.g. PCB routing); longer calls end the turn with an explicit timeout error. Takes effect after the plugin restarts | `300` |
200
203
  | `show_tool_log` | Show tool-call log panel by default | `true` |
201
204
  | `llm_context_tokens` | Total context window size in tokens | `128000` |
202
205
  | `llm_compact_threshold` | Trigger context compaction at this usage fraction | `0.70` |
@@ -6,6 +6,8 @@ Tested on **KiCad 10.0 / Linux & Windows**.
6
6
 
7
7
  [![CI](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml/badge.svg)](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml)
8
8
 
9
+ **Contributions welcome!** Bug reports, feature ideas, and pull requests are all appreciated — see [Contributing](#contributing) for how to get started.
10
+
9
11
  ## Table of Contents
10
12
 
11
13
  - [KiCad AI Assistant](#kicad-ai-assistant)
@@ -157,6 +159,7 @@ All settings can be changed through **Options → Settings** in the plugin panel
157
159
  | `llm_aws_secret_access_key` | AWS secret access key for SigV4 auth | *(empty)* |
158
160
  | `llm_aws_session_token` | Optional STS session token for temporary AWS credentials | *(empty)* |
159
161
  | `server_port` | Fixed port for the built-in MCP server (`0` = auto) | `0` |
162
+ | `mcp_tool_timeout_seconds` | Per-call deadline (s) for MCP tool calls (e.g. PCB routing); longer calls end the turn with an explicit timeout error. Takes effect after the plugin restarts | `300` |
160
163
  | `show_tool_log` | Show tool-call log panel by default | `true` |
161
164
  | `llm_context_tokens` | Total context window size in tokens | `128000` |
162
165
  | `llm_compact_threshold` | Trigger context compaction at this usage fraction | `0.70` |
@@ -6,6 +6,7 @@ KiCad AI Assistant 是一个 KiCad 动作插件,在 KiCad 内部直接嵌入
6
6
 
7
7
  [![CI](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml/badge.svg)](https://github.com/paul356/KiCad-AI-Assistant/actions/workflows/ci.yml)
8
8
 
9
+ **欢迎贡献!** Bug 报告、功能建议和 Pull Request 都非常欢迎——参见[贡献指南](#贡献指南)了解如何开始。
9
10
 
10
11
  ## 目录
11
12
 
@@ -134,6 +135,7 @@ setup_plugin.bat
134
135
  | `llm_model` | 模型名称 | `gpt-4o` |
135
136
  | `llm_base_url` | 自定义接口地址(`llm_provider` 为 `custom` 时使用) | *(使用提供商默认值)* |
136
137
  | `server_port` | 内置 MCP 服务器固定端口(`0` = 自动选择) | `0` |
138
+ | `mcp_tool_timeout_seconds` | MCP 工具调用的单次超时(秒);超过后本轮对话以明确的超时错误结束。重启插件后生效 | `300` |
137
139
  | `show_tool_log` | 默认显示工具调用日志面板 | `true` |
138
140
  | `llm_context_tokens` | LLM 上下文窗口总 token 数 | `128000` |
139
141
  | `llm_compact_threshold` | 上下文使用率超过此比例时触发压缩 | `0.70` |
@@ -0,0 +1,20 @@
1
+ """
2
+ PCB routing algorithm library for the KiCad MCP server.
3
+
4
+ Implements a simplified version of KiCad's PNS (Push and Shove) router.
5
+ Given a start pad and an end pad on the same net, the router produces a
6
+ DRC-clean sequence of ``segment`` and ``via`` S-expression nodes that
7
+ connect them while avoiding obstacles: the route walks around fixed
8
+ solids and shoves movable tracks out of the way. Single-layer and
9
+ multi-layer routes emit straight 0/45/90 segments — corner mode is
10
+ fixed (mitered45); the sole exception is a cocircular waypoint chain,
11
+ which emits one covering arc. Disturbed legs and via junctions
12
+ themselves stay straight segments.
13
+
14
+ Module map:
15
+
16
+ * :mod:`kcaa.router.world_model` — PCB → obstacle list
17
+ * :mod:`kcaa.router.visibility_graph` — Obstacles → visibility graph
18
+ * :mod:`kcaa.router.path_postprocess` — Miter corners, segment emission
19
+ * :mod:`kcaa.router.router` — Orchestration / public API
20
+ """
@@ -33,7 +33,7 @@ from dataclasses import dataclass
33
33
  import heapq
34
34
  import math
35
35
 
36
- from shapely.geometry import LineString, Point
36
+ from shapely.geometry import LineString, Point, box
37
37
 
38
38
  # Grid resolution (mm per cell).
39
39
  # 0.1 mm is a good balance: it captures fine-pitch pin gaps (~0.5 mm → 5 cells)
@@ -97,19 +97,42 @@ class GridMap:
97
97
  origin_y: float
98
98
  blocked: list[bool]
99
99
 
100
+ # ``True`` for cells blocked because their centre lies outside the
101
+ # board fence (``build_grid_map(fence_bbox=...)``), as opposed to
102
+ # obstacle coverage. ``None`` when no fence was applied.
103
+ # ``grid_a_star`` relocates A* anchors that land on fence-blocked
104
+ # cells (an edge-connector pad may straddle the outline) but keeps
105
+ # obstacle-blocked anchors failing the search.
106
+ fence_blocked: list[bool] | None = None
107
+
100
108
  # ── coordinate helpers ──────────────────────────────────────────
101
109
 
102
110
  def to_grid(self, x: float, y: float) -> tuple[int, int]:
103
- """World coordinate → (col, row)."""
104
- gx = round((x - self.origin_x) / self.resolution)
105
- gy = round((y - self.origin_y) / self.resolution)
111
+ """World coordinate → (col, row).
112
+
113
+ Cell ``g``'s centre is at ``origin + (g + 0.5) * resolution``
114
+ (see :meth:`to_world`), so the inverse mapping subtracts half a
115
+ cell before rounding: ``round((x - origin) / res - 0.5)`` picks
116
+ the cell whose centre is nearest, and ``to_grid(to_world(g))``
117
+ round-trips exactly.
118
+ """
119
+ gx = round((x - self.origin_x) / self.resolution - 0.5)
120
+ gy = round((y - self.origin_y) / self.resolution - 0.5)
106
121
  return int(gx), int(gy)
107
122
 
108
123
  def to_world(self, gx: int, gy: int) -> tuple[float, float]:
109
- """(col, row) → world coordinate (cell centre)."""
124
+ """(col, row) → world coordinate (cell centre).
125
+
126
+ Rasterisation marks a cell blocked by testing the cell's centre
127
+ against obstacle polygons; A* walks cell centres, so the path
128
+ output must be the same cell centres (not the corner). A path
129
+ built from corners sits ``resolution / 2`` closer to every
130
+ obstacle than the grid promised, which passes the grid check and
131
+ then fails the true clearance audit.
132
+ """
110
133
  return (
111
- gx * self.resolution + self.origin_x,
112
- gy * self.resolution + self.origin_y,
134
+ (gx + 0.5) * self.resolution + self.origin_x,
135
+ (gy + 0.5) * self.resolution + self.origin_y,
113
136
  )
114
137
 
115
138
  def in_bounds(self, gx: int, gy: int) -> bool:
@@ -135,13 +158,24 @@ def build_grid_map(
135
158
  board_bbox: tuple[float, float, float, float] | None,
136
159
  resolution: float = GRID_RESOLUTION,
137
160
  margin: float = 2.0,
161
+ fence_bbox: tuple[float, float, float, float] | None = None,
138
162
  ) -> GridMap:
139
163
  """Rasterise *obstacles* onto a uniform grid.
140
164
 
141
165
  Each obstacle is a ``shapely`` Polygon stored as the ``.shape``
142
166
  attribute of whatever object is in the list (typically
143
167
  :class:`~kcaa.router.world_model.Obstacle`). A cell is BLOCKED if
144
- its centre falls inside **any** obstacle shape.
168
+ its square footprint intersects **any** obstacle shape.
169
+
170
+ When ``fence_bbox`` is given, cells whose centre lies **outside** it
171
+ are also blocked: the search can never step past the fence even
172
+ though the grid extent (and margin) covers it. The router passes the
173
+ board's Edge.Cuts bbox here so A* cannot wander into the margin
174
+ around the board and emit an out-of-board first segment. The fence
175
+ uses the cell centre, so an edge-connector pad whose centre sits on
176
+ the outline keeps a free terminus cell (pad copper is a legal
177
+ endpoint, exempted elsewhere); the segment-level board check still
178
+ verifies the copper stays inside.
145
179
 
146
180
  Args:
147
181
  obstacles: Iterable of objects with a ``.shape`` (``Polygon``).
@@ -149,6 +183,8 @@ def build_grid_map(
149
183
  When ``None`` a 100×100 mm area is assumed.
150
184
  resolution: Grid cell size in mm.
151
185
  margin: Extra space (mm) around the board bbox.
186
+ fence_bbox: Optional ``(min_x, min_y, max_x, max_y)`` restricting
187
+ free cells to its interior (default: no restriction).
152
188
 
153
189
  Returns:
154
190
  A populated :class:`GridMap`.
@@ -175,18 +211,14 @@ def build_grid_map(
175
211
  s = getattr(obs, "shape", obs)
176
212
  if s is not None and not s.is_empty:
177
213
  shapes.append(s)
178
- if not shapes:
179
- return GridMap(
180
- width=width,
181
- height=height,
182
- resolution=resolution,
183
- origin_x=origin_x,
184
- origin_y=origin_y,
185
- blocked=blocked,
186
- )
187
214
 
188
215
  # Rasterise: iterate over each obstacle's bounding box and mark
189
- # cells whose centre falls inside the obstacle polygon.
216
+ # cells whose square footprint intersects the obstacle polygon.
217
+ # A centre-point test would let an 8-direction diagonal segment cross
218
+ # an obstacle corner (cells on both sides free, the segment between
219
+ # them clips the corner) and pass the grid check only to fail the
220
+ # true clearance audit. The cell-square test blocks any cell the
221
+ # obstacle touches, so every walked segment keeps its promised gap.
190
222
  for shp in shapes:
191
223
  bxmin, bymin, bxmax, bymax = shp.bounds
192
224
  gx0 = max(0, int(math.floor((bxmin - origin_x) / resolution)))
@@ -200,9 +232,34 @@ def build_grid_map(
200
232
  if blocked[gy * width + gx]:
201
233
  continue
202
234
  wx = gx * resolution + origin_x + resolution / 2
203
- if shp.contains(Point(wx, cy)):
235
+ cell = box(
236
+ wx - resolution / 2,
237
+ cy - resolution / 2,
238
+ wx + resolution / 2,
239
+ cy + resolution / 2,
240
+ )
241
+ if shp.intersects(cell):
204
242
  blocked[gy * width + gx] = True
205
243
 
244
+ # Board fence: block every cell whose centre is outside fence_bbox.
245
+ fence_blocked: list[bool] | None = None
246
+ if fence_bbox is not None:
247
+ fence_blocked = [False] * (width * height)
248
+ fmin_x, fmin_y, fmax_x, fmax_y = fence_bbox
249
+ for gy in range(height):
250
+ cy = gy * resolution + origin_y + resolution / 2
251
+ if cy < fmin_y or cy > fmax_y:
252
+ row = gy * width
253
+ for gx in range(width):
254
+ blocked[row + gx] = True
255
+ fence_blocked[row + gx] = True
256
+ continue
257
+ for gx in range(width):
258
+ wx = gx * resolution + origin_x + resolution / 2
259
+ if wx < fmin_x or wx > fmax_x:
260
+ blocked[gy * width + gx] = True
261
+ fence_blocked[gy * width + gx] = True
262
+
206
263
  return GridMap(
207
264
  width=width,
208
265
  height=height,
@@ -210,6 +267,7 @@ def build_grid_map(
210
267
  origin_x=origin_x,
211
268
  origin_y=origin_y,
212
269
  blocked=blocked,
270
+ fence_blocked=fence_blocked,
213
271
  )
214
272
 
215
273
 
@@ -244,6 +302,55 @@ def _octile_dist(gx: int, gy: int, ex: int, ey: int) -> float:
244
302
  return _DIAG_COST * dx + (dy - dx)
245
303
 
246
304
 
305
+ # How far an A* start/end anchor may be relocated (in cells) to reach the
306
+ # nearest walkable cell. 10 cells = 1 mm at the default 0.1 mm resolution:
307
+ # enough to absorb an edge-connector pad whose centre sits exactly on (or
308
+ # marginally outside) the Edge.Cuts line, while a pad that is truly beyond
309
+ # the board still fails the search instead of being rescued from far away.
310
+ _RELOCATE_RADIUS_CELLS = 10
311
+
312
+
313
+ def _nearest_free_cell(
314
+ gx: int,
315
+ gy: int,
316
+ grid: GridMap,
317
+ max_radius: int = _RELOCATE_RADIUS_CELLS,
318
+ ) -> tuple[int, int]:
319
+ """Return the closest free cell to ``(gx, gy)`` within ``max_radius``.
320
+
321
+ The closest cell is found by expanding square rings outward, so the
322
+ result is deterministic. Falls back to the original cell when no
323
+ free cell exists in range — the caller's ``is_free`` guard then
324
+ fails the search with ``path=None``.
325
+ """
326
+ if grid.is_free(gx, gy):
327
+ return gx, gy
328
+ for r in range(1, max_radius + 1):
329
+ for dy in range(-r, r + 1):
330
+ for dx in range(-r, r + 1):
331
+ if abs(dx) != r and abs(dy) != r:
332
+ continue # ring only, not the already-visited interior
333
+ nx, ny = gx + dx, gy + dy
334
+ if grid.in_bounds(nx, ny) and grid.is_free(nx, ny):
335
+ return nx, ny
336
+ return gx, gy
337
+
338
+
339
+ def _clamp_to_walkable(gx: int, gy: int, grid: GridMap) -> tuple[int, int]:
340
+ """Relocate an A* anchor blocked by the board fence to a free cell.
341
+
342
+ A start/end on a *fence*-blocked cell (outside the Edge.Cuts outline)
343
+ moves to the nearest free cell — an edge-connector pad may straddle
344
+ the outline. An anchor blocked by a real obstacle stays put, so the
345
+ search fails as before instead of silently bypassing a keepout.
346
+ """
347
+ if grid.is_free(gx, gy):
348
+ return gx, gy
349
+ if grid.fence_blocked is not None and grid.fence_blocked[gy * grid.width + gx]:
350
+ return _nearest_free_cell(gx, gy, grid)
351
+ return gx, gy
352
+
353
+
247
354
  def grid_a_star(
248
355
  grids: list[GridMap],
249
356
  start_world: tuple[float, float],
@@ -296,6 +403,18 @@ def grid_a_star(
296
403
  ex = max(0, min(W - 1, ex))
297
404
  ey = max(0, min(H - 1, ey))
298
405
 
406
+ # Clamp to the nearest walkable cell. An anchor that lands on a
407
+ # fence-blocked cell (board margin — e.g. an edge-connector pad whose
408
+ # centre sits on the Edge.Cuts line) moves to the closest free cell
409
+ # so the search still finds the board interior; the router
410
+ # post-process re-anchors the route onto the exact pad centres
411
+ # afterwards. Anchors blocked by a real obstacle keep their cell and
412
+ # fail the search (no silent bypass of keepouts). When no free cell
413
+ # exists nearby, the clamped cell is kept and the is_free guards
414
+ # below fail the search.
415
+ sx, sy = _clamp_to_walkable(sx, sy, grids[start_layer_idx])
416
+ ex, ey = _clamp_to_walkable(ex, ey, grids[end_layer_idx])
417
+
299
418
  if not grids[start_layer_idx].is_free(sx, sy):
300
419
  return AStarResult(path=None)
301
420
  if not grids[end_layer_idx].is_free(ex, ey):
@@ -455,6 +574,7 @@ def hierarchical_a_star(
455
574
  fine_resolution: float = GRID_RESOLUTION,
456
575
  route_bbox: tuple[float, float, float, float] | None = None,
457
576
  turn_penalty: float = _TURN_PENALTY,
577
+ fence_bbox: tuple[float, float, float, float] | None = None,
458
578
  ) -> AStarResult:
459
579
  """Run hierarchical A* with auto-detection of single-pass vs two-pass.
460
580
 
@@ -468,6 +588,10 @@ def hierarchical_a_star(
468
588
  end_world: ``(x, y)`` in mm.
469
589
  fine_resolution: Grid cell size in mm for the fine pass.
470
590
  route_bbox: ``(min_x, min_y, max_x, max_y)`` of the route area.
591
+ turn_penalty: Turn-penalty distance equivalent (mm).
592
+ fence_bbox: Optional board bbox; cells outside it are blocked in
593
+ every pass (including the fine band, which may extend past
594
+ the board), so the search cannot step outside the board.
471
595
 
472
596
  Returns:
473
597
  :class:`AStarResult`.
@@ -489,11 +613,11 @@ def hierarchical_a_star(
489
613
  fine_cells = int(math.ceil(bw / fine_resolution)) * int(math.ceil(bh / fine_resolution))
490
614
 
491
615
  if fine_cells < _SINGLE_PASS_THRESHOLD:
492
- grid = build_grid_map(obstacles, bbox, resolution=fine_resolution)
616
+ grid = build_grid_map(obstacles, bbox, resolution=fine_resolution, fence_bbox=fence_bbox)
493
617
  return grid_a_star([grid], start_world, end_world, turn_penalty=turn_penalty)
494
618
 
495
619
  coarse_res = fine_resolution * COARSE_FACTOR
496
- coarse_grid = build_grid_map(obstacles, bbox, resolution=coarse_res)
620
+ coarse_grid = build_grid_map(obstacles, bbox, resolution=coarse_res, fence_bbox=fence_bbox)
497
621
  coarse_result = grid_a_star([coarse_grid], start_world, end_world, turn_penalty=turn_penalty)
498
622
  if coarse_result.path is None:
499
623
  return AStarResult(path=None, cells_visited=coarse_result.cells_visited)
@@ -509,7 +633,7 @@ def hierarchical_a_star(
509
633
  min(bbox[3], band[3]),
510
634
  )
511
635
 
512
- fine_grid = build_grid_map(obstacles, band, resolution=fine_resolution)
636
+ fine_grid = build_grid_map(obstacles, band, resolution=fine_resolution, fence_bbox=fence_bbox)
513
637
  result = grid_a_star([fine_grid], start_world, end_world, turn_penalty=turn_penalty)
514
638
  if result.path is not None:
515
639
  result.cells_visited += coarse_result.cells_visited
@@ -569,6 +693,7 @@ def multi_layer_a_star(
569
693
  via_cost: float = _VIA_COST,
570
694
  via_forbidden_zones: list | None = None,
571
695
  turn_penalty: float = _TURN_PENALTY,
696
+ fence_bbox: tuple[float, float, float, float] | None = None,
572
697
  ) -> MultiLayerAStarResult:
573
698
  """Run A* across multiple copper layers.
574
699
 
@@ -587,6 +712,8 @@ def multi_layer_a_star(
587
712
  via_cost: Distance-equivalent cost per via transition.
588
713
  via_forbidden_zones: ``shapely`` Polygon list where vias are
589
714
  forbidden (e.g. start/end pad AABBs).
715
+ fence_bbox: Optional board bbox; cells outside it are blocked on
716
+ every layer grid.
590
717
 
591
718
  Returns:
592
719
  :class:`MultiLayerAStarResult`.
@@ -598,7 +725,9 @@ def multi_layer_a_star(
598
725
  grids_list: list[GridMap] = []
599
726
  for layer in layers:
600
727
  obs = obstacles_by_layer.get(layer, [])
601
- grids_list.append(build_grid_map(obs, route_bbox, resolution=fine_resolution))
728
+ grids_list.append(
729
+ build_grid_map(obs, route_bbox, resolution=fine_resolution, fence_bbox=fence_bbox)
730
+ )
602
731
 
603
732
  # Build via adjacency index.
604
733
  via_from: dict[int, set[int]] = {}
@@ -37,6 +37,7 @@ to)``; the diameter / drill are taken from the project netclass
37
37
  from __future__ import annotations
38
38
 
39
39
  from dataclasses import dataclass
40
+ import math
40
41
  from typing import Any
41
42
 
42
43
  import sexpdata
@@ -58,6 +59,23 @@ class OutputSegment:
58
59
  net: str
59
60
 
60
61
 
62
+ @dataclass
63
+ class OutputArc:
64
+ """A single track arc in KiCad's 3-point form (start/mid/end).
65
+
66
+ Mirrors ``(arc (start X Y) (mid X Y) (end X Y) (width W)
67
+ (layer L) (net N))``; ``mid`` is any point the arc passes through
68
+ (not the center).
69
+ """
70
+
71
+ start: tuple[float, float]
72
+ mid: tuple[float, float]
73
+ end: tuple[float, float]
74
+ width: float
75
+ layer: str
76
+ net: str
77
+
78
+
61
79
  @dataclass
62
80
  class OutputVia:
63
81
  """A single via ready to be emitted as a S-expression node."""
@@ -265,6 +283,24 @@ def emit_segment_nodes(segments: list[OutputSegment]) -> list[list[Any]]:
265
283
  return nodes
266
284
 
267
285
 
286
+ def emit_arc_nodes(arcs: list[OutputArc]) -> list[list[Any]]:
287
+ """Convert a list of :class:`OutputArc` into raw ``arc`` sexp nodes."""
288
+ nodes: list[list[Any]] = []
289
+ for a in arcs:
290
+ nodes.append(
291
+ [
292
+ sexpdata.Symbol("arc"),
293
+ [sexpdata.Symbol("start"), a.start[0], a.start[1]],
294
+ [sexpdata.Symbol("mid"), a.mid[0], a.mid[1]],
295
+ [sexpdata.Symbol("end"), a.end[0], a.end[1]],
296
+ [sexpdata.Symbol("width"), a.width],
297
+ [sexpdata.Symbol("layer"), a.layer],
298
+ [sexpdata.Symbol("net"), a.net],
299
+ ]
300
+ )
301
+ return nodes
302
+
303
+
268
304
  def emit_via_nodes(vias: list[OutputVia]) -> list[list[Any]]:
269
305
  """Convert a list of :class:`OutputVia` into raw ``via`` sexp nodes."""
270
306
  nodes: list[list[Any]] = []
@@ -358,11 +394,22 @@ def _apply_miters(
358
394
  out.append(a)
359
395
  continue
360
396
 
397
+ # The miter diagonal M→N is m√2 long. A shoulder short enough
398
+ # to make M→N **shorter than the track width** would emit a
399
+ # sub-width segment (a degenerate stub that later shove passes
400
+ # classify as a fixed solid). Floor the shoulder so the
401
+ # diagonal is always ≥ width; a corner whose legs are too short
402
+ # keeps the original 90° angle instead.
403
+ shoulder_min = a.width / math.sqrt(2.0)
404
+ if m_max < shoulder_min:
405
+ out.append(a)
406
+ continue
407
+
361
408
  # Find the largest miter length ≤ m_max whose 45° diagonal is
362
409
  # obstacle-free and doesn't encroach on no-diagonal zones.
363
410
  m = m_max
364
411
  chosen_m: float | None = None
365
- while m >= 1e-3:
412
+ while m >= shoulder_min:
366
413
  # Point M: back along A by *m* from the corner.
367
414
  if a_h:
368
415
  mx = cx - m if a.x2 > a.x1 else cx + m
@@ -0,0 +1,15 @@
1
+ """
2
+ KiCad-style PNS routing engine (self-built, MIT clean).
3
+
4
+ Replaces the grid A* path search: skeleton trace generation
5
+ (``DIRECTION_45::BuildInitialTrace`` port), walkaround of fixed solids,
6
+ shove of movable tracks. Pure Python + shapely; GPL KiCad code is used
7
+ only as an algorithm reference, never linked or copied verbatim.
8
+
9
+ Phases:
10
+ * M0 — geometry foundation (direction45 skeleton, line data structures,
11
+ hull primitives).
12
+ * M1 — single-obstacle walkaround (``walkaround.py``, a port of KiCad
13
+ ``PNS::LINE::Walkaround`` graph traversal) plus the STRtree obstacle
14
+ space (``node.py``). The two connect in ``route_engine.py`` (M1/M2).
15
+ """