-
Notifications
You must be signed in to change notification settings - Fork 7
/
spb_Crv_match.py
1495 lines (1218 loc) · 54.8 KB
/
spb_Crv_match.py
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
"""
Notes on UI's _Match:
A unitized tangent vector, as obtained with Curve.CurvatureAt, seems to be used for
Tangent and Curvature matches (at least with Average disabled)
For Tangent matches, NurbsCurve.SetEndCondition results are identical.
For Curvature matches, identical results were not found but were closer when using
the unitized tangent vector than when using the 1st derivative vector of Curve B directly.
"""
"""
190708-25: Created.
190824: Now, a unit vector is used when target continuity is G1. Otherwise, SetEndCondition may move the control point quite far from the closest possible position.
Added curve deviation feedback.
190831: Now tests whether joint is already at desired continuity before calculating new curve(s).
190907: Refactored. Added bLimitCrvDev and fDevTol.
190908-12: More refactoring and optimization of curves.
190913: Added sContinuity in place of iContinuity in most functions. Various debugging and refactoring.
190918: createForCurveA: Now curves with dev of None will not pass.
createForBothCurves is functional for position and tangency continuities.
190919: Bug fix.
190924, 1010, 1020: Import-related update.
191208: Printed output bug fix.
200112-16: Updated Opts to latest code format. Import-related updates.
200120: Refactored, nesting some functions for simpler outside code calling this module.
200505: Import-related updates.
200630: Now correctly compares control point positions between curves of different degrees for C1 matching.
Improved printed feedback when curve is not modified.
201122, 210908: Import-related updates.
211029: Simplified curve to modify option from 3 to 2 choices. Added fAngleTol_Deg.
220328, 0425, 1122: Import-related update.
TODO:
Try to adjust for G1 to same G0G1 length as original curve. Check its deviation against SetEndCondition result.
Determine whether to keep C1 continuity (and add C2).
If so, one scenario is to set all curve domains to [0.0,1.0] before matching.
"""
import Rhino
import Rhino.Geometry as rg
import Rhino.Input as ri
import scriptcontext as sc
from System import Enum
from System import Guid
from System.Drawing import Color
import spb_Crv_continuityBetween2
import spb_Crv_fitRebuild
import spb_Crv_inflections
import spb_Crv_radiusMinima
import spb_NurbsCrv_maximizeMinimumRadius
sOpts_Continuity = ['G0', 'G1', 'C1', 'G2']
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
riAddOpts = {}
stickyKeys = {}
def addOptionDouble(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionDouble(
getObj, englishName=names[key], numberValue=riOpts[key])
def addOptionInteger(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionInteger(
getObj, englishName=names[key], intValue=riOpts[key])
def addOptionList(key, names, listValues, values):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionList(
getObj,
englishOptionName=names[key],
listValues=listValues,
listCurrentIndex=values[key])
def addOptionToggle(key, names, riOpts):
return lambda getObj: ri.Custom.GetBaseClass.AddOptionToggle(
getObj, englishName=names[key], toggleValue=riOpts[key])
key = 'iContinuity'; keys.append(key)
values[key] = 1
riAddOpts[key] = addOptionList(key, names, sOpts_Continuity, values)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fAngleTol_Deg'; keys.append(key)
values[key] = 0.1 * sc.doc.ModelAngleToleranceDegrees
names[key] = 'AngleTol'
riOpts[key] = ri.Custom.OptionDouble(values[key])
riAddOpts[key] = addOptionDouble(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bSkipIfAlreadyAtContinuity'; keys.append(key)
values[key] = True
names[key] = 'IfAlreadyAtContinuity'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Process', 'Skip')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'iPreserveOtherEnd'; keys.append(key)
values[key] = 2
names[key] = 'PreserveOtherEnd'
riAddOpts[key] = addOptionList(key, names,
Enum.GetNames(rg.NurbsCurve.NurbsCurveEndConditionType),
values)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bLimitCrvDev'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fDevTol'; keys.append(key)
values[key] = 0.1 * sc.doc.ModelAbsoluteTolerance
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key])
riAddOpts[key] = addOptionDouble(key, names, riOpts)
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bMaximizeMinRadius'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bModOnly1stPicked'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(initialValue=values[key], offValue='No', onValue='Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDeformLines'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(initialValue=values[key], offValue='No', onValue='Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bRebuildRationals'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(initialValue=values[key], offValue='No', onValue='Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bReplace'; keys.append(key)
values[key] = True
names[key] = 'Action'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Add', 'Replace')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bEcho'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDebug'; keys.append(key)
values[key] = False
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
riAddOpts[key] = addOptionToggle(key, names, riOpts)
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 key in riOpts:
riOpts[key].CurrentValue = values[key] = sc.sticky[stickyKeys[key]]
else:
values[key] = sc.sticky[stickyKeys[key]]
@classmethod
def setValues(cls):
for key in cls.keys:
if key in cls.riOpts:
cls.values[key] = cls.riOpts[key].CurrentValue
@classmethod
def saveSticky(cls):
for key in cls.stickyKeys:
if key in cls.riOpts:
sc.sticky[cls.stickyKeys[key]] = cls.riOpts[key].CurrentValue
else:
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
def addGeoms(geoms, bRedraw=True):
""" For debugging. """
if not hasattr(geoms, '__iter__'):
geoms = [geoms]
for geom in geoms:
if isinstance(geom, tuple):
gOut = sc.doc.Objects.AddSurface(geom[1])
elif isinstance(geom, rg.Curve):
gOut = sc.doc.Objects.AddCurve(geom)
elif isinstance(geom, rg.Surface):
gOut = sc.doc.Objects.AddSurface(geom)
elif isinstance(geom, rg.Point3d):
gOut = sc.doc.Objects.AddPoint(geom)
elif isinstance(geom, rg.Plane):
intrvl = rg.Interval(-sc.doc.ModelAbsoluteTolerance*1000.0, sc.doc.ModelAbsoluteTolerance*1000.0)
psrf = rg.PlaneSurface(geom, intrvl, intrvl)
gOut = sc.doc.Objects.AddSurface(psrf)
else:
raise ValueError("Method to add {} missing from addGeoms.".format(geom))
if bRedraw: sc.doc.Views.Redraw()
return gOut
def getInput():
"""
Get curve and parameter with optional input.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select 2 curves near their ends to match")
go.GeometryFilter = Rhino.DocObjects.ObjectType.Curve
go.OneByOnePostSelect = True
go.DisablePreSelect()
go.AcceptNumber(True, acceptZero=True)
idxs_Opts = {}
while True:
idxs_Opts['iContinuity'] = Opts.riAddOpts['iContinuity'](go)
idxs_Opts['fAngleTol_Deg'] = Opts.riAddOpts['fAngleTol_Deg'](go)
Opts.riAddOpts['bSkipIfAlreadyAtContinuity'](go)
idxs_Opts['iPreserveOtherEnd'] = Opts.riAddOpts['iPreserveOtherEnd'](go)
Opts.riAddOpts['bLimitCrvDev'](go)
if Opts.values['bLimitCrvDev']: Opts.riAddOpts['fDevTol'](go)
if sOpts_Continuity[Opts.values['iContinuity']] in ('G0', 'G1'):
Opts.riAddOpts['bMaximizeMinRadius'](go)
Opts.riAddOpts['bModOnly1stPicked'](go)
Opts.riAddOpts['bDeformLines'](go)
Opts.riAddOpts['bRebuildRationals'](go)
Opts.riAddOpts['bReplace'](go)
Opts.riAddOpts['bEcho'](go)
Opts.riAddOpts['bDebug'](go)
res = go.GetMultiple(minimumNumber=2, maximumNumber=2)
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
objrefs = go.Objects()
go.Dispose()
return tuple([objrefs] + [Opts.values[key] for key in Opts.keys])
# An option was selected or a number was entered.
key = 'fAngleTol_Deg'
if Opts.riOpts[key].CurrentValue <= 0.0:
Opts.riOpts[key].CurrentValue = Opts.riOpts[key].InitialValue
if res == ri.GetResult.Number:
Opts.riOpts['fDevTol'].CurrentValue = go.Number()
elif res == ri.GetResult.Option:
if go.Option().Index == idxs_Opts['iContinuity']:
Opts.values['iContinuity'] = (
go.Option().CurrentListOptionIndex)
elif go.Option().Index == idxs_Opts['iPreserveOtherEnd']:
Opts.values['iPreserveOtherEnd'] = (
go.Option().CurrentListOptionIndex)
if Opts.riOpts['bLimitCrvDev'].CurrentValue:
key = 'fDevTol'
if Opts.riOpts[key].CurrentValue <= 0.0:
Opts.riOpts[key].CurrentValue = Opts.riOpts[key].InitialValue
Opts.setValues()
Opts.saveSticky()
go.ClearCommandOptions()
def getMaximumDeviation(rgCrvA, rgCrvB):
rc = rg.Curve.GetDistancesBetweenCurves(
rgCrvA,
rgCrvB,
tolerance=0.1*sc.doc.ModelAbsoluteTolerance)
if rc[0]:
return rc[1]
def formatDistance(fDistance):
if fDistance is None:
return "(None)"
if fDistance == Rhino.RhinoMath.UnsetValue:
return "(Infinite)"
if fDistance < 10.0**(-(sc.doc.DistanceDisplayPrecision-3)):
return "{:.2e}".format(fDistance)
return "{:.{}f}".format(fDistance, sc.doc.ModelDistanceDisplayPrecision)
def createNurbsCurves(rgCurveA, rgCurveB, bT1WorkEnd_A, bT1WorkEnd_B, bModifyA, bModifyB, **kwargs):
"""
Parameters:
rgCurveA
rgCurveB
bT1WorkEnd_A
bT1WorkEnd_B
bModifyA: If both bModifyA and bModifyB are False, will return the curve with less deviation result.
bModifyB: (See bModifyA.)
Returns:
Success (One of the following):
rg.NurbsCurve, rg.NurbsCurve
rg.NurbsCurve, None
None, rg.NurbsCurve
Fail: None
"""
def getOpt(key): return kwargs[key] if key in kwargs else Opts.values[key]
if 'sContinuity' in kwargs:
sContinuity = kwargs['sContinuity']
else:
sContinuity = sOpts_Continuity[Opts.values['iContinuity']]
fAngleTol_Deg = getOpt('fAngleTol_Deg')
bSkipIfAlreadyAtContinuity = getOpt('bSkipIfAlreadyAtContinuity')
iPreserveOtherEnd = getOpt('iPreserveOtherEnd')
fDevTol = getOpt('fDevTol')
bMaximizeMinRadius = getOpt('bMaximizeMinRadius')
bDeformLines = getOpt('bDeformLines')
bRebuildRationals = getOpt('bRebuildRationals')
bEcho = getOpt('bEcho')
bDebug = getOpt('bDebug')
if not bModifyA and not bModifyB:
print "Neither curve is supposed to be modified."
return
def areCurvesAlreadyAtDesiredContinuity():
"""
"""
nc0_A = rgCurveA.ToNurbsCurve()
if bT1WorkEnd_A:
t_WorkEnd_A = nc0_A.Domain.T1
crvEvalSide_A = rg.CurveEvaluationSide.Below
idxCp_Pos_A = nc0_A.Points.Count - 1
idxCp_Tan_A = nc0_A.Points.Count - 2
else:
t_WorkEnd_A = nc0_A.Domain.T0
crvEvalSide_A = rg.CurveEvaluationSide.Above
idxCp_Pos_A = 0
idxCp_Tan_A = 1
nc0_B = rgCurveB.ToNurbsCurve()
if bT1WorkEnd_B:
t_WorkEnd_B = nc0_B.Domain.T1
crvEvalSide_B = rg.CurveEvaluationSide.Below
idxCp_Pos_B = nc0_B.Points.Count - 1
idxCp_Tan_B = nc0_B.Points.Count - 2
else:
t_WorkEnd_B = nc0_B.Domain.T0
crvEvalSide_B = rg.CurveEvaluationSide.Above
idxCp_Pos_B = 0
idxCp_Tan_B = 1
rc = spb_Crv_continuityBetween2.processCurves(
nc0_A,
nc0_B,
bEvalT1End_A=bT1WorkEnd_A,
bEvalT1End_B=bT1WorkEnd_B,
fDistTol=Rhino.RhinoMath.ZeroTolerance,
fAngleTol_Vector_Deg=fAngleTol_Deg,
bAlignCrvDirs=True,
bDebug=bDebug,
)
if not rc:
print "Error in obtaining data from spb_Crv_continuityBetween2.processCurves."
return
iContinuity0_G, iContinuity0_C, sContinuityDescr = rc
if bDebug:
print sContinuityDescr
sEval='sContinuity'; print sEval+': ',eval(sEval)
s = "Starting continuity: G{}/C{} ".format(iContinuity0_G, iContinuity0_C)
if sContinuity == 'G0':
if iContinuity0_G:
if bEcho:
s += " Curves' endpoints already meet at G{} continuity.".format(
iContinuity0_G)
print s
nc0_A.Dispose()
nc0_B.Dispose()
return True
elif sContinuity == 'G1':
if iContinuity0_G >= 1:
if bEcho:
s += " Curves' endpoints already meet at G{} continuity.".format(
iContinuity0_G)
print s
nc0_A.Dispose()
nc0_B.Dispose()
return True
elif sContinuity == 'C1':
if iContinuity0_C >= 1:
if bEcho:
s += " Curves' endpoints already meet at G{} continuity.".format(
iContinuity0_G)
print s
nc0_A.Dispose()
nc0_B.Dispose()
return True
elif sContinuity == 'G2':
if iContinuity0_G >= 2:
if bEcho:
s += " Curves' endpoints already meet at G{} continuity.".format(
iContinuity0_G)
print s
nc0_A.Dispose()
nc0_B.Dispose()
return True
if bEcho: print s
return False
def rebuildRationalCurve(crv):
if bRebuildRationals and crv.IsRational:
degree = 3 if crv.Degree < 3 else crv.Degree
if not fDevTol:
# Create Bezier.
rc = crv.Rebuild(
pointCount=degree+1,
degree=degree,
preserveTangents=True)
if rc:
return rc
else:
rc = spb_Crv_fitRebuild.rebuildCurve(
crv,
fDevTol=0.5*fDevTol,
iDegree=degree,
bPreserveEndTans=True,
bFurtherTranslateCps=True,
iMinCpCt=None,
iMaxCpCt=40,
bDebug=False,
)
if rc[0] is not None:
return rc[0]
def doCrvsMatchWithinDistDev(cA, cB, fDevTol=fDevTol):
if fDevTol:
fDev = getMaximumDeviation(cA, cB)
if fDev is None:
print "Curve is not acceptable because its deviation cannot be determined."
return False
elif fDev > fDevTol:
print "Curve is not acceptable because deviation would be {}.".format(
formatDistance(fDev))
return False
return True
def createForBothCurves(rgCurveA, rgCurveB, bT1WorkEnd_A, bT1WorkEnd_B):
"""
Returns on success: (rg.NurbsCurve, rg.NurbsCurve)
Returns on fail: None
"""
c0_A = rgCurveA
c0_B = rgCurveB
c0s = [rgCurveA, rgCurveB]
bT1WorkEnds = bT1WorkEnd_A, bT1WorkEnd_B
ncs_PreMatch = [c0_A.ToNurbsCurve(), c0_B.ToNurbsCurve()]
if bRebuildRationals:
for i in 0,1:
rc = rebuildRationalCurve(ncs_PreMatch[i])
if rc:
ncs_PreMatch[i].Dispose()
ncs_PreMatch[i] = rc
nc_A_PreMatch = ncs_PreMatch[0]
if bT1WorkEnd_A:
t_WorkEnd_A = nc_A_PreMatch.Domain.T1
crvEvalSide_A = rg.CurveEvaluationSide.Below
idxCp_Pos_A = nc_A_PreMatch.Points.Count - 1
idxCp_Tan_A = nc_A_PreMatch.Points.Count - 2
idxCp_Crv_A = nc_A_PreMatch.Points.Count - 3
else:
t_WorkEnd_A = nc_A_PreMatch.Domain.T0
crvEvalSide_A = rg.CurveEvaluationSide.Above
idxCp_Pos_A = 0
idxCp_Tan_A = 1
idxCp_Crv_A = 2
nc_B_PreMatch = ncs_PreMatch[1]
if bT1WorkEnd_B:
t_WorkEnd_B = nc_B_PreMatch.Domain.T1
crvEvalSide_B = rg.CurveEvaluationSide.Below
idxCp_Pos_B = nc_B_PreMatch.Points.Count - 1
idxCp_Tan_B = nc_B_PreMatch.Points.Count - 2
idxCp_Crv_B = nc_B_PreMatch.Points.Count - 3
else:
t_WorkEnd_B = nc_B_PreMatch.Domain.T0
crvEvalSide_B = rg.CurveEvaluationSide.Above
idxCp_Pos_B = 0
idxCp_Tan_B = 1
idxCp_Crv_B = 2
#vectsDerivatives_A = nc0_A.DerivativeAt(
# t_WorkEnd_A,
# derivativeCount=2,
# side=crvEvalSide_A)
#print vectsDerivatives_A[2], nc0_A.CurvatureAt(t_WorkEnd_A)
#vectsDerivatives_B = nc0_B.DerivativeAt(
# t_WorkEnd_B,
# derivativeCount=2,
# side=crvEvalSide_B)
#print vectsDerivatives_B[2], nc0_B.CurvatureAt(t_WorkEnd_B)
# (PC to maintain condition type at opposite end of curve) + (PC to modify working side of curve), where PC is "required min. point count".
if sContinuity == 'G0':
iCt_Cp_MinNeeded = iPreserveOtherEnd + 1
elif sContinuity in ('G1', 'C1'):
iCt_Cp_MinNeeded = iPreserveOtherEnd + 2
elif sContinuity == 'G2':
iCt_Cp_MinNeeded = iPreserveOtherEnd + 3
nc_WIP_A = None
nc_WIP_B = None
if bDeformLines:
for i in 0,1:
if ncs_PreMatch[i].Points.Count < iCt_Cp_MinNeeded:
if ncs_PreMatch[i].Points.Count == 2:
ts = ncs_PreMatch[i].DivideByCount(
segmentCount=iCt_Cp_MinNeeded-1,
includeEnds=True)
rc = rg.NurbsCurve.Create(
periodic=False,
degree=3,
points=[ncs_PreMatch[i].PointAt(t) for t in ts])
ncs_PreMatch[i].Dispose()
ncs_PreMatch[i] = rc
nc_A_PreMatch = ncs_PreMatch[0]
nc_B_PreMatch = ncs_PreMatch[1]
if (
nc_A_PreMatch.Points.Count < iCt_Cp_MinNeeded
and
nc_B_PreMatch.Points.Count < iCt_Cp_MinNeeded
):
print "Neither curve has enough control points for this continuity modification."
for i in 0,1:
if ncs_PreMatch[i] is not None: ncs_PreMatch[i].Dispose()
return
elif nc_A_PreMatch.Points.Count < iCt_Cp_MinNeeded:
print "Curve A doesn't have enough control points for this continuity modification."
for i in 0,1:
if ncs_PreMatch[i] is not None: ncs_PreMatch[i].Dispose()
return
elif nc_B_PreMatch.Points.Count < iCt_Cp_MinNeeded:
print "Curve B doesn't have enough control points for this continuity modification."
for i in 0,1:
if ncs_PreMatch[i] is not None: ncs_PreMatch[i].Dispose()
return
nc_WIP_A = nc_A_PreMatch.Duplicate()
nc_WIP_B = nc_B_PreMatch.Duplicate()
# First, modify position.
pt_Average = (0.5 * nc_WIP_A.Points[idxCp_Pos_A].Location +
0.5 * nc_WIP_B.Points[idxCp_Pos_B].Location)
if nc_WIP_A.Points[idxCp_Pos_A] != pt_Average:
nc_WIP_A.Points[idxCp_Pos_A] = pt_Average
nc_WIP_B.Points[idxCp_Pos_B] = pt_Average
nc_WIPs = [nc_WIP_A, nc_WIP_B]
if not (
doCrvsMatchWithinDistDev(nc_WIPs[0], ncs_PreMatch[0]) and
doCrvsMatchWithinDistDev(nc_WIPs[1], ncs_PreMatch[1])
):
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
nc_WIPs[0].Dispose()
nc_WIPs[1].Dispose()
return
# Determine tangent vector(s).
vectTan_A1 = nc_A_PreMatch.TangentAt(t_WorkEnd_A)
vectTan_B1 = nc_B_PreMatch.TangentAt(t_WorkEnd_B)
if bT1WorkEnd_A == bT1WorkEnd_B:
vectTan_Target_B = (0.5 * -vectTan_A1) + (0.5 * vectTan_B1)
vectTan_Target_A = -vectTan_Target_B
else:
vectTan_Target_A = (0.5 * vectTan_A1) + (0.5 * vectTan_B1)
vectTan_Target_B = vectTan_Target_A
# Modify tangency.
if sContinuity in ('G1', 'C1', 'G2'):
# for G1 or (C1 and the adjacent curve is linear or circular-arc-shaped).
bEndConditionSet_A = nc_WIP_A.SetEndCondition(
bSetEnd=bT1WorkEnd_A,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Tangency,
point=pt_Average,
tangent=vectTan_Target_A)
bEndConditionSet_B = nc_WIP_B.SetEndCondition(
bSetEnd=bT1WorkEnd_B,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Tangency,
point=pt_Average,
tangent=vectTan_Target_B)
# Deviation check.
if not (
doCrvsMatchWithinDistDev(nc_WIPs[0], ncs_PreMatch[0]) and
doCrvsMatchWithinDistDev(nc_WIPs[1], ncs_PreMatch[1])
):
#addGeoms(nc_WIPs); 1/0
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
nc_WIPs[0].Dispose()
nc_WIPs[1].Dispose()
return
if sContinuity == 'C1' and not nc_A_PreMatch.CurvatureAt(t_WorkEnd_A).IsTiny() and not nc_B_PreMatch.CurvatureAt(t_WorkEnd_B).IsTiny():
# TODO: Make average.
# In the following, some of the paretheses are included to obtain Point3d instead of Vector3d.
pt_Tan1_A = 0.5 * nc_A_PreMatch.Points[idxCp_Tan_A].Location + 0.5 * (
nc_B_PreMatch.Points[idxCp_Pos_B].Location -
float(nc_B_PreMatch.Degree / nc_WIP_A.Degree) *
(nc_B_PreMatch.Points[idxCp_Tan_B].Location -
nc_B_PreMatch.Points[idxCp_Pos_B].Location))
#sc.doc.Objects.AddPoint(pt_Tan1_A)
pt_Tan1_B = 0.5 * nc_B_PreMatch.Points[idxCp_Tan_B].Location + 0.5 * (
nc_A_PreMatch.Points[idxCp_Pos_A].Location -
float(nc_A_PreMatch.Degree / nc_WIP_B.Degree) *
(nc_A_PreMatch.Points[idxCp_Tan_A].Location -
nc_A_PreMatch.Points[idxCp_Pos_A].Location))
#sc.doc.Objects.AddPoint(pt_Tan1_B)
if nc_WIP_A.Points[idxCp_Tan_A] != pt_Tan1_A:
nc_WIP_A.Points[idxCp_Tan_A] = pt_Tan1_A
if nc_WIP_B.Points[idxCp_Tan_B] != pt_Tan1_B:
nc_WIP_B.Points[idxCp_Tan_B] = pt_Tan1_B
# Deviation check.
if not (
doCrvsMatchWithinDistDev(nc_WIPs[0], ncs_PreMatch[0]) and
doCrvsMatchWithinDistDev(nc_WIPs[1], ncs_PreMatch[1])
):
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
nc_WIPs[0].Dispose()
nc_WIPs[1].Dispose()
return
if bMaximizeMinRadius and sContinuity not in ('C1', 'C2', 'G2'):
s = "Adjusting tangent control point spread ..."
if bEcho: print s
nc_WIPs = [nc_WIP_A.ToNurbsCurve(), nc_WIP_B.ToNurbsCurve()]
for i in 0,1:
rc = spb_NurbsCrv_maximizeMinimumRadius.adjustTanCpSpread_OneEndOnly(
nc_WIPs[i],
bT1WorkEnds[i],
fDevTol,
ncs_PreMatch[i],
bDebug=bDebug,
)
if rc:
nc_WIPs[i].Dispose()
nc_WIPs[i] = rc[0]
nc_WIP_A, nc_WIP_B = nc_WIPs
# Deviation has already been checked in adjustTanCpSpread.
if sContinuity == 'G2':
# Determine curvature vector(s).
vectCrv_A1 = nc_A_PreMatch.CurvatureAt(t_WorkEnd_A)
vectCrv_B1 = nc_B_PreMatch.CurvatureAt(t_WorkEnd_B)
if bT1WorkEnd_A == bT1WorkEnd_B:
vectCrv_Target_B = (0.5 * -vectCrv_A1) + (0.5 * vectCrv_B1)
vectCrv_Target_A = -vectCrv_Target_B
else:
vectCrv_Target_A = vectCrv_Target_B = (0.5 * vectCrv_A1) + (0.5 * vectCrv_B1)
bEndConditionSet_A = nc_WIP_A.SetEndCondition(
bSetEnd=bT1WorkEnd_A,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Curvature,
point=pt_Average,
tangent=vectTan_Target_A,
curvature=vectCrv_Target_A)
bEndConditionSet_B = nc_WIP_B.SetEndCondition(
bSetEnd=bT1WorkEnd_B,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Curvature,
point=pt_Average,
tangent=vectTan_Target_B,
curvature=vectCrv_Target_B)
# Deviation check.
if not (
doCrvsMatchWithinDistDev(nc_WIPs[0], ncs_PreMatch[0]) and
doCrvsMatchWithinDistDev(nc_WIPs[1], ncs_PreMatch[1])
):
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
nc_WIPs[0].Dispose()
nc_WIPs[1].Dispose()
return
# Curve is within tolerance.
for i in 0,1:
if nc_WIPs[i].EpsilonEquals(ncs_PreMatch[i], 1e-12):
print "Curve was not modified."
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
nc_WIPs[0].Dispose()
nc_WIPs[1].Dispose()
return
ncs_PreMatch[0].Dispose()
ncs_PreMatch[1].Dispose()
return tuple(nc_WIPs)
def createForOneCurve(rgCurve_One, rgCurve_Ref, bT1WorkEnd_One, bT1WorkEnd_Ref):
"""
Parameters:
rgCurve_One: For which to create a new curve.
rgCurve_Ref: Reference.
Returns:
Single NurbsCurve on success.
None on fail.
"""
kwargs_reviewDuringDebug = kwargs
ncOne_PreMatch = rgCurve_One.ToNurbsCurve()
# (PC to maintain condition type at opposite end of curve) + (PC to modify working side of curve), where PC is "required min. point count".
if sContinuity == 'G0':
iCt_Cp_MinNeeded = iPreserveOtherEnd + 1
elif sContinuity in ('G1', 'C1'):
iCt_Cp_MinNeeded = iPreserveOtherEnd + 2
elif sContinuity == 'G2':
iCt_Cp_MinNeeded = iPreserveOtherEnd + 3
if bDeformLines:
if ncOne_PreMatch.Points.Count < iCt_Cp_MinNeeded:
if ncOne_PreMatch.Points.Count == 2:
ts = ncOne_PreMatch.DivideByCount(
segmentCount=iCt_Cp_MinNeeded-1,
includeEnds=True)
rc = rg.NurbsCurve.Create(
periodic=False,
degree=3,
points=[ncOne_PreMatch.PointAt(t) for t in ts])
ncOne_PreMatch.Dispose()
ncOne_PreMatch = rc
if bRebuildRationals and ncOne_PreMatch.IsRational:
rc = rebuildRationalCurve(ncOne_PreMatch)
if rc:
ncOne_PreMatch.Dispose()
ncOne_PreMatch = rc
else:
print "Rational curve was not rebuit."
return
if bT1WorkEnd_One:
t_WorkEnd_One = ncOne_PreMatch.Domain.T1
crvEvalSide_One = rg.CurveEvaluationSide.Below
idxCp_Pos_One = ncOne_PreMatch.Points.Count - 1
idxCp_Tan_One = ncOne_PreMatch.Points.Count - 2
idxCp_Crv_One = ncOne_PreMatch.Points.Count - 3
else:
t_WorkEnd_One = ncOne_PreMatch.Domain.T0
crvEvalSide_One = rg.CurveEvaluationSide.Above
idxCp_Pos_One = 0
idxCp_Tan_One = 1
idxCp_Crv_One = 2
nc_Ref = rgCurve_Ref.ToNurbsCurve()
if bT1WorkEnd_Ref:
t_WorkEnd_Ref = nc_Ref.Domain.T1
crvEvalSide_Ref = rg.CurveEvaluationSide.Below
idxCp_Pos_Ref = nc_Ref.Points.Count - 1
idxCp_Tan_Ref = nc_Ref.Points.Count - 2
idxCp_Crv_Ref = nc_Ref.Points.Count - 3
else:
t_WorkEnd_Ref = nc_Ref.Domain.T0
crvEvalSide_Ref = rg.CurveEvaluationSide.Above
idxCp_Pos_Ref = 0
idxCp_Tan_Ref = 1
idxCp_Crv_Ref = 2
#vectsDerivatives_A = nc0_A.DerivativeAt(
# t_WorkEnd_A,
# derivativeCount=2,
# side=crvEvalSide_A)
#print vectsDerivatives_A[2], nc0_A.CurvatureAt(t_WorkEnd_A)
vectsDerivatives_B = nc_Ref.DerivativeAt(
t_WorkEnd_Ref,
derivativeCount=2,
side=crvEvalSide_Ref)
#print vectsDerivatives_B[2], nc0_B.CurvatureAt(t_WorkEnd_B)
if ncOne_PreMatch.Points.Count < iCt_Cp_MinNeeded:
if nc_Ref.Points.Count < iCt_Cp_MinNeeded:
print "Neither curve has enough control points" \
" for this continuity modification."
ncOne_PreMatch.Dispose()
nc_Ref.Dispose()
return
if bEcho:
s = "Curve A has {} control points, but needs {}.".format(
ncOne_PreMatch.Points.Count,
iCt_Cp_MinNeeded)
if nc_Ref.Points.Count < iCt_Cp_MinNeeded:
s += " Curve B also doesn't have enough."
if bRebuildRationals and nc_Ref.IsRational:
s += ", but unrationalization was not performed on rational B yet."
else:
s += "."
else:
s += ", but Curve B does."
print s
ncOne_PreMatch.Dispose()
nc_Ref.Dispose()
return
def createForCurvature():
rgNurbsCrv_WIP_A = ncOne_PreMatch.Duplicate()
vectTanForA = nc_Ref.TangentAt(t_WorkEnd_Ref)
if bT1WorkEnd_One == bT1WorkEnd_Ref:
bReversedTanForA = vectTanForA.Reverse()
if bDebug: sEval='bReversedTanForA'; print sEval+': ',eval(sEval)
bEndConditionSet_A = rgNurbsCrv_WIP_A.SetEndCondition(
bSetEnd=bT1WorkEnd_One,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Curvature,
point=nc_Ref.PointAtEnd if bT1WorkEnd_Ref else nc_Ref.PointAtStart,
tangent=vectTanForA,
curvature=nc_Ref.CurvatureAt(t_WorkEnd_Ref))
return [rgNurbsCrv_WIP_A]
def createForC1():
if nc_Ref.CurvatureAt(t_WorkEnd_Ref).IsTiny(): # or not vectsDerivatives_B[2].IsTiny(): # Does it matter which one is used?
return
nc1_A = ncOne_PreMatch.Duplicate()
# First, modify the end control point's position.
if nc1_A.Points[idxCp_Pos_One] != nc_Ref.Points[idxCp_Pos_Ref]:
nc1_A.Points[idxCp_Pos_One] = nc_Ref.Points[idxCp_Pos_Ref]
# Now check control point spans to avoid distorting curve.
dist_Cp0Cp2_A = nc1_A.Points[idxCp_Pos_One].Location.DistanceTo(
nc1_A.Points[idxCp_Crv_One].Location)
dist_Cp0Cp1_R = nc_Ref.Points[idxCp_Pos_Ref].Location.DistanceTo(
nc_Ref.Points[idxCp_Tan_Ref].Location)
degA = nc1_A.Degree
degR = nc_Ref.Degree
dist_Cp0Cp2_A_Scaled = float(degR)*dist_Cp0Cp2_A
dist_Cp0Cp1_R_Scaled = float(degA)*dist_Cp0Cp1_R
if dist_Cp0Cp2_A_Scaled < dist_Cp0Cp1_R_Scaled:
if bDebug:
print "Avoided moving Tan Cp beyond Crv Cp."
return
# Now, modify the tangent (second from end) control point's position.
# In the following, some of the paretheses are included
# to obtain Point3d instead of Vector3d.
pt_Target = (
nc_Ref.Points[idxCp_Pos_Ref].Location -
(
(float(nc_Ref.Degree) / float(nc1_A.Degree)) *
(nc_Ref.Points[idxCp_Tan_Ref].Location -
nc_Ref.Points[idxCp_Pos_Ref].Location)
)
)
if nc1_A.Points[idxCp_Tan_One] != pt_Target:
nc1_A.Points[idxCp_Tan_One] = pt_Target
#sc.doc.Objects.AddCurve(nc1_A); sc.doc.Views.Redraw()
return nc1_A
def createForTangency():
ncs = []
# Version: C1 continuity. Also used as an optional result for G1.
rc = createForC1()
if rc: ncs.append(rc)
#
if sContinuity == 'C1' and not nc_Ref.CurvatureAt(t_WorkEnd_Ref).IsTiny():
# If IsTiny, control point span can be anything for C1,
# so test other tangent solutions.
return ncs
#
# Version: Move tangency control point to closest point inline with
# tangency line of Curve B.
ncs.append(ncOne_PreMatch.Duplicate())
# First, modify the end control point's position.
if ncs[-1].Points[idxCp_Pos_One] != nc_Ref.Points[idxCp_Pos_Ref]:
ncs[-1].Points[idxCp_Pos_One] = nc_Ref.Points[idxCp_Pos_Ref]
# Now, modify the tangent (second from end) control point's position
# to be inline with the 2 end ones of Curve B.
# Cannot modify the ControlPoint Location directly. Use SetPoint instead.
line = rg.Line(
nc_Ref.Points[idxCp_Pos_Ref].Location,
nc_Ref.Points[idxCp_Tan_Ref].Location)
pt_Target = line.ClosestPoint(
ncs[-1].Points[idxCp_Tan_One].Location,
limitToFiniteSegment=False)
ncs[-1].Points.SetPoint(idxCp_Tan_One, pt_Target)
#sc.doc.Objects.AddCurve(ncs[-1]); sc.doc.Views.Redraw(); return
#
#
# Version: Using NurbsCurve.SetEndCondition.
ncs.append(ncOne_PreMatch.Duplicate())
vectTanForA = nc_Ref.TangentAt(t_WorkEnd_Ref)
if bT1WorkEnd_One == bT1WorkEnd_Ref:
bReversedTanForA = vectTanForA.Reverse()
if bDebug: sEval='bReversedTanForA'; print sEval+': ',eval(sEval)
bEndConditionSet_A = ncs[-1].SetEndCondition(
bSetEnd=bT1WorkEnd_One,
continuity=rg.NurbsCurve.NurbsCurveEndConditionType.Tangency,
point=nc_Ref.PointAtEnd if bT1WorkEnd_Ref else nc_Ref.PointAtStart,
tangent=vectTanForA)
#sc.doc.Objects.AddCurve(ncs[-1]); sc.doc.Views.Redraw(); return
#
return ncs
def createForPosition():
ncs = []