-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutil.py
More file actions
1125 lines (892 loc) · 37.8 KB
/
util.py
File metadata and controls
1125 lines (892 loc) · 37.8 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
# -*- coding: utf-8 -*-
"""
Utility functions for GearWorkbench
General-purpose helper functions extracted from CycloidGearBox
for use across different gear types.
Copyright 2019-2025, Chris Bruner
License LGPL V2.1
"""
import math
import logging
from typing import Tuple, List, Dict, Any, Optional
import FreeCAD
from FreeCAD import Base
try:
import FreeCADGui as Gui
GUI_AVAILABLE = True
except ImportError:
GUI_AVAILABLE = False
import FreeCAD as App
import Sketcher
import Part
from Part import BSplineCurve, Wire
from inspect import currentframe
# Setup logging
logger = logging.getLogger(__name__)
if not logging.getLogger().handlers:
logging.basicConfig(level=logging.WARNING, format='%(levelname)s - %(message)s')
# Module-level constants
MIN_TOOTH_COUNT = 3
MAX_TOOTH_COUNT = 200
DEG_TO_RAD = math.pi / 180.0
RAD_TO_DEG = 180.0 / math.pi
# ============================================================================
# Exception Classes
# ============================================================================
class ParameterValidationError(ValueError):
"""Raised when gear parameters are invalid."""
pass
# ============================================================================
# Debugging Utilities
# ============================================================================
def getLinenumber() -> int:
"""Get the current line number for debugging.
Returns:
Current line number in calling code
"""
cf = currentframe()
return cf.f_back.f_lineno
def QT_TRANSLATE_NOOP(scope: str, text: str) -> str:
"""Qt translation placeholder.
Args:
scope: Translation scope
text: Text to translate
Returns:
Original text (no actual translation)
"""
return text
# ============================================================================
# Coordinate Conversion
# ============================================================================
def toPolar(x: float, y: float) -> Tuple[float, float]:
"""Convert Cartesian to polar coordinates.
Args:
x: X coordinate
y: Y coordinate
Returns:
Tuple of (radius, angle_in_radians)
"""
return (x ** 2.0 + y ** 2.0) ** 0.5, math.atan2(y, x)
def toCart(r: float, a: float) -> Tuple[float, float]:
"""Convert polar to Cartesian coordinates.
Args:
r: Radius
a: Angle in radians
Returns:
Tuple of (x, y) coordinates
"""
return r * math.cos(a), r * math.sin(a)
def mirrorPointsX(points: List[App.Vector]) -> List[App.Vector]:
"""Mirror a list of points across the Y-axis (X -> -X).
Args:
points: List of FreeCAD Vectors
Returns:
New list of FreeCAD Vectors, mirrored and reversed
"""
return [App.Vector(-p.x, p.y, p.z) for p in reversed(points)]
# ============================================================================
# Math Utilities
# ============================================================================
def clamp1(a: float) -> float:
"""Clamp value to range [-1, 1].
Args:
a: Value to clamp
Returns:
Clamped value between -1 and 1
"""
return min(1, max(a, -1))
def clamp(value: float, min_val: float, max_val: float) -> float:
"""Clamp value to range [min_val, max_val].
Args:
value: Value to clamp
min_val: Minimum value
max_val: Maximum value
Returns:
Clamped value
"""
return max(min_val, min(value, max_val))
def involuteFunction(angle: float) -> float:
"""Calculate the involute function: inv(α) = tan(α) - α.
The involute function is used in gear calculations to relate
pressure angles at different radii.
Args:
angle: Angle in radians
Returns:
Involute function value in radians
"""
return math.tan(angle) - angle
def involutePoint(base_radius: float, theta: float) -> Tuple[float, float]:
"""Calculate a point on the involute curve.
An involute curve is generated by unwrapping a string from a circle.
This is the fundamental profile shape of gear teeth.
Args:
base_radius: Radius of the base circle from which involute is generated
theta: Roll angle in radians (how far the string has unwrapped)
Returns:
Tuple of (x, y) coordinates
"""
x = base_radius * (math.cos(theta) + theta * math.sin(theta))
y = base_radius * (math.sin(theta) - theta * math.cos(theta))
return x, y
# ============================================================================
# FreeCAD Vector Utilities
# ============================================================================
def fcVec(x: List[float]) -> App.Vector:
"""Convert list to FreeCAD Vector.
Args:
x: List of 2 or 3 coordinates
Returns:
FreeCAD Vector object
"""
if len(x) == 2:
return App.Vector(x[0], x[1], 0)
else:
return App.Vector(x[0], x[1], x[2])
def vectorDistance(v1: App.Vector, v2: App.Vector) -> float:
"""Calculate distance between two FreeCAD vectors.
Args:
v1: First vector
v2: Second vector
Returns:
Distance between vectors
"""
dx = v2.x - v1.x
dy = v2.y - v1.y
dz = v2.z - v1.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
# ============================================================================
# BSpline/Curve Utilities
# ============================================================================
def makeBspline(pts, periodic=False):
"""Create BSpline curves from point lists.
Args:
pts: List of point lists, where each inner list contains points for one curve
periodic: If True, create a closed/periodic BSpline
Returns:
List of BSplineCurve objects
"""
curve = []
for i in pts:
out = BSplineCurve()
point_list = list(map(fcVec, i))
if periodic:
# For periodic curves, ensure enough points and don't duplicate first/last
if len(point_list) < 3:
raise ValueError("Periodic BSpline requires at least 3 points")
out.interpolate(point_list, PeriodicFlag=True)
else:
out.interpolate(point_list)
curve.append(out)
return curve
def makeBsplineWire(pts):
"""Create BSpline wire from point lists.
Args:
pts: List of point lists
Returns:
Wire object containing BSpline curves
"""
wi = []
for i in pts:
out = BSplineCurve()
out.interpolate(list(map(fcVec, i)))
wi.append(out.toShape())
return Wire(wi)
# ============================================================================
# Sketcher Helper Functions
# ============================================================================
def createSketch(body, name=''):
"""Create a new sketch in a body.
All sketches are centered around XY plane.
Args:
body: FreeCAD body object
name: Base name for the sketch (will append 'Sketch')
Returns:
Created sketch object
"""
name = name + 'Sketch'
sketch = body.Document.addObject('Sketcher::SketchObject', name)
# Try to set Support - not all FreeCAD versions support this attribute
try:
xy_plane = body.Document.getObject('XY_Plane')
if xy_plane:
sketch.Support = (xy_plane, [''])
sketch.MapMode = 'FlatFace'
except (AttributeError, TypeError) as e:
# FreeCAD version doesn't support Support attribute or XY_Plane doesn't exist
# Sketch will be created without support reference
logger.debug(f"Could not set sketch support: {e}")
result = body.addObject(sketch)
# body.addObject may return a tuple in some versions - ignore return value
# and use the original sketch object
try:
sketch.Visibility = False
except AttributeError:
# If sketch somehow became invalid, try to get it from document
sketch = body.Document.getObject(name)
if sketch:
sketch.Visibility = False
return sketch
def createPad(body, sketch, height, name='', midplane=False):
"""Create a pad feature from a sketch.
Args:
body: FreeCAD body object
sketch: Sketch to pad
height: Pad height
name: Base name for the pad (will append 'Pad')
midplane: If True, extrude symmetrically from sketch plane (handled by caller setting sketch placement)
Returns:
Created pad object
"""
name = name + 'Pad'
pad = body.Document.addObject("PartDesign::Pad", name)
body.addObject(pad)
pad.Profile = sketch
pad.Length = height # Always extrude by 'height' in one direction
# The 'midplane' argument is now primarily informational for the caller,
# as centering is expected to be handled by the sketch's Placement.
# We explicitly remove the SideType setting here to avoid inconsistent behavior.
# For symmetry, the caller should set sketch.Placement.Base.Z = -height/2.0
sketch.Visibility = False
return pad
def createPolar(body, pad, sketch, count, name=''):
"""Create a polar pattern.
Args:
body: FreeCAD body object
pad: Feature to pattern
sketch: Reference sketch
count: Number of occurrences
name: Base name for the pattern (will append 'Polar')
Returns:
Created polar pattern object
"""
name = name + 'Polar'
polar = body.newObject('PartDesign::PolarPattern', name)
polar.Axis = (sketch, ['N_Axis'])
polar.Angle = 360
polar.Occurrences = count
return polar
def createPocket(body, sketch, height, name='', reversed=True):
"""Create a pocket feature from a sketch.
Args:
body: FreeCAD body object
sketch: Sketch to pocket
height: Pocket depth
name: Base name for the pocket (will append 'Pocket')
reversed: Direction
Returns:
Created pocket object
"""
name = name + 'Pocket'
pocket = body.Document.addObject("PartDesign::Pocket", name)
body.addObject(pocket)
pocket.Length = height
pocket.Profile = sketch
pocket.Reversed = reversed
# Hide the sketch directly (pocket.Profile returns a tuple, not the object)
sketch.Visibility = False
return pocket
# ============================================================================
# BORE GENERATION
# ============================================================================
def createBore(body, parameters, height, placement=None, reversed=True):
"""
Dispatcher function to create a bore based on type.
"""
bore_type = parameters.get("bore_type", "none")
bore_diameter = parameters.get("bore_diameter", 0.0)
if bore_type == "circular":
_createCircularBore(body, bore_diameter, height, placement, reversed)
elif bore_type == "square":
_createSquareBore(body, bore_diameter, parameters.get("square_corner_radius", 0.5), height, placement, reversed)
elif bore_type == "hexagonal":
_createHexBore(body, bore_diameter, parameters.get("hex_corner_radius", 0.5), height, placement, reversed)
elif bore_type == "keyway":
_createKeywayBore(body, bore_diameter, parameters.get("keyway_width", 2.0), parameters.get("keyway_depth", 1.0), height, placement, reversed)
def _applyPlacement(sketch, placement):
if placement:
sketch.MapMode = 'Deactivated'
sketch.Placement = placement
def _createCircularBore(body, diameter, height, placement, reversed):
sketch = createSketch(body, 'CircularBore')
_applyPlacement(sketch, placement)
circle = sketch.addGeometry(Part.Circle(App.Vector(0, 0, 0), App.Vector(0, 0, 1), diameter / 2), False)
sketch.addConstraint(Sketcher.Constraint('Coincident', circle, 3, -1, 1))
sketch.addConstraint(Sketcher.Constraint('Diameter', circle, diameter))
pocket = createPocket(body, sketch, height, 'Bore', reversed)
body.Tip = pocket
def _createSquareBore(body, size, corner_radius, height, placement, reversed):
sketch = createSketch(body, 'SquareBore')
_applyPlacement(sketch, placement)
half_size = size / (2 * math.sqrt(2))
points = [App.Vector(half_size, half_size, 0), App.Vector(-half_size, half_size, 0),
App.Vector(-half_size, -half_size, 0), App.Vector(half_size, -half_size, 0)]
addPolygonToSketch(sketch, points, closed=True)
pocket = createPocket(body, sketch, height, 'Bore', reversed)
body.Tip = pocket
def _createHexBore(body, diameter, corner_radius, height, placement, reversed):
sketch = createSketch(body, 'HexBore')
_applyPlacement(sketch, placement)
radius = diameter / 2.0
points = []
for i in range(6):
angle = i * 60 * DEG_TO_RAD
points.append(App.Vector(radius * math.cos(angle), radius * math.sin(angle), 0))
addPolygonToSketch(sketch, points, closed=True)
pocket = createPocket(body, sketch, height, 'Bore', reversed)
body.Tip = pocket
def _createKeywayBore(body, bore_diameter, keyway_width, keyway_depth, height, placement, reversed):
# Keyway consists of a circular bore + a keyway slot
_createCircularBore(body, bore_diameter, height, placement, reversed)
sketch = createSketch(body, 'Keyway')
_applyPlacement(sketch, placement)
# Keyway rectangle: centered on X-axis, extending from bore edge outward
w = keyway_width / 2.0
r = bore_diameter / 2.0 # Bore radius
# Position keyway so it starts at the bore edge and extends outward
# The keyway slot sits at the top of the bore (positive Y direction)
points = [
App.Vector(-w, r - keyway_depth, 0), # Inner edge, left
App.Vector(w, r - keyway_depth, 0), # Inner edge, right
App.Vector(w, r + keyway_depth, 0), # Outer edge, right
App.Vector(-w, r + keyway_depth, 0), # Outer edge, left
]
addPolygonToSketch(sketch, points, closed=True)
# Recompute to ensure sketch is valid
body.Document.recompute()
# Keyway pocket cuts through the full height (same as bore)
pocket = createPocket(body, sketch, height, 'Keyway', reversed)
body.Tip = pocket
def _constrainSketchPoint(sketch, geo_index, point_index, point_vector):
"""
Helper function to apply X and Y position constraints to a specific point
within a sketch geometry (e.g., line start/end point, arc center).
"""
x_val = point_vector.x
y_val = point_vector.y
if x_val == 0 and y_val == 0:
# Coincident with global origin (-1, 1)
sketch.addConstraint(Sketcher.Constraint('Coincident', geo_index, point_index, -1, 1))
else:
# Handle X constraint
if x_val == 0:
# Point on Y Axis (Index -2)
sketch.addConstraint(Sketcher.Constraint('PointOnObject', geo_index, point_index, -2))
else:
# Distance from Y Axis (Reference -1, 1 which is Origin? or Reference -2?)
# DistanceX is distance FROM Y axis (measured along X).
# Constraint('DistanceX', Geo, Point, -1, 1, Val) measures from Root Point?
# Standard way: Constraint('DistanceX', Geo, Point, Val) - implicitly from origin?
# Let's stick to explicit reference if possible, or simple form.
# Using -1, 1 (Root) as reference for DistanceX is standard.
sketch.addConstraint(Sketcher.Constraint('DistanceX', geo_index, point_index, -1, 1, x_val))
# Handle Y constraint
if y_val == 0:
# Point on X Axis (Index -1)
sketch.addConstraint(Sketcher.Constraint('PointOnObject', geo_index, point_index, -1))
else:
sketch.addConstraint(Sketcher.Constraint('DistanceY', geo_index, point_index, -1, 1, y_val))
def sketchLineByPoints(sketch, startPoint, endPoint, addConstrainLength=False, addConstrainStart=False, addConstrainEnd=False, isConstruction=False):
"""Add a line to a sketch with proper constraints and return key info.
The line is defined by two FreeCAD Vectors. Constraints are applied based on flags.
Args:
sketch: Sketch object
start_p: FreeCAD Vector for start point
end_p: FreeCAD Vector for end point
constrainLength: If True, adds a fixed length constraint.
constrainStart: If True, fixes the start point position absolutely.
constrainEnd: If True, fixes the end point position absolutely.
ref: If True, make it a construction line
Returns:
A dictionary with 'index' (int), 'start_point' (App.Vector),
and 'end_point' (App.Vector) of the created line geometry.
"""
# 1. Create the Part.LineSegment object
line_geometry = Part.LineSegment(startPoint, endPoint)
# 2. Add the initialized geometry to the sketch
geo_index = sketch.addGeometry(line_geometry, isConstruction)
# 3. Apply position constraints using the helper function
if addConstrainStart:
_constrainSketchPoint(sketch, geo_index, 1, startPoint)
if addConstrainEnd:
_constrainSketchPoint(sketch, geo_index, 2, endPoint)
# 4. Apply length constraint if requested
if addConstrainLength:
# Calculate the actual length of the line segment
# Use distanceToPoint for FreeCAD vectors
length = startPoint.distanceToPoint(endPoint)
# Add a fixed distance constraint
# 'Distance' (index of geom, point 1 index, index of geom 2, point 2 index, value)
sketch.addConstraint(Sketcher.Constraint('Distance', geo_index, 1, geo_index, 2, length))
# 5. Return the index and the calculated points
return {
'index': geo_index,
'start_point': startPoint,
'end_point': endPoint
}
def sketchLineByCoordinates(sketch, x1, y1, x2, y2, addConstrainLength=False, addConstrainStart=False, addConstrainEnd=False, isConstruction=False):
"""Add a line to a sketch with proper constraints and return key info.
The line is defined by absolute coordinates and fully constrained by adding
Coincident or Distance constraints to its start and end points.
Args:
sketch: Sketch object
x1: X coordinate of start point
y1: Y coordinate of start point
x2: X coordinate of end point
y2: Y coordinate of end point
ref: If True, make it a construction line
Returns:
A dictionary with 'index' (int), 'start_point' (App.Vector),
and 'end_point' (App.Vector) of the created line geometry.
"""
# 1. Define the start and end points
p1 = App.Vector(x1, y1, 0.0)
p2 = App.Vector(x2, y2, 0.0)
return sketchLineByPoints(sketch,p1,p2,addConstrainLength,addConstrainStart,addConstrainEnd,isConstruction)
def sketchArc(sketch, x, y, diameter, startAngle, endAngle, Name="", isConstruction=False):
"""Add an arc to a sketch with proper constraints and return key info.
Args:
sketch: Sketch object
x: X coordinate of center
y: Y coordinate of center
diameter: Arc diameter
startAngle: Start angle in radians
endAngle: End angle in radians
Name: Optional name for diameter constraint
ref: If True, make it a construction arc
Returns:
A dictionary with 'index' (int), 'start_point' (App.Vector),
and 'end_point' (App.Vector) of the created arc geometry.
"""
radius = diameter / 2.0
center = App.Vector(x, y, 0)
axis = App.Vector(0, 0, 1)
base_circle = Part.Circle(center, axis, radius)
arc_geometry = Part.ArcOfCircle(base_circle, startAngle, endAngle)
# Extract the points BEFORE adding to sketch
start_p = arc_geometry.StartPoint
end_p = arc_geometry.EndPoint
geo_index = sketch.addGeometry(arc_geometry, isConstruction)
# Add constraints to fix position and diameter
if x == 0 and y == 0:
sketch.addConstraint(Sketcher.Constraint('Coincident', geo_index, 3, -1, 1))
else:
if x == 0:
sketch.addConstraint(Sketcher.Constraint('PointOnObject', geo_index, 3, -2)) # On Y Axis
else:
sketch.addConstraint(Sketcher.Constraint('DistanceX', geo_index, 3, -1, 1, x))
if y == 0:
sketch.addConstraint(Sketcher.Constraint('PointOnObject', geo_index, 3, -1)) # On X Axis
else:
sketch.addConstraint(Sketcher.Constraint('DistanceY', geo_index, 3, -1, 1, y))
rad_cst_index = sketch.addConstraint(Sketcher.Constraint('Diameter', geo_index, diameter))
if Name != "":
sketch.renameConstraint(rad_cst_index, Name)
# Return the index and the calculated points
return {
'index': geo_index,
'start_point': start_p,
'end_point': end_p
}
def sketchCircle(sketch, x, y, diameter, last, Name="", isConstruction=False):
"""Add a circle to a sketch with proper constraints.
Args:
sketch: Sketch object
x: X coordinate of center
y: Y coordinate of center
diameter: Circle diameter
last: Index of last circle (for Equal constraint), or -1 for first
Name: Optional name for diameter constraint
ref: If True, make it a construction circle
Returns:
Index of created circle geometry
"""
c = sketch.addGeometry(Part.Circle())
if x == 0 and y == 0:
cst = sketch.addConstraint(Sketcher.Constraint('Coincident', c, 3, -1, 1))
else:
if x == 0:
cst = sketch.addConstraint(Sketcher.Constraint('PointOnObject', c, 3, -2))
else:
cst = sketch.addConstraint(Sketcher.Constraint('DistanceX', c, 3, -1, 1, x))
if y == 0:
cst = sketch.addConstraint(Sketcher.Constraint('PointOnObject', c, 3, -1))
else:
cst = sketch.addConstraint(Sketcher.Constraint('DistanceY', c, 3, -1, 1, y))
if last != -1:
rad = sketch.addConstraint(Sketcher.Constraint('Equal', last, c))
else:
rad = sketch.addConstraint(Sketcher.Constraint('Diameter', c, diameter))
if Name != "":
sketch.renameConstraint(rad, Name)
if isConstruction:
sketch.toggleConstruction(c)
return c
def finalizeSketchGeometry(sketch, geo_indices, closed=True, block=True):
"""
Connects a list of geometry indices in a sketch with Coincident constraints
and optionally applies Block constraints.
"""
count = len(geo_indices)
if count < 2: return
# Connect end of item i to start of item i+1
for i in range(count - 1):
sketch.addConstraint(Sketcher.Constraint('Coincident', geo_indices[i], 2, geo_indices[i+1], 1))
# Close the loop
if closed:
sketch.addConstraint(Sketcher.Constraint('Coincident', geo_indices[count-1], 2, geo_indices[0], 1))
if block:
for idx in geo_indices:
sketch.addConstraint(Sketcher.Constraint('Block', idx))
def sketchCircleOfCircles(sketch, circleRadius, outerCircleRadius, outerCircleCount, orgX, orgY, name):
"""Add a circle of Circles to a sketch.
Args:
sketch: Sketch object
circle_radius: Radius of circle on which holes are placed
hole_radius: Radius of each hole
hole_count: Number of holes
orgx: X coordinate of circle center
orgy: Y coordinate of circle center
name: Base name for holes
"""
last = -1
for i in range(outerCircleCount):
x = orgX + circleRadius * math.cos((2.0 * math.pi / outerCircleCount) * i)
y = orgY + circleRadius * math.sin((2.0 * math.pi / outerCircleCount) * i)
last = sketchCircle(sketch, x, y, outerCircleRadius, last, "")
def parametricCircle(radius, segmentCount, segmentIndex):
"""Calculate position of a hole in a circular pattern.
Args:
radius: Radius of circle on which holes are placed
hole_count: Total number of holes
hole_number: Index of this hole (0-based)
Returns:
Tuple of (x, y) coordinates
"""
x = radius * math.cos((2.0 * math.pi / segmentCount) * segmentIndex)
y = radius * math.sin((2.0 * math.pi / segmentCount) * segmentIndex)
return x, y
def constrainSketchPoint(sketch, geo_index, point_index, point_vector):
"""
Helper function to apply X and Y position constraints to a specific point
within a sketch geometry (e.g., line start/end point, arc center).
"""
x_val = point_vector.x
y_val = point_vector.y
if x_val == 0 and y_val == 0:
# Coincident with global origin (-1, 1)
sketch.addConstraint(Sketcher.Constraint('Coincident', geo_index, point_index, -1, 1))
else:
# Use distance constraints otherwise
if x_val != 0:
sketch.addConstraint(Sketcher.Constraint('DistanceX', geo_index, point_index, -1, 1, x_val))
if y_val != 0:
sketch.addConstraint(Sketcher.Constraint('DistanceY', geo_index, point_index, -1, 1, y_val))
def addPolygonToSketch(sketch, points, closed=True):
"""Add a polygon (series of line segments) to a sketch.
Args:
sketch: FreeCAD Sketcher object
points: List of FreeCAD Vectors or (x,y) tuples
closed: If True, connect last point back to first
Returns:
List of geometry indices for the line segments
"""
# Convert tuples to Vectors if needed
vec_points = []
for p in points:
if isinstance(p, tuple) or isinstance(p, list):
vec_points.append(App.Vector(p[0], p[1], 0))
else:
vec_points.append(p)
indices = []
num_points = len(vec_points)
# Add line segments
for i in range(num_points - 1):
line = Part.LineSegment(vec_points[i], vec_points[i + 1])
idx = sketch.addGeometry(line, False)
indices.append(idx)
# Close the polygon if requested
if closed and num_points > 2:
line = Part.LineSegment(vec_points[-1], vec_points[0])
idx = sketch.addGeometry(line, False)
indices.append(idx)
# Add coincident constraints to connect segments
for i in range(len(indices) - 1):
sketch.addConstraint(Sketcher.Constraint('Coincident', indices[i], 2, indices[i + 1], 1))
# If closed, connect last to first
if closed and len(indices) > 1:
sketch.addConstraint(Sketcher.Constraint('Coincident', indices[-1], 2, indices[0], 1))
return indices
def connectGeometry(sketch, geo1_idx, geo1_point, geo2_idx, geo2_point, tolerance=0.001):
"""Connect two geometry elements, adding a line if needed.
If the endpoints are coincident (within tolerance), only add a Coincident constraint.
If the endpoints are separated, add a line segment to connect them with Coincident
constraints at both ends.
Args:
sketch: FreeCAD Sketcher object
geo1_idx: Index of first geometry element (or Vector for point)
geo1_point: Point ID on first geometry (1=start, 2=end, 3=center) or None if geo1_idx is Vector
geo2_idx: Index of second geometry element (or Vector for point)
geo2_point: Point ID on second geometry (1=start, 2=end, 3=center) or None if geo2_idx is Vector
tolerance: Maximum distance to consider points coincident (default 0.001mm)
Returns:
Index of connecting line if created, None if only constraint added
"""
# Get the actual point coordinates
if isinstance(geo1_idx, App.Vector):
p1 = geo1_idx
geo1_is_point = True
else:
geom1 = sketch.Geometry[geo1_idx]
if geo1_point == 1:
p1 = geom1.StartPoint if hasattr(geom1, 'StartPoint') else geom1.Center
elif geo1_point == 2:
p1 = geom1.EndPoint if hasattr(geom1, 'EndPoint') else geom1.Center
else:
p1 = geom1.Center
geo1_is_point = False
if isinstance(geo2_idx, App.Vector):
p2 = geo2_idx
geo2_is_point = True
else:
geom2 = sketch.Geometry[geo2_idx]
if geo2_point == 1:
p2 = geom2.StartPoint if hasattr(geom2, 'StartPoint') else geom2.Center
elif geo2_point == 2:
p2 = geom2.EndPoint if hasattr(geom2, 'EndPoint') else geom2.Center
else:
p2 = geom2.Center
geo2_is_point = False
# Calculate distance between points
distance = p1.distanceToPoint(p2)
if distance < tolerance:
# Points are coincident - just add constraint if both are geometry (not raw points)
if not geo1_is_point and not geo2_is_point:
sketch.addConstraint(Sketcher.Constraint('Coincident', geo1_idx, geo1_point, geo2_idx, geo2_point))
return None
else:
# Points are separated - add connecting line
line = Part.LineSegment(p1, p2)
line_idx = sketch.addGeometry(line, False)
# Add coincident constraints
if not geo1_is_point:
sketch.addConstraint(Sketcher.Constraint('Coincident', geo1_idx, geo1_point, line_idx, 1))
if not geo2_is_point:
sketch.addConstraint(Sketcher.Constraint('Coincident', line_idx, 2, geo2_idx, geo2_point))
return line_idx
def connectGeometryChain(sketch, geo_indices, tolerance=0.001):
"""Connect a chain of geometry elements by finding closest endpoints.
Given a list of geometry indices, this function finds the two closest endpoints
among all the geometries and connects them (either with a constraint if coincident,
or with a line if separated). It repeats until all geometries are connected.
Args:
sketch: FreeCAD Sketcher object
geo_indices: List of geometry indices to connect
tolerance: Maximum distance to consider points coincident (default 0.001mm)
Returns:
List of connecting line indices (if any were created)
"""
if len(geo_indices) < 2:
return []
connecting_lines = []
remaining = geo_indices.copy()
# Build a list of all endpoints: (geo_idx, point_id, position_vector)
endpoints = []
for geo_idx in geo_indices:
geom = sketch.Geometry[geo_idx]
if hasattr(geom, 'StartPoint') and hasattr(geom, 'EndPoint'):
# Line or arc with start/end points
endpoints.append((geo_idx, 1, geom.StartPoint))
endpoints.append((geo_idx, 2, geom.EndPoint))
elif hasattr(geom, 'Center'):
# Circle - use center
endpoints.append((geo_idx, 3, geom.Center))
# Connect closest pairs until done
while len(endpoints) > 2:
# Find the two closest endpoints
min_dist = float('inf')
best_pair = None
for i in range(len(endpoints)):
for j in range(i + 1, len(endpoints)):
# Don't connect two points from the same geometry
if endpoints[i][0] == endpoints[j][0]:
continue
dist = endpoints[i][2].distanceToPoint(endpoints[j][2])
if dist < min_dist:
min_dist = dist
best_pair = (i, j)
if best_pair is None:
break
# Connect the closest pair
i, j = best_pair
geo1_idx, geo1_point, _ = endpoints[i]
geo2_idx, geo2_point, _ = endpoints[j]
line_idx = connectGeometry(sketch, geo1_idx, geo1_point, geo2_idx, geo2_point, tolerance)
if line_idx is not None:
connecting_lines.append(line_idx)
# Remove these endpoints from the list (remove higher index first)
if i > j:
endpoints.pop(i)
endpoints.pop(j)
else:
endpoints.pop(j)
endpoints.pop(i)
# Handle remaining two endpoints (close the loop)
if len(endpoints) == 2:
geo1_idx, geo1_point, _ = endpoints[0]
geo2_idx, geo2_point, _ = endpoints[1]
line_idx = connectGeometry(sketch, geo1_idx, geo1_point, geo2_idx, geo2_point, tolerance)
if line_idx is not None:
connecting_lines.append(line_idx)
return connecting_lines
def addBSplineToSketch(sketch, points, periodic=False):
"""Add a BSpline curve to a sketch.
Args:
sketch: FreeCAD Sketcher object
points: List of FreeCAD Vectors or (x,y) tuples
periodic: If True, create a closed BSpline
Returns:
Index of the BSpline geometry
"""
# Convert tuples to Vectors if needed
vec_points = []
for p in points:
if isinstance(p, tuple) or isinstance(p, list):
vec_points.append(App.Vector(p[0], p[1], 0))
else:
vec_points.append(p)
# Create BSpline curve
bspline = Part.BSplineCurve()
bspline.interpolate(vec_points, PeriodicFlag=periodic)
# Add to sketch
idx = sketch.addGeometry(bspline, False)
return idx
def rotatePoint(x, y, angle_rad):
"""Rotate a point around the origin.
Args:
x: X coordinate
y: Y coordinate
angle_rad: Rotation angle in radians (positive = counter-clockwise)
Returns:
Tuple of (x_rot, y_rot)
"""
cos_a = math.cos(angle_rad)
sin_a = math.sin(angle_rad)
x_rot = x * cos_a - y * sin_a
y_rot = x * sin_a + y * cos_a
return x_rot, y_rot
# ============================================================================
# Part Management
# ============================================================================
def findPlane(body, plane_name: str) -> Optional[object]:
"""
Find a plane in a body's Origin features robustly.
Args:
body: FreeCAD body object.
plane_name: Name of the plane to find ('XY', 'XZ', 'YZ').
Returns:
The found plane object or None if not found.
"""
if not hasattr(body, 'Origin') or not body.Origin:
logger.warning(f"Body '{body.Name}' has no Origin feature.")