-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathlength_matching.py
More file actions
2769 lines (2297 loc) · 107 KB
/
length_matching.py
File metadata and controls
2769 lines (2297 loc) · 107 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Length matching for PCB routes using trombone-style meanders.
Adds length to shorter routes by inserting perpendicular zigzag patterns
at the longest straight segment.
"""
import fnmatch
import math
import re
from typing import List, Tuple, Optional, Dict
from dataclasses import dataclass
from kicad_parser import Segment, PCBData
from routing_config import GridRouteConfig
from routing_utils import segment_length
from net_queries import calculate_route_length, expand_pad_layers
from geometry_utils import (
point_to_segment_distance,
segments_intersect,
segment_to_segment_distance,
)
# Meander geometry constants
CHAMFER_SIZE = 0.1 # mm - 45-degree chamfer size at meander corners
MIN_AMPLITUDE = 0.2 # mm - minimum useful meander amplitude
MIN_SEGMENT_LENGTH = 0.001 # mm - minimum meaningful segment length
COLINEAR_DOT_THRESHOLD = 0.99 # dot product threshold for colinearity check
POSITION_TOLERANCE = 0.01 # mm - tolerance for position comparisons
CORNER_BLOAT_FACTOR = 0.42 # sqrt(2) - 1, extra copper extension at 90-degree corners
SPATIAL_CELL_SIZE = 2.0 # mm - spatial index cell size
class ClearanceIndex:
"""
Spatial index for efficient clearance checking.
Divides the board into cells and stores references to segments/vias/pads
in each cell they overlap. This allows efficient queries for items within
a specific region rather than checking all items.
"""
def __init__(self, cell_size: float = SPATIAL_CELL_SIZE):
self.cell_size = cell_size
self.segment_cells: Dict[Tuple[int, int], List] = {} # cell -> list of (seg, layer)
self.via_cells: Dict[Tuple[int, int], List] = {} # cell -> list of vias
self.pad_cells: Dict[Tuple[int, int], List] = {} # cell -> list of (pad, expanded_layers)
self._pad_layer_cache: Dict[int, List[str]] = {} # id(pad) -> expanded layers
def _cell_key(self, x: float, y: float) -> Tuple[int, int]:
"""Convert (x, y) coordinates to cell key."""
return (int(x / self.cell_size), int(y / self.cell_size))
def _cells_for_segment(self, x1: float, y1: float, x2: float, y2: float, margin: float = 0) -> List[Tuple[int, int]]:
"""Get all cells that a segment (with margin) might touch."""
min_x = min(x1, x2) - margin
max_x = max(x1, x2) + margin
min_y = min(y1, y2) - margin
max_y = max(y1, y2) + margin
min_cx, min_cy = self._cell_key(min_x, min_y)
max_cx, max_cy = self._cell_key(max_x, max_y)
cells = []
for cx in range(min_cx, max_cx + 1):
for cy in range(min_cy, max_cy + 1):
cells.append((cx, cy))
return cells
def _cells_for_point(self, x: float, y: float, radius: float) -> List[Tuple[int, int]]:
"""Get all cells within radius of a point."""
min_cx, min_cy = self._cell_key(x - radius, y - radius)
max_cx, max_cy = self._cell_key(x + radius, y + radius)
cells = []
for cx in range(min_cx, max_cx + 1):
for cy in range(min_cy, max_cy + 1):
cells.append((cx, cy))
return cells
def build(self, pcb_data: PCBData, config: GridRouteConfig,
extra_segments: List[Segment] = None, extra_vias: List = None):
"""
Build the spatial index from PCB data.
Args:
pcb_data: PCB data with segments, vias, pads
config: Routing configuration (for clearance margin in cell assignment)
extra_segments: Additional segments to include
extra_vias: Additional vias to include
"""
# Clearance margin for cell assignment - ensures we find all potentially conflicting items
margin = config.track_width + config.clearance + config.meander_amplitude
# Index segments
for seg in pcb_data.segments:
cells = self._cells_for_segment(seg.start_x, seg.start_y, seg.end_x, seg.end_y, margin)
for cell in cells:
if cell not in self.segment_cells:
self.segment_cells[cell] = []
self.segment_cells[cell].append(seg)
if extra_segments:
for seg in extra_segments:
cells = self._cells_for_segment(seg.start_x, seg.start_y, seg.end_x, seg.end_y, margin)
for cell in cells:
if cell not in self.segment_cells:
self.segment_cells[cell] = []
self.segment_cells[cell].append(seg)
# Index vias
via_margin = config.via_size / 2 + margin
for via in pcb_data.vias:
cells = self._cells_for_point(via.x, via.y, via_margin)
for cell in cells:
if cell not in self.via_cells:
self.via_cells[cell] = []
self.via_cells[cell].append(via)
if extra_vias:
for via in extra_vias:
cells = self._cells_for_point(via.x, via.y, via_margin)
for cell in cells:
if cell not in self.via_cells:
self.via_cells[cell] = []
self.via_cells[cell].append(via)
# Index pads and pre-compute expanded layers
for pad_net_id, pad_list in pcb_data.pads_by_net.items():
for pad in pad_list:
pad_radius = max(pad.size_x, pad.size_y) / 2 + margin
cells = self._cells_for_point(pad.global_x, pad.global_y, pad_radius)
# Pre-compute expanded layers once per pad
expanded = expand_pad_layers(pad.layers, config.layers)
self._pad_layer_cache[id(pad)] = expanded
for cell in cells:
if cell not in self.pad_cells:
self.pad_cells[cell] = []
self.pad_cells[cell].append((pad, expanded))
def add_segments(self, segments: List[Segment], margin: float):
"""Incrementally add segments to the index after initial build."""
for seg in segments:
cells = self._cells_for_segment(seg.start_x, seg.start_y, seg.end_x, seg.end_y, margin)
for cell in cells:
if cell not in self.segment_cells:
self.segment_cells[cell] = []
self.segment_cells[cell].append(seg)
def query_segments(self, x1: float, y1: float, x2: float, y2: float, margin: float) -> List:
"""Get segments potentially within margin of a line segment."""
cells = self._cells_for_segment(x1, y1, x2, y2, margin)
seen = set()
result = []
for cell in cells:
for seg in self.segment_cells.get(cell, []):
seg_id = id(seg)
if seg_id not in seen:
seen.add(seg_id)
result.append(seg)
return result
def query_vias(self, x1: float, y1: float, x2: float, y2: float, margin: float) -> List:
"""Get vias potentially within margin of a line segment."""
cells = self._cells_for_segment(x1, y1, x2, y2, margin)
seen = set()
result = []
for cell in cells:
for via in self.via_cells.get(cell, []):
via_id = id(via)
if via_id not in seen:
seen.add(via_id)
result.append(via)
return result
def query_pads(self, x1: float, y1: float, x2: float, y2: float, margin: float) -> List[Tuple]:
"""Get pads (with expanded layers) potentially within margin of a line segment."""
cells = self._cells_for_segment(x1, y1, x2, y2, margin)
seen = set()
result = []
for cell in cells:
for pad_tuple in self.pad_cells.get(cell, []):
pad_id = id(pad_tuple[0])
if pad_id not in seen:
seen.add(pad_id)
result.append(pad_tuple)
return result
def get_bump_segments(
cx: float, cy: float,
ux: float, uy: float,
px: float, py: float,
direction: int,
amplitude: float,
chamfer: float = 0.1,
is_first_bump: bool = True
) -> List[Tuple[float, float, float, float]]:
"""
Calculate the segments that would form a meander bump.
Args:
is_first_bump: If True, includes entry chamfer. If False, bump connects
directly from previous bump (no entry chamfer needed).
Returns list of (x1, y1, x2, y2) tuples for each segment.
"""
riser_height = amplitude - 2 * chamfer
if riser_height < 0.1:
riser_height = 0.1
segments = []
x, y = cx, cy
# Entry 45° chamfer (only for first bump)
if is_first_bump:
nx = x + ux * chamfer + px * chamfer * direction
ny = y + uy * chamfer + py * chamfer * direction
segments.append((x, y, nx, ny))
x, y = nx, ny
# Riser away from centerline
nx = x + px * riser_height * direction
ny = y + py * riser_height * direction
segments.append((x, y, nx, ny))
x, y = nx, ny
# Top chamfer 1
nx = x + ux * chamfer + px * chamfer * direction
ny = y + uy * chamfer + py * chamfer * direction
segments.append((x, y, nx, ny))
x, y = nx, ny
# Top chamfer 2
nx = x + ux * chamfer - px * chamfer * direction
ny = y + uy * chamfer - py * chamfer * direction
segments.append((x, y, nx, ny))
x, y = nx, ny
# Riser back toward centerline
nx = x - px * riser_height * direction
ny = y - py * riser_height * direction
segments.append((x, y, nx, ny))
x, y = nx, ny
# No exit chamfer - next bump connects directly
# (Exit chamfer is only added at the very end of all meanders)
return segments
def get_safe_amplitude_at_point(
cx: float, cy: float,
ux: float, uy: float,
px: float, py: float,
direction: int,
max_amplitude: float,
min_amplitude: float,
layer: str,
pcb_data: PCBData,
net_id: int,
config: GridRouteConfig,
extra_segments: List[Segment] = None,
extra_vias: List = None,
is_first_bump: bool = True,
paired_net_id: int = None,
clearance_index: 'ClearanceIndex' = None
) -> float:
"""
Find the maximum safe amplitude for a meander bump at a specific point.
Args:
cx, cy: Center point of the bump on the trace
ux, uy: Unit vector along the trace direction
px, py: Perpendicular unit vector
direction: 1 for positive perpendicular, -1 for negative
max_amplitude: Maximum amplitude to try
min_amplitude: Minimum useful amplitude
layer: Layer of the trace
pcb_data: PCB data with all segments and vias
net_id: Net ID of the route (to exclude self)
config: Routing configuration
extra_segments: Additional segments to check against (e.g., from other nets in same length-match pass)
extra_vias: Additional vias to check against (e.g., from other nets in same length-match pass)
paired_net_id: Optional paired net ID to also exclude (for intra-pair diff pair matching)
clearance_index: Pre-built spatial index for efficient collision detection (optional)
Returns:
Safe amplitude, or 0 if no safe amplitude found
"""
# Add margin to account for segment merging/optimization when writing output
# The routing uses grid-snapped segments, but output merges them into longer
# segments that may have slightly different coordinates (up to half a grid step)
meander_clearance_margin = config.grid_step / 2
# Add corner margin for track width bloat at 45-degree chamfered corners
corner_margin = config.track_width / 2 * CORNER_BLOAT_FACTOR
required_clearance = config.track_width + config.clearance + meander_clearance_margin + corner_margin
via_clearance = config.via_size / 2 + config.track_width / 2 + config.clearance + meander_clearance_margin + corner_margin
paired_clearance = config.track_width + config.clearance
chamfer = CHAMFER_SIZE
# Binary search for safe amplitude
# Start with max_amplitude and reduce if there are conflicts
test_amplitudes = [max_amplitude]
# Add intermediate values for binary search
amp = max_amplitude
while amp > min_amplitude:
amp *= 0.7
if amp >= min_amplitude:
test_amplitudes.append(amp)
test_amplitudes.append(min_amplitude)
for test_amp in test_amplitudes:
# Generate bump segments for this amplitude
bump_segs = get_bump_segments(cx, cy, ux, uy, px, py, direction, test_amp, chamfer, is_first_bump)
conflict_found = False
# Calculate bump bounding box for spatial queries
bump_min_x = min(min(bx1, bx2) for bx1, by1, bx2, by2 in bump_segs)
bump_max_x = max(max(bx1, bx2) for bx1, by1, bx2, by2 in bump_segs)
bump_min_y = min(min(by1, by2) for bx1, by1, bx2, by2 in bump_segs)
bump_max_y = max(max(by1, by2) for bx1, by1, bx2, by2 in bump_segs)
# Use spatial index if available, otherwise fall back to full iteration
if clearance_index is not None:
# Query segments in the bump region
nearby_segments = clearance_index.query_segments(
bump_min_x, bump_min_y, bump_max_x, bump_max_y, required_clearance
)
# Check each bump segment against nearby segments on the same layer
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for other_seg in nearby_segments:
# Layer check first (most likely to skip)
if other_seg.layer != layer:
continue
if other_seg.net_id == net_id:
continue
# For paired net (intra-pair meanders), use minimum clearance
if other_seg.net_id == paired_net_id:
check_clearance = paired_clearance
else:
check_clearance = required_clearance
# Check segment-to-segment distance
dist = segment_to_segment_distance(
bx1, by1, bx2, by2,
other_seg.start_x, other_seg.start_y, other_seg.end_x, other_seg.end_y
)
if dist < check_clearance:
conflict_found = True
break
# Check bump segments against nearby vias
if not conflict_found:
nearby_vias = clearance_index.query_vias(
bump_min_x, bump_min_y, bump_max_x, bump_max_y, via_clearance
)
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for via in nearby_vias:
if via.net_id == net_id:
continue
# Distance from via center to bump segment
dist = point_to_segment_distance(via.x, via.y, bx1, by1, bx2, by2)
if dist < via_clearance:
conflict_found = True
break
# Check bump segments against nearby pads (on same layer)
if not conflict_found:
pad_clearance = config.track_width / 2 + config.clearance + corner_margin
nearby_pads = clearance_index.query_pads(
bump_min_x, bump_min_y, bump_max_x, bump_max_y, pad_clearance + 2.0
)
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for pad, expanded_pad_layers in nearby_pads:
if layer not in expanded_pad_layers:
continue
# Treat pad as circle with radius = max(size_x, size_y)/2
pad_radius = max(pad.size_x, pad.size_y) / 2
dist = point_to_segment_distance(pad.global_x, pad.global_y, bx1, by1, bx2, by2)
if dist < pad_radius + pad_clearance:
conflict_found = True
break
else:
# Fallback: iterate all segments (slower, but works without index)
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for other_seg in pcb_data.segments:
# Layer check first (most likely to skip)
if other_seg.layer != layer:
continue
if other_seg.net_id == net_id:
continue
# For paired net (intra-pair meanders), use minimum clearance
if other_seg.net_id == paired_net_id:
check_clearance = paired_clearance
else:
check_clearance = required_clearance
# Quick distance check
seg_center_x = (other_seg.start_x + other_seg.end_x) / 2
seg_center_y = (other_seg.start_y + other_seg.end_y) / 2
seg_half_len = math.sqrt((other_seg.end_x - other_seg.start_x)**2 +
(other_seg.end_y - other_seg.start_y)**2) / 2
bump_center_x = (bx1 + bx2) / 2
bump_center_y = (by1 + by2) / 2
rough_dist = math.sqrt((bump_center_x - seg_center_x)**2 + (bump_center_y - seg_center_y)**2)
if rough_dist > test_amp + seg_half_len + required_clearance + 1.0:
continue
# Check segment-to-segment distance
dist = segment_to_segment_distance(
bx1, by1, bx2, by2,
other_seg.start_x, other_seg.start_y, other_seg.end_x, other_seg.end_y
)
if dist < check_clearance:
conflict_found = True
break
# Check extra_segments too
if not conflict_found and extra_segments:
for other_seg in extra_segments:
if other_seg.layer != layer:
continue
if other_seg.net_id == net_id:
continue
if other_seg.net_id == paired_net_id:
check_clearance = paired_clearance
else:
check_clearance = required_clearance
dist = segment_to_segment_distance(
bx1, by1, bx2, by2,
other_seg.start_x, other_seg.start_y, other_seg.end_x, other_seg.end_y
)
if dist < check_clearance:
conflict_found = True
break
# Check bump segments against vias
if not conflict_found:
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for via in pcb_data.vias:
if via.net_id == net_id:
continue
dist = point_to_segment_distance(via.x, via.y, bx1, by1, bx2, by2)
if dist < via_clearance:
conflict_found = True
break
# Check extra_vias too
if not conflict_found and extra_vias:
for via in extra_vias:
if via.net_id == net_id:
continue
dist = point_to_segment_distance(via.x, via.y, bx1, by1, bx2, by2)
if dist < via_clearance:
conflict_found = True
break
# Check bump segments against pads (on same layer)
if not conflict_found:
pad_clearance = config.track_width / 2 + config.clearance + corner_margin
for bx1, by1, bx2, by2 in bump_segs:
if conflict_found:
break
for pad_net_id, pad_list in pcb_data.pads_by_net.items():
if pad_net_id == net_id:
continue
if conflict_found:
break
for pad in pad_list:
expanded_pad_layers = expand_pad_layers(pad.layers, config.layers)
if layer not in expanded_pad_layers:
continue
pad_radius = max(pad.size_x, pad.size_y) / 2
dist = point_to_segment_distance(pad.global_x, pad.global_y, bx1, by1, bx2, by2)
if dist < pad_radius + pad_clearance:
conflict_found = True
break
if not conflict_found:
return test_amp
# All amplitudes had conflicts
return 0
def check_meander_clearance(
segment: Segment,
amplitude: float,
pcb_data: PCBData,
net_id: int,
config: GridRouteConfig,
paired_net_id: int = None
) -> bool:
"""
Check if a meander at this segment would have clearance from other traces/vias.
This is a quick check - detailed per-bump checking is done during generation.
Args:
segment: The segment where meander would be placed
amplitude: Height of meander perpendicular to trace
pcb_data: PCB data with all segments and vias
net_id: Net ID of the route being meandered (to exclude self)
config: Routing configuration
paired_net_id: Optional paired net ID to also exclude (for intra-pair diff pair matching)
Returns:
True if meander area appears clear, False if obviously blocked
"""
# Calculate segment direction and perpendicular
dx = segment.end_x - segment.start_x
dy = segment.end_y - segment.start_y
seg_len = math.sqrt(dx * dx + dy * dy)
if seg_len < MIN_SEGMENT_LENGTH:
return False
ux = dx / seg_len
uy = dy / seg_len
px = -uy
py = ux
margin = config.track_width / 2 + config.clearance * 1.5
# Quick check: is there ANY space for meanders?
# Sample a few points along the segment
for t in [0.25, 0.5, 0.75]:
cx = segment.start_x + ux * seg_len * t
cy = segment.start_y + uy * seg_len * t
# Check both directions
amp_pos = get_safe_amplitude_at_point(cx, cy, ux, uy, px, py, 1, amplitude, 0.1,
segment.layer, pcb_data, net_id, config,
paired_net_id=paired_net_id)
amp_neg = get_safe_amplitude_at_point(cx, cy, ux, uy, px, py, -1, amplitude, 0.1,
segment.layer, pcb_data, net_id, config,
paired_net_id=paired_net_id)
if amp_pos >= 0.1 or amp_neg >= 0.1:
return True # At least some meanders possible
return False
def segments_are_colinear(seg1: Segment, seg2: Segment, tolerance: float = POSITION_TOLERANCE) -> bool:
"""
Check if two segments are colinear (same direction and connected).
Args:
seg1: First segment
seg2: Second segment (should start where seg1 ends)
tolerance: Position tolerance in mm
Returns:
True if segments are colinear and connected
"""
# Check if seg2 starts where seg1 ends
if abs(seg1.end_x - seg2.start_x) > tolerance or abs(seg1.end_y - seg2.start_y) > tolerance:
return False
# Check if same layer
if seg1.layer != seg2.layer:
return False
# Calculate direction vectors
dx1 = seg1.end_x - seg1.start_x
dy1 = seg1.end_y - seg1.start_y
dx2 = seg2.end_x - seg2.start_x
dy2 = seg2.end_y - seg2.start_y
# Normalize
len1 = math.sqrt(dx1*dx1 + dy1*dy1)
len2 = math.sqrt(dx2*dx2 + dy2*dy2)
if len1 < MIN_SEGMENT_LENGTH or len2 < MIN_SEGMENT_LENGTH:
return False
dx1, dy1 = dx1/len1, dy1/len1
dx2, dy2 = dx2/len2, dy2/len2
# Check if same direction (dot product close to 1)
dot = dx1*dx2 + dy1*dy2
return dot > COLINEAR_DOT_THRESHOLD
def find_longest_straight_run(segments: List[Segment], min_length: float = 1.0) -> Optional[Tuple[int, int, float]]:
"""
Find the longest run of colinear segments suitable for meander insertion.
Args:
segments: List of route segments
min_length: Minimum run length to consider (mm)
Returns:
(start_idx, end_idx, length) of longest run, or None if none found
"""
if not segments:
return None
best_run = None
best_length = 0.0
i = 0
while i < len(segments):
# Start a new run
run_start = i
run_length = segment_length(segments[i])
# Extend the run while segments are colinear
j = i + 1
while j < len(segments) and segments_are_colinear(segments[j-1], segments[j]):
run_length += segment_length(segments[j])
j += 1
if run_length >= min_length and run_length > best_length:
best_length = run_length
best_run = (run_start, j - 1, run_length)
i = j
return best_run
def find_longest_segment(segments: List[Segment], min_length: float = 1.0) -> Optional[int]:
"""
Find the index of the longest segment suitable for meander insertion.
Args:
segments: List of route segments
min_length: Minimum segment length to consider (mm)
Returns:
Index of longest segment, or None if no suitable segment found
"""
best_idx = None
best_length = 0.0
for i, seg in enumerate(segments):
length = segment_length(seg)
if length >= min_length and length > best_length:
best_length = length
best_idx = i
return best_idx
def generate_trombone_meander(
segment: Segment,
extra_length: float,
amplitude: float,
track_width: float,
pcb_data: PCBData = None,
config: GridRouteConfig = None,
extra_segments: List[Segment] = None,
extra_vias: List = None,
min_bumps: int = 0,
paired_net_id: int = None,
clearance_index: 'ClearanceIndex' = None
) -> Tuple[List[Segment], int]:
"""
Generate trombone-style meander segments to replace a straight segment.
The meander creates simple up-down bumps with 45° chamfered corners:
Original: ────────────────────────────────────>
Meander: ──╮╭╮╭╮╭──>
││││││
╰╯╰╯╰╯
Each "bump" consists of:
- 45° corner going perpendicular
- Straight segment perpendicular to trace (the "riser" going up)
- 45° corner at top (U-turn)
- Straight segment back down (the "riser" going down)
- 45° corner returning to trace
Args:
segment: Original segment to replace
extra_length: Additional length to add (mm)
amplitude: Maximum height of meander perpendicular to trace (mm)
track_width: Track width for new segments (mm)
pcb_data: PCB data for per-bump clearance checking (optional)
config: Routing configuration for clearance checking (optional)
extra_segments: Additional segments to check against (e.g., from other nets already processed)
extra_vias: Additional vias to check against (e.g., from other nets already processed)
min_bumps: Minimum number of bumps to generate (0 = use extra_length to determine)
paired_net_id: Optional paired net ID to also exclude (for intra-pair diff pair matching)
Returns:
Tuple of (segments, bump_count) - the meander segments and number of bumps added
"""
if extra_length <= 0 and min_bumps <= 0:
return [segment], 0
# Calculate segment direction
dx = segment.end_x - segment.start_x
dy = segment.end_y - segment.start_y
seg_len = math.sqrt(dx * dx + dy * dy)
if seg_len < MIN_SEGMENT_LENGTH:
return [segment], 0
# Unit vectors along and perpendicular to segment
ux = dx / seg_len
uy = dy / seg_len
# Perpendicular (90° counterclockwise)
px = -uy
py = ux
# 45° chamfer size - use a small chamfer for smooth corners
chamfer = CHAMFER_SIZE # mm - small 45° chamfer at corners
min_amplitude = MIN_AMPLITUDE # mm - minimum useful amplitude
# Horizontal distance consumed by one bump (just the chamfers' horizontal components)
bump_width = 4 * chamfer
# Estimate number of bumps we can fit
max_bumps = int(seg_len * 0.9 / bump_width)
if max_bumps < 1:
return [segment], 0
# Calculate how much extra length we need per bump on average
target_extra_per_bump = extra_length / max_bumps
# Each bump adds approximately 2 * (amplitude - 2*chamfer) extra length
# So target_amplitude = target_extra_per_bump / 2 + 2*chamfer
# But we cap at the configured amplitude
# Build segment list
new_segments = []
# Current position - start at segment start
cx = segment.start_x
cy = segment.start_y
# Track how much extra length we've added
total_extra_added = 0.0
# Generate meander bumps
direction = 1 # Alternates: 1 = up (positive perpendicular), -1 = down
first_bump_direction = None # Track direction of first bump for exit chamfer
prev_bump_direction = None # Track previous bump direction for same-direction spacing
blocked_direction = None # Track which direction is completely blocked (safe_amp=0)
bump_count = 0
# Leave some margin at start and end
margin = bump_width
# Straight lead-in
if margin > POSITION_TOLERANCE:
end_x = cx + ux * margin
end_y = cy + uy * margin
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=end_x, end_y=end_y,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = end_x, end_y
# Keep adding bumps until we've added enough length or run out of space
# If min_bumps > 0: generate exactly min_bumps (for amplitude scaling - don't let extra_length add more)
# If min_bumps == 0: use extra_length to determine bump count
def should_continue():
if min_bumps > 0:
return bump_count < min_bumps
else:
return total_extra_added < extra_length
while should_continue():
# Check if we have room for another bump
dist_to_end = math.sqrt((segment.end_x - cx)**2 + (segment.end_y - cy)**2)
if dist_to_end < bump_width + margin:
break
# Determine amplitude for this bump
bump_amplitude = amplitude
# First bump includes entry chamfer, subsequent bumps don't
is_first = (bump_count == 0)
has_entry_chamfer = is_first
# Calculate the ACTUAL bump start position (after any same-direction spacing)
# This is where the clearance check should be done
check_cx, check_cy = cx, cy
# For same-direction bumps, we need to account for the spacing chamfers
# that will be added before the bump. The bump will start 2*chamfer further along.
needs_same_dir_spacing = (prev_bump_direction is not None and prev_bump_direction == direction)
if needs_same_dir_spacing:
# The bump will start after exit chamfer + entry chamfer = 2*chamfer forward
check_cx = cx + ux * 2 * chamfer
check_cy = cy + uy * 2 * chamfer
# If we have clearance checking, find safe amplitude at the ACTUAL bump position
if pcb_data is not None and config is not None:
safe_amp = get_safe_amplitude_at_point(
check_cx, check_cy, ux, uy, px, py, direction, amplitude, min_amplitude,
segment.layer, pcb_data, segment.net_id, config, extra_segments, extra_vias, is_first,
paired_net_id=paired_net_id, clearance_index=clearance_index
)
if safe_amp < min_amplitude:
# Try the other direction
# For the other direction, same-direction spacing might not be needed
other_dir = -direction
other_needs_spacing = (prev_bump_direction is not None and prev_bump_direction == other_dir)
if other_needs_spacing:
other_check_cx = cx + ux * 2 * chamfer
other_check_cy = cy + uy * 2 * chamfer
else:
other_check_cx, other_check_cy = cx, cy
safe_amp_other = get_safe_amplitude_at_point(
other_check_cx, other_check_cy, ux, uy, px, py, other_dir, amplitude, min_amplitude,
segment.layer, pcb_data, segment.net_id, config, extra_segments, extra_vias, is_first,
paired_net_id=paired_net_id, clearance_index=clearance_index
)
if safe_amp_other >= min_amplitude:
# Mark the original direction as blocked if safe_amp was 0
# But NOT for intra-pair matching (paired_net_id set) - the paired track
# blocks full bumps but exit chamfers back to centerline are always valid
# since the original track position is already properly spaced
if safe_amp == 0 and paired_net_id is None:
blocked_direction = direction
direction = other_dir
safe_amp = safe_amp_other
needs_same_dir_spacing = other_needs_spacing
check_cx, check_cy = other_check_cx, other_check_cy
else:
# No room for a bump here, skip forward with a straight segment
skip_dist = 0.2
new_x = cx + ux * skip_dist
new_y = cy + uy * skip_dist
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=new_x, end_y=new_y,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = new_x, new_y
continue
bump_amplitude = min(amplitude, safe_amp)
riser_height = bump_amplitude - 2 * chamfer
if riser_height < 0.1:
riser_height = 0.1
bump_amplitude = riser_height + 2 * chamfer
# Calculate extra length added by this bump
# With entry/exit chamfers: 4 chamfers + 2 risers
# Without inter-bump chamfers: 2 top chamfers + 2 risers (for middle bumps)
chamfer_diag = chamfer * math.sqrt(2)
if has_entry_chamfer:
# Full bump with entry chamfer
bump_path_length = 3 * chamfer_diag + 2 * riser_height # entry + 2 top chamfers + risers
else:
# No entry chamfer - connect directly from previous bump's end
bump_path_length = 2 * chamfer_diag + 2 * riser_height # just 2 top chamfers + risers
# Horizontal distance consumed (for checking if we have room)
if has_entry_chamfer:
this_bump_width = 3 * chamfer # entry chamfer + 2 top chamfers
else:
this_bump_width = 2 * chamfer # just 2 top chamfers
extra_this_bump = bump_path_length - this_bump_width
# Generate this bump
# Add chamfers between same-direction bumps to prevent risers from touching
# This happens when clearance checking forces all bumps to one side (e.g., intra-pair matching)
if needs_same_dir_spacing:
# After a bump, we're at +chamfer offset from centerline.
# Add exit chamfer (to centerline) + entry chamfer (back to offset) to separate bumps
# Check if chamfers would go into blocked direction - use flat segments instead
exit_goes_blocked = (blocked_direction is not None and -prev_bump_direction == blocked_direction)
if exit_goes_blocked:
# Can't return to centerline (blocked direction), so stay at current offset
# Use a single flat segment for separation - we're already at the correct offset
# for the next bump since both bumps go in the same (unblocked) direction
nx = cx + ux * 2 * chamfer # Double length to maintain spacing
ny = cy + uy * 2 * chamfer
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
else:
# Normal case: exit chamfer returns to centerline, entry goes to new offset
# Exit chamfer (return to centerline)
nx = cx + ux * chamfer - px * chamfer * prev_bump_direction
ny = cy + uy * chamfer - py * chamfer * prev_bump_direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Entry chamfer (go to offset for next bump's riser)
nx = cx + ux * chamfer + px * chamfer * direction
ny = cy + uy * chamfer + py * chamfer * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Entry chamfer (only for first bump)
if has_entry_chamfer:
first_bump_direction = direction # Record direction for exit chamfer
# Direction switching already ensured we're going in the unblocked direction
nx = cx + ux * chamfer + px * chamfer * direction
ny = cy + uy * chamfer + py * chamfer * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Riser going away from centerline
nx = cx + px * riser_height * direction
ny = cy + py * riser_height * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Top 45° chamfer 1 (continuing away from centerline + forward)
nx = cx + ux * chamfer + px * chamfer * direction
ny = cy + uy * chamfer + py * chamfer * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Top 45° chamfer 2 (now returning toward centerline + forward)
nx = cx + ux * chamfer - px * chamfer * direction
ny = cy + uy * chamfer - py * chamfer * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny
# Riser going back toward centerline
nx = cx - px * riser_height * direction
ny = cy - py * riser_height * direction
new_segments.append(Segment(
start_x=cx, start_y=cy,
end_x=nx, end_y=ny,
width=segment.width, layer=segment.layer, net_id=segment.net_id
))
cx, cy = nx, ny