Repository navigation
Expand file tree
/
Copy pathspb_Crv_Join.py
More file actions
793 lines (604 loc) · 27.4 KB
/
Copy pathspb_Crv_Join.py
File metadata and controls
793 lines (604 loc) · 27.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
"""
This script is an alternative to _Join for curves.
Unlike _Join,
1. It can optionally join curves that share a layer and/or color.
2. It optionally does not simplify/convert curves.
3. It has a tolerance setting.
Send any questions, comments, or script development service needs to
@spb on the McNeel Forums, https://discourse.mcneel.com/
"""
#! python 2 Must be on a line number less than 32.
from __future__ import absolute_import, division, print_function, unicode_literals
"""
180207: Created, starting with joinBreps.
...
180316: Added support for brep edge curves.
...
190513: Fixed bug where breps of selected edges were being joined.
250109-10,15: Reenabled the RhinoCommon method.
Disabled support for BrepEdges until script is working properly for just wires.
Refactored.
250204: Bug fix.
250326: Reimplemented the _Join routine for Rhino < 8.12.
251012: Due to the reference to the model units, a global variable was replaced with another variable that is calculated at run time.
TODO:
Reenable support for BrepEdges.
Possibly reenable RC routine for < 8.12.
The indices of the joined input are not returned by V5's JoinCurves method and overloads.
_Join (at least in V8.14) appears to use 1.8 * ModelAbsoluteTolerance as the
endpoint distance (gap or overlap) threshold to perform the join.
simpleJoin in Curve.JoinCurves will preserve curve types. That also means contiguous
LineCurves will connect as LineCurve segments in PolyCurves instead of converting to PolylineCurve segment.
"""
import Rhino
import Rhino.DocObjects as rd
import Rhino.Geometry as rg
import Rhino.Input as ri
import rhinoscriptsyntax as rs
import scriptcontext as sc
from System import Guid
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'fJoinTol'; keys.append(key)
values[key] = max((0.1 * sc.doc.ModelAbsoluteTolerance, 1e-6)) # Default in _Join is 1.8 * sc.doc.ModelAbsoluteTolerance.
names[key] = 'Tolerance'
riOpts[key] = ri.Custom.OptionDouble(initialValue=values[key])
stickyKeys[key] = '{}({})({})'.format(key, __file__, sc.doc.Name)
key = 'bByLayer'; keys.append(key)
values[key] = True
names[key] = 'JoinByLayer'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bByColor'; keys.append(key)
values[key] = True
names[key] = 'JoinByColor'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bUseUiJoinCmd'; keys.append(key)
values[key] = False
names[key] = 'Use'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'RhinoCommon', 'JoinCommand')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bSimpleJoin'; 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 key in riOpts:
riOpts[key].CurrentValue = values[key] = sc.sticky[stickyKeys[key]]
else:
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 == 'fJoinTol':
if cls.riOpts[key].CurrentValue < 0.0:
cls.values[key] = cls.riOpts[key].CurrentValue = cls.riOpts[key].InitialValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
if cls.riOpts[key].CurrentValue < Rhino.RhinoMath.ZeroTolerance:
cls.values[key] = cls.riOpts[key].CurrentValue = Rhino.RhinoMath.ZeroTolerance
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
cls.values[key] = cls.riOpts[key].CurrentValue
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
return
if key in cls.riOpts:
cls.values[key] = cls.riOpts[key].CurrentValue
elif key in cls.listValues:
cls.values[key] = idxList
else:
return
sc.sticky[cls.stickyKeys[key]] = cls.values[key]
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 _isCurveJoinable(rdCrv):
"""Joinable is valid and open."""
rgC = rdCrv.CurveGeometry
if not rgC.IsValid: return False
return not rgC.IsClosed
def _getAllNormalJoinableWires():
oes = rd.ObjectEnumeratorSettings()
oes.LockedObjects = False # Default is True.
oes.ObjectTypeFilter = rd.ObjectType.Curve
return [rdC for rdC in sc.doc.Objects.GetObjectList(oes) if _isCurveJoinable(rdC)]
def getInput():
"""
Get curves with optional input.
"""
go = ri.Custom.GetObject()
go.SetCommandPrompt("Select curves")
go.SetCommandPromptDefault("All normal when none are selected")
go.GeometryFilter = rd.ObjectType.Curve
go.GeometryAttributeFilter = (
ri.Custom.GeometryAttributeFilter.OpenCurve
|
ri.Custom.GeometryAttributeFilter.WireCurve
)
go.SubObjectSelect = False
#go.AlreadySelectedObjectSelect = True
go.DeselectAllBeforePostSelect = False # So objects won't be deselected on repeats of While loop.
go.AcceptNothing(True)
go.AcceptNumber(True, acceptZero=True)
go.EnableClearObjectsOnEntry(False) # Keep objects in go on repeats of While loop.
#go.EnableUnselectObjectsOnExit(False)
bPreselectedObjsChecked = False
#bSequentialSel = False
#print("Seq1Sel = Sequential single selection")
idxs_Opt = {}
def addOption(key): idxs_Opt[key] = Opts.addOption(go, key)
bPre812 = (
Rhino.RhinoApp.ExeVersion < 8 or
(Rhino.RhinoApp.ExeVersion == 8 and Rhino.RhinoApp.ExeServiceRelease < 12)
)
while True:
go.ClearCommandOptions()
idxs_Opt.clear()
addOption('fJoinTol')
idxs_Opt['Toggle'] = go.AddOption("ToggleFilters")
addOption('bByLayer')
addOption('bByColor')
if not bPre812:
addOption('bUseUiJoinCmd')
if not Opts.values['bUseUiJoinCmd']:
addOption('bSimpleJoin')
addOption('bEcho')
addOption('bDebug')
res = go.GetMultiple(minimumNumber=1, maximumNumber=0)
# minimumNumber isn't set to 2 because when only 1 curve is selected,
# ri.GetResult.Nothing is triggered.
if res == ri.GetResult.Cancel:
go.Dispose()
return
# Use bPreselectedObjsChecked so that only objects before the
# first call to go.GetMultiple is considered.
if not bPreselectedObjsChecked:
if (
go.ObjectsWerePreselected and
go.ObjectCount == 1
):
if go.ObjectCount == 1:
if bDebug: print("Only 1 object was preselected.")
bPreselectedObjsChecked = True
go.EnablePreSelect(enable=False, ignoreUnacceptablePreselectedObjects=True)
go.AlreadySelectedObjectSelect = True
continue
elif bDebug:
print("{} objects were preselected.".format(go.ObjectCount))
else:
# This is another good place to print join option settings.
pass
if res == ri.GetResult.Nothing:
go.Dispose()
return _getAllNormalJoinableWires()
if res == ri.GetResult.Object:
if go.ObjectCount < 2:
print("At least 2 breps must be selected.")
go.Dispose()
return
objrefs = go.Objects()
go.Dispose()
return objrefs
#if res == ri.GetResult.Option and go.OptionIndex() == 1:
# bSequentialSel = True
# break
if res == ri.GetResult.Number:
key = 'fJoinTol'
Opts.riOpts[key].CurrentValue = go.Number()
Opts.setValue(key)
continue
if 'Toggle' in idxs_Opt and go.Option().Index == idxs_Opt['Toggle']:
for key in 'bByLayer', 'bByColor':
Opts.riOpts[key].CurrentValue = not Opts.riOpts[key].CurrentValue
Opts.setValue(key)
continue
for key in idxs_Opt:
if go.Option().Index == idxs_Opt[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
1/0
# Unnecessary due to go.GetMultiple' minimumNumber=2 ?
# # At least 2 curves must be selected.
# if go.ObjectCount < 2: return
gCrvs_FromWire = []; gCrvs_FromEdge = []
for objref in go.Objects():
if objref.GeometryComponentIndex.Index == -1:
gCrvs_FromWire.append(objref.ObjectId)
else:
rdObj = objref.Object()
if rdObj.ObjectType == rd.ObjectType.InstanceReference:
print("Objects in block instances are not supported.")
continue
# Add curves of edges.
gCrv = sc.doc.Objects.AddCurve(objref.Geometry())
if gCrv != Guid.Empty:
gCrvs_FromEdge.append(gCrv)
go.Dispose()
def _getCurveObjects(rhCrvs):
if all((isinstance(rhC, rd.CurveObject) for rhC in rhCrvs)): return rhCrvs
rdCs_In = []
for rhC in rhCrvs:
if isinstance(rhC, rd.CurveObject):
rdCs_In.append(rhC)
else:
rdC = rs.coercerhinoobject(rhC)
if rdC.ObjectType != rd.ObjectType.Curve:
raise Exception("{} passed to separateInputIntoJoiningSets.".format(
rdC.GetType().Name))
rdCs_In.append(rdC)
return rdCs_In
def _separateInputIntoJoiningSets(rhCrvs, bByLayer=True, bByColor=True, bDebug=False):
rdCs_In = _getCurveObjects(rhCrvs)
if not (bByLayer or bByColor):
return [rdCs_In] # Nested 1-level for actual separation (see below).
if bByLayer and bByColor:
rdCs_Per_to_join = [] # Nested 1-level.
sLayers = [] # Full layer paths (with '::').
colors = [] # May be System.Drawing.Color or int for rs.ObjectColorSource.
for rdC in rdCs_In:
sLayer = rs.ObjectLayer(rdC) # Full layer path (with '::').
ocs = rs.ObjectColorSource(rdC)
color = rs.ObjectColor(rdC) if ocs == 1 else rs.ObjectColorSource(rdC)
if (sLayer not in sLayers) or (color not in colors):
rdCs_Per_to_join.append([rdC])
sLayers.append(sLayer)
colors.append(color)
continue
idxs_Layer_match = [idx for idx, _ in enumerate(sLayers) if _ == sLayer]
idxs_color_match = [idx for idx, _ in enumerate(colors) if _ == color]
matches = list(set(idxs_Layer_match) & set(idxs_color_match))
if len(matches) == 0:
rdCs_Per_to_join.append([rdC])
sLayers.append(sLayer)
colors.append(color)
elif len(matches) == 1:
idx_Match = matches[0]
rdCs_Per_to_join[idx_Match].append(rdC)
else:
raise Exception("Multiple layer and color matches.")
if bDebug:
sEval = "sLayers"; print(sEval, '=', eval(sEval))
sEval = "colors"; print(sEval, '=', eval(sEval))
return rdCs_Per_to_join
if bByLayer:
rdCs_Per_to_join = [] # Nested 1-level.
sLayers = [] # Full layer paths (with '::').
for rdC in rdCs_In:
sLayer = rs.ObjectLayer(rdC) # Full layer path (with '::').
if sLayer in sLayers:
idx = sLayers.index(sLayer)
rdCs_Per_to_join[idx].append(rdC)
else:
rdCs_Per_to_join.append([rdC])
sLayers.append(sLayer)
if bDebug: sEval = "sLayers"; print(sEval, '=', eval(sEval))
return rdCs_Per_to_join
if bByColor:
rdCs_Per_to_join = [] # Nested 1-level.
colors = [] # May be System.Drawing.Color or int for rs.ObjectColorSource.
for rdC in rdCs_In:
ocs = rs.ObjectColorSource(rdC)
color = rs.ObjectColor(rdC) if ocs == 1 else rs.ObjectColorSource(rdC)
if color in colors:
idx = colors.index(color)
rdCs_Per_to_join[idx].append(rdC)
else:
rdCs_Per_to_join.append([rdC])
colors.append(color)
if bDebug: sEval = "colors"; print(sEval, '=', eval(sEval))
return rdCs_Per_to_join
raise Exception("What happened?")
def joinCurves_using_RC_method(rgCrvs_In, fJoinTol=None, bSimpleJoin=False, bDebug=False):
"""
Returns:
list(rg.Curves from Join)
list(int of indices of rgCrvs_In)
str: Error
"""
if len(rgCrvs_In) == 0:
return None, None, "No curves in set to join."
if len(rgCrvs_In) < 2:
return None, None, "Only 1 curves in set to join."
if fJoinTol is None:
fJoinTol = 1.8 * sc.doc.ModelAbsoluteTolerance # The same as _Join for curves (per Rhino 8.14).
rgCs_Joined, idxs_Out_per_In = rg.Curve.JoinCurves(
rgCrvs_In,
joinTolerance=fJoinTol,
preserveDirection=False,
simpleJoin=bSimpleJoin)
#sEval = "len(rgCs_Joined)"; print(sEval, '=', eval(sEval))
#sEval = "max(idxs_Out_per_In) + 1"; print(sEval, '=', eval(sEval))
#sEval = "idxs_Out_per_In"; print(sEval, '=', eval(sEval))
#print(idxs_Out_per_In)
#for rgC_Joined in rgCs_Joined:
# sc.doc.Objects.AddCurve(rgC_Joined)
#sc.doc.Views.Redraw()
#return
idxs_Out_per_In = list(idxs_Out_per_In)
rgCs_Out = [] # Actual joins, not all output from JoinCurves.
idxs_In_perOut = []
for idx_Joined in range(len(rgCs_Joined)):
if idxs_Out_per_In.count(idx_Joined) > 1:
rgCs_Out.append(rgCs_Joined[idx_Joined])
idxs_In_perOut.append([])
#sEval = "len(rgCs_Out)"; print(sEval, '=', eval(sEval))
for idx_In, idx_Out_per_In in enumerate(idxs_Out_per_In):
iCt = idxs_Out_per_In.count(idx_Out_per_In)
if iCt > 1:
idxs_In_perOut[idx_Out_per_In].append(idx_In)
return rgCs_Out, idxs_In_perOut, None
"""
For simpleJoin=True,
Set True to use the simple joining method. In general, set this parameter to false.
(https://developer.rhino3d.com/api/rhinocommon/rhino.geometry.curve/joincurves)
RhinoMergeCurves()
Description: Join a bunch of ON_Curves into one or more ON_Curves Parameters:
input_curves [in] Array of pointers to ON_Curves to be joined output [out] Array
of pointers to joined results join_tol [in] max distance between endpoints to be joined.
If join_tol < ON_EPSILON, use CRhinoDoc::AbsoluteTolerance() bPreserveDir [in] if TRUE,
don't reverse input curves to get them to join key [out] if non-null, curves[i] is part of output[key[i]] WARNING - key[i] may be -1 for some i, in particular if curves[i] is extremely short, key[i] will be -1 and curves[i] will not contribute to the joined results. Returns: @untitled table TRUE Success False Failure Remarks: Join as many of the input curves as have matching endpoints. If the input curve is a NURBS curve or a line, the endpoints within the specified tolerance are trued up to meet exactly. All of the input curves are copied and the caller must free the results. When curves are joined they are made into polycurves. Memory for the curves is allocated and becomes the responsibility of the caller.
(https://developer.rhino3d.com/api/cpp/group___rhino.html#ga422fa1a9386624b9cbdb77faaeb1bc5b)
"""
def join_Cmd(rdCrvs_In, fJoinTol=None, bEcho=False, bDebug=False):
"""
rdCrvs_In: rd.BrepObjects or their GUIDs
"""
if rs.SelectObjects(rdCrvs_In) == 0:
print(s + "Error! Crvs should be selected. Command stopped.")
return
if not Rhino.RhinoMath.EpsilonEquals(
fJoinTol,
1.8*sc.doc.ModelAbsoluteTolerance,
epsilon=1e-6 * Rhino.RhinoMath.UnitScale(Rhino.UnitSystem.Millimeters, sc.doc.ModelUnitSystem)
):
fModelTol_Saved = sc.doc.ModelAbsoluteTolerance
fModelTol_ForJoin = sc.doc.ModelAbsoluteTolerance = fJoinTol / 1.8
if bDebug:
print("ModelAbsTol was changed from {} to {}"
" because _Join's tolerance is 1.8 * ModelAbsTol.".format(
_formatDistance(fModelTol_Saved),
_formatDistance(sc.doc.ModelAbsoluteTolerance)))
bChangedMAT = True
else:
bChangedMAT = False
rdObj_MostRecent = sc.doc.Objects.MostRecentObject()
uInt32_MostRecent = rdObj_MostRecent.RuntimeSerialNumber
rs.Command("_NoEcho _Join", bEcho)
if bChangedMAT:
sc.doc.ModelAbsoluteTolerance = fModelTol_Saved
if bDebug:
print("ModelAbsTol was returned to {}.".format(
_formatDistance(sc.doc.ModelAbsoluteTolerance)))
sc.doc.Objects.UnselectAll()
return list(sc.doc.Objects.AllObjectsSince(uInt32_MostRecent))
def join_CurveObjects(rhCrvs_In, bByLayer=True, bByColor=True, bUseUiJoinCmd=False, bSimpleJoin=False, fJoinTol=None, bEcho=False, bDebug=False):
rdCrvs_Separated = _separateInputIntoJoiningSets(rhCrvs_In, bByLayer, bByColor)
gCs_Out = []
iCt_gCs_Closed = 0
gCs_DeleteFails = []
rdCs_replaced_with_joins = []
for rdCrvs_PerSet in rdCrvs_Separated:
if (bUseUiJoinCmd or
Rhino.RhinoApp.ExeVersion < 8 or
(Rhino.RhinoApp.ExeVersion == 8 and Rhino.RhinoApp.ExeServiceRelease < 12)
):
fModelTol_Saved = sc.doc.ModelAbsoluteTolerance
try:
rdCs_Joins_this_set = join_Cmd(rdCrvs_PerSet, fJoinTol, bEcho, bDebug)
except Exception as e:
pass
else:
e = None
finally:
if sc.doc.ModelAbsoluteTolerance != fModelTol_Saved:
sc.doc.ModelAbsoluteTolerance = fModelTol_Saved
if e:
raise
#sEval = ""; print(sEval,'=',eval(sEval))
if not rdCs_Joins_this_set:
continue
gCs_Out.extend([rdC.Id for rdC in rdCs_Joins_this_set])
iCt_gCs_Closed += sum([rdC.CurveGeometry.IsClosed for rdC in rdCs_Joins_this_set])
for rdC in rdCrvs_PerSet:
if rdC.IsDeleted:
rdCs_replaced_with_joins.append(rdC)
else:
rgCrvs_perSet = [rdC.CurveGeometry for rdC in rdCrvs_PerSet]
rvs = joinCurves_using_RC_method(
rgCrvs_perSet,
fJoinTol=fJoinTol,
bSimpleJoin=bSimpleJoin,
bDebug=bDebug)
if rvs is None:
continue
(
rgCs_Joins_this_set,
idxs_rgCs_Joined_input_per_join_this_set,
sLog,
) = rvs
if not rgCs_Joins_this_set:
if bDebug and sLog:
print(sLog)
continue
#print(rvs)
for idx_Joined, rgC_Joined in enumerate(rgCs_Joins_this_set):
attr = rdCrvs_PerSet[idxs_rgCs_Joined_input_per_join_this_set[idx_Joined][0]].Attributes
gC_Out = sc.doc.Objects.AddCurve(rgC_Joined, attr)
if gC_Out != Guid.Empty:
gCs_Out.append(gC_Out)
for idx_rdC_In in idxs_rgCs_Joined_input_per_join_this_set[idx_Joined]:
bDeleted = sc.doc.Objects.Delete(rdCrvs_PerSet[idx_rdC_In], quiet=False)
if bDeleted:
rdCs_replaced_with_joins.append(rdCrvs_PerSet[idx_rdC_In])
else:
gCs_DeleteFails.append(rdCrvs_PerSet[idx_rdC_In].Id)
if rgC_Joined.IsClosed:
iCt_gCs_Closed += 1
#print(rdCs_replaced_with_joins)
if gCs_Out:
if not gCs_DeleteFails:
if iCt_gCs_Closed == len(gCs_Out):
print("Replaced {} curves with {} joined, closed curves.".format(
len(rdCs_replaced_with_joins),
len(gCs_Out),
)
)
else:
print("Replaced {} curves with {} joined curves. {} of which are closed.".format(
len(rdCs_replaced_with_joins),
len(gCs_Out),
iCt_gCs_Closed),
)
else:
print("Added {} joined curves.".format(len(gCs_Out)))
print("Failed to delete {} curves.".format(len(gCs_DeleteFails)))
else:
print("None of the {} curves were joined.".format(len(rhCrvs_In)))
return gCs_Out
def main():
#if Rhino.RhinoApp.ExeVersion < 8:
# print("This script uses a method added to RhinoCommon 8.12. Rhino 7 is not current supported in this branch of the script.")
# return
#if Rhino.RhinoApp.ExeVersion == 8 and Rhino.RhinoApp.ExeServiceRelease < 12:
# print("This script uses a method added to RhinoCommon 8.12. Upgrade your Rhino 8 to use this script.")
# return
gObjs_Preselected = [rdObj.Id for rdObj in sc.doc.Objects.GetSelectedObjects(includeLights=False, includeGrips=False)]
rhCrvs = getInput() # ObjRefs, rd.CurveObjects, or None.
if rhCrvs is None: return
fJoinTol = Opts.values['fJoinTol']
bByLayer = Opts.values['bByLayer']
bByColor = Opts.values['bByColor']
bUseUiJoinCmd = Opts.values['bUseUiJoinCmd']
bSimpleJoin = Opts.values['bSimpleJoin']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
#if gCrvs0_FromEdge:
# # If any edge curves were selected, curves will be joined ignoring layer and color.
# if bByLayer:
# print("Edge curve in selection, so all curves' layers will be ignored.")
# bByLayer = False
# if bByColor:
# print("Edge curve in selection, so all curves' layers will be ignored.")
# bByColor = False
if not bDebug: sc.doc.Views.RedrawEnabled = False
sc.doc.Objects.UnselectAll()
gCs_Res = join_CurveObjects(
rhCrvs,
bByLayer=bByLayer,
bByColor=bByColor,
bUseUiJoinCmd=bUseUiJoinCmd,
bSimpleJoin=bSimpleJoin,
fJoinTol=fJoinTol,
bEcho=bEcho,
bDebug=bDebug,
)
if gObjs_Preselected:
for gObj in gObjs_Preselected: sc.doc.Objects.Select(gObj)
for gC in gCs_Res: sc.doc.Objects.Select(gC)
# Note that one case when gCs_Res is None is when _Join is used.
if gCs_Res:
sc.doc.Views.Redraw()
sc.doc.Views.RedrawEnabled = True
return
if len(gCrvs0_FromWire + gCrvs0_FromEdge) == len(rgCrvs1):
print("Unable to join any curves.")
if len(gCrvs0_FromEdge): sc.doc.Views.Redraw()
return
isClosedCt = 0
gCrvs1 = []
for rgCrv1 in rgCrvs1:
# Don't modify monoface curves.
if rgCrv1.Faces.Count == 1:
continue
if not rgCrv1.IsValid:
print("The geometry of at least one of the new curves is invalid."
"Crv will not be modified.")
continue
if gCrv0:
gCrv0 = gCrvs0_FromMarker[0] # Get 1st to take its attribute instead of the last's.
rdCrv0 = rs.coercerhinoobject(gCrv0) # Using last gCrv0 in gCrvs0_FromMarker.
if rdCrv0 is None and Rhino.RhinoApp.ExeVersion >= 6:
# If using Rhino V6 or newer, try using sc.doc.Objects.Find.
print("sc.doc.Objects.FindId failed! Using sc.doc.Objects.Find instead ...")
rdCrv0 = sc.doc.Objects.Find(gCrv0)
if rdCrv0 is None:
print("DocObject for {} not found!".format(gCrv0))
continue
attr = rdCrv0.Attributes.Duplicate()
else:
attr = None
gCrv1 = sc.doc.Objects.AddCrv(rgCrv1, attr)
if gCrv1 == Guid.Empty:
print("GUID is empty! Check results.")
continue
if rgCrv1.IsClosed:
isClosedCt += 1
# Remove user string marker.
removeMarkers(gCrv1)
# Delete old curves.
for gCrv0 in gCrvs0_FromMarker:
sc.doc.Objects.Delete(gCrv0, quiet=False)
gCrvs1.append(gCrv1)
#rs.MatchObjectAttributes(gCrvs1, gCrvs0[0])
s = "{} wire curves and {} curves from edges joined into".format(
len(gCrvs0_FromWire), len(gCrvs0_FromEdge))
sPolyInfos = []
if isClosedCt > 0:
sPolyInfos.append(" {} closed polycurves(s)".format(isClosedCt))
if isClosedCt < len(gCrvs1):
sPolyInfos.append(" {} open polycurves(s).".format(
len(gCrvs1) - isClosedCt))
print(s + ",".join(sPolyInfos))
if gObjs_Preselected:
rs.SelectObjects(gObjs_Preselected)
sc.doc.Views.RedrawEnabled = True
if __name__ == '__main__': main()