forked from tscircuit/core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGroup.ts
More file actions
1488 lines (1302 loc) · 49.4 KB
/
Group.ts
File metadata and controls
1488 lines (1302 loc) · 49.4 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 { convertSrjToGraphicsObject } from "@tscircuit/capacity-autorouter"
import { getBoundsFromPoints } from "@tscircuit/math-utils"
import {
type AutorouterConfig,
type SubcircuitGroupProps,
groupProps,
} from "@tscircuit/props"
import {
type AnyCircuitElement,
type LayerRef,
type PcbTrace,
type PcbVia,
type SchematicComponent,
type SchematicPort,
distance,
} from "circuit-json"
import Debug from "debug"
import type { GraphicsObject } from "graphics-debug"
import type { PrimitiveComponent } from "lib/components/base-components/PrimitiveComponent"
import { AutorouterError } from "lib/errors/AutorouterError"
import { TscircuitAutorouter } from "lib/utils/autorouting/CapacityMeshAutorouter"
import type { GenericLocalAutorouter } from "lib/utils/autorouting/GenericLocalAutorouter"
import type { SimplifiedPcbTrace } from "lib/utils/autorouting/SimpleRouteJson"
import type { SimpleRouteJson } from "lib/utils/autorouting/SimpleRouteJson"
import { createSourceTracesFromOffboardConnections } from "lib/utils/autorouting/createSourceTracesFromOffboardConnections"
import { getPresetAutoroutingConfig } from "lib/utils/autorouting/getPresetAutoroutingConfig"
import { getBoundsOfPcbComponents } from "lib/utils/get-bounds-of-pcb-components"
import { getViaDiameterDefaults } from "lib/utils/pcbStyle/getViaDiameterDefaults"
import { getSimpleRouteJsonFromCircuitJson } from "lib/utils/public-exports"
import { z } from "zod"
import { NormalComponent } from "../../base-components/NormalComponent/NormalComponent"
import type { Trace } from "../Trace/Trace"
import { TraceHint } from "../TraceHint"
import { Group_doInitialPcbCalcPlacementResolution } from "./Group_doInitialPcbCalcPlacementResolution"
import { Group_doInitialPcbComponentAnchorAlignment } from "./Group_doInitialPcbComponentAnchorAlignment"
import { Group_doInitialPcbLayoutFlex } from "./Group_doInitialPcbLayoutFlex"
import { Group_doInitialPcbLayoutGrid } from "./Group_doInitialPcbLayoutGrid"
import { Group_doInitialPcbLayoutPack } from "./Group_doInitialPcbLayoutPack/Group_doInitialPcbLayoutPack"
import { Group_doInitialSchematicLayoutFlex } from "./Group_doInitialSchematicLayoutFlex"
import { Group_doInitialSchematicLayoutGrid } from "./Group_doInitialSchematicLayoutGrid"
import { Group_doInitialSchematicLayoutMatchAdapt } from "./Group_doInitialSchematicLayoutMatchAdapt"
import { Group_doInitialSchematicLayoutMatchPack } from "./Group_doInitialSchematicLayoutMatchPack"
import { Group_doInitialSchematicTraceRender } from "./Group_doInitialSchematicTraceRender/Group_doInitialSchematicTraceRender"
import { Group_doInitialSimulationSpiceEngineRender } from "./Group_doInitialSimulationSpiceEngineRender"
import { Group_doInitialSourceAddConnectivityMapKey } from "./Group_doInitialSourceAddConnectivityMapKey"
import type { RoutingPhasePlan } from "./GroupRoutingPhasePlan"
import { Group_getRoutingPhasePlans } from "./Group_getRoutingPhasePlans"
import {
Group_filterSimpleRouteJsonForPhase,
Group_getObstaclesFromRoutedTraces,
Group_hasPhasedAutorouting,
} from "./Group_phasedAutoroutingUtils"
import type { ISubcircuit } from "./Subcircuit/ISubcircuit"
import { addPortIdsToTracesAtJumperPads } from "./add-port-ids-to-traces-at-jumper-pads"
import { insertAutoplacedJumpers } from "./insert-autoplaced-jumpers"
import { splitPcbTracesOnJumperSegments } from "./split-pcb-traces-on-jumper-segments"
import { computeCenterFromAnchorPosition } from "./utils/computeCenterFromAnchorPosition"
export class Group<Props extends z.ZodType<any, any, any> = typeof groupProps>
extends NormalComponent<Props>
implements ISubcircuit
{
pcb_group_id: string | null = null
schematic_group_id: string | null = null
subcircuit_id: string | null = null
_hasStartedAsyncAutorouting = false
_isInflatedFromCircuitJson = false
_isolatedCircuitJson: AnyCircuitElement[] | null = null
get _isIsolatedSubcircuit(): boolean {
return Boolean(this.getInheritedProperty("_subcircuitCachingEnabled"))
}
_normalComponentNameMap: Map<string, NormalComponent[]> | null = null
/**
* Returns a cached map of component names to NormalComponent instances within this subcircuit.
* The map is built lazily on first access and cached for subsequent calls.
*/
getNormalComponentNameMap(): Map<string, NormalComponent[]> {
if (this._normalComponentNameMap) {
return this._normalComponentNameMap
}
const nameMap = new Map<string, NormalComponent[]>()
const collectNamedComponents = (component: PrimitiveComponent) => {
if ((component as NormalComponent)._isNormalComponent && component.name) {
const componentsWithSameName = nameMap.get(component.name)
if (componentsWithSameName) {
componentsWithSameName.push(component as NormalComponent)
} else {
nameMap.set(component.name, [component as NormalComponent])
}
}
for (const child of component.children) {
if (!child.isSubcircuit) collectNamedComponents(child)
}
}
for (const child of this.children) {
if (!child.isSubcircuit) collectNamedComponents(child)
}
this._normalComponentNameMap = nameMap
return nameMap
}
_asyncAutoroutingResult: {
output_simple_route_json?: SimpleRouteJson
output_pcb_traces?: (PcbTrace | PcbVia)[]
output_jumpers?: Array<{
jumper_footprint: string
center: { x: number; y: number }
orientation: string
pads: Array<{
center: { x: number; y: number }
width: number
height: number
layer: string
}>
}>
} | null = null
get config() {
return {
zodProps: groupProps as unknown as Props,
componentName: "Group",
}
}
doInitialSourceGroupRender() {
const { db } = this.root!
const hasExplicitName =
typeof (this._parsedProps as { name?: unknown }).name === "string" &&
(this._parsedProps as { name?: string }).name!.length > 0
const source_group = db.source_group.insert({
name: this.name,
is_subcircuit: this.isSubcircuit,
was_automatically_named: !hasExplicitName,
})
this.source_group_id = source_group.source_group_id
if (this.isSubcircuit) {
this.subcircuit_id = `subcircuit_${source_group.source_group_id}` as any
db.source_group.update(source_group.source_group_id, {
subcircuit_id: this.subcircuit_id!,
})
}
}
doInitialSourceRender() {
const { db } = this.root!
for (const child of this.children) {
db.source_component.update(child.source_component_id!, {
source_group_id: this.source_group_id!,
})
}
}
doInitialSourceParentAttachment() {
const { db } = this.root!
const parentGroup = this.parent?.getGroup?.()
if (parentGroup?.source_group_id) {
db.source_group.update(this.source_group_id!, {
parent_source_group_id: parentGroup.source_group_id,
})
}
if (!this.isSubcircuit) return
const parent_subcircuit_id = this.parent?.getSubcircuit?.()?.subcircuit_id
if (!parent_subcircuit_id) return
db.source_group.update(this.source_group_id!, {
parent_subcircuit_id,
})
}
doInitialPcbComponentRender() {
if (this.root?.pcbDisabled) return
const { db } = this.root!
const { _parsedProps: props } = this
const groupProps = props as SubcircuitGroupProps
const hasOutline = groupProps.outline && groupProps.outline.length > 0
const numericOutline = hasOutline
? groupProps.outline!.map((point) => ({
x: distance.parse(point.x),
y: distance.parse(point.y),
}))
: undefined
const ctx = this.props
const anchorPosition = this._getGlobalPcbPositionBeforeLayout()
const center = computeCenterFromAnchorPosition(anchorPosition, ctx)
const pcb_group = db.pcb_group.insert({
is_subcircuit: this.isSubcircuit,
subcircuit_id: this.subcircuit_id ?? this.getSubcircuit()?.subcircuit_id!,
name: this.name,
anchor_position: anchorPosition,
center,
...(hasOutline ? { outline: numericOutline } : { width: 0, height: 0 }),
pcb_component_ids: [],
source_group_id: this.source_group_id!,
autorouter_configuration: props.autorouter
? {
trace_clearance: props.autorouter.traceClearance,
}
: undefined,
anchor_alignment: props.pcbAnchorAlignment ?? null,
})
this.pcb_group_id = pcb_group.pcb_group_id
for (const child of this.children) {
db.pcb_component.update(child.pcb_component_id!, {
pcb_group_id: pcb_group.pcb_group_id,
})
}
}
doInitialPcbPrimitiveRender(): void {
this.calculatePcbGroupBounds()
}
calculatePcbGroupBounds() {
if (!this.pcb_group_id) return
if (this.root?.pcbDisabled) return
const { db } = this.root!
const props = this._parsedProps as SubcircuitGroupProps
const hasOutline = props.outline && props.outline.length > 0
// Check if explicit positioning is provided (pcbX or pcbY)
const hasExplicitPositioning =
this._parsedProps.pcbX !== undefined ||
this._parsedProps.pcbY !== undefined
// If outline is specified, calculate bounds from outline
if (hasOutline) {
const numericOutline = props.outline!.map((point) => ({
x: distance.parse(point.x),
y: distance.parse(point.y),
}))
const outlineBounds = getBoundsFromPoints(numericOutline)
if (!outlineBounds) return
const centerX = (outlineBounds.minX + outlineBounds.maxX) / 2
const centerY = (outlineBounds.minY + outlineBounds.maxY) / 2
// Preserve explicit positioning when pcbX/pcbY are set
// Otherwise use calculated center from outline
const center = hasExplicitPositioning
? (db.pcb_group.get(this.pcb_group_id)?.center ?? {
x: centerX,
y: centerY,
})
: { x: centerX, y: centerY }
// For groups with outline, don't set width/height
db.pcb_group.update(this.pcb_group_id, {
center,
})
return
}
// Original logic for groups without outline
const bounds = getBoundsOfPcbComponents(this.children)
let width = bounds.width
let height = bounds.height
let centerX = (bounds.minX + bounds.maxX) / 2
let centerY = (bounds.minY + bounds.maxY) / 2
if (this.isSubcircuit) {
const { padLeft, padRight, padTop, padBottom } = this._resolvePcbPadding()
width += padLeft + padRight
height += padTop + padBottom
centerX += (padRight - padLeft) / 2
centerY += (padTop - padBottom) / 2
}
// Preserve explicit positioning when pcbX/pcbY are set
// Otherwise use calculated center from child bounds
const center = hasExplicitPositioning
? (db.pcb_group.get(this.pcb_group_id)?.center ?? {
x: centerX,
y: centerY,
})
: { x: centerX, y: centerY }
db.pcb_group.update(this.pcb_group_id, {
width: Number(props.width ?? width),
height: Number(props.height ?? height),
center,
})
}
updatePcbPrimitiveRender(): void {
this.calculatePcbGroupBounds()
}
unnamedElementCounter: Record<string, number> = {}
getNextAvailableName(elm: PrimitiveComponent): string {
this.unnamedElementCounter[elm.lowercaseComponentName] ??= 1
return `unnamed_${elm.lowercaseComponentName}${this.unnamedElementCounter[elm.lowercaseComponentName]++}`
}
_resolvePcbPadding(): {
padLeft: number
padRight: number
padTop: number
padBottom: number
} {
const props = this._parsedProps as SubcircuitGroupProps
const layout = props.pcbLayout
// Helper function to get a padding value from layout or props
const getPaddingValue = (key: string): number | undefined => {
const layoutValue = layout?.[key as keyof typeof layout] as
| number
| undefined
const propsValue = props[key as keyof typeof props] as number | undefined
if (typeof layoutValue === "number") return layoutValue
if (typeof propsValue === "number") return propsValue
return undefined
}
const generalPadding = getPaddingValue("padding") ?? 0
const paddingX = getPaddingValue("paddingX")
const paddingY = getPaddingValue("paddingY")
const padLeft = getPaddingValue("paddingLeft") ?? paddingX ?? generalPadding
const padRight =
getPaddingValue("paddingRight") ?? paddingX ?? generalPadding
const padTop = getPaddingValue("paddingTop") ?? paddingY ?? generalPadding
const padBottom =
getPaddingValue("paddingBottom") ?? paddingY ?? generalPadding
return { padLeft, padRight, padTop, padBottom }
}
doInitialCreateTraceHintsFromProps(): void {
const { _parsedProps: props } = this
const { db } = this.root!
const groupProps = props as SubcircuitGroupProps
if (!this.isSubcircuit) return
const manualTraceHints = groupProps.manualEdits?.manual_trace_hints
if (!manualTraceHints) return
for (const manualTraceHint of manualTraceHints) {
this.add(
new TraceHint({
for: manualTraceHint.pcb_port_selector,
offsets: manualTraceHint.offsets,
}),
)
}
}
doInitialSourceAddConnectivityMapKey(): void {
Group_doInitialSourceAddConnectivityMapKey(this)
}
_areChildSubcircuitsRouted(): boolean {
const subcircuitChildren = this.selectAll("group").filter(
(g) => g.isSubcircuit,
) as Group[]
for (const subcircuitChild of subcircuitChildren) {
if (
subcircuitChild._shouldRouteAsync() &&
!subcircuitChild._asyncAutoroutingResult
) {
return false
}
}
return true
}
_shouldRouteAsync(): boolean {
const autorouter = this._getAutorouterConfig()
if (autorouter.groupMode === "sequential-trace") return false
// Local subcircuit mode should use async routing with the CapacityMeshAutorouter
if (autorouter.local && autorouter.groupMode === "subcircuit") return true
// Remote autorouting always uses async
if (!autorouter.local) return true
return false
}
_getRoutingPhasePlans(): RoutingPhasePlan[] {
return Group_getRoutingPhasePlans(this)
}
_hasTracesToRoute(): boolean {
const debug = Debug("tscircuit:core:_hasTracesToRoute")
const routingPhasePlans = this._getRoutingPhasePlans()
let traceCount = 0
for (const routingPhasePlan of routingPhasePlans) {
traceCount += routingPhasePlan.traces.length
}
debug(`[${this.getString()}] has ${traceCount} traces to route`)
return traceCount > 0
}
async _runEffectMakeHttpAutoroutingRequest() {
const { db } = this.root!
const debug = Debug("tscircuit:core:_runEffectMakeHttpAutoroutingRequest")
const props = this._parsedProps as SubcircuitGroupProps
const autorouterConfig = this._getAutorouterConfig()
// Remote autorouting
const serverUrl = autorouterConfig.serverUrl!
const serverMode = autorouterConfig.serverMode!
const fetchWithDebug = (url: string, options: RequestInit) => {
debug("fetching", url)
if (options.headers) {
// @ts-ignore
options.headers["Tscircuit-Core-Version"] = this.root?.getCoreVersion()!
}
return fetch(url, options)
}
// Only include source and pcb elements
const pcbAndSourceCircuitJson = this.root!.db.toArray().filter(
(element) => {
return (
element.type.startsWith("source_") || element.type.startsWith("pcb_")
)
},
)
if (serverMode === "solve-endpoint") {
// Legacy solve endpoint mode
if (this.props.autorouter?.inputFormat === "simplified") {
const { autorouting_result } = await fetchWithDebug(
`${serverUrl}/autorouting/solve`,
{
method: "POST",
body: JSON.stringify({
input_simple_route_json: getSimpleRouteJsonFromCircuitJson({
db,
minTraceWidth: this.props.autorouter?.minTraceWidth ?? 0.15,
nominalTraceWidth: this.props.nominalTraceWidth,
subcircuit_id: this.subcircuit_id,
subcircuitComponent: this,
}).simpleRouteJson,
subcircuit_id: this.subcircuit_id!,
}),
headers: {
"Content-Type": "application/json",
},
},
).then((r) => r.json())
this._asyncAutoroutingResult = autorouting_result
this._markDirty("PcbTraceRender")
return
}
const { autorouting_result } = await fetchWithDebug(
`${serverUrl}/autorouting/solve`,
{
method: "POST",
body: JSON.stringify({
input_circuit_json: pcbAndSourceCircuitJson,
subcircuit_id: this.subcircuit_id!,
}),
headers: {
"Content-Type": "application/json",
},
},
).then((r) => r.json())
this._asyncAutoroutingResult = autorouting_result
this._markDirty("PcbTraceRender")
return
}
const { autorouting_job } = await fetchWithDebug(
`${serverUrl}/autorouting/jobs/create`,
{
method: "POST",
body: JSON.stringify({
input_circuit_json: pcbAndSourceCircuitJson,
provider: "freerouting",
autostart: true,
display_name: this.root?.name,
subcircuit_id: this.subcircuit_id,
server_cache_enabled: autorouterConfig.serverCacheEnabled,
}),
headers: {
"Content-Type": "application/json",
},
},
).then((r) => r.json())
// Poll until job is complete
while (true) {
const { autorouting_job: job } = (await fetchWithDebug(
`${serverUrl}/autorouting/jobs/get`,
{
method: "POST",
body: JSON.stringify({
autorouting_job_id: autorouting_job.autorouting_job_id,
}),
headers: { "Content-Type": "application/json" },
},
).then((r) => r.json())) as {
autorouting_job: {
autorouting_job_id: string
is_running: boolean
is_started: boolean
is_finished: boolean
has_error: boolean
error: { message: string } | null
autorouting_provider: "freerouting" | "tscircuit"
created_at: string
started_at?: string
finished_at?: string
}
}
if (job.is_finished) {
const { autorouting_job_output } = await fetchWithDebug(
`${serverUrl}/autorouting/jobs/get_output`,
{
method: "POST",
body: JSON.stringify({
autorouting_job_id: autorouting_job.autorouting_job_id,
}),
headers: { "Content-Type": "application/json" },
},
).then((r) => r.json())
this._asyncAutoroutingResult = {
output_pcb_traces: autorouting_job_output.output_pcb_traces,
}
this._markDirty("PcbTraceRender")
break
}
if (job.has_error) {
const err = new AutorouterError(
`Autorouting job failed: ${JSON.stringify(job.error)}`,
)
db.pcb_autorouting_error.insert({
pcb_error_id: autorouting_job.autorouting_job_id,
error_type: "pcb_autorouting_error",
message: err.message,
})
throw err
}
// Wait before polling again
await new Promise((resolve) => setTimeout(resolve, 100))
}
}
/**
* Run local autorouting using the CapacityMeshAutorouter
*/
async _runLocalAutorouting() {
const { db } = this.root!
const props = this._parsedProps as SubcircuitGroupProps
const debug = Debug("tscircuit:core:_runLocalAutorouting")
debug(`[${this.getString()}] starting local autorouting`)
const autorouterConfig = this._getAutorouterConfig()
const isLaserPrefabPreset = this._isLaserPrefabAutorouter(autorouterConfig)
const isAutoJumperPreset = this._isAutoJumperAutorouter(autorouterConfig)
const isSingleLayerBoard = this._getSubcircuitLayerCount() === 1
const { simpleRouteJson: baseSimpleRouteJson } =
getSimpleRouteJsonFromCircuitJson({
db,
minTraceWidth: this.props.autorouter?.minTraceWidth ?? 0.15,
nominalTraceWidth: this.props.nominalTraceWidth,
subcircuit_id: this.subcircuit_id,
subcircuitComponent: this,
})
const routingPhasePlans = this._getRoutingPhasePlans()
const hasPhasedAutorouting = Group_hasPhasedAutorouting(routingPhasePlans)
const outputTraces: SimplifiedPcbTrace[] = []
const outputJumpers: Array<{
jumper_footprint: string
center: { x: number; y: number }
orientation: string
pads: Array<{
center: { x: number; y: number }
width: number
height: number
layer: string
}>
}> = []
for (const routingPhasePlan of routingPhasePlans) {
let simpleRouteJson = baseSimpleRouteJson
if (hasPhasedAutorouting) {
simpleRouteJson = Group_filterSimpleRouteJsonForPhase(
baseSimpleRouteJson,
routingPhasePlan,
)
simpleRouteJson.obstacles = [
...simpleRouteJson.obstacles,
...Group_getObstaclesFromRoutedTraces(outputTraces),
]
}
if (hasPhasedAutorouting && simpleRouteJson.connections.length === 0) {
continue
}
// Enable jumpers for auto_jumper preset
if (isAutoJumperPreset) {
simpleRouteJson.allowJumpers = true
if (autorouterConfig.availableJumperTypes) {
simpleRouteJson.availableJumperTypes =
autorouterConfig.availableJumperTypes
}
}
if (debug.enabled) {
;(global as any).debugOutputArray?.push({
name: `simpleroutejson-${this.props.name}.json`,
obj: simpleRouteJson,
})
}
if (debug.enabled) {
const graphicsObject = convertSrjToGraphicsObject(
simpleRouteJson as any,
) as GraphicsObject
graphicsObject.title = `autorouting-${this.props.name}`
;(global as any).debugGraphics?.push(graphicsObject)
}
this.root?.emit("autorouting:start", {
subcircuit_id: this.subcircuit_id,
componentDisplayName: this.getString(),
simpleRouteJson,
})
// Create the autorouter instance
let autorouter: GenericLocalAutorouter
if (autorouterConfig.algorithmFn) {
autorouter = await autorouterConfig.algorithmFn(simpleRouteJson)
} else {
const autorouterVersion = this.props.autorouterVersion
const effortLevel = this.props.autorouterEffortLevel
const effort = effortLevel
? Number.parseInt(effortLevel.replace("x", ""), 10)
: undefined
autorouter = new TscircuitAutorouter(simpleRouteJson, {
// Optional configuration parameters
capacityDepth: this.props.autorouter?.capacityDepth,
targetMinCapacity: this.props.autorouter?.targetMinCapacity,
useAssignableSolver: isLaserPrefabPreset || isSingleLayerBoard,
useAutoJumperSolver: isAutoJumperPreset,
autorouterVersion,
effort,
onSolverStarted: ({ solverName, solverParams }) =>
this.root?.emit("solver:started", {
type: "solver:started",
solverName,
solverParams,
componentName: this.getString(),
}),
})
}
// Create a promise that will resolve when autorouting is complete
const routingPromise = new Promise<SimplifiedPcbTrace[]>(
(resolve, reject) => {
autorouter.on("complete", (event) => {
debug(`[${this.getString()}] local autorouting complete`)
resolve(event.traces)
})
autorouter.on("error", (event) => {
debug(
`[${this.getString()}] local autorouting error: ${event.error.message}`,
)
reject(event.error)
})
},
)
autorouter.on("progress", (event) => {
this.root?.emit("autorouting:progress", {
subcircuit_id: this.subcircuit_id,
componentDisplayName: this.getString(),
...event,
})
})
// Start the autorouting process
autorouter.start()
try {
// Wait for the autorouting to complete
const traces = await routingPromise
// Create source_traces for interconnect ports that were connected via
// off-board paths during routing. This allows DRC to understand that
// these ports are intentionally connected.
if (autorouter.getConnectedOffboardObstacles) {
const connectedOffboardObstacles =
autorouter.getConnectedOffboardObstacles()
createSourceTracesFromOffboardConnections({
db,
connectedOffboardObstacles,
simpleRouteJson,
subcircuit_id: this.subcircuit_id,
})
}
// Get jumper output from solver
const solver = (autorouter as any).solver
if (solver?.getOutputJumpers) {
outputJumpers.push(...(solver.getOutputJumpers() || []))
}
outputTraces.push(...traces)
} catch (error) {
const { db } = this.root!
// Record the error
db.pcb_autorouting_error.insert({
pcb_error_id: `pcb_autorouter_error_subcircuit_${this.subcircuit_id}`,
error_type: "pcb_autorouting_error",
message: error instanceof Error ? error.message : String(error),
})
this.root?.emit("autorouting:error", {
subcircuit_id: this.subcircuit_id,
componentDisplayName: this.getString(),
error: {
message: error instanceof Error ? error.message : String(error),
},
simpleRouteJson,
})
throw error
} finally {
// Ensure the autorouter is stopped
autorouter.stop()
}
}
// Store the result
this._asyncAutoroutingResult = {
output_pcb_traces: outputTraces as any,
output_jumpers: outputJumpers,
}
// Mark the component as needing to re-render the PCB traces
this._markDirty("PcbTraceRender")
}
_startAsyncAutorouting() {
if (this._hasStartedAsyncAutorouting) return
this._hasStartedAsyncAutorouting = true
if (this._getAutorouterConfig().local) {
this._queueAsyncEffect("capacity-mesh-autorouting", async () =>
this._runLocalAutorouting(),
)
} else {
this._queueAsyncEffect("make-http-autorouting-request", async () =>
this._runEffectMakeHttpAutoroutingRequest(),
)
}
}
doInitialPcbTraceRender() {
const debug = Debug("tscircuit:core:doInitialPcbTraceRender")
if (!this.isSubcircuit) return
if (this.root?.pcbDisabled) return
if (
this.root?.pcbRoutingDisabled ||
this.getInheritedProperty("routingDisabled")
)
return
if (this._isInflatedFromCircuitJson) return
if (this._shouldUseTraceByTraceRouting()) return
if (!this._areChildSubcircuitsRouted()) {
debug(
`[${this.getString()}] child subcircuits are not routed, skipping async autorouting until subcircuits routed`,
)
return
}
debug(
`[${this.getString()}] no child subcircuits to wait for, initiating async routing`,
)
if (!this._hasTracesToRoute()) return
this._startAsyncAutorouting()
}
doInitialSchematicTraceRender() {
Group_doInitialSchematicTraceRender(this as any)
}
updatePcbTraceRender() {
const debug = Debug("tscircuit:core:updatePcbTraceRender")
debug(`[${this.getString()}] updating...`)
if (!this.isSubcircuit) return
if (this._isInflatedFromCircuitJson) return
if (
this._shouldRouteAsync() &&
this._hasTracesToRoute() &&
!this._hasStartedAsyncAutorouting
) {
if (this._areChildSubcircuitsRouted()) {
debug(
`[${this.getString()}] child subcircuits are now routed, starting async autorouting`,
)
this._startAsyncAutorouting()
}
return
}
if (!this._asyncAutoroutingResult) return
if (this._shouldUseTraceByTraceRouting()) return
const { db } = this.root!
if (this._asyncAutoroutingResult.output_simple_route_json) {
debug(
`[${this.getString()}] updating PCB traces from simple route json (${this._asyncAutoroutingResult.output_simple_route_json.traces?.length} traces)`,
)
this._updatePcbTraceRenderFromSimpleRouteJson()
return
}
if (this._asyncAutoroutingResult.output_pcb_traces) {
debug(
`[${this.getString()}] updating PCB traces from ${this._asyncAutoroutingResult.output_pcb_traces.length} traces`,
)
this._updatePcbTraceRenderFromPcbTraces()
return
}
}
_updatePcbTraceRenderFromSimpleRouteJson() {
const { db } = this.root!
const { traces: routedTraces } =
this._asyncAutoroutingResult!.output_simple_route_json!
if (!routedTraces) return
// Delete any previously created traces
// TODO
// Apply each routed trace to the corresponding circuit trace
// const circuitTraces = this.selectAll("trace") as Trace[]
for (const routedTrace of routedTraces) {
// const circuitTrace = circuitTraces.find(
// (t) => t.source_trace_id === routedTrace.,
// )
// Create the PCB trace with the routed path
// TODO use upsert to make sure we're not re-creating traces
const pcb_trace = db.pcb_trace.insert({
subcircuit_id: this.subcircuit_id!,
route: routedTrace.route as any,
// source_trace_id: circuitTrace.source_trace_id!,
})
// circuitTrace.pcb_trace_id = pcb_trace.pcb_trace_id
// Create vias for any layer transitions
// for (const point of routedTrace.route) {
// if (point.route_type === "via") {
// db.pcb_via.insert({
// pcb_trace_id: pcb_trace.pcb_trace_id,
// x: point.x,
// y: point.y,
// hole_diameter: 0.3,
// outer_diameter: 0.6,
// layers: [point.from_layer as LayerRef, point.to_layer as LayerRef],
// from_layer: point.from_layer as LayerRef,
// to_layer: point.to_layer as LayerRef,
// })
// }
// }
}
}
_updatePcbTraceRenderFromPcbTraces() {
const { output_pcb_traces, output_jumpers } = this._asyncAutoroutingResult!
if (!output_pcb_traces) return
const { db } = this.root!
// Delete any previously created traces
// TODO
// Apply each routed trace to the corresponding circuit trace
const pcbStyle = this.getInheritedMergedProperty("pcbStyle")
const { holeDiameter, padDiameter } = getViaDiameterDefaults(pcbStyle)
const board = db.pcb_board.list()[0]
const routedViaHoleDiameter = board?.min_via_hole_diameter ?? holeDiameter
const routedViaPadDiameter = board?.min_via_pad_diameter ?? padDiameter
// First, create jumper components from getOutputJumpers() result
if (output_jumpers && output_jumpers.length > 0) {
insertAutoplacedJumpers({
db,
output_jumpers,
subcircuit_id: this.subcircuit_id,
})
}
for (const pcb_trace of output_pcb_traces) {
// vias can be included
if (pcb_trace.type !== "pcb_trace") continue
pcb_trace.subcircuit_id = this.subcircuit_id!
if ((pcb_trace as any).connection_name) {
const sourceTraceId = (pcb_trace as any).connection_name
pcb_trace.source_trace_id = sourceTraceId
}
// Split traces at jumper locations (based on explicit jumper route markers)
let segments = splitPcbTracesOnJumperSegments(pcb_trace.route)
// If no explicit jumper splits, use the original route
if (segments === null) {
segments = [pcb_trace.route]
}
// Add port IDs to trace segments at jumper pad locations
const processedSegments = addPortIdsToTracesAtJumperPads(segments, db)
// Insert each segment as a separate trace
for (const segment of processedSegments) {
if (segment.length > 0) {
db.pcb_trace.insert({
...pcb_trace,
route: segment,
})
}
}
}
// Create vias for layer transitions (this shouldn't be necessary, but
// the Circuit JSON spec is ambiguous as to whether a via should have a
// separate element from the route)
for (const pcb_trace of output_pcb_traces) {
if (pcb_trace.type === "pcb_via") {
// TODO handling here- may need to handle if redundant with pcb_trace
// below (i.e. don't insert via if one already exists at that location)
continue
}
if (pcb_trace.type === "pcb_trace") {
for (const point of pcb_trace.route) {
if (point.route_type === "via") {
const routedViaPoint = point as typeof point & {
via_diameter?: number
via_hole_diameter?: number
outer_diameter?: number
hole_diameter?: number
}
db.pcb_via.insert({
pcb_trace_id: pcb_trace.pcb_trace_id,
x: point.x,
y: point.y,
hole_diameter:
routedViaPoint.via_hole_diameter ??
routedViaPoint.hole_diameter ??
routedViaHoleDiameter,
outer_diameter:
routedViaPoint.via_diameter ??
routedViaPoint.outer_diameter ??
routedViaPadDiameter,
layers: [
point.from_layer as LayerRef,
point.to_layer as LayerRef,
],
from_layer: point.from_layer as LayerRef,
to_layer: point.to_layer as LayerRef,
})
}
}
}
}
}
doInitialSchematicComponentRender() {
if (this.root?.schematicDisabled) return
const { db } = this.root!
const { _parsedProps: props } = this
const schematic_group = db.schematic_group.insert({
is_subcircuit: this.isSubcircuit,