-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathAutoroutingDrcEngine.ts
More file actions
1084 lines (986 loc) · 32.5 KB
/
Copy pathAutoroutingDrcEngine.ts
File metadata and controls
1084 lines (986 loc) · 32.5 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
import {
getBoundsFromPoints,
getSegmentIntersection,
pointToSegmentClosestPoint,
segmentToBoundsMinDistance,
segmentToCircleMinDistance,
segmentToSegmentMinDistance,
} from "@tscircuit/math-utils"
import type { ConnectivityMap } from "circuit-json-to-connectivity-map"
import {
applyToPoint,
applyToPoints,
compose,
inverse,
type Matrix,
rotateDEG,
translate,
} from "transformation-matrix"
import type {
SimpleRouteJson,
SimplifiedPcbTrace,
SimplifiedPcbTraces,
} from "../types"
import { getViaLayers } from "../utils/getViaLayers"
type Point = { x: number; y: number }
type Bounds = {
minX: number
minY: number
maxX: number
maxY: number
}
type WireRoutePoint = Extract<
SimplifiedPcbTrace["route"][number],
{ route_type: "wire" }
>
type TraceSegment = {
kind: "trace_segment"
order: number
traceId: string
netId: string
start: Point
end: Point
width: number
layer: string
pcbPortIds: string[]
}
type Via = {
kind: "via"
order: number
viaId: string
traceId: string
netId: string
x: number
y: number
diameter: number
layers: string[]
}
type StaticObstacle = {
kind: "obstacle"
obstacleType: "pcb_smtpad" | "pcb_plated_hole"
obstacleId: string
connectedTo: string[]
x: number
y: number
width: number
height: number
radius?: number
padToBoardTransform: Matrix
boardToPadTransform: Matrix
layers: string[]
pcbPortId?: string
}
type DynamicCollidable = TraceSegment | Via
export type AutoroutingDrcError = {
type:
| "pcb_trace_error"
| "pcb_via_clearance_error"
| "pcb_pad_pad_clearance_error"
error_type:
| "pcb_trace_error"
| "pcb_via_clearance_error"
| "pcb_pad_pad_clearance_error"
message: string
center?: Point
pcb_center?: Point
pcb_via_pair_net_relation?: "same_net" | "different_net"
[key: string]: unknown
}
export interface AutoroutingDrcResult {
errors: AutoroutingDrcError[]
errorsWithCenters: AutoroutingDrcError[]
locationAwareErrors: Array<AutoroutingDrcError & { center: Point }>
}
export interface AutoroutingDrcEngineOptions {
/**
* Copper-edge clearance used for trace-to-trace, trace-to-via, and
* trace-to-obstacle checks.
*/
traceClearance?: number
/**
* Copper-edge clearance used for both same-net and different-net via pairs.
* Values below 0.1 mm are clamped to the repair solver's safety minimum.
*/
viaClearance?: number
/** Copper-edge clearance used for via-to-pad checks. */
viaToPadClearance?: number
/**
* Optional broad-phase cell size. The engine derives one from the board
* bounds when this is omitted.
*/
spatialCellSize?: number
/**
* Optional connectivity map for designs whose equivalent net identifiers
* are not fully represented by the SRJ connection metadata.
*/
connMap?: ConnectivityMap
/**
* Include explicit trace/via owner ids for preload-aware repair targeting.
* Defaults to false so legacy callers receive the original error shape.
*/
includeTraceViaOwnerMetadata?: boolean
}
export interface AutoroutingDrcEngineRunStats {
traceCount: number
segmentCount: number
viaCount: number
obstacleCount: number
broadPhaseCandidateCount: number
exactCheckCount: number
}
const DEFAULT_TRACE_CLEARANCE = 0.1
const MIN_VIA_CLEARANCE = 0.1
const DEFAULT_VIA_TO_PAD_CLEARANCE = 0.1
const DRC_EPSILON = 5e-3
const POSITION_EPSILON = 1e-6
const expandBounds = (bounds: Bounds, amount: number): Bounds => ({
minX: bounds.minX - amount,
minY: bounds.minY - amount,
maxX: bounds.maxX + amount,
maxY: bounds.maxY + amount,
})
const getSegmentBounds = (segment: TraceSegment): Bounds =>
expandBounds(
{
minX: Math.min(segment.start.x, segment.end.x),
minY: Math.min(segment.start.y, segment.end.y),
maxX: Math.max(segment.start.x, segment.end.x),
maxY: Math.max(segment.start.y, segment.end.y),
},
segment.width / 2,
)
const getViaBounds = (via: Via): Bounds => {
const radius = via.diameter / 2
return {
minX: via.x - radius,
minY: via.y - radius,
maxX: via.x + radius,
maxY: via.y + radius,
}
}
const getObstacleBounds = (obstacle: StaticObstacle): Bounds =>
getBoundsFromPoints(
applyToPoints(obstacle.padToBoardTransform, [
{ x: -obstacle.width / 2, y: -obstacle.height / 2 },
{ x: obstacle.width / 2, y: -obstacle.height / 2 },
{ x: obstacle.width / 2, y: obstacle.height / 2 },
{ x: -obstacle.width / 2, y: obstacle.height / 2 },
]),
)!
const getObstacleLocalBounds = (obstacle: StaticObstacle): Bounds => ({
minX: -obstacle.width / 2,
minY: -obstacle.height / 2,
maxX: obstacle.width / 2,
maxY: obstacle.height / 2,
})
const getCellKey = (cellX: number, cellY: number) => `${cellX}:${cellY}`
class SpatialHash<T> {
private readonly cells = new Map<string, T[]>()
constructor(private readonly cellSize: number) {}
insert(item: T, bounds: Bounds) {
const minCellX = Math.floor(bounds.minX / this.cellSize)
const maxCellX = Math.floor(bounds.maxX / this.cellSize)
const minCellY = Math.floor(bounds.minY / this.cellSize)
const maxCellY = Math.floor(bounds.maxY / this.cellSize)
for (let cellX = minCellX; cellX <= maxCellX; cellX += 1) {
for (let cellY = minCellY; cellY <= maxCellY; cellY += 1) {
const key = getCellKey(cellX, cellY)
const items = this.cells.get(key)
if (items) {
items.push(item)
} else {
this.cells.set(key, [item])
}
}
}
}
query(bounds: Bounds): T[] {
const minCellX = Math.floor(bounds.minX / this.cellSize)
const maxCellX = Math.floor(bounds.maxX / this.cellSize)
const minCellY = Math.floor(bounds.minY / this.cellSize)
const maxCellY = Math.floor(bounds.maxY / this.cellSize)
const results = new Set<T>()
for (let cellX = minCellX; cellX <= maxCellX; cellX += 1) {
for (let cellY = minCellY; cellY <= maxCellY; cellY += 1) {
const items = this.cells.get(getCellKey(cellX, cellY))
if (!items) continue
for (const item of items) results.add(item)
}
}
return [...results]
}
}
const getClosestPointBetweenSegments = (
segmentA: TraceSegment,
segmentB: TraceSegment,
): Point => {
const intersection = getSegmentIntersection(
segmentA.start,
segmentA.end,
segmentB.start,
segmentB.end,
)
if (intersection) return intersection
const candidates = [
{
left: segmentA.start,
right: pointToSegmentClosestPoint(
segmentA.start,
segmentB.start,
segmentB.end,
),
},
{
left: segmentA.end,
right: pointToSegmentClosestPoint(
segmentA.end,
segmentB.start,
segmentB.end,
),
},
{
left: pointToSegmentClosestPoint(
segmentB.start,
segmentA.start,
segmentA.end,
),
right: segmentB.start,
},
{
left: pointToSegmentClosestPoint(
segmentB.end,
segmentA.start,
segmentA.end,
),
right: segmentB.end,
},
]
let closest = {
left: segmentA.start,
right: segmentB.start,
}
let closestDistance = Number.POSITIVE_INFINITY
for (const candidate of candidates) {
const distance = Math.hypot(
candidate.left.x - candidate.right.x,
candidate.left.y - candidate.right.y,
)
if (distance < closestDistance) {
closest = candidate
closestDistance = distance
}
}
return {
x: (closest.left.x + closest.right.x) / 2,
y: (closest.left.y + closest.right.y) / 2,
}
}
const getClosestPointBetweenSegmentAndPoint = (
segment: TraceSegment,
point: Point,
): Point => {
const closest = pointToSegmentClosestPoint(point, segment.start, segment.end)
return {
x: (closest.x + point.x) / 2,
y: (closest.y + point.y) / 2,
}
}
const getClosestPointBetweenSegmentAndBounds = (
segment: TraceSegment,
bounds: Bounds,
): Point => {
const boundsCenter = {
x: (bounds.minX + bounds.maxX) / 2,
y: (bounds.minY + bounds.maxY) / 2,
}
const pointOnSegment = pointToSegmentClosestPoint(
boundsCenter,
segment.start,
segment.end,
)
const pointOnBounds = {
x: Math.max(bounds.minX, Math.min(bounds.maxX, pointOnSegment.x)),
y: Math.max(bounds.minY, Math.min(bounds.maxY, pointOnSegment.y)),
}
return {
x: (pointOnSegment.x + pointOnBounds.x) / 2,
y: (pointOnSegment.y + pointOnBounds.y) / 2,
}
}
const getTracePortIds = (trace: SimplifiedPcbTrace) => {
const portIds = new Set<string>()
for (const routePoint of trace.route) {
if (routePoint.route_type !== "wire") continue
if (routePoint.start_pcb_port_id) {
portIds.add(routePoint.start_pcb_port_id)
}
if (routePoint.end_pcb_port_id) {
portIds.add(routePoint.end_pcb_port_id)
}
}
return [...portIds]
}
const createTraceErrorMessage = (
traceId: string,
otherDescription: string,
gap: number,
) =>
gap < 0
? `PCB trace ${traceId} overlaps with ${otherDescription} (accidental contact)`
: `PCB trace ${traceId} is too close to ${otherDescription} (gap: ${gap.toFixed(
3,
)}mm)`
/**
* A lightweight DRC evaluator for autorouting candidate scoring.
*
* Static SRJ obstacle geometry and connectivity aliases are compiled once in
* the constructor. Each evaluation builds only the route-dependent trace/via
* broad phase and performs exact distance checks for nearby objects.
*
* This intentionally implements the checks used by the repair solver's
* relaxed objective. It is not a replacement for the full-board
* `@tscircuit/checks` validation suite.
*/
export class AutoroutingDrcEngine {
private readonly traceClearance: number
private readonly viaClearance: number
private readonly viaToPadClearance: number
private readonly cellSize: number
private readonly connMap?: ConnectivityMap
private readonly includeTraceViaOwnerMetadata: boolean
private readonly canonicalNetByAlias = new Map<string, string>()
private readonly connMapNetByCanonicalNet = new Map<string, string>()
private readonly obstacles: StaticObstacle[]
private readonly obstacleIndexesByLayer = new Map<
string,
SpatialHash<StaticObstacle>
>()
lastRunStats: AutoroutingDrcEngineRunStats = {
traceCount: 0,
segmentCount: 0,
viaCount: 0,
obstacleCount: 0,
broadPhaseCandidateCount: 0,
exactCheckCount: 0,
}
constructor(
private readonly srj: SimpleRouteJson,
options: AutoroutingDrcEngineOptions = {},
) {
this.traceClearance = options.traceClearance ?? DEFAULT_TRACE_CLEARANCE
this.viaClearance = Math.max(
options.viaClearance ?? MIN_VIA_CLEARANCE,
MIN_VIA_CLEARANCE,
)
this.viaToPadClearance =
options.viaToPadClearance ??
this.srj.minViaEdgeToPadEdgeClearance ??
DEFAULT_VIA_TO_PAD_CLEARANCE
this.connMap = options.connMap
this.includeTraceViaOwnerMetadata =
options.includeTraceViaOwnerMetadata ?? false
this.cellSize = options.spatialCellSize ?? this.getDefaultSpatialCellSize()
if (!Number.isFinite(this.traceClearance) || this.traceClearance < 0) {
throw new Error("traceClearance must be a non-negative finite number")
}
if (!Number.isFinite(this.viaClearance)) {
throw new Error("viaClearance must be a finite number")
}
if (
!Number.isFinite(this.viaToPadClearance) ||
this.viaToPadClearance < 0
) {
throw new Error("viaToPadClearance must be a non-negative finite number")
}
if (!Number.isFinite(this.cellSize) || this.cellSize <= 0) {
throw new Error("spatialCellSize must be a positive finite number")
}
this.compileConnectionAliases()
this.obstacles = this.compileStaticObstacles()
this.indexStaticObstacles()
}
private getDefaultSpatialCellSize() {
const boardWidth = Math.max(0, this.srj.bounds.maxX - this.srj.bounds.minX)
const boardHeight = Math.max(0, this.srj.bounds.maxY - this.srj.bounds.minY)
return Math.max(
0.25,
Math.max(boardWidth, boardHeight) / 64,
(this.srj.minViaDiameter ?? 0.3) +
Math.max(this.traceClearance, this.viaToPadClearance),
)
}
private compileConnectionAliases() {
const connMapNetsByCanonicalNet = new Map<string, Set<string>>()
for (const connection of this.srj.connections) {
const canonicalNet =
connection.netConnectionName ??
connection.rootConnectionName ??
connection.name
const aliases = [
connection.name,
connection.rootConnectionName,
connection.netConnectionName,
...(connection.mergedConnectionNames ?? []),
...connection.pointsToConnect.flatMap((point) => [
point.pointId,
point.pcb_port_id,
]),
]
for (const alias of aliases) {
if (!alias) continue
this.canonicalNetByAlias.set(alias, canonicalNet)
const connMapNetId = this.connMap?.getNetConnectedToId(alias)
if (!connMapNetId) continue
let connMapNets = connMapNetsByCanonicalNet.get(canonicalNet)
if (!connMapNets) {
connMapNets = new Set<string>()
connMapNetsByCanonicalNet.set(canonicalNet, connMapNets)
}
connMapNets.add(connMapNetId)
}
this.canonicalNetByAlias.set(canonicalNet, canonicalNet)
}
// A sparse connectivity map may recognize only one alias in an SRJ net.
// Promote only unambiguous map nets across the rest of that alias group.
for (const [canonicalNet, connMapNets] of connMapNetsByCanonicalNet) {
if (connMapNets.size !== 1) continue
this.connMapNetByCanonicalNet.set(
canonicalNet,
connMapNets.values().next().value!,
)
}
}
private resolveNetId(id: string) {
const connMapNetId = this.connMap?.getNetConnectedToId(id)
if (connMapNetId) return connMapNetId
const canonicalNet = this.canonicalNetByAlias.get(id)
if (!canonicalNet) return id
return this.connMapNetByCanonicalNet.get(canonicalNet) ?? canonicalNet
}
private areConnected(left: string, right: string) {
if (left === right) return true
if (this.connMap?.areIdsConnected(left, right)) return true
return this.resolveNetId(left) === this.resolveNetId(right)
}
private compileStaticObstacles() {
const obstacles: StaticObstacle[] = []
const addedSmtPadIds = new Set<string>()
const addedPlatedHoleIds = new Set<string>()
for (const obstacle of this.srj.obstacles) {
if (obstacle.layers.length === 0) continue
const smtPadId = obstacle.connectedTo.find((id) =>
id.startsWith("pcb_smtpad_"),
)
const platedHoleId = obstacle.connectedTo.find((id) =>
id.startsWith("pcb_plated_hole_"),
)
const pcbPortId = obstacle.connectedTo.find((id) =>
id.startsWith("pcb_port_"),
)
if (!smtPadId && !platedHoleId && !pcbPortId) continue
const isMultiLayer = obstacle.layers.length > 1
const obstacleType = isMultiLayer
? ("pcb_plated_hole" as const)
: ("pcb_smtpad" as const)
const obstacleId = isMultiLayer
? (platedHoleId ??
`pcb_plated_hole_${obstacle.center.x.toFixed(
3,
)}_${obstacle.center.y.toFixed(3)}`)
: (smtPadId ??
`pcb_smtpad_${obstacle.center.x.toFixed(
3,
)}_${obstacle.center.y.toFixed(3)}`)
const addedIds = isMultiLayer ? addedPlatedHoleIds : addedSmtPadIds
if (addedIds.has(obstacleId)) continue
addedIds.add(obstacleId)
const hasRotation =
typeof obstacle.ccwRotationDegrees === "number" &&
Number.isFinite(obstacle.ccwRotationDegrees)
const padToBoardTransform = compose(
translate(obstacle.center.x, obstacle.center.y),
rotateDEG(hasRotation ? obstacle.ccwRotationDegrees! : 0),
)
// Explicit rotation describes a rectangular pad, including square pads.
// Only legacy, unrotated multilayer obstacles use the circular inference.
const isCircular =
!hasRotation &&
isMultiLayer &&
Math.abs(obstacle.width - obstacle.height) < 0.001
obstacles.push({
kind: "obstacle",
obstacleType,
obstacleId,
connectedTo: obstacle.connectedTo,
x: obstacle.center.x,
y: obstacle.center.y,
width: obstacle.width,
height: obstacle.height,
padToBoardTransform,
boardToPadTransform: inverse(padToBoardTransform),
...(isCircular
? { radius: Math.max(obstacle.width, obstacle.height) / 2 }
: {}),
layers: obstacle.layers,
...(pcbPortId ? { pcbPortId } : {}),
})
}
return obstacles
}
private indexStaticObstacles() {
for (const obstacle of this.obstacles) {
const bounds = expandBounds(
getObstacleBounds(obstacle),
Math.max(this.traceClearance, this.viaToPadClearance),
)
for (const layer of obstacle.layers) {
let index = this.obstacleIndexesByLayer.get(layer)
if (!index) {
index = new SpatialHash<StaticObstacle>(this.cellSize)
this.obstacleIndexesByLayer.set(layer, index)
}
index.insert(obstacle, bounds)
}
}
}
private collectDynamicGeometry(traces: SimplifiedPcbTraces) {
const segments: TraceSegment[] = []
const vias: Via[] = []
const viaLocations = new Set<string>()
for (const trace of traces) {
const netId = this.resolveNetId(trace.connection_name)
const pcbPortIds = getTracePortIds(trace)
for (let index = 0; index < trace.route.length - 1; index += 1) {
const start = trace.route[index]
const end = trace.route[index + 1]
if (
start?.route_type !== "wire" ||
end?.route_type !== "wire" ||
start.layer !== end.layer
) {
continue
}
if (
Math.abs(start.x - end.x) <= POSITION_EPSILON &&
Math.abs(start.y - end.y) <= POSITION_EPSILON
) {
continue
}
segments.push({
kind: "trace_segment",
order: segments.length,
traceId: trace.pcb_trace_id,
netId,
start: { x: start.x, y: start.y },
end: { x: end.x, y: end.y },
width: getWireWidth(start, end),
layer: start.layer,
pcbPortIds,
})
}
for (const routePoint of trace.route) {
if (routePoint.route_type !== "via") continue
const locationKey = `${routePoint.x},${routePoint.y},${routePoint.from_layer},${routePoint.to_layer}`
if (viaLocations.has(locationKey)) continue
viaLocations.add(locationKey)
vias.push({
kind: "via",
order: vias.length,
viaId: `via_${vias.length}`,
traceId: trace.pcb_trace_id,
netId,
x: routePoint.x,
y: routePoint.y,
diameter: routePoint.via_diameter ?? this.srj.minViaDiameter ?? 0.3,
layers: getViaLayers(routePoint, this.srj.layerCount),
})
}
}
return { segments, vias }
}
private buildDynamicIndexes(
segments: TraceSegment[],
vias: Via[],
): Map<string, SpatialHash<DynamicCollidable>> {
const indexes = new Map<string, SpatialHash<DynamicCollidable>>()
const addToLayer = (
layer: string,
item: DynamicCollidable,
bounds: Bounds,
) => {
let index = indexes.get(layer)
if (!index) {
index = new SpatialHash<DynamicCollidable>(this.cellSize)
indexes.set(layer, index)
}
index.insert(item, expandBounds(bounds, this.traceClearance))
}
for (const segment of segments) {
addToLayer(segment.layer, segment, getSegmentBounds(segment))
}
for (const via of vias) {
for (const layer of via.layers) {
addToLayer(layer, via, getViaBounds(via))
}
}
return indexes
}
private obstacleSharesNet(netId: string, obstacle: StaticObstacle) {
return obstacle.connectedTo.some((connectedId) =>
this.areConnected(netId, connectedId),
)
}
private checkTracePair(
segmentA: TraceSegment,
segmentB: TraceSegment,
): AutoroutingDrcError | undefined {
if (this.areConnected(segmentA.netId, segmentB.netId)) return undefined
this.lastRunStats.exactCheckCount += 1
const gap =
segmentToSegmentMinDistance(
segmentA.start,
segmentA.end,
segmentB.start,
segmentB.end,
) -
segmentA.width / 2 -
segmentB.width / 2
if (gap > this.traceClearance - DRC_EPSILON) return undefined
const forwardId = `overlap_${segmentA.traceId}_${segmentB.traceId}`
return {
type: "pcb_trace_error",
error_type: "pcb_trace_error",
message: createTraceErrorMessage(
segmentA.traceId,
`PCB trace ${segmentB.traceId}`,
gap,
),
pcb_trace_id: segmentA.traceId,
source_trace_id: "",
pcb_trace_error_id: forwardId,
minimum_clearance: this.traceClearance,
actual_clearance: gap,
pcb_component_ids: [],
pcb_port_ids: [
...new Set([...segmentA.pcbPortIds, ...segmentB.pcbPortIds]),
],
center: getClosestPointBetweenSegments(segmentA, segmentB),
}
}
private checkTraceVia(
segment: TraceSegment,
via: Via,
): AutoroutingDrcError | undefined {
if (this.areConnected(segment.netId, via.netId)) return undefined
this.lastRunStats.exactCheckCount += 1
const gap =
segmentToCircleMinDistance(segment.start, segment.end, {
x: via.x,
y: via.y,
radius: via.diameter / 2,
}) -
segment.width / 2
if (gap > this.traceClearance - DRC_EPSILON) return undefined
const errorId = `overlap_${segment.traceId}_${via.viaId}`
return {
type: "pcb_trace_error",
error_type: "pcb_trace_error",
message: createTraceErrorMessage(
segment.traceId,
`pcb_via "${via.viaId}"`,
gap,
),
pcb_trace_id: segment.traceId,
...(this.includeTraceViaOwnerMetadata
? {
pcb_trace_ids: [segment.traceId, via.traceId],
pcb_via_id: via.viaId,
pcb_via_ids: [via.viaId],
}
: {}),
source_trace_id: "",
pcb_trace_error_id: errorId,
minimum_clearance: this.traceClearance,
actual_clearance: gap,
pcb_component_ids: [],
pcb_port_ids: segment.pcbPortIds,
center: getClosestPointBetweenSegmentAndPoint(segment, via),
}
}
private checkTraceObstacle(
segment: TraceSegment,
obstacle: StaticObstacle,
): AutoroutingDrcError | undefined {
if (this.obstacleSharesNet(segment.netId, obstacle)) return undefined
this.lastRunStats.exactCheckCount += 1
const obstacleBounds = getObstacleLocalBounds(obstacle)
const localSegment = {
...segment,
start: applyToPoint(obstacle.boardToPadTransform, segment.start),
end: applyToPoint(obstacle.boardToPadTransform, segment.end),
}
const shapeDistance =
obstacle.radius === undefined
? segmentToBoundsMinDistance(
localSegment.start,
localSegment.end,
obstacleBounds,
)
: segmentToCircleMinDistance(segment.start, segment.end, {
x: obstacle.x,
y: obstacle.y,
radius: obstacle.radius,
})
const gap = shapeDistance - segment.width / 2
if (gap + DRC_EPSILON >= this.traceClearance) return undefined
const errorId = `overlap_${segment.traceId}_${obstacle.obstacleId}`
return {
type: "pcb_trace_error",
error_type: "pcb_trace_error",
message: createTraceErrorMessage(
segment.traceId,
`${obstacle.obstacleType} "${obstacle.obstacleId}"`,
gap,
),
pcb_trace_id: segment.traceId,
source_trace_id: "",
pcb_trace_error_id: errorId,
minimum_clearance: this.traceClearance,
actual_clearance: gap,
pcb_component_ids: [],
pcb_port_ids: [
...new Set([
...segment.pcbPortIds,
...(obstacle.pcbPortId ? [obstacle.pcbPortId] : []),
]),
],
center:
obstacle.radius === undefined
? applyToPoint(
obstacle.padToBoardTransform,
getClosestPointBetweenSegmentAndBounds(
localSegment,
obstacleBounds,
),
)
: getClosestPointBetweenSegmentAndPoint(segment, obstacle),
}
}
private checkViaObstacle(
via: Via,
obstacle: StaticObstacle,
): AutoroutingDrcError | undefined {
if (this.obstacleSharesNet(via.netId, obstacle)) return undefined
this.lastRunStats.exactCheckCount += 1
const obstacleBounds = getObstacleLocalBounds(obstacle)
const localVia = applyToPoint(obstacle.boardToPadTransform, via)
const pointToObstacleDistance =
obstacle.radius === undefined
? Math.hypot(
Math.max(
obstacleBounds.minX - localVia.x,
0,
localVia.x - obstacleBounds.maxX,
),
Math.max(
obstacleBounds.minY - localVia.y,
0,
localVia.y - obstacleBounds.maxY,
),
)
: Math.hypot(via.x - obstacle.x, via.y - obstacle.y) - obstacle.radius
const gap = pointToObstacleDistance - via.diameter / 2
if (gap + DRC_EPSILON >= this.viaToPadClearance) return undefined
const errorId = `via_pad_clearance_${via.viaId}_${obstacle.obstacleId}`
const center = {
x: (via.x + obstacle.x) / 2,
y: (via.y + obstacle.y) / 2,
}
return {
type: "pcb_pad_pad_clearance_error",
error_type: "pcb_pad_pad_clearance_error",
pcb_pad_pad_clearance_error_id: errorId,
message: `pcb_via "${via.viaId}" and ${obstacle.obstacleType} "${obstacle.obstacleId}" are too close (gap: ${gap.toFixed(3)}mm)`,
pcb_trace_id: via.traceId,
pcb_pad_ids: [via.viaId, obstacle.obstacleId],
pcb_via_ids: [via.viaId],
minimum_clearance: this.viaToPadClearance,
actual_clearance: gap,
center,
}
}
private checkViaPairs(vias: Via[]): AutoroutingDrcError[] {
if (vias.length < 2) return []
const errors: AutoroutingDrcError[] = []
const index = new SpatialHash<Via>(this.cellSize)
for (const via of vias) {
index.insert(via, expandBounds(getViaBounds(via), this.viaClearance))
}
for (const viaA of vias) {
for (const viaB of index.query(getViaBounds(viaA))) {
this.lastRunStats.broadPhaseCandidateCount += 1
if (viaB.order <= viaA.order) continue
this.lastRunStats.exactCheckCount += 1
const centerDistance = Math.hypot(viaA.x - viaB.x, viaA.y - viaB.y)
if (centerDistance <= POSITION_EPSILON) continue
const gap = centerDistance - viaA.diameter / 2 - viaB.diameter / 2
if (gap + DRC_EPSILON >= this.viaClearance) continue
const sameNet = this.areConnected(viaA.netId, viaB.netId)
const pairId = [viaA.viaId, viaB.viaId].sort().join("_")
const center = {
x: (viaA.x + viaB.x) / 2,
y: (viaA.y + viaB.y) / 2,
}
errors.push({
type: "pcb_via_clearance_error",
error_type: "pcb_via_clearance_error",
pcb_error_id: `${
sameNet ? "same_net" : "different_net"
}_vias_close_${pairId}`,
message: `Vias ${viaA.viaId} and ${viaB.viaId}${
sameNet ? "" : " from different nets"
} are too close together (gap: ${gap.toFixed(3)}mm)`,
pcb_via_ids: [viaA.viaId, viaB.viaId],
...(this.includeTraceViaOwnerMetadata
? { pcb_trace_ids: [viaA.traceId, viaB.traceId] }
: {}),
pcb_via_pair_net_relation: sameNet ? "same_net" : "different_net",
minimum_clearance: this.viaClearance,
actual_clearance: gap,
pcb_center: center,
center,
})
}
}
return errors
}
evaluate(traces: SimplifiedPcbTraces): AutoroutingDrcResult {
return this.evaluateInternal(traces, true)
}
/**
* Evaluates the established trace/via DRC set used by the first repair
* stage. Via-to-pad errors remain part of the normal complete evaluation and
* are handled by the subsequent staged repair pass.
*/
evaluateLegacy(traces: SimplifiedPcbTraces): AutoroutingDrcResult {
return this.evaluateInternal(traces, false)
}
private evaluateInternal(
traces: SimplifiedPcbTraces,
includeViaPadErrors: boolean,
): AutoroutingDrcResult {
const { segments, vias } = this.collectDynamicGeometry(traces)
const dynamicIndexesByLayer = this.buildDynamicIndexes(segments, vias)
const detectedTraceErrors: AutoroutingDrcError[] = []
const detectedViaPadErrors: AutoroutingDrcError[] = []
this.lastRunStats = {
traceCount: traces.length,
segmentCount: segments.length,
viaCount: vias.length,
obstacleCount: this.obstacles.length,
broadPhaseCandidateCount: 0,
exactCheckCount: 0,
}
for (const segment of segments) {
const queryBounds = getSegmentBounds(segment)
const dynamicCandidates =
dynamicIndexesByLayer.get(segment.layer)?.query(queryBounds) ?? []
const obstacleCandidates =
this.obstacleIndexesByLayer.get(segment.layer)?.query(queryBounds) ?? []
for (const candidate of dynamicCandidates) {
this.lastRunStats.broadPhaseCandidateCount += 1
if (
candidate.kind === "trace_segment" &&
candidate.order <= segment.order
) {
continue
}
const error =
candidate.kind === "trace_segment"
? this.checkTracePair(segment, candidate)
: this.checkTraceVia(segment, candidate)
if (error) detectedTraceErrors.push(error)
}
for (const obstacle of obstacleCandidates) {
this.lastRunStats.broadPhaseCandidateCount += 1
const error = this.checkTraceObstacle(segment, obstacle)
if (error) detectedTraceErrors.push(error)