-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspb_Crv_Ellipse_Approximate_with_arcs.py
More file actions
983 lines (728 loc) · 30.1 KB
/
spb_Crv_Ellipse_Approximate_with_arcs.py
File metadata and controls
983 lines (728 loc) · 30.1 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
"""
The script creates a 4-arc or 8-arc approximation of an ellipse. This is useful when an
ellipse or its NURBS equivalent are not wanted or allowed, as is the case of
some CAM software.
The construction geometry for the 4-arc method is based on Section 3 of https://www.researchgate.net/publication/241719740_Approximating_an_ellipse_with_four_circular_arcs
"""
#! python 2 Must be on a line less than 32.
from __future__ import absolute_import, division, print_function, unicode_literals
"""
250728-0803: Created.
TODO:
"""
import Rhino
import Rhino.Geometry as rg
import Rhino.Input as ri
import scriptcontext as sc
import math
class Opts:
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'fTol_IsEllipse'; keys.append(key)
values[key] = 1e-6 * Rhino.RhinoMath.UnitScale(
Rhino.UnitSystem.Millimeters, sc.doc.ModelUnitSystem)
names[key] = 'IsEllipseTol'
riOpts[key] = ri.Custom.OptionDouble(values[key], setLowerLimit=True,
limit=Rhino.RhinoMath.ZeroTolerance)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.ModelUnitSystem)
key = 'b8Arcs_not4'; keys.append(key)
values[key] = True
names[key] = 'NumOfArcsInEntireEllipse'
riOpts[key] = ri.Custom.OptionToggle(values[key], '4', '8')
stickyKeys[key] = '{}({})'.format(key, __file__)
#key = 'iNumPtsToCheck'; keys.append(key)
#values[key] = 31
#riOpts[key] = ri.Custom.OptionInteger(values[key], lowerLimit=1, upperLimit=255)
#stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bPolyCrvOutput_notArcs'; keys.append(key)
values[key] = True
names[key] = 'OutputCrv'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Arcs', 'Poly')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bReplace'; keys.append(key)
values[key] = False
names[key] = 'DocAction'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Add', 'Replace')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bAddEllipticalDeg2NurbsIfInputIsNot'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bEcho'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDebug'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
for key in keys:
if key not in names:
names[key] = key[1:]
# Load sticky.
for key in stickyKeys:
if stickyKeys[key] in sc.sticky:
if riOpts[key]:
values[key] = riOpts[key].CurrentValue = sc.sticky[stickyKeys[key]]
else:
# For OptionList.
values[key] = sc.sticky[stickyKeys[key]]
@classmethod
def addOption(cls, go, key):
idxOpt = None
if key in cls.riOpts:
if key[0] == 'b':
idxOpt = go.AddOptionToggle(
cls.names[key], cls.riOpts[key])[0]
elif key[0] == 'f':
idxOpt = go.AddOptionDouble(
cls.names[key], cls.riOpts[key])[0]
elif key[0] == 'i':
idxOpt = go.AddOptionInteger(
englishName=cls.names[key], intValue=cls.riOpts[key])[0]
elif key in cls.listValues:
idxOpt = go.AddOptionList(
englishOptionName=cls.names[key],
listValues=cls.listValues[key],
listCurrentIndex=cls.values[key])
else:
print("{} is not a valid key in Opts.".format(key))
return idxOpt
@classmethod
def setValue(cls, key, idxList=None):
#if key == 'fSearchTol':
# if cls.riOpts[key].CurrentValue < 0.0:
# cls.riOpts[key].CurrentValue = cls.values[key] = cls.riOpts[key].InitialValue
# sc.sticky[cls.stickyKeys[key]] = cls.values[key]
# return
# sc.sticky[cls.stickyKeys[key]] = cls.values[key] = cls.riOpts[key].CurrentValue
# return
if key == 'fTol_IsEllipse':
if cls.riOpts[key].CurrentValue < 0.0:
cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
elif cls.riOpts[key].CurrentValue < cls.riOpts[key].InitialValue:
cls.riOpts[key].CurrentValue = Rhino.RhinoMath.ZeroTolerance
sc.sticky[cls.stickyKeys[key]] = cls.values[key] = cls.riOpts[key].CurrentValue
return
if key in cls.riOpts:
sc.sticky[cls.stickyKeys[key]] = cls.values[key] = cls.riOpts[key].CurrentValue
return
if key in cls.listValues:
sc.sticky[cls.stickyKeys[key]] = cls.values[key] = idxList
print("Invalid key?")
def getInput(bDebug=False):
"""
Get curves or ellipse diameters.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select elliptical-shaped curves")
go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
#go.GeometryAttributeFilter = (
# ri.Custom.GeometryAttributeFilter.
#go.AcceptNumber(True, acceptZero=False)
go.EnableClearObjectsOnEntry(False) # If not set to False, faces will be unselected when result == ri.GetResult.Object
idxs_Opts = {}
def addOption(key): idxs_Opts[key] = Opts.addOption(go, key)
while True:
go.ClearCommandOptions()
idxs_Opts.clear()
addOption('fTol_IsEllipse')
addOption('b8Arcs_not4')
#addOption('iNumPtsToCheck')
addOption('bPolyCrvOutput_notArcs')
addOption('bReplace')
addOption('bAddEllipticalDeg2NurbsIfInputIsNot')
addOption('bEcho')
addOption('bDebug')
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return objrefs
if res == ri.GetResult.Number:
key = 'fTol_IsEllipse'
Opts.riOpts[key].CurrentValue = go.Number()
Opts.setValue(key)
continue
# An option was selected.
for key in idxs_Opts:
if go.Option().Index == idxs_Opts[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
def _formatDistance(fDistance, fPrecision=None):
if fDistance is None:
return "(None)"
if fDistance == Rhino.RhinoMath.UnsetValue:
return "(Infinite)"
if fPrecision is None:
fPrecision = sc.doc.ModelDistanceDisplayPrecision
if fDistance < 10.0**(-(fPrecision-1)):
# For example, if fDistance is 1e-5 and fPrecision == 5,
# the end of this script would display only one digit.
# Instead, this return displays 2 digits.
return "{:.2e}".format(fDistance)
return "{:.{}f}".format(fDistance, fPrecision)
def _is_iterable(obj):
try:
iter(obj)
return True
except TypeError:
return False
def _joinCrvs(curves_In):
rv = rg.Curve.JoinCurves(curves_In)
if len(rv) != 1:
#for c in rv: sc.doc.Objects.AddCurve(c)
raise Exception("JoinCurves produced {} curves.".format(len(rv)))
return rv[0]
def _getMaxDev(curvesA, curveB):
if _is_iterable(curvesA):
crv_WIP = _joinCrvs(curvesA)
else:
crv_WIP = curvesA.DuplicateCurve()
if not isinstance(curveB, rg.Curve):
curveB = curveB.ToNurbsCurve()
rv = rg.Curve.GetDistancesBetweenCurves(crv_WIP, curveB, tolerance=0.1*sc.doc.ModelAbsoluteTolerance)
crv_WIP.Dispose()
if not rv[0]:
raise Exception("GetDistancesBetweenCurves failed.")
return rv[1]
devs = []
for curveA in curvesA:
rv = rg.Curve.GetDistancesBetweenCurves(curveA, curveB, tolerance=0.1*sc.doc.ModelAbsoluteTolerance)
if not rv[0]:
for c in curvesA: sc.doc.Objects.AddCurve(c)
raise Exception("GetDistancesBetweenCurves failed.")
devs.append(rv[1])
return max(devs)
def create4ArcApproximation(a, b, iNumPtsToCheck=31, bDebug=False):
if a > b:
bFlippedAB = False
else:
a, b = b, a
bFlippedAB = True
ellipse_Ref = rg.Ellipse(rg.Plane.WorldXY, radius1=a, radius2=b)
nc_ellipse_Ref = ellipse_Ref.ToNurbsCurve()
nc_EllipticalArc_Ref = nc_ellipse_Ref.Trim(nc_ellipse_Ref.Domain.T0, nc_ellipse_Ref.Domain.Mid/2.0)
nc_ellipse_Ref.Dispose()
if bDebug: sc.doc.Objects.AddCurve(nc_EllipticalArc_Ref)
C = rg.Point3d(
x= (a-b)/2.0,
y=-(a-b)/2.0,
z=0.0)
if bDebug: sEval = "C"; print(sEval,'=',eval(sEval))
incircle = rg.Circle(center=C, radius=(a-b)/2.0)
arc_in = rg.Arc(
circle=incircle,
angleIntervalRadians=rg.Interval(
t0=Rhino.RhinoMath.ToRadians(-90.0),
t1=0.0))
arcCrv_in = rg.ArcCurve(arc_in)
if bDebug: sc.doc.Objects.AddCurve(arcCrv_in)
A = rg.Point3d(a, 0.0, 0.0)
B = rg.Point3d(0.0, b, 0.0)
E = rg.Point3d(a, b, 0.0)
radius_conArc = (A - C).Length
if bDebug: sEval = "radius_conArc"; print(sEval,'=',eval(sEval))
if bDebug: sEval = "type(radius_conArc)"; print(sEval,'=',eval(sEval))
concentriccircle = rg.Circle(center=C, radius=radius_conArc)
lineBE = rg.Line(B, E)
#if bDebug: sc.doc.Objects.AddLine(lineBE)
# Alternative method to determine D.
#rvs = rg.Intersect.Intersection.LineCircle(lineBE, concentriccircle)
#D = rvs[4]
D = rg.Point3d(a-b, b, 0.0)
if bDebug: sEval = "D"; print(sEval,'=',eval(sEval))
angleIntervalRadians = rg.Interval(
math.atan2(A.Y - C.Y, A.X - C.X),
math.atan2(D.Y - C.Y, D.X - C.X))
if bDebug: sEval = "angleIntervalRadians"; print(sEval,'=',eval(sEval))
arc_con = rg.Arc(
circle=concentriccircle,
angleIntervalRadians=angleIntervalRadians)
#sc.doc.Objects.AddArc(arc_con)
domainLength = arc_con.AngleDomain.Length
domainStart = arc_con.AngleDomain.T0
domainEnd = arc_con.AngleDomain.T1
def getArcsAtT(T):
bSuccess, t = arcCrv_in.GetLocalTangentPoint(
testPoint=T,
seedParmameter=arcCrv_in.Domain.Mid)
if bDebug: sEval = "t"; print(sEval,'=',eval(sEval))
line_tan = rg.Line(T, arcCrv_in.PointAt(t))
if bDebug: sEval = "line_tan"; print(sEval,'=',eval(sEval))
if bDebug: sc.doc.Objects.AddLine(line_tan)
lineOA = rg.Line(rg.Point3d.Origin, A)
#if bDebug: sc.doc.Objects.AddLine(lineOA)
lineOB = rg.Line(rg.Point3d.Origin, B)
#if bDebug: sc.doc.Objects.AddLine(lineOB)
bSuccess, tOA, t_tan = rg.Intersect.Intersection.LineLine(lineOA, line_tan)
if not bSuccess:
raise Exception("Intersection.LineLine failed.")
C1 = lineOA.PointAt(tOA)
if bDebug: sEval = "C1"; print(sEval,'=',eval(sEval))
if bDebug: sc.doc.Objects.AddPoint(C1)
bSuccess, tOB, t_tan = rg.Intersect.Intersection.LineLine(lineOB, line_tan)
if not bSuccess:
raise Exception("Intersection.LineLine failed.")
C2 = lineOB.PointAt(tOB)
if bDebug: sEval = "C2"; print(sEval,'=',eval(sEval))
if bDebug: sc.doc.Objects.AddPoint(C2)
circle_AT = rg.Circle(center=C1, radius=(A-C1).Length)
if bDebug: sc.doc.Objects.AddCircle(circle_AT)
angle = math.atan2(T.Y - C1.Y, T.X - C1.X)
angleIntervalRadians = rg.Interval(-angle, angle)
arc_AT = rg.Arc(
circle=circle_AT,
angleIntervalRadians=angleIntervalRadians)
#sc.doc.Objects.AddArc(arc_AT)
arcCrv_AT = rg.ArcCurve(arc_AT)
circle_BT = rg.Circle(center=C2, radius=(B-C2).Length)
if bDebug: sc.doc.Objects.AddCircle(circle_BT)
angle = math.atan2(T.Y - C2.Y, T.X - C2.X)
angleIntervalRadians = rg.Interval(angle, math.pi-angle)
#sEval = "angleIntervalRadians"; print(sEval,'=',eval(sEval))
arc_BT = rg.Arc(
circle=circle_BT,
angleIntervalRadians=angleIntervalRadians)
#sc.doc.Objects.AddArc(arc_BT)
arcCrv_BT = rg.ArcCurve(arc_BT)
return arcCrv_AT, arcCrv_BT
##
# Equally-spaced method
Ts = []
devs = []
arcCrvs_AT = []
arcCrvs_BT = []
def checkAllEquallySpacedPts():
for i in range(1, (iNumPtsToCheck+1)):
sc.escape_test()
tangle = (float(i)/float(iNumPtsToCheck+1))*domainLength + domainStart
T = arc_con.PointAt(tangle)
#sc.doc.Objects.AddPoint(T)
arcCrv_AT, arcCrv_BT = getArcsAtT(T)
dev = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
Ts.append(T)
devs.append(dev)
arcCrvs_AT.append(arcCrv_AT)
arcCrvs_BT.append(arcCrv_BT)
# Graph deviations.
#sc.doc.Objects.AddLine(
# rg.Point3d(float(i), 0.0, 0.0),
# rg.Point3d(float(i), dev, 0.0))
idxWinner = devs.index(min(devs))
print("Index {} of {} pts".format(idxWinner, len(Ts)))
print("Max. dev. from ellipse: {}".format(_formatDistance(devs[idxWinner])))
T = Ts[idxWinner]
arcCrv_AT = arcCrvs_AT[idxWinner]
arcCrv_BT = arcCrvs_BT[idxWinner]
return arcCrv_AT, arcCrv_BT
#arcCrv_AT, arcCrv_BT = checkAllEquallySpacedPts()
##
##
# Quarter search method
arcCrv_con = rg.ArcCurve(arc_con)
if bDebug: sc.doc.Objects.AddCurve(arcCrv_con)
#sEval = "arc_con.AngleDomain"; print(sEval,'=',eval(sEval))
#sEval = "arcCrv_con.Domain"; print(sEval,'=',eval(sEval))
ts_arcCrv = arcCrv_con.DivideByLength(10.0*sc.doc.ModelAbsoluteTolerance, includeEnds=False)
T_H = arcCrv_con.PointAt(ts_arcCrv[-1])
t_H = arc_con.ClosestParameter(T_H)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_H)
#sc.doc.Objects.AddCurve(arcCrv_AT)
#sc.doc.Objects.AddCurve(arcCrv_BT)
dev_H = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
T_L = arcCrv_con.PointAt(ts_arcCrv[0])
t_L = arc_con.ClosestParameter(T_L)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_L)
dev_L = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
#sc.doc.Objects.AddPoint(T_L)
i = 0
while T_H.DistanceTo(T_L) > (0.1 * sc.doc.ModelAbsoluteTolerance):
sc.escape_test()
i += 1
#print('-'*20)
#sEval = "dev_H"; print(sEval,'=',eval(sEval))
t_MH = 0.75*t_H + 0.25*t_L
T_MH = arc_con.PointAt(t_MH)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_MH)
dev_MH = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
#sEval = "dev_MH"; print(sEval,'=',eval(sEval))
t_MM = 0.5*t_H + 0.5*t_L
T_MM = arc_con.PointAt(t_MM)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_MM)
dev_MM = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
#sEval = "dev_MM"; print(sEval,'=',eval(sEval))
t_ML = 0.25*t_H + 0.75*t_L
T_ML = arc_con.PointAt(t_ML)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_ML)
dev_ML = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
#sEval = "dev_ML"; print(sEval,'=',eval(sEval))
#sEval = "dev_L"; print(sEval,'=',eval(sEval))
bChanged = False
if dev_MM < dev_MH < dev_H:
T_H = T_MH
t_H = t_MH
dev_H = dev_MH
bChanged = True
if dev_MM < dev_ML < dev_L:
T_L = T_ML
t_L = t_ML
dev_L = dev_ML
bChanged = True
if not bChanged:
raise Exception("No change.")
#print("Search took {} iterations.".format(i))
#print('-'*20)
t_MM = 0.5*t_H + 0.5*t_L
T_MM = arc_con.PointAt(t_MM)
arcCrv_AT, arcCrv_BT = getArcsAtT(T_MM)
dev_MM = _getMaxDev((arcCrv_AT, arcCrv_BT), nc_EllipticalArc_Ref)
#sEval = "dev_MM"; print(sEval,'=',eval(sEval))
if bFlippedAB:
xform = rg.Transform.Mirror(
mirrorPlane=rg.Plane(
origin=rg.Point3d.Origin,
normal=rg.Vector3d(-1.0, 1.0, 0.0)))
arcCrv_AT.Transform(xform)
arcCrv_BT.Transform(xform)
xform = rg.Transform.Rotation(
angleRadians=math.pi,
rotationCenter=rg.Point3d.Origin)
arcCrv_AT_Dup = rg.ArcCurve(arcCrv_AT)
bSuccess = arcCrv_AT_Dup.Transform(xform)
#sc.doc.Objects.AddCurve(arcCrv_AT)
#sc.doc.Objects.AddCurve(arcCrv_AT_Dup)
arcCrv_BT_Dup = rg.ArcCurve(arcCrv_BT)
bSuccess = arcCrv_BT_Dup.Transform(xform)
#sc.doc.Objects.AddCurve(arcCrv_BT)
#sc.doc.Objects.AddCurve(arcCrv_BT_Dup)
if bFlippedAB:
return (arcCrv_BT, arcCrv_AT, arcCrv_BT_Dup, arcCrv_AT_Dup), dev_MM
else:
return (arcCrv_AT, arcCrv_BT, arcCrv_AT_Dup, arcCrv_BT_Dup), dev_MM
def create8ArcApproximation(a, b, bDebug=False):
if abs(a - b) < sc.doc.ModelAbsoluteTolerance:
return
if a > b:
bFlippedAB = False
else:
a, b = b, a
bFlippedAB = True
ellipse_Ref = rg.Ellipse(rg.Plane.WorldXY, radius1=a, radius2=b)
nc_ellipse_Ref = ellipse_Ref.ToNurbsCurve()
nc_EllipticalArc_Ref = nc_ellipse_Ref.Trim(nc_ellipse_Ref.Domain.T0, nc_ellipse_Ref.Domain.Mid/2.0)
nc_ellipse_Ref.Dispose()
if bDebug: sc.doc.Objects.AddCurve(nc_EllipticalArc_Ref)
rA = (b**2)/a
rB = (a**2)/b
if min((rA, rB)) < 10.0*sc.doc.ModelAbsoluteTolerance:
print("One arc radius is {}.".format(
_formatDistance(min((rA, rB)))),
"(The ellipse's eccentricity is {}.)".format(ellipse_Ref.FocalDistance / a),
"The ellipse is not supported by this script.")
return
if bDebug: sEval = "rA"; print(sEval,'=',eval(sEval))
if bDebug: sEval = "rB"; print(sEval,'=',eval(sEval))
rF = 0.5*(rA + rB)
CA = rg.Point3d(a-rA, 0.0, 0.0)
circle_A = rg.Circle(center=CA, radius=rA)
if bDebug: sc.doc.Objects.AddCircle(circle_A)
arc_A = rg.Arc(
circle=circle_A,
angleIntervalRadians=rg.Interval(
t0=0.0,
t1=math.pi/2.0))
if bDebug: sc.doc.Objects.AddArc(arc_A)
arcCrv_A = rg.ArcCurve(arc_A)
if bDebug: sc.doc.Objects.AddCurve(arcCrv_A)
CB = rg.Point3d(0.0, b-rB, 0.0)
circle_B = rg.Circle(center=CB, radius=rB)
if bDebug: sc.doc.Objects.AddCircle(circle_B)
arc_B = rg.Arc(
circle=circle_B,
angleIntervalRadians=rg.Interval(
t0=0.0,
t1=math.pi/2))
if bDebug: sc.doc.Objects.AddArc(arc_B)
arcCrv_B = rg.ArcCurve(arc_B)
if arcCrv_B.PointAtStart.X > a:
bSuccess, t = arcCrv_B.ClosestPoint(arc_A.Center)
if not bSuccess:
raise Exception("ClosestPoint failed.")
arcCrv_B = arcCrv_B.Trim(t, arcCrv_B.Domain.T1)
if bDebug: sc.doc.Objects.AddCurve(arcCrv_B)
#arc_F = rg.Curve.CreateFillet(
# curve0=arcCrv_A,
# curve1=arcCrv_B,
# radius=rF,
# t0Base=arcCrv_A.Domain.Mid,
# t1Base=arcCrv_B.Domain.Mid)
#sc.doc.Objects.AddArc(arc_F)
A = rg.Point3d(a, 0.0, 0.0)
B = rg.Point3d(0.0, b, 0.0)
def createFilletCurves(radius):
for point0 in arcCrv_A.PointAtMid, arcCrv_A.PointAtStart, arcCrv_A.PointAtEnd:
for point1 in arcCrv_B.PointAtMid, arcCrv_B.PointAtEnd, arcCrv_B.PointAtStart:
rv = rg.Curve.CreateFilletCurves(
curve0=arcCrv_A,
point0=point0,
curve1=arcCrv_B,
point1=point1,
radius=radius,
join=False,
trim=True,
arcExtension=True,
tolerance=0.1*sc.doc.ModelAbsoluteTolerance,
angleTolerance=0.1*sc.doc.ModelAngleToleranceRadians)
if len(rv) == 0:
raise Exception("No curves.")
for c in rv:
if not c.IsValid:
raise Exception("Curve from CreateFilletCurves is invalid.")
for c in rv:
if c.AngleDegrees > 90.0:
#print("Curve of {} degrees found in CreateFilletCurves with radius of {} and point0 at {} and point1 at {}.".format(
# c.AngleDegrees, radius, point0, point1))
for c in rv:
c.Dispose()
break
else:
# Success.
return rv
raise Exception("CreateFilletCurves failed to provide all good curves < 90 degrees.")
if bDebug: sEval = "rv"; print(sEval,'=',eval(sEval))
if bDebug: sc.doc.Objects.AddCurve(rv[2])
r_H = (a**2 + a*b) / (2*b)
r_L = (b**2 + a*b) / (2*a)
crvs_H = createFilletCurves(r_H)
dev_H = _getMaxDev(crvs_H, nc_EllipticalArc_Ref)
crvs_L = createFilletCurves(r_L)
dev_L = _getMaxDev(crvs_L, nc_EllipticalArc_Ref)
i = 0
while (r_H - r_L) > 0.1 * sc.doc.ModelAbsoluteTolerance:
sc.escape_test()
i += 1
r_MH = 0.75*r_H + 0.25*r_L
crvs_MH = createFilletCurves(r_MH)
dev_MH = _getMaxDev(crvs_MH, nc_EllipticalArc_Ref)
r_MM = 0.5*r_H + 0.5*r_L
crvs_MM = createFilletCurves(r_MM)
dev_MM = _getMaxDev(crvs_MM, nc_EllipticalArc_Ref)
r_ML = 0.25*r_H + 0.75*r_L
crvs_ML = createFilletCurves(r_ML)
dev_ML = _getMaxDev(crvs_ML, nc_EllipticalArc_Ref)
bChanged = False
if dev_MM < dev_MH < dev_H:
r_H = r_MH
dev_H = dev_MH
for c in crvs_H: c.Dispose()
crvs_H = crvs_MH
bChanged = True
elif dev_MM < dev_H and dev_MM < dev_MH:
r_H = r_MH
dev_H = dev_MH
for c in crvs_H: c.Dispose()
crvs_H = crvs_MH
bChanged = True
if dev_MM < dev_L and dev_MM < dev_ML:
r_L = r_ML
dev_L = dev_ML
for c in crvs_L: c.Dispose()
crvs_L = crvs_ML
bChanged = True
if not bChanged:
if dev_ML < dev_MH:
r_H = r_MH
dev_H = dev_MH
for c in crvs_H: c.Dispose()
crvs_H = crvs_MH
bChanged = True
elif dev_MH < dev_ML:
r_L = r_ML
dev_L = dev_ML
for c in crvs_L: c.Dispose()
crvs_L = crvs_ML
bChanged = True
if not bChanged:
sEval = "dev_H"; print(sEval,'=',eval(sEval))
sEval = "dev_MH"; print(sEval,'=',eval(sEval))
sEval = "dev_MM"; print(sEval,'=',eval(sEval))
sEval = "dev_ML"; print(sEval,'=',eval(sEval))
sEval = "dev_L"; print(sEval,'=',eval(sEval))
#for c in crvs_H: sc.doc.Objects.AddCurve(c)
print("Iterations: {}".format(i))
print("Eccentricy of ellipse may be too large for this script.")
return
for c in crvs_MH: c.Dispose()
for c in crvs_MM: c.Dispose()
for c in crvs_ML: c.Dispose()
print("Search took {} iterations.".format(i))
r_MM = 0.5*r_H + 0.5*r_L
#sc.doc.Objects.AddCurve(arcCrv_A)
#sc.doc.Objects.AddCurve(arcCrv_B)
#return
rv = createFilletCurves(r_MM)
if len(rv) != 3:
raise Exception("len(rv) : ".format(len(rv)))
dev_MM = _getMaxDev(rv, nc_EllipticalArc_Ref)
#for c in rv:
# sc.doc.Objects.AddCurve(c)
arcCrv_A, arcCrv_B, arcCrv_F = rv
if bFlippedAB:
xform = rg.Transform.Mirror(
mirrorPlane=rg.Plane(
origin=rg.Point3d.Origin,
normal=rg.Vector3d(-1.0, 1.0, 0.0)))
arcCrv_A.Transform(xform)
arcCrv_B.Transform(xform)
arcCrv_F.Transform(xform)
arc_A = arcCrv_A.Arc
arc_B = arcCrv_B.Arc
#for c in rv:
# sc.doc.Objects.AddCurve(c)
#return
arc_A.StartAngle = -arc_A.EndAngle
arcCrv_A = rg.ArcCurve(arc_A)
#sc.doc.Objects.AddCurve(arcCrv_A)
arc_B.EndAngle = math.pi - arc_B.StartAngle
arcCrv_B = rg.ArcCurve(arc_B)
#sc.doc.Objects.AddCurve(arcCrv_B)
arcCrv_A_Dup = rg.ArcCurve(arcCrv_A)
arcCrv_B_Dup = rg.ArcCurve(arcCrv_B)
arcCrv_F_Dup1 = rg.ArcCurve(arcCrv_F)
xform = rg.Transform.Mirror(
mirrorPlane=rg.Plane(
origin=rg.Point3d.Origin,
normal=rg.Vector3d(0.0, 1.0, 0.0)))
bSuccess = arcCrv_B_Dup.Transform(xform)
bSuccess = arcCrv_F_Dup1.Transform(xform)
arcCrv_F_Dup2 = rg.ArcCurve(arcCrv_F)
arcCrv_F_Dup3 = rg.ArcCurve(arcCrv_F_Dup1)
xform = rg.Transform.Mirror(
mirrorPlane=rg.Plane(
origin=rg.Point3d.Origin,
normal=rg.Vector3d(1.0, 0.0, 0.0)))
bSuccess = arcCrv_A_Dup.Transform(xform)
bSuccess = arcCrv_F_Dup2.Transform(xform)
bSuccess = arcCrv_F_Dup3.Transform(xform)
return ((
arcCrv_A,
arcCrv_F,
arcCrv_B,
arcCrv_F_Dup2,
arcCrv_A_Dup,
arcCrv_F_Dup3,
arcCrv_B_Dup,
arcCrv_F_Dup1
),
dev_MM
)
def main():
objrefs = getInput()
if objrefs is None: return
fTol_IsEllipse = Opts.values['fTol_IsEllipse']
b8Arcs_not4 = Opts.values['b8Arcs_not4']
#iNumPtsToCheck = Opts.values['iNumPtsToCheck']
bPolyCrvOutput_notArcs = Opts.values['bPolyCrvOutput_notArcs']
bAddEllipticalDeg2NurbsIfInputIsNot = Opts.values['bAddEllipticalDeg2NurbsIfInputIsNot']
bReplace = Opts.values['bReplace']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
if not bDebug: sc.doc.Views.RedrawEnabled = False
fDevs = []
gAdded = []
gReplaced = []
for objref in objrefs:
rgC_In = objref.Curve()
if rgC_In is None:
raise Exception("Curve not found!")
continue
if isinstance(rgC_In, rg.ArcCurve):
if bEcho and len(objrefs) == 1:
print("Skipped ArcCurve.")
return
continue
if rgC_In.IsArc():
if bEcho and len(objrefs) == 1:
print("Skipped arc-shaped curve.")
return
continue
bSuccess, ellipse = rgC_In.TryGetEllipse()
if bSuccess:
bInputIsAccurateEllipse = True
else:
bSuccess, ellipse = rgC_In.TryGetEllipse(tolerance=fTol_IsEllipse)
if not bSuccess:
continue
bInputIsAccurateEllipse = False
if isinstance(rgC_In, rg.BrepEdge):
bIsEdge = True
rgC_In_NotProxy = rgC_In.DuplicateCurve()
else:
bIsEdge = False
rgC_In_NotProxy = rgC_In
bIsNurbsCrv = isinstance(rgC_In_NotProxy, rg.NurbsCurve)
#radius = arc.Radius
#radii.append(radius)
a = ellipse.Radius1
b = ellipse.Radius2
if b8Arcs_not4:
rv = create8ArcApproximation(a, b, bDebug=bDebug)
else:
rv = create4ArcApproximation(a, b, bDebug=bDebug)
if rv is None:
continue
arcCrvs_Res, fDev = rv
fDevs.append(fDev)
xform = rg.Transform.PlaneToPlane(rg.Plane.WorldXY, ellipse.Plane)
if bPolyCrvOutput_notArcs:
polycrv = rg.Curve.JoinCurves(arcCrvs_Res)[0]
polycrv.Transform(xform)
if bReplace and not bIsEdge:
if sc.doc.Objects.Replace(objref, curve=polycrv):
gReplaced.append(objref.ObjectId)
else:
print("Could not replace curve, {}.".format(objref.ObjectId))
else:
gOut = sc.doc.Objects.AddCurve(polycrv)
if gOut != gOut.Empty:
gAdded.append(gOut)
else:
print("Could not add curve approximation of {}.".format(objref.ObjectId))
else:
bFailedToAddSomeArcs = False
for c in arcCrvs_Res:
c.Transform(xform)
gOut = sc.doc.Objects.AddCurve(c)
if gOut != gOut.Empty:
gAdded.append(gOut)
else:
bFailedToAddSomeArcs = True
print("Could not add ArcCurve for approximation of {}.".format(objref.ObjectId))
if bReplace and not bIsEdge:
if not bFailedToAddSomeArcs:
if sc.doc.Objects.Delete(objref, quiet=False):
gReplaced.append(objref.ObjectId)
if bAddEllipticalDeg2NurbsIfInputIsNot:
if not (bInputIsAccurateEllipse and bIsNurbsCrv and rgC_In_NotProxy.Degree == 2):
gOut = sc.doc.Objects.AddEllipse(ellipse)
if gOut != gOut.Empty:
gAdded.append(gOut)
if bEcho:
ss = []
if gAdded:
ss.append("Added {} curves.".format(len(gAdded)))
if gReplaced:
ss.append("Replaced {} curves.".format(len(gReplaced)))
if fDevs:
ss.append("{} maximum deviation.".format(_formatDistance(max(fDevs))))
print(*ss)
sc.doc.Views.RedrawEnabled = True
if __name__ == '__main__': main()