-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoroid-ease.py
More file actions
executable file
·1934 lines (1608 loc) · 78.6 KB
/
toroid-ease.py
File metadata and controls
executable file
·1934 lines (1608 loc) · 78.6 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
#!/usr/bin/env python3
"""
Toroid-Ease: FPC (Flexible Printed Circuit) generator for toroidal inductors.
Generates KiCad 9 PCB files for FPC windings that wrap around toroid cores.
The FPC wraps: OD -> flat face -> ID bore -> flat face -> OD, where the
B-edge solders to the A-edge to continue the helix.
Usage:
./toroid-ease.py -c T68 -t 20 -a 1.0 -o my_coil.kicad_pcb
./toroid-ease.py -c FT-50 -t 30 -a 2.0 --layers 2 -o high_current.kicad_pcb
"""
import sys
import argparse
import math
import os
import pcbnew
# =============================================================================
# JLCPCB FLEX PCB DESIGN RULES
# =============================================================================
# Based on JLCPCB flex PCB capabilities (2024/2025)
# These are applied to the board and enforced by DRC
JLCPCB_RULES = {
"clearance": 0.1, # Min copper-to-copper clearance (mm)
"track_width": 0.1, # Min track width (mm) - JLCPCB can do 0.05mm but 0.1 is safer
"via_drill": 0.2, # Min via drill (mm)
"via_diameter": 0.45, # Min via pad diameter (mm)
"annular_ring": 0.125, # Min annular ring (mm)
"hole_to_hole": 0.5, # Min hole-to-hole spacing (mm)
"edge_clearance": 0.2, # Min copper-to-edge clearance (mm)
"silk_clearance": 0.15, # Min silk-to-edge clearance (mm)
"min_slot_width": 0.8, # Min routed slot/cutout width (mm)
}
# =============================================================================
# FABRICATION CONSTANTS
# =============================================================================
# Adjust these values to match your FPC fabricator's capabilities.
# These defaults target JLCPCB flex PCB production.
# --- Copper Geometry (using JLCPCB rules) ---
MIN_TRACE_WIDTH_MM = JLCPCB_RULES["track_width"]
MIN_GAP_MM = JLCPCB_RULES["clearance"]
MIN_ANNULAR_RING_MM = JLCPCB_RULES["annular_ring"]
EDGE_TO_COPPER_MM = JLCPCB_RULES["edge_clearance"]
# --- Copper Thickness Options ---
# Map of common copper weight/thickness specifications to mm
COPPER_THICKNESS = {
"0.5oz": 0.0175, # 17.5 microns - thinnest common FPC copper
"18u": 0.018, # 18 microns
"1oz": 0.035, # 35 microns - standard
"35u": 0.035, # 35 microns
"2oz": 0.070, # 70 microns - heavy copper
"70u": 0.070, # 70 microns
}
# --- Current Capacity ---
# IPC-2221 for external conductors with 20°C temperature rise.
# For 1oz copper in open air (external FPC), approximately:
# I = 0.048 * dT^0.44 * A^0.725 where A is cross-sectional area in mil²
# For 20°C rise with 1oz copper (1.4 mil thick):
# ~0.3mm width per amp is conservative for external traces
# Both layers carry current in parallel, so total capacity doubles.
MM_PER_AMP_1OZ = 0.3 # Conservative: mm trace width per amp for 1oz external
# Current capacity per via (0.3mm drill in 1oz copper, ~0.5A each)
AMPS_PER_VIA = 0.5
# If True, allow designs even if current capacity is below requested
ALLOW_UNDERCURRENT = True
# --- Via Geometry ---
DEFAULT_VIA_DRILL_MM = 0.3 # Via drill diameter
DEFAULT_VIA_SIZE_MM = 0.6 # Via pad diameter (drill + 2*annular ring)
VIA_SPACING_MM = 0.8 # Center-to-center via spacing in arrays
# --- Bend Radius ---
# Minimum bend radius = BEND_RADIUS_K * (FPC thickness + copper thickness)
# K factor: RA (rolled annealed) copper ~6-8, ED (electrodeposited) ~10-12
# For double-sided: K = 12 per JLCPCB guidelines
BEND_RADIUS_K = 12.0
# --- Fold Radius at Toroid Corners ---
# The toroid core has slightly rounded corners where the FPC bends.
# This radius affects the bend allowance added to the flat pattern.
# Manufacturer doesn't specify corner radius, so we assume a small value.
# Bend allowance per 90° fold = π × FOLD_RADIUS_MM / 2
FOLD_RADIUS_MM = 0.1 # Assumed toroid corner radius (mm) - tune as needed
# --- Slit/Rip-stop Geometry ---
# Rip-stop is a circular hole at the fold line, with two slits fanning outward
RIPSTOP_DIAMETER_MM = JLCPCB_RULES["min_slot_width"] # 0.8mm minimum for routed features
SLIT_WIDTH_MM = JLCPCB_RULES["min_slot_width"] # Slit width (laser cut)
SLIT_SPREAD_MM = 0.1 # How much slits spread apart at OD end
# --- SMD Pad Geometry ---
SMD_PAD_WIDTH_MM = 1.5 # Width of lap/connection pads
SMD_PAD_HEIGHT_MM = 4.0 # Height of lap/connection pads
SMD_PAD_ROUNDRECT_RATIO = 0.1 # Corner rounding ratio
# --- Stiffener ---
STIFFENER_MARGIN_MM = 1.0 # Margin around pads for stiffener outline
STIFFENER_LINE_WIDTH_MM = 0.15 # Line width for stiffener outline
# --- Silkscreen ---
SILK_LINE_WIDTH_MM = 0.15 # Silkscreen line width
SILK_DASH_LENGTH_MM = 1.0 # Length of dashes for fold lines
SILK_GAP_LENGTH_MM = 0.5 # Gap between dashes
# =============================================================================
# CORE DATABASE
# =============================================================================
# Format: "CoreName": (OD_mm, ID_mm, axialHeight_mm)
# Dimensions from manufacturer datasheets.
CORES = {
# T-series (Micrometals/Amidon powdered iron)
"T200": (50.80, 31.75, 14.00),
"T157": (40.00, 23.50, 14.50),
"T130": (33.00, 19.50, 11.00),
"T106": (26.90, 14.50, 11.10),
"T94": (23.90, 14.30, 9.50),
"T80": (20.30, 12.70, 6.35),
"T68": (17.50, 9.40, 4.80),
"T50": (12.70, 7.70, 4.80),
"T44": (11.20, 5.80, 4.00),
"T37": ( 9.50, 5.20, 3.25),
"T30": ( 7.80, 3.80, 3.25),
"T25": ( 6.35, 3.05, 2.55),
# FT-series (Fair-Rite ferrite toroids)
"FT240": (61.00, 35.55, 12.70),
"FT140": (35.55, 23.00, 12.70),
"FT114": (29.00, 19.00, 7.50),
"FT82": (21.00, 13.00, 6.35),
"FT50": (12.70, 7.15, 4.80),
"FT37": ( 9.53, 4.75, 3.18),
}
# =============================================================================
# Core Lookup
# =============================================================================
def lookupCore(name):
"""
Look up core dimensions by name.
Accepts formats: T68, T-68, FT68, FT-68, t68, ft-68, etc.
Returns (OD, ID, axialHeight) in mm, or None if not found.
"""
# Normalize: uppercase, remove hyphens
normalized = name.upper().replace("-", "")
# Try direct lookup first
if normalized in CORES:
return CORES[normalized]
# Try stripping 'F' prefix (FT68 -> T68)
if normalized.startswith("F") and normalized[1:] in CORES:
return CORES[normalized[1:]]
# Try adding 'F' prefix (T68 -> FT68)
if not normalized.startswith("F") and ("F" + normalized) in CORES:
return CORES["F" + normalized]
# Not found - print available cores
print(f"Error: Core '{name}' not found.", file=sys.stderr)
print("\nAvailable cores:", file=sys.stderr)
print(f" {'Name':<8} {'OD (mm)':<10} {'ID (mm)':<10} {'Height (mm)':<12}", file=sys.stderr)
print(f" {'-'*8} {'-'*10} {'-'*10} {'-'*12}", file=sys.stderr)
for coreName in sorted(CORES.keys()):
od, coreId, height = CORES[coreName]
print(f" {coreName:<8} {od:<10.2f} {coreId:<10.2f} {height:<12.2f}", file=sys.stderr)
print("\nAccepted formats: T68, T-68, FT68, FT-68 (case insensitive)", file=sys.stderr)
return None
# =============================================================================
# Copper Thickness Parsing
# =============================================================================
def parseCopperThickness(spec):
"""
Parse copper thickness specification.
Accepts: "1oz", "35u", "0.5oz", "2oz", "70u", etc.
Returns thickness in mm.
"""
normalized = spec.lower().strip()
if normalized in COPPER_THICKNESS:
return COPPER_THICKNESS[normalized]
# Try without 'u' suffix as microns
if normalized.endswith("u"):
try:
microns = float(normalized[:-1])
return microns / 1000.0
except ValueError:
pass
# Try as direct mm value
try:
return float(normalized)
except ValueError:
pass
print(f"Error: Unknown copper thickness '{spec}'", file=sys.stderr)
print("Accepted values: 0.5oz, 18u, 1oz, 35u, 2oz, 70u", file=sys.stderr)
sys.exit(1)
# =============================================================================
# Configuration Calculation
# =============================================================================
def calculateConfiguration(coreOd, coreId, axialHeight, turns, amps,
layers, copperThickness, fpcThickness,
bendRadius, slitEndDiameter, mount):
"""
Calculate all geometric parameters for the FPC design.
Returns a dict with all calculated values, or None if design is impossible.
"""
# Calculate bend radius if not specified
if bendRadius is None:
bendRadius = BEND_RADIUS_K * (fpcThickness + copperThickness)
# Core geometry
radialThickness = (coreOd - coreId) / 2.0
# Check if bend radius fits within radial thickness
if bendRadius > radialThickness * 0.8:
print(f"Warning: Bend radius {bendRadius:.2f}mm is large relative to "
f"radial thickness {radialThickness:.2f}mm", file=sys.stderr)
# ID circumference determines the pitch
idCircumference = coreId * math.pi
pitch = idCircumference / turns
# OD circumference for fan-out calculation
odCircumference = coreOd * math.pi
odPitch = odCircumference / turns
# Calculate zone/trace geometry
# With copper zones, we fill maximum area and only need minimum gap between zones
# Scale for copper thickness relative to 1oz (thicker copper = more capacity)
copperScale = copperThickness / COPPER_THICKNESS["1oz"]
# Gap between traces must accommodate petal slit lines with edge clearance
# Slit geometry: lines run between traces at trace angle
# Required: slit_line_width/2 + edge_clearance on each side of centerline
# Edge clearance is typically 0.2mm, slit line width is 0.1mm
# So gap >= 0.1mm (slit) + 2*0.2mm (edge clearance) = 0.5mm
SLIT_LINE_WIDTH_MM = 0.1
EDGE_CLEARANCE_MM = 0.2
slitGapRequired = SLIT_LINE_WIDTH_MM + 2 * EDGE_CLEARANCE_MM
gap = max(MIN_GAP_MM, slitGapRequired) # 0.5mm minimum for edge clearance
# Zone width at narrowest point (ID) = pitch - gap
zoneWidthAtID = pitch - gap
# Check if design is feasible
if zoneWidthAtID < MIN_TRACE_WIDTH_MM:
print(f"Error: Zone width at ID {zoneWidthAtID:.3f}mm is below "
f"minimum {MIN_TRACE_WIDTH_MM}mm", file=sys.stderr)
print(f" (pitch={pitch:.3f}mm, gap={gap:.3f}mm)", file=sys.stderr)
return None
# For compatibility, store as traceWidth (zone width at narrowest point)
traceWidth = zoneWidthAtID
# Calculate required width for current capacity
# Formula: width = amps * mm_per_amp / layers / copper_scale
# Both layers carry current in parallel, thicker copper carries more
requiredWidth = amps * MM_PER_AMP_1OZ / (layers * copperScale)
# Check if current requirement can be met
if requiredWidth > zoneWidthAtID:
if ALLOW_UNDERCURRENT:
print(f"Warning: Requested {amps}A requires {requiredWidth:.3f}mm width,", file=sys.stderr)
print(f" but zone width at ID is {zoneWidthAtID:.3f}mm. Design will proceed.", file=sys.stderr)
else:
print(f"Error: Required width {requiredWidth:.3f}mm exceeds "
f"zone width {zoneWidthAtID:.3f}mm at ID", file=sys.stderr)
return None
# Calculate current capacity achieved at narrowest point
# capacity = width / mm_per_amp * layers * copper_scale
currentCapacity = zoneWidthAtID / MM_PER_AMP_1OZ * layers * copperScale
# Via count for 2-layer parallel connection
viasNeeded = 0
if layers == 2:
viasNeeded = max(2, math.ceil(amps / AMPS_PER_VIA))
# FPC dimensions (unfolded)
#
# The FPC wraps around the UPPER LIMB cross-section of the toroid.
# Cutting the toroid along its axis reveals a rectangular cross-section:
# - Width (axial direction): axialHeight = 14mm for T200
# - Height (radial direction): radialThickness = 9.525mm for T200
#
# The wrap path goes around this rectangle:
# 1. OD surface (top of rectangle) - where A and B pads overlap
# 2. Left flat face (left side of rectangle) - radialThickness
# 3. ID surface (bottom of rectangle, through the bore) - axialHeight
# 4. Right flat face (right side of rectangle) - radialThickness
# 5. Back to OD surface - where B-pad overlaps next turn's A-pad
#
# The A-pad and B-pad regions sit on the OD surface (top of the rectangle).
# They must overlap precisely when wrapped, spanning the axialHeight (14mm).
# The overlap zone = radialThickness / 2 (pad size for proper overlap).
# Distance from bend to pad = (axialHeight - padOverlapSize) / 2
#
# Layout (Y increasing from A-edge to B-edge):
# Y=0: A-edge of FPC
# Y=odSection: OD fold A (transition to left flat face)
# Y=odSection+bend: Start of flat face 1
# Y=odSection+bend+radial: ID fold 1
# Y=odSection+2*bend+radial: Start of ID section
# Y=odSection+2*bend+radial+axial: ID fold 2
# Y=odSection+3*bend+radial+axial: Start of flat face 2
# Y=odSection+3*bend+2*radial+axial: OD fold B
# Y=fpcHeight: B-edge of FPC
# Bend allowance for each 90° fold at the toroid corners
# Arc length = π × radius / 2 for a quarter circle
bendAllowance = math.pi * FOLD_RADIUS_MM / 2.0
# OD section geometry:
# The OD surface spans axialHeight (14mm for T200) from bend #1 to bend #4.
# A-pad and B-pad sit on this surface and must overlap when wrapped.
# Layout on OD surface (from bend #1 toward center, and bend #4 toward center):
# - Trace from bend to pad: (axialHeight - padOverlapSize) / 2
# - Pad overlap zone: padOverlapSize = radialThickness / 2
# - Trace from pad to other bend: (axialHeight - padOverlapSize) / 2
# Total = axialHeight, with pads overlapping in the middle.
#
# On UNFOLDED FPC, each OD section (from FPC edge to bend) includes:
# - Edge clearance
# - Pad (padOverlapSize)
# - Trace from pad to bend (where vias should go)
padOverlapSize = radialThickness / 2.0
traceToBend = (axialHeight - padOverlapSize) / 2.0
odSection = EDGE_TO_COPPER_MM + padOverlapSize + traceToBend
# Total FPC height = 2 OD sections + 2 flat faces + ID section + 4 bend allowances
fpcHeight = (2 * odSection +
2 * radialThickness +
axialHeight +
4 * bendAllowance)
# Width = span of all traces + edge clearance on each side
# The parallelogram has the same width at A-edge and B-edge (it's a true parallelogram)
# For N turns: A0 to BN-1 spans N pitches (A0 at 0.5*pitch, BN-1 at (N+0.5)*pitch - but helix offset shifts B-edge)
# At A-edge: traces span from A0 (0.5*pitch) to A(N-1) ((N-0.5)*pitch) = (N-1) pitches
# At B-edge: traces span from B0 (1.5*pitch) to B(N-1) ((N+0.5)*pitch) = (N-1) pitches
# Board width at A-edge: from (A0 - half_trace - clearance) to (A(N-1) + half_trace + clearance)
# But we now have turn N-1's trace going to B(N-1), so we need room for B(N-1) as well
# Width at A-edge: from 0 to B(N-1)'s A-edge projection + half_trace + clearance
# Actually simpler: N turns = N traces, each trace spans 1 pitch, so total span = N pitches
traceHalfWidth = traceWidth / 2.0
leftMargin = EDGE_TO_COPPER_MM + traceHalfWidth # edge_clearance + half_trace_width
# Width needs to accommodate: A0 to B(N-1) which spans N pitches (from 0.5 to N+0.5)
fpcWidth = turns * pitch + traceWidth + 2 * EDGE_TO_COPPER_MM
# Fold line positions (Y coordinates on unfolded FPC)
# There are 4 fold lines for wrapping around the toroid:
# 1. foldOD_A: OD fold at A-edge (after OD section, before flat face 1)
# 2. foldLine1Y: ID fold (after flat face 1, before ID bore)
# 3. foldLine2Y: ID fold (after ID bore, before flat face 2)
# 4. foldOD_B: OD fold at B-edge (after flat face 2, before OD section)
#
# Note: bend allowances are distributed around each fold point
foldOD_A = odSection
foldLine1Y = odSection + bendAllowance + radialThickness
foldLine2Y = odSection + 2 * bendAllowance + radialThickness + axialHeight
foldOD_B = odSection + 3 * bendAllowance + 2 * radialThickness + axialHeight
# Slit positions - start at ID fold lines, extend toward pads to allow petals to spread
# Keep slits from extending into the ID section
slitLength = min(3.0, radialThickness * 0.5) # 3mm or 50% of radial thickness
# Fan-out ratio: how much wider traces get at OD vs ID
fanRatio = odCircumference / idCircumference
# Trace angle calculation
# Each trace goes from A-pad center to B-pad center, with helix offset of one pitch
# Y positions of pad centers:
aEdgeY = EDGE_TO_COPPER_MM + padOverlapSize / 2.0
bEdgeY = fpcHeight - EDGE_TO_COPPER_MM - padOverlapSize / 2.0
# Delta for trace direction:
traceHeight = bEdgeY - aEdgeY
traceDeltaX = pitch # Helix offset
# Angle from vertical (degrees) - positive means trace leans right going down
traceAngleDeg = math.degrees(math.atan2(traceDeltaX, traceHeight))
return {
# Core parameters
"coreOd": coreOd,
"coreId": coreId,
"axialHeight": axialHeight,
# User parameters
"turns": turns,
"amps": amps,
"layers": layers,
"mount": mount,
# Material parameters
"copperThickness": copperThickness,
"fpcThickness": fpcThickness,
"bendRadius": bendRadius,
"slitEndDiameter": slitEndDiameter,
# Calculated geometry
"radialThickness": radialThickness,
"idCircumference": idCircumference,
"odCircumference": odCircumference,
"pitch": pitch,
"odPitch": odPitch,
"traceWidth": traceWidth,
"gap": gap,
"fanRatio": fanRatio,
# FPC dimensions
"fpcWidth": fpcWidth,
"fpcHeight": fpcHeight,
"odSection": odSection,
"padOverlapSize": padOverlapSize,
"traceToBend": traceToBend,
"bendAllowance": bendAllowance,
"foldOD_A": foldOD_A,
"foldLine1Y": foldLine1Y,
"foldLine2Y": foldLine2Y,
"foldOD_B": foldOD_B,
"slitLength": slitLength,
"leftMargin": leftMargin,
"traceAngleDeg": traceAngleDeg,
"traceHeight": traceHeight,
# Electrical
"currentCapacity": currentCapacity,
"viasNeeded": viasNeeded,
}
def printConfiguration(cfg):
"""Print all configuration parameters to stderr."""
print("=" * 60, file=sys.stderr)
print("TOROID-EASE FPC DESIGN", file=sys.stderr)
print("=" * 60, file=sys.stderr)
print("\nCore Dimensions:", file=sys.stderr)
print(f" OD: {cfg['coreOd']:.2f} mm", file=sys.stderr)
print(f" ID: {cfg['coreId']:.2f} mm", file=sys.stderr)
print(f" Axial Height: {cfg['axialHeight']:.2f} mm", file=sys.stderr)
print(f" Radial: {cfg['radialThickness']:.2f} mm", file=sys.stderr)
print("\nDesign Parameters:", file=sys.stderr)
print(f" Turns: {cfg['turns']}", file=sys.stderr)
print(f" Current: {cfg['amps']:.2f} A (requested)", file=sys.stderr)
print(f" Layers: {cfg['layers']}", file=sys.stderr)
print(f" Mount: {cfg['mount']}", file=sys.stderr)
print("\nMaterial:", file=sys.stderr)
print(f" Copper: {cfg['copperThickness']*1000:.1f} um", file=sys.stderr)
print(f" FPC Base: {cfg['fpcThickness']:.2f} mm", file=sys.stderr)
print(f" Bend Radius: {cfg['bendRadius']:.2f} mm", file=sys.stderr)
print("\nCalculated Trace Geometry:", file=sys.stderr)
print(f" Pitch at ID: {cfg['pitch']:.3f} mm", file=sys.stderr)
print(f" Pitch at OD: {cfg['odPitch']:.3f} mm", file=sys.stderr)
print(f" Trace Width: {cfg['traceWidth']:.3f} mm", file=sys.stderr)
print(f" Gap: {cfg['gap']:.3f} mm", file=sys.stderr)
print(f" Fan Ratio: {cfg['fanRatio']:.2f}x", file=sys.stderr)
print("\nFPC Dimensions (unfolded parallelogram):", file=sys.stderr)
print(f" Width: {cfg['fpcWidth']:.2f} mm", file=sys.stderr)
print(f" Height: {cfg['fpcHeight']:.2f} mm", file=sys.stderr)
print(f" Helix Skew: {cfg['pitch']:.2f} mm (B-edge shifted right)", file=sys.stderr)
print("\nOD Section Layout (each end):", file=sys.stderr)
print(f" Total: {cfg['odSection']:.2f} mm", file=sys.stderr)
print(f" Edge clear: {EDGE_TO_COPPER_MM:.2f} mm", file=sys.stderr)
print(f" Pad: {cfg['padOverlapSize']:.2f} mm (overlap zone)", file=sys.stderr)
print(f" Trace: {cfg['traceToBend']:.2f} mm (to bend, vias here)", file=sys.stderr)
print("\nWrap Path:", file=sys.stderr)
print(f" Flat Face: {cfg['radialThickness']:.2f} mm (each, radialThickness)", file=sys.stderr)
print(f" ID Section: {cfg['axialHeight']:.2f} mm (axialHeight)", file=sys.stderr)
print(f" Bend Allow: {cfg['bendAllowance']:.3f} mm (each of 4 folds)", file=sys.stderr)
print(f" Fold Radius: {FOLD_RADIUS_MM:.2f} mm (toroid corner radius)", file=sys.stderr)
print("\nFold Positions:", file=sys.stderr)
print(f" OD Fold A: Y = {cfg['foldOD_A']:.2f} mm", file=sys.stderr)
print(f" ID Fold 1: Y = {cfg['foldLine1Y']:.2f} mm", file=sys.stderr)
print(f" ID Fold 2: Y = {cfg['foldLine2Y']:.2f} mm", file=sys.stderr)
print(f" OD Fold B: Y = {cfg['foldOD_B']:.2f} mm", file=sys.stderr)
print("\nElectrical:", file=sys.stderr)
print(f" Current Cap: {cfg['currentCapacity']:.2f} A", file=sys.stderr)
if cfg['layers'] == 2:
print(f" Vias/trace: {cfg['viasNeeded']}", file=sys.stderr)
print("\nSlit Geometry:", file=sys.stderr)
print(f" Slit Length: {cfg['slitLength']:.2f} mm", file=sys.stderr)
print(f" Rip-stop Dia: {cfg['slitEndDiameter']:.2f} mm", file=sys.stderr)
print("=" * 60, file=sys.stderr)
# =============================================================================
# Geometry Helpers
# =============================================================================
def toNm(mm):
"""Convert mm to nanometers (KiCad internal units)."""
return int(mm * 1e6)
# Board origin offset (in mm) - used to position FPC on the KiCad page
_originX = 0.0
_originY = 0.0
def setOrigin(x, y):
"""Set the board origin offset in mm."""
global _originX, _originY
_originX = x
_originY = y
def vec(x, y):
"""Create a KiCad VECTOR2I from mm coordinates, applying origin offset."""
return pcbnew.VECTOR2I(toNm(x + _originX), toNm(y + _originY))
def addLine(board, start, end, layer, width=0.1):
"""Add a line segment to the board."""
seg = pcbnew.PCB_SHAPE(board)
seg.SetShape(pcbnew.SHAPE_T_SEGMENT)
seg.SetStart(start)
seg.SetEnd(end)
seg.SetLayer(layer)
seg.SetWidth(toNm(width))
board.Add(seg)
return seg
def addArc(board, center, start, angle_deg, layer, width=0.1):
"""Add an arc to the board. Angle is in degrees, positive = CCW."""
arc = pcbnew.PCB_SHAPE(board)
arc.SetShape(pcbnew.SHAPE_T_ARC)
arc.SetCenter(center)
arc.SetStart(start)
arc.SetArcAngleAndEnd(pcbnew.EDA_ANGLE(angle_deg, pcbnew.DEGREES_T))
arc.SetLayer(layer)
arc.SetWidth(toNm(width))
board.Add(arc)
return arc
def addCircle(board, center, radius, layer, width=0.1):
"""Add a circle to the board."""
circle = pcbnew.PCB_SHAPE(board)
circle.SetShape(pcbnew.SHAPE_T_CIRCLE)
circle.SetCenter(center)
circle.SetEnd(pcbnew.VECTOR2I(center.x + toNm(radius), center.y))
circle.SetLayer(layer)
circle.SetWidth(toNm(width))
board.Add(circle)
return circle
def addTrack(board, start, end, layer, width):
"""Add a copper track to the board."""
track = pcbnew.PCB_TRACK(board)
track.SetStart(start)
track.SetEnd(end)
track.SetLayer(layer)
track.SetWidth(toNm(width))
board.Add(track)
return track
def addVia(board, pos, drill, size):
"""Add a through-hole via to the board."""
via = pcbnew.PCB_VIA(board)
via.SetPosition(pos)
via.SetDrill(toNm(drill))
via.SetWidth(toNm(size))
via.SetViaType(pcbnew.VIATYPE_THROUGH)
via.SetLayerPair(pcbnew.F_Cu, pcbnew.B_Cu)
board.Add(via)
return via
def addSmdPad(board, pos, name, width, height, layer, roundrect=True, angleDeg=0):
"""Add an SMD pad to the board via a footprint.
Args:
angleDeg: Rotation angle in degrees (0 = long axis vertical, 90 = horizontal)
"""
fp = pcbnew.FOOTPRINT(board)
fp.SetPosition(pos)
fp.SetReference(f"PAD{name}")
fp.SetValue(name)
fp.Reference().SetVisible(False)
fp.Value().SetVisible(False)
pad = pcbnew.PAD(fp)
pad.SetPosition(pos)
pad.SetName(str(name))
pad.SetNumber(str(name))
pad.SetSize(pcbnew.VECTOR2I(toNm(width), toNm(height)))
if roundrect:
pad.SetShape(pcbnew.PAD_SHAPE_ROUNDRECT)
pad.SetRoundRectRadiusRatio(SMD_PAD_ROUNDRECT_RATIO)
else:
pad.SetShape(pcbnew.PAD_SHAPE_RECT)
pad.SetAttribute(pcbnew.PAD_ATTRIB_SMD)
lset = pcbnew.LSET()
lset.AddLayer(layer)
pad.SetLayerSet(lset)
# Apply rotation if specified
if angleDeg != 0:
pad.SetOrientation(pcbnew.EDA_ANGLE(angleDeg, pcbnew.DEGREES_T))
fp.Add(pad)
board.Add(fp)
return pad
def addText(board, pos, text, layer, height=1.0, thickness=0.15):
"""Add text to the board."""
txt = pcbnew.PCB_TEXT(board)
txt.SetText(text)
txt.SetPosition(pos)
txt.SetLayer(layer)
txt.SetTextHeight(toNm(height))
txt.SetTextThickness(toNm(thickness))
txt.SetHorizJustify(pcbnew.GR_TEXT_H_ALIGN_CENTER)
txt.SetVertJustify(pcbnew.GR_TEXT_V_ALIGN_CENTER)
board.Add(txt)
return txt
# =============================================================================
# Board Setup and Design Rules
# =============================================================================
def applyJLCPCBRules(board):
"""
Apply JLCPCB flex PCB design rules to the board.
These rules are stored in the board file and enforced by DRC.
"""
settings = board.GetDesignSettings()
# Set board-level constraints (DRC minimums)
settings.m_MinClearance = toNm(JLCPCB_RULES["clearance"])
settings.m_TrackMinWidth = toNm(JLCPCB_RULES["track_width"])
settings.m_ViasMinSize = toNm(JLCPCB_RULES["via_diameter"])
settings.m_MinThroughDrill = toNm(JLCPCB_RULES["via_drill"])
settings.m_ViasMinAnnularWidth = toNm(JLCPCB_RULES["annular_ring"])
settings.m_HoleClearance = toNm(JLCPCB_RULES["hole_to_hole"])
settings.m_CopperEdgeClearance = toNm(JLCPCB_RULES["edge_clearance"])
settings.m_SilkClearance = toNm(JLCPCB_RULES["silk_clearance"])
# Also set default netclass clearance to match JLCPCB rules
# This prevents netclass 'Default' from overriding with larger clearance
try:
netSettings = settings.m_NetSettings
defaultNetclass = netSettings.GetDefaultNetclass()
defaultNetclass.SetClearance(toNm(JLCPCB_RULES["clearance"]))
defaultNetclass.SetTrackWidth(toNm(JLCPCB_RULES["track_width"]))
except Exception as e:
print(f"Note: Could not set netclass defaults: {e}", file=sys.stderr)
def setLayerColors(board):
"""Set custom layer colors for better visibility."""
# Note: Layer colors are typically set in the project file, not the board.
# This function is a placeholder for when color customization is needed.
# User.1 should be bright blue - this is handled in KiCad settings.
pass
# =============================================================================
# Edge Cuts Generation
# =============================================================================
def generateEdgeCuts(board, cfg):
"""
Generate board outline as Edge.Cuts layer with sawtooth edges and petal separators.
Creates independent petals for each winding, connected only at the ID section.
Each petal separator has:
- A 180° arc centered ON the fold line (bend #2 or #3), opening away from midline
- Two lines extending from arc ends at the trace angle toward the edge
- A horizontal closing line at the edge (just past the pad area)
"""
layer = pcbnew.Edge_Cuts
width = 0.05 # Edge cut line width (minimum for visibility)
fpcHeight = cfg["fpcHeight"]
turns = cfg["turns"]
pitch = cfg["pitch"]
traceWidth = cfg["traceWidth"]
gap = cfg["gap"]
foldLine1Y = cfg["foldLine1Y"] # Bend #2
foldLine2Y = cfg["foldLine2Y"] # Bend #3
foldOD_A = cfg["foldOD_A"] # Bend #1
foldOD_B = cfg["foldOD_B"] # Bend #4
mount = cfg["mount"]
leftMargin = cfg.get("leftMargin", 0)
traceAngleDeg = cfg.get("traceAngleDeg", 0)
# Flap dimensions - just enough for pad + small margin
flapLength = 5.0
maxPadWidth = pitch - gap
padWidth = min(maxPadWidth, max(SMD_PAD_WIDTH_MM, traceWidth))
# Flap width must be wider than trace to provide edge clearance
flapWidth = traceWidth + 2 * EDGE_TO_COPPER_MM # trace + clearance on each side
# Ripstop radius (arc radius at fold line)
ripstopRadius = RIPSTOP_DIAMETER_MM / 2.0
# Helix offset for parallelogram shape
helixOffset = pitch
cfg["helixOffset"] = helixOffset
# Board width at A-edge (top) - minimal, just enough for traces with edge clearance
# Last trace A-edge center is at leftMargin + (turns - 0.5) * pitch
# Right edge needs traceWidth/2 + edge clearance beyond that
boardWidth = leftMargin + (turns - 0.5) * pitch + traceWidth/2 + EDGE_TO_COPPER_MM
cfg["boardWidth"] = boardWidth
# Calculate petal boundary X position at any Y (follows trace angle)
padOverlapSize = cfg.get("padOverlapSize", SMD_PAD_HEIGHT_MM)
aEdgeY = EDGE_TO_COPPER_MM + padOverlapSize / 2.0
bEdgeY = fpcHeight - EDGE_TO_COPPER_MM - padOverlapSize / 2.0
traceHeight = bEdgeY - aEdgeY
# Trace angle tangent (dx/dy ratio)
traceSlope = pitch / traceHeight if traceHeight > 0 else 0
def boundaryX(petalIdx, y):
"""Calculate X position of boundary between petals at Y."""
baseX = leftMargin + petalIdx * pitch
if traceHeight > 0:
frac = (y - aEdgeY) / traceHeight
return baseX + pitch * frac
return baseX
# Y positions where slits meet the edge (just past pad area)
padHeight = padOverlapSize
slitEndY_A = EDGE_TO_COPPER_MM + padHeight + 0.3 # Just past A-pad
slitEndY_B = fpcHeight - EDGE_TO_COPPER_MM - padHeight - 0.3 # Just past B-pad
# Main outline: left edge, A-edge with sawtooth, right edge, B-edge with sawtooth
startFlapX = leftMargin + pitch / 2.0
endFlapX = leftMargin + (turns - 1 + 1.5) * pitch
# Build outline by tracing around all petals
# The slits create a sawtooth pattern at the A and B edges
if mount == "flat":
# Left edge (from bottom to top)
addLine(board, vec(helixOffset, fpcHeight), vec(0, 0), layer, width)
# A-edge with START flap and sawtooth pattern
addLine(board, vec(0, 0), vec(startFlapX - flapWidth/2, 0), layer, width)
addLine(board, vec(startFlapX - flapWidth/2, 0), vec(startFlapX - flapWidth/2, -flapLength), layer, width)
addLine(board, vec(startFlapX - flapWidth/2, -flapLength), vec(startFlapX + flapWidth/2, -flapLength), layer, width)
addLine(board, vec(startFlapX + flapWidth/2, -flapLength), vec(startFlapX + flapWidth/2, 0), layer, width)
addLine(board, vec(startFlapX + flapWidth/2, 0), vec(boardWidth, 0), layer, width)
# Right edge (from top to bottom)
addLine(board, vec(boardWidth, 0), vec(boardWidth + helixOffset, fpcHeight), layer, width)
# B-edge with END flap
addLine(board, vec(boardWidth + helixOffset, fpcHeight), vec(endFlapX + flapWidth/2, fpcHeight), layer, width)
addLine(board, vec(endFlapX + flapWidth/2, fpcHeight), vec(endFlapX + flapWidth/2, fpcHeight + flapLength), layer, width)
addLine(board, vec(endFlapX + flapWidth/2, fpcHeight + flapLength), vec(endFlapX - flapWidth/2, fpcHeight + flapLength), layer, width)
addLine(board, vec(endFlapX - flapWidth/2, fpcHeight + flapLength), vec(endFlapX - flapWidth/2, fpcHeight), layer, width)
addLine(board, vec(endFlapX - flapWidth/2, fpcHeight), vec(helixOffset, fpcHeight), layer, width)
else: # rolling mount - START on A-edge, END on B-edge
# V-shaped slits instead of arcs - two lines meeting at the fold line
# This fits in the gap without requiring arc clearance
# Pre-calculate boundary 1 slot position (between START/A0 and A1)
# START flap will extend from board edge to this slot
edgeClearance = 0.2
halfSlotWidth = max(0.025, gap/2 - edgeClearance - width/2)
vPointX_1 = boundaryX(1, foldLine1Y)
deltaY_1 = foldLine1Y
deltaX_1 = deltaY_1 * traceSlope
centerAtEdge_1 = vPointX_1 - deltaX_1 # Boundary 1 at A-edge
slot1_leftEdge = centerAtEdge_1 - halfSlotWidth
slot1_rightEdge = centerAtEdge_1 + halfSlotWidth
slot1_leftVpoint = vPointX_1 - halfSlotWidth
slot1_rightVpoint = vPointX_1 + halfSlotWidth
# START flap: trace aligned with turn 0's A-edge position, flap provides edge clearance
# Turn 0's A-edge is at leftMargin + 0.5*pitch
turn0_X = leftMargin + 0.5 * pitch
startFlapLeftX = turn0_X - traceWidth/2 - EDGE_TO_COPPER_MM # Just enough for edge clearance
startFlapRightX = slot1_leftEdge # Flap right edge meets slot left edge
startFlapWidth = startFlapRightX - startFlapLeftX
cfg["startFlapLeftX"] = startFlapLeftX
cfg["startFlapRightX"] = startFlapRightX
cfg["startFlapWidth"] = startFlapWidth
cfg["startFlapCenterX"] = turn0_X # Trace at turn 0's actual position
# Left edge (diagonal for parallelogram) - starts at startFlapLeftX, not 0
leftEdgeBottomX = startFlapLeftX + helixOffset # B-edge left corner
addLine(board, vec(leftEdgeBottomX, fpcHeight), vec(startFlapLeftX, 0), layer, width)
# A-edge with integrated petal cutouts (V-shaped sawtooth pattern)
# START flap extends from startFlapLeftX to slot1_leftEdge, with flap extending downward
addLine(board, vec(startFlapLeftX, 0), vec(startFlapLeftX, -flapLength), layer, width) # Left edge of flap
addLine(board, vec(startFlapLeftX, -flapLength), vec(startFlapRightX, -flapLength), layer, width) # Bottom of flap
addLine(board, vec(startFlapRightX, -flapLength), vec(slot1_leftEdge, 0), layer, width) # Right edge to A-edge
# Boundary 1 slot V-shape (between START/A0 and A1)
addLine(board, vec(slot1_leftEdge, 0), vec(slot1_leftVpoint, foldLine1Y), layer, width)
addLine(board, vec(slot1_leftVpoint, foldLine1Y), vec(slot1_rightVpoint, foldLine1Y), layer, width)
addLine(board, vec(slot1_rightVpoint, foldLine1Y), vec(slot1_rightEdge, 0), layer, width)
currentX = slot1_rightEdge
for i in range(2, turns - 1):
# Boundary between petals at fold line
vPointX = boundaryX(i, foldLine1Y)
vPointY = foldLine1Y
# Gap at A-edge (Y=0), centered on projected boundary
deltaY = foldLine1Y
deltaX = deltaY * traceSlope
centerAtEdge = vPointX - deltaX
# Slot width: need edge clearance (0.2mm) on each side of slot within gap
# slot_half_width = gap/2 - edge_clearance - line_half_width
edgeClearance = 0.2
halfSlotWidth = max(0.025, gap/2 - edgeClearance - width/2)
leftEdgeX = centerAtEdge - halfSlotWidth
rightEdgeX = centerAtEdge + halfSlotWidth
# Slit legs go parallel to traces (at traceSlope)
leftVpointX = vPointX - halfSlotWidth
rightVpointX = vPointX + halfSlotWidth
# Line along A-edge to left slit start
addLine(board, vec(currentX, 0), vec(leftEdgeX, 0), layer, width)
# Left slit line going down (parallel to trace)
addLine(board, vec(leftEdgeX, 0), vec(leftVpointX, vPointY), layer, width)
# Horizontal line connecting the two legs at fold line
addLine(board, vec(leftVpointX, vPointY), vec(rightVpointX, vPointY), layer, width)
# Right slit line going back up (parallel to trace)
addLine(board, vec(rightVpointX, vPointY), vec(rightEdgeX, 0), layer, width)
currentX = rightEdgeX
# Pre-calculate last boundary slot position on A-edge (between A50 and END/A51)
vPointX_lastA = boundaryX(turns - 1, foldLine1Y)
deltaY_lastA = foldLine1Y
deltaX_lastA = deltaY_lastA * traceSlope
centerAtEdge_lastA = vPointX_lastA - deltaX_lastA # Last boundary at A-edge
slotLastA_leftEdge = centerAtEdge_lastA - halfSlotWidth
slotLastA_rightEdge = centerAtEdge_lastA + halfSlotWidth
slotLastA_leftVpoint = vPointX_lastA - halfSlotWidth
slotLastA_rightVpoint = vPointX_lastA + halfSlotWidth
# END flap on A-edge: trace aligned with turn 51's A-edge position
# Turn 51's A-edge is at leftMargin + (turns - 1 + 0.5) * pitch = leftMargin + (turns - 0.5) * pitch
# But turn 51's B-edge (B51) is one pitch further right
turn51_A_X = leftMargin + (turns - 0.5) * pitch
turn51_B_X = leftMargin + (turns + 0.5) * pitch # B51 position
endFlapLeftX = slotLastA_rightEdge # Flap left edge meets slot right edge
endFlapRightX = turn51_A_X + traceWidth/2 + EDGE_TO_COPPER_MM # END flap right edge
endFlapWidth = endFlapRightX - endFlapLeftX
cfg["endFlapLeftX"] = endFlapLeftX
cfg["endFlapRightX"] = endFlapRightX
cfg["endFlapWidth"] = endFlapWidth
cfg["endFlapCenterX"] = turn51_A_X # Trace at turn 51's actual A-edge position
# Board right edge extends to B51 (turn 51's B-edge), not just END flap
boardRightEdgeX = turn51_B_X + traceWidth/2 + EDGE_TO_COPPER_MM
# Slot at last A-edge boundary (between A50 and END/A51)
addLine(board, vec(currentX, 0), vec(slotLastA_leftEdge, 0), layer, width)
addLine(board, vec(slotLastA_leftEdge, 0), vec(slotLastA_leftVpoint, foldLine1Y), layer, width)
addLine(board, vec(slotLastA_leftVpoint, foldLine1Y), vec(slotLastA_rightVpoint, foldLine1Y), layer, width)
addLine(board, vec(slotLastA_rightVpoint, foldLine1Y), vec(slotLastA_rightEdge, 0), layer, width)
# END flap on A-edge (extends upward like START) - open shape, not closed loop
addLine(board, vec(slotLastA_rightEdge, 0), vec(slotLastA_rightEdge, -flapLength), layer, width) # Left edge up
addLine(board, vec(slotLastA_rightEdge, -flapLength), vec(endFlapRightX, -flapLength), layer, width) # Top of flap
addLine(board, vec(endFlapRightX, -flapLength), vec(endFlapRightX, 0), layer, width) # Right edge down
# A-edge continues from END flap to board right edge (for turn 51 trace area)
addLine(board, vec(endFlapRightX, 0), vec(boardRightEdgeX, 0), layer, width)
# Right edge - diagonal like left edge (parallelogram shape)
# Goes from A-edge to B-edge with helix offset
rightEdgeTopX = boardRightEdgeX
rightEdgeBottomX = boardRightEdgeX + helixOffset
addLine(board, vec(rightEdgeTopX, 0), vec(rightEdgeBottomX, fpcHeight), layer, width)
# B-edge with boundary slots including B51
currentX = rightEdgeBottomX
# B-edge slots from turns-1 down to 1 (include boundary 51 for B50/B51)
for i in range(turns - 1, 0, -1):
# Boundary between petals at fold line
vPointX = boundaryX(i, foldLine2Y)
vPointY = foldLine2Y
# Gap at B-edge (Y=fpcHeight), centered on projected boundary
deltaY = fpcHeight - foldLine2Y
deltaX = deltaY * traceSlope
centerAtEdge = vPointX + deltaX
# Slot width: need edge clearance (0.2mm) on each side of slot within gap
# slot_half_width = gap/2 - edge_clearance - line_half_width
edgeClearance = 0.2
halfSlotWidth = max(0.025, gap/2 - edgeClearance - width/2)
leftEdgeX = centerAtEdge - halfSlotWidth
rightEdgeX = centerAtEdge + halfSlotWidth
# Slit legs go parallel to traces
leftVpointX = vPointX - halfSlotWidth
rightVpointX = vPointX + halfSlotWidth
# Line along B-edge to right slit start
addLine(board, vec(currentX, fpcHeight), vec(rightEdgeX, fpcHeight), layer, width)
# Right slit line going up (parallel to trace)
addLine(board, vec(rightEdgeX, fpcHeight), vec(rightVpointX, vPointY), layer, width)
# Horizontal line connecting the two legs at fold line
addLine(board, vec(rightVpointX, vPointY), vec(leftVpointX, vPointY), layer, width)
# Left slit line going back down (parallel to trace)
addLine(board, vec(leftVpointX, vPointY), vec(leftEdgeX, fpcHeight), layer, width)
currentX = leftEdgeX
# Finish B-edge to left corner (must match the left edge starting point)
addLine(board, vec(currentX, fpcHeight), vec(leftEdgeBottomX, fpcHeight), layer, width)
def generatePetalSlitWithArc(board, arcCenterX, arcCenterY, edgeY, arcRadius, traceSlope, layer, width, openUpward=True):
"""
Generate a petal separator slit with arc at fold line extending to edge.
Geometry:
- 180° arc centered at (arcCenterX, arcCenterY) on the fold line
- Arc opens away from FPC midline (upward for A-side, downward for B-side)
- Two lines extend from arc endpoints at trace angle toward edgeY
- Horizontal line at edgeY connects the two lines, closing the slit
Args:
arcCenterX, arcCenterY: Center of the arc (on the fold line)
edgeY: Y position where slit meets the edge (just past pad area)
arcRadius: Radius of the semicircular arc (ripstop)
traceSlope: dx/dy ratio for trace angle
openUpward: True if arc opens toward smaller Y (A-side), False for B-side
"""
import math
# Arc endpoints (left and right of center)
arcLeftX = arcCenterX - arcRadius
arcRightX = arcCenterX + arcRadius
# Distance from arc to edge
deltaY = arcCenterY - edgeY if openUpward else edgeY - arcCenterY
if deltaY <= 0:
return # Edge is past the arc, nothing to draw
# X offset for trace angle
deltaX = deltaY * traceSlope
# Line endpoints at the edge (following trace angle from arc endpoints)
if openUpward:
# Lines go from arc upward to edgeY
leftLineEndX = arcLeftX - deltaX
rightLineEndX = arcRightX - deltaX
leftLineEndY = edgeY
rightLineEndY = edgeY
# Draw closed slit:
# 1. Left line from edge to arc
addLine(board, vec(leftLineEndX, edgeY), vec(arcLeftX, arcCenterY), layer, width)
# 2. Arc from left to right, going through bottom (opening toward ID section)
addArc(board, vec(arcCenterX, arcCenterY), vec(arcLeftX, arcCenterY), 180, layer, width)
# 3. Right line from arc to edge
addLine(board, vec(arcRightX, arcCenterY), vec(rightLineEndX, edgeY), layer, width)
# 4. Horizontal line at edge to close
addLine(board, vec(rightLineEndX, edgeY), vec(leftLineEndX, edgeY), layer, width)
else:
# Lines go from arc downward to edgeY
leftLineEndX = arcLeftX + deltaX
rightLineEndX = arcRightX + deltaX
leftLineEndY = edgeY
rightLineEndY = edgeY
# Draw closed slit:
# 1. Left line from edge to arc
addLine(board, vec(leftLineEndX, edgeY), vec(arcLeftX, arcCenterY), layer, width)
# 2. Arc from left to right, going through top (opening toward ID section)
addArc(board, vec(arcCenterX, arcCenterY), vec(arcLeftX, arcCenterY), -180, layer, width)
# 3. Right line from arc to edge
addLine(board, vec(arcRightX, arcCenterY), vec(rightLineEndX, edgeY), layer, width)
# 4. Horizontal line at edge to close
addLine(board, vec(rightLineEndX, edgeY), vec(leftLineEndX, edgeY), layer, width)