-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspb_Block_PartBuilder.py
More file actions
700 lines (530 loc) · 21.1 KB
/
spb_Block_PartBuilder.py
File metadata and controls
700 lines (530 loc) · 21.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
"""
Inspired by CadQuery, this script manages build history in block defintions.
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 less than 32.
from __future__ import absolute_import, division, print_function, unicode_literals
"""
250214-: WIP: Created.
TODO:
Assign random color to each layer that is created.
"""
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
import spb_Block_UserDict_Geom
sOptions = (
'ReadGeomFromKVPs',
'WriteGeomToKVPs',
'CreateLayersForBlocks',
'ListKVPsWithGeom',
'RemoveKeys',
)
class Opts():
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'bReadAll'; keys.append(key)
values[key] = False
names[key] = 'ReadMode'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'SelectKeys', 'AllKeys')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bWriteAllNormalGeomPerLayers'; keys.append(key)
values[key] = True
#names[key] = 'WriteMode'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bAppend_Not_overwrite'; keys.append(key)
values[key] = False
names[key] = 'WriteMode'
riOpts[key] = ri.Custom.OptionToggle(values[key], 'Overwrite', 'Append')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDeleteInputOnWrite'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bDeleteLayersOnWrite'; keys.append(key)
values[key] = True
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]
else:
idxOpt = go.AddOptionList(
englishOptionName=cls.names[key],
listValues=cls.listValues[key],
listCurrentIndex=cls.values[key])
return idxOpt
@classmethod
def setValue(cls, key, idxList=None):
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 getOption():
stickyKey_DefaultOpt = 'DefaultOpt({})'.format(__file__)
if sc.sticky.has_key(stickyKey_DefaultOpt):
idxOpt_Default = sc.sticky[stickyKey_DefaultOpt]
if idxOpt_Default >= len(sOptions):
sc.sticky[stickyKey_DefaultOpt] = idxOpt_Default = 0
else:
idxOpt_Default = 0
go = ri.Custom.GetOption()
go.SetCommandPrompt("Choose option")
go.SetCommandPromptDefault(defaultValue=sOptions[idxOpt_Default])
go.AcceptNothing(True)
# for idxOpt of 1 - n, not 0.
idxs_Opt = {}
def addOption(key): idxs_Opt[key] = Opts.addOption(go, key)
# for s in listPropOpts: gs.AddOption(s)
while True:
go.ClearCommandOptions()
idxs_Opt.clear()
for sDirection in sOptions:
go.AddOption(sDirection)
#addOption('bDeleteInputOnWrite')
#addOption('bLayers')
#if Opts.values['bLayers']:
# addOption('bBlockParentLayer')
#addOption('bEcho')
#addOption('bDebug')
res = go.Get()
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Nothing:
go.Dispose()
idxOpt = idxOpt_Default
return sOptions[idxOpt]
for key in idxs_Opt:
if go.Option().Index == idxs_Opt[key]:
Opts.setValue(key, go.Option().CurrentListOptionIndex)
break
else:
idxOpt = go.Option().Index - 1 # '- 1' because go.Option().Index is base 1.
go.Dispose()
sc.sticky[stickyKey_DefaultOpt] = idxOpt
return sOptions[idxOpt]
def getInput_OneBlockInst(bWrite_NotRead):
go = ri.Custom.GetObject()
go.SetCommandPrompt('Select block instance')
go.GeometryFilter = rd.ObjectType.InstanceReference
def addOption(key):
Opts.addOption(go, key)
keys_in_order_added.append(key)
while True:
go.ClearCommandOptions()
keys_in_order_added = [None] # None is just a placeholder since option indices are base 1.
if bWrite_NotRead:
addOption('bWriteAllNormalGeomPerLayers')
addOption('bAppend_Not_overwrite')
addOption('bDeleteInputOnWrite')
if Opts.values['bDeleteInputOnWrite']:
addOption('bDeleteLayersOnWrite')
else:
addOption('bReadAll')
#addOption('bLayers')
#if Opts.values['bLayers']:
# addOption('bBlockParentLayer')
addOption('bEcho')
addOption('bDebug')
res = go.Get()
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Object:
objref = go.Object(0)
go.Dispose()
return objref
Opts.setValue(keys_in_order_added[go.Option().Index])
if Opts.values['bReadAll']:
return getInput_MultiBlockInsts(bWrite_NotRead)
def getInput_MultiBlockInsts(bWrite_NotRead):
go = ri.Custom.GetObject()
go.SetCommandPrompt('Select block instances')
go.GeometryFilter = rd.ObjectType.InstanceReference
def addOption(key):
Opts.addOption(go, key)
keys_in_order_added.append(key)
while True:
go.ClearCommandOptions()
keys_in_order_added = [None] # None is just a placeholder since option indices are base 1.
if bWrite_NotRead:
addOption('bAppend_Not_overwrite')
addOption('bDeleteInputOnWrite')
else:
addOption('bReadAll')
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
Opts.setValue(keys_in_order_added[go.Option().Index])
if Opts.values['bReadAll']:
return getInput_OneBlockInst(bWrite_NotRead)
def create_geometry_in_block(sBlock):
"""
Parameters:
Returns:
"""
sEval = "sBlock"; print(sEval,'=',eval(sEval))
rdIdef = sc.doc.InstanceDefinitions.Find(sBlock)
if rdIdef is None:
raise Exception("Definition for block '{}' doesn't exist.".format(sBlock))
# # print(type(rdIdef))
# # crvs_perimeter = 1/0
# keys_with_geoms = _get_keys_for_geometries(rdIdef)
# if not keys_with_geoms:
# print("No keys for geometry.")
# return
# geoms = rdIdef.UserDictionary['sketch1']
def _get_keys_for_geometries(rgIref_or_rdIdef):
"""
Returns one of the following:
None for no dictionary
Empty list for no keys with values containing geometry or iterable of geometry
Non-empty list for keys with values containing geometry or iterable of geometry
"""
if isinstance(rgIref_or_rdIdef, rd.InstanceDefinition):
rdIdef = rgIref_or_rdIdef
elif isinstance(rgIref_or_rdIdef, rg.InstanceReferenceGeometry):
rgIref = rgIref_or_rdIdef
rdIdef = sc.doc.InstanceDefinitions.FindId(rgIref.ParentIdefId)
else:
import sys
raise Exception("{} sent to {}.".format(
rgIref_or_rdIdef.GetType().Name,
sys._getframe().f_code.co_name))
if rdIdef.UserDictionary.Count == 0:
return
sKeys_with_geom = []
for sKey in rdIdef.UserDictionary.Keys:
if spb_Block_UserDict_Geom._is_key_for_geometry(rdIdef, sKey):
sKeys_with_geom.append(sKey)
return sKeys_with_geom
def prepareLayer(sLayerName, sLayerName_Parent=None):
"""
Returns: str of layer path.
"""
if sLayerName_Parent:
sLayerPath = "{}::{}".format(sLayerName_Parent, sLayerName)
else:
sLayerPath = sLayerName
if not rs.IsLayer(sLayerPath):
return rs.AddLayer(
name=sLayerPath,
color=None,
visible=True,
locked=False,
parent=None)
if not rs.IsLayerVisible(sLayerPath):
rs.LayerVisible(sLayerPath)
if rs.IsLayerLocked(sLayerPath):
rs.LayerLocked(sLayerPath, locked=False)
return sLayerPath
def createLayersForBlocks():
res, objrefs_Iref = ri.RhinoGet.GetMultipleObjects(
"Select instances <All>",
acceptNothing=True,
filter=rd.ObjectType.InstanceReference)
if res != Rhino.Commands.Result.Success: return
if objrefs_Iref is None:
rdIdefs = list(sc.doc.InstanceDefinitions)
else:
rdIdefs = []
for objref in objrefs_Iref:
rgIref = objref.Geometry()
rdIdef = sc.doc.InstanceDefinitions.FindId(rgIref.ParentIdefId)
if rdIdef not in rdIdefs:
rdIdefs.append(rdIdef)
iDictsWithGeomValues = 0
for rdIdef in rdIdefs:
#prepareLayer(rdIdef.Name)
#sKeys = _get_keys_for_geometries(rdIdef)
sKeys = spb_Block_UserDict_Geom._get_keys_for_geometries(rdIdef)
if sKeys is None:
if len(rdIdefs) == 1:
print("There is no dictionary in {}.".format(rdIdef.Name))
continue
if len(sKeys) == 0:
if len(rdIdefs) == 1:
print("There is no geometry in {}'s dictionary.".format(rdIdef.Name))
continue
iDictsWithGeomValues += 1
for sKey in sKeys:
if not rd.ModelComponent.IsValidComponentName(sKey):
print("{} is not a valid layer name and will be skipped".format(sKey))
continue
prepareLayer(sKey, rdIdef.Name)
if iDictsWithGeomValues == 0:
print("There are no dictionary values of geometry in any of the {} definitions.".format(len(rdIdefs)))
def getAllNormalObjectsOnLayer(sLayerPath):
oes = rd.ObjectEnumeratorSettings()
oes.LockedObjects = False # Default is True.
oes.ObjectTypeFilter = (
rd.ObjectType.Brep |
rd.ObjectType.Curve |
rd.ObjectType.Extrusion |
rd.ObjectType.None
)
idxLayer = sc.doc.Layers.FindByFullPath(
layerPath=sLayerPath,
ignoreDeletedLayers=True)
#sEval = "idxLayer"; print(sEval,'=',eval(sEval))
rdObjs_Out = []
for rdObj in sc.doc.Objects.GetObjectList(oes):
if rdObj.Attributes.LayerIndex == idxLayer:
rdObjs_Out.append(rdObj)
return rdObjs_Out
def readGeomFromKVPs():
if Opts.values['bReadAll']:
objrefs_Iref = getInput_MultiBlockInsts(bWrite_NotRead=False)
if objrefs_Iref is None: return
else:
objref_Iref = getInput_OneBlockInst(bWrite_NotRead=False)
if objref_Iref is None: return
objrefs_Iref = [objref_Iref]
bReadAll = Opts.values['bReadAll']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
#res, objref_Iref = ri.RhinoGet.GetOneObject(
# "Select block instance",
# acceptNothing=False,
# filter=rd.ObjectType.InstanceReference)
#if res != Rhino.Commands.Result.Success: return
#sEval = "sc.doc.Objects.SelectedObjectsExist(objectType=rd.ObjectType.AnyObject, checkSubObjects=False)"; print(sEval,'=',eval(sEval))
sc.doc.Objects.UnselectAll()
for objref_Iref in objrefs_Iref:
rgIref = objref_Iref.Geometry()
rdIdef = sc.doc.InstanceDefinitions.FindId(rgIref.ParentIdefId)
keys_with_geoms = _get_keys_for_geometries(rgIref)
if not keys_with_geoms:
print("No keys for geometry.")
return
if bReadAll:
sKeys = keys_with_geoms
elif len(keys_with_geoms) == 1:
if bEcho: print("Only 1 key/value pair with geometry.")
sKeys = keys_with_geoms
else:
sKeys = rs.MultiListBox(
items=keys_with_geoms,
message="Pick keys to access their geometries.",
title="Get Geometry per Key",
defaults=None)
if sKeys is None:
return
for sKey in sKeys:
geoms_ret = spb_Block_UserDict_Geom._get_geoms_transformed_to_instance(rgIref, sKey)
if not geoms_ret:
continue
if not rd.ModelComponent.IsValidComponentName(sKey):
print("{} is not a valid layer name and will be skipped".format(sKey))
continue
if '::' in sKey:
print("{} is not a valid layer name and will be skipped".format(sKey))
continue
sLayerPath = prepareLayer(
sLayerName=sKey,
sLayerName_Parent=rdIdef.Name)
attr = rd.ObjectAttributes()
idxLayer = sc.doc.Layers.FindByFullPath(
layerPath=sLayerPath,
ignoreDeletedLayers=True)
attr.LayerIndex = idxLayer
nFails = 0
for geom_ret in geoms_ret:
gOut = sc.doc.Objects.Add(geom_ret, attributes=attr)
if gOut == gOut.Empty:
print("Could not add {}.".format(geom_ret))
nFails += 1
sc.doc.Objects.UnselectAll()
sc.doc.Views.Redraw()
def writeGeomToKVPs():
objref_Iref = getInput_OneBlockInst(bWrite_NotRead=True)
if objref_Iref is None: return
bWriteAllNormalGeomPerLayers = Opts.values['bWriteAllNormalGeomPerLayers']
bAppend_Not_overwrite = Opts.values['bAppend_Not_overwrite']
bDeleteInputOnWrite = Opts.values['bDeleteInputOnWrite']
bDeleteLayersOnWrite = Opts.values['bDeleteLayersOnWrite']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
#res, objref_Iref = ri.RhinoGet.GetOneObject(
# "Select block instance",
# acceptNothing=False,
# filter=rd.ObjectType.InstanceReference)
#if res != Rhino.Commands.Result.Success: return
sc.doc.Objects.UnselectAll()
if bWriteAllNormalGeomPerLayers:
rgIref = objref_Iref.Geometry()
rdIdef = sc.doc.InstanceDefinitions.FindId(rgIref.ParentIdefId)
if not rs.IsLayer(rdIdef.Name):
print("Layer '{}' does not exist, so no geometry will be written to its dictionary.".format(rdIdef.Name))
return
if rs.LayerChildCount(rdIdef.Name) == 0:
print("Layer '{}' has no children, so no geometry will be written to its dictionary.".format(rdIdef.Name))
return
for sChildLayerPath in rs.LayerChildren(rdIdef.Name):
rdObjs_OnLayer = getAllNormalObjectsOnLayer(sChildLayerPath)
bSuccess = spb_Block_UserDict_Geom._store_in_def_of_ref_Geoms_of_rdObjs(
rgIref,
rdObjs_OnLayer,
sChildLayerPath.split('::')[-1],
bAppend=bAppend_Not_overwrite,
bEcho=bEcho,
bDebug=bDebug)
if bSuccess and bDeleteInputOnWrite:
[sc.doc.Objects.Delete(o, quiet=False) for o in rdObjs_OnLayer]
#rs.DeleteObjects([o.ObjectId for o in objrefs_Geom_In])
#rs.DeleteLayer(key)
return
res, objrefs_Geom_In = ri.RhinoGet.GetMultipleObjects(
"Select objects to save in block",
acceptNothing=False,
filter=rd.ObjectType.AnyObject)
if res != Rhino.Commands.Result.Success: return
objrefs_Geom_In = list(objrefs_Geom_In) # from Array.
# If the container block is in selection, remove it.
for objref_ToPack in objrefs_Geom_In:
if objref_ToPack.ObjectId == objref_Iref.ObjectId:
objrefs_Geom_In.remove(objref_ToPack)
if len(objrefs_Geom_In) == 0:
print("No objects.")
return
print("Subject instance was removed from selection.")
break
#if 'New' in sOption:
# sKey = rs.StringBox(message="Enter key", default_value=None, title="New Storage Set")
# if sKey is None: return
# rgIref = objref_Iref.Geometry()
#if sOption in ('a', 'ad'):
# # WIP: Get keys.
# rgIref = objref_Iref.Geometry()
# rdIdef = sc.doc.InstanceDefinitions.FindId(rgIref.ParentIdefId)
# for key in rdIdef.UserDictionary.Keys:
# pass
rgIref = objref_Iref.Geometry()
#keys_with_geoms = _get_keys_for_geometries(rgIref)
keys_with_geoms = spb_Block_UserDict_Geom._get_keys_for_geometries(rgIref)
if not keys_with_geoms:
sKey = rs.StringBox(message="Enter key", default_value=None, title="New Storage Set")
if sKey is None: return
else:
sKey = rs.ListBox(
items=keys_with_geoms,
message="Pick key to write to its value or <Cancel> to type a new key",
title="Write",
default=None)
sEval = "sKey"; print(sEval,'=',eval(sEval))
if sKey is None:
sKey = rs.StringBox(message="Enter key", default_value=None, title="New Storage Set")
if sKey is None: return
bSuccess = _store_in_def_of_ref_Geoms_of_objrefs(
rgIref,
objrefs_Geom_In,
sKey,
bAppend=bAppend_Not_overwrite,
bEcho=bEcho,
bDebug=bDebug)
if bSuccess and bDeleteInputOnWrite:
[sc.doc.Objects.Delete(o, quiet=False) for o in objrefs_Geom_In]
#rs.DeleteObjects([o.ObjectId for o in objrefs_Geom_In])
#rs.DeleteLayer(key)
sc.doc.Objects.UnselectAll()
sc.doc.Views.Redraw()
def main():
if sc.doc.InstanceDefinitions.ActiveCount == 0:
print("No blocks in document. Create blocks/instance(s) before running this script.")
return
bDebug = Opts.values['bDebug']
if bDebug:
spb_Block_UserDict_Geom._auditAllBlockDefsForGeometry()
rc = getOption()
if rc is None: return
sOption = rc
if sOption == 'ReadGeomFromKVPs':
readGeomFromKVPs()
return
if sOption == 'WriteGeomToKVPs':
writeGeomToKVPs()
return
if sOption == 'CreateLayersForBlocks':
createLayersForBlocks()
return
return
res, objref = ri.RhinoGet.GetOneObject(
prompt="Select instance",
acceptNothing=False,
filter=rd.ObjectType.InstanceReference)
sBlock = 'box'
create_geometry_in_block(sBlock)
return
res, objrefs = ri.RhinoGet.GetMultipleObjects(
"Select curves",
acceptNothing=False,
filter=rd.ObjectType.Curve)
if res != Rhino.Commands.Result.Success: return
gObj = rs.GetObject(
"Select object",
filter=0,
preselect=True,
select=True)
gObjs = rs.GetObjects(
"Select objects",
filter=0,
preselect=True,
select=True)
if rs.SelectedObjects():
gObjs = rs.GetObjects("Select objects", filter=0,
preselect=True, select=True)
else:
gObjs = rs.GetObjects("Select objects", filter=0)
if not gObjs: return
brep = rs.coercebrep(gObj)
bDebug = True
if bDebug: sEval="brep"; print("{}: {}".format(sEval, eval(sEval)))
if __name__ == '__main__': main()