-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathspb_Block_ScaleDefObjs.py
More file actions
500 lines (395 loc) · 16.8 KB
/
spb_Block_ScaleDefObjs.py
File metadata and controls
500 lines (395 loc) · 16.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
"""
For a STEP export to include block instances, not their exploded results,
the block instances need to be at full scale and not mirrored.
Note: For block definitions that are represented by a single block instance,
those instances will also be exploded on STEP export.
"""
#! python 2 Must be on a line number less than 32.
from __future__ import absolute_import, division, print_function, unicode_literals
"""
180709: Created, replacing EvaluateBlockInstanceScale.rvb.
180725: Now supports multiple selected objects.
181117: Refactored. Added scale routine.
190208: Various bug fixes.
230718: Split from another script.
251027: Refactored many places and removed reliance on rhinoscriptsyntax.
Added options for modifying block definitions and instances for STEP export.
251101: Now, correctly scales nested instances when their definition units doesn't match
that of parent definition.
Now, prints number of scale unit changes for each starting unit.
"""
import Rhino
import Rhino.DocObjects as rd
import Rhino.Geometry as rg
import Rhino.Input as ri
import scriptcontext as sc
class Opts:
keys = []
values = {}
names = {}
riOpts = {}
listValues = {}
stickyKeys = {}
key = 'bFixScalingForStepExport'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bScaleNonDocUnitBlocks'; keys.append(key)
values[key] = True
riOpts[key] = ri.Custom.OptionToggle(values[key], 'No', 'Yes')
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'fScale'; keys.append(key)
values[key] = 1.0/25.4
riOpts[key] = ri.Custom.OptionDouble(values[key], True, Rhino.RhinoMath.SqrtEpsilon)
stickyKeys[key] = '{}({})'.format(key, __file__)
key = 'bInverselyScaleModDefsInsts'; 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 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 == 'fScale':
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 _staticBlockDefs():
"""
Static == Embedded only
"""
ret = []
for rdDef in sc.doc.InstanceDefinitions.GetList(ignoreDeleted=True):
if rdDef.UpdateType == rd.InstanceDefinitionUpdateType.Static:
ret.append(rdDef)
return ret
def getInput():
"""
Get options.
"""
go = ri.Custom.GetOption()
go.SetCommandPrompt("Set options")
go.AcceptNothing(True)
idxs_Opts = {}
def addOption(key): idxs_Opts[key] = Opts.addOption(go, key)
while True:
go.ClearCommandOptions()
idxs_Opts.clear()
addOption('bFixScalingForStepExport')
if Opts.values['bFixScalingForStepExport']:
go.AcceptNumber(False, acceptZero=False)
else:
addOption('bScaleNonDocUnitBlocks')
if Opts.values['bScaleNonDocUnitBlocks']:
go.AcceptNumber(False, acceptZero=False)
else:
addOption('fScale')
go.AcceptNumber(True, acceptZero=False)
addOption('bInverselyScaleModDefsInsts')
addOption('bEcho')
addOption('bDebug')
res = go.Get()
if res == ri.GetResult.Cancel:
go.Dispose()
return
if res == ri.GetResult.Nothing:
go.Dispose()
return True
if res == ri.GetResult.Number:
key = 'fScale'
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 scaleContentsOfBlockDefinition(rdDef, fScale, bEcho=True, bDebug=False):
"""
"""
if fScale <= 0.0:
print("fScale must be > 0.0. {} was provided".format(fScale))
return
rdObjs_InBlock = rdDef.GetObjects()
if not rdObjs_InBlock:
if bEcho:
print("Block definition, {}, contains no objects, so it will not be processed.".format(
rdDef.Name))
return
if fScale == 1.0:
scale = None
else:
scale = rg.Transform.Scale(
anchor=rg.Point3d.Origin,
scaleFactor=fScale)
geoms = []
attrs = []
for rdObj_InBlock in rdObjs_InBlock:
geom = rdObj_InBlock.Geometry
attr = rdObj_InBlock.Attributes
if isinstance(rdObj_InBlock, rd.InstanceObject):
#pt = rg.Point3d.Origin
#pt.Transform(rdObj_InBlock.InstanceXform)
pt = rdObj_InBlock.InsertionPoint
rdDef_ofNestedInst = rdObj_InBlock.InstanceDefinition
if rdDef_ofNestedInst.UnitSystem != rdDef.UnitSystem:
if bDebug:
print("NOT EQUAL! {}, {}".format(
rdDef_ofNestedInst.UnitSystem, rdDef.UnitSystem))
scale_Inst = rg.Transform.Scale(
anchor=pt,
scaleFactor=Rhino.RhinoMath.UnitScale(
rdDef.UnitSystem,
rdDef_ofNestedInst.UnitSystem,
)
)
geom.Transform(scale_Inst)
if scale is not None:
translation = rg.Transform.Translation(fScale*pt - pt)
geom.Transform(translation)
else:
if scale is not None:
geom.Transform(scale)
geoms.append(rdObj_InBlock.Geometry)
attrs.append(rdObj_InBlock.Attributes)
return sc.doc.InstanceDefinitions.ModifyGeometry(rdDef.Index, geoms, attrs)
def _getInstanceScaleComponents(rdInst):
xform = rdInst.InstanceXform
return tuple(
[(xform[0,c]**2.0 + xform[1,c]**2.0 + xform[2,c]**2.0)**0.5 for c in (0,1,2)]
)
def scaleRootLevelInstances(rdDef, fScale, bEcho=True, bDebug=False):
"""
"""
if fScale <= 0.0:
print("fScale must be > 0.0. {} was provided".format(fScale))
return
rdInsts = rdDef.GetReferences(wheretoLook=0)
if not rdInsts:
if bDebug: print("No instances at root level for {}.".format(rdDef.Name))
return
#sEval = "fScale"; print(sEval, '=', eval(sEval))
gInsts_Scaled = []
gFails = []
for rdInst in rdInsts:
pt = rg.Point3d.Origin
pt.Transform(rdInst.InstanceXform)
#sEval = "pt"; print(sEval, '=', eval(sEval))
xform_Scale = rg.Transform.Scale(
anchor=pt,
scaleFactor=fScale)
#id = scriptcontext.doc.Objects.Transform(old_id, xform, not copy)
rv = sc.doc.Objects.Transform(
obj=rdInst,
xform=xform_Scale,
deleteOriginal=True)
#if not rdInst.Geometry.Transform(xform_Scale):
# print("Failed to scale the instance geometry of {}.".format(rdDef.Name))
# return
#rv = rdInst.CommitChanges() # CommitChanges doesn't work.
if bDebug: print(rv)
if rv != rdInst.Id:
print("Scaling {} failed.".format(rdInst.Id))
gFails.append(rdInst.Id)
else:
gInsts_Scaled.append(rdInst.Id)
rdInst_Out = sc.doc.Objects.FindId(rv)
svs = _getInstanceScaleComponents(rdInst_Out)
for sv in svs:
if not Rhino.RhinoMath.EpsilonEquals(sv, 1.0, epsilon=Rhino.RhinoMath.Epsilon):
print("Warning, instance {} of block {} is not at full scale, but instead {}, {}, {}".format(
rdInst_Out.Id, rdDef.Name, *svs))
break
return gInsts_Scaled
#print("Scaled {} root-level instance(s) by {:.20g} about their insertion points.".format(
# n_Insts_processed, 1.0/fScale))
def main():
rdDefs_Static = _staticBlockDefs()
if not rdDefs_Static:
print("Document has no static block definitions.")
return
if False: #sc.doc.Modified:
showMessageResult = Rhino.UI.Dialogs.ShowMessage(
message="This document has been modified since the last save." \
"\n\nIn the case that this script produces erroneous results," \
" it is recommended to first press the Cancel button" \
" then _Save or _SaveACopy before proceeding." \
"\n\nPress OK to continue fixing the scaling.",
title="Document Not Saved",
buttons=Rhino.UI.ShowMessageButton.OKCancel,
icon=Rhino.UI.ShowMessageIcon.Warning)
if showMessageResult == Rhino.UI.ShowMessageResult.Cancel:
return
rv = getInput()
if rv is None: return
bFixScalingForStepExport = Opts.values['bFixScalingForStepExport']
if bFixScalingForStepExport:
bScaleNonDocUnitBlocks = True
fScale = None
bInverselyScaleModDefsInsts = True
else:
bScaleNonDocUnitBlocks = Opts.values['bScaleNonDocUnitBlocks']
fScale = Opts.values['fScale']
bInverselyScaleModDefsInsts = Opts.values['bInverselyScaleModDefsInsts']
bEcho = Opts.values['bEcho']
bDebug = Opts.values['bDebug']
if not bDebug: sc.doc.Views.RedrawEnabled = True
if bScaleNonDocUnitBlocks:
rdDefs_toProcess = []
for rdDef in rdDefs_Static:
if rdDef.UnitSystem != sc.doc.ModelUnitSystem:
rdDefs_toProcess.append(rdDef)
continue
rdObjs_InBlock = rdDef.GetObjects()
if not rdObjs_InBlock:
continue
for rdObj_InBlock in rdObjs_InBlock:
if not isinstance(rdObj_InBlock, rd.InstanceObject):
continue
rdDef_ofNestedInst = rdObj_InBlock.InstanceDefinition
if rdDef_ofNestedInst.UnitSystem != rdDef.UnitSystem:
rdDefs_toProcess.append(rdDef)
break
#rdDefs_toProcess = [rdDef for rdDef in rdDefs_Static if rdDef.UnitSystem != sc.doc.ModelUnitSystem]
if not rdDefs_toProcess:
print("No block definitions exist whose units are not {}, the document units.".format(
sc.doc.ModelUnitSystem))
return
else:
rdDefs_toProcess = rdDefs_Static
#res, bProceed = ri.RhinoGet.GetBool(
# prompt="{} block definitions to have their contents scaled. Proceed?".format(
# len(rdDefs_toProcess)),
# acceptNothing=True,
# offPrompt="No", onPrompt="Yes", boolValue=False)
#if res != Rhino.Commands.Result.Success or not bProceed:
# print("Nothing was modified.")
# return
rdDefs_Scaled = []
rdInsts_Scaled = []
units_Previous = []
if bScaleNonDocUnitBlocks:
if bDebug: print("Doc unit: {}".format(sc.doc.ModelUnitSystem))
rdDefs_Processed_Stage1 = []
for rdDef in rdDefs_toProcess:
if bDebug: print("{} unit: {}".format(rdDef.Name, rdDef.UnitSystem))
if rdDef.UnitSystem == sc.doc.ModelUnitSystem:
if bDebug: print("Units match, so this block definition should contain instances of definitions with units that do not match this definition.")
fScale_ThisBlock = 1.0
else:
fScale_ThisBlock = Rhino.RhinoMath.UnitScale(
rdDef.UnitSystem,
sc.doc.ModelUnitSystem)
if bDebug: print("Will scale block objects by {}.".format(fScale_ThisBlock))
rv = scaleContentsOfBlockDefinition(
rdDef,
fScale=fScale_ThisBlock,
bEcho=bEcho,
bDebug=bDebug)
if rv:
rdDefs_Scaled.append(rdDef)
else:
print("Failed to scale contents of {}.".format(rdDef.Name))
continue
rdDefs_Processed_Stage1.append(rdDef)
rdDefs_toProcess_Stage2 = rdDefs_Processed_Stage1
# Stage 2. UnitSystem was not modified in Stage 1 to allow correct scaling
# of nested instances with units not matching that of the parent definition.
# For example, cm definition instance inside a mm definition.
for rdDef in rdDefs_toProcess_Stage2:
units_Previous.append(rdDef.UnitSystem)
rdDef.UnitSystem = sc.doc.ModelUnitSystem
if bInverselyScaleModDefsInsts:
rv = scaleRootLevelInstances(
rdDef,
fScale=1.0/fScale_ThisBlock,
bEcho=bEcho,
bDebug=bDebug)
if bDebug: print(rv)
if rv is None: continue
rdInsts_Scaled.extend(rv)
else:
for rdDef in rdDefs_toProcess:
rv = scaleContentsOfBlockDefinition(
rdDef,
fScale=fScale,
bEcho=bEcho,
bDebug=bDebug)
if rv:
rdDefs_Scaled.append(rdDef)
else:
print("Failed to scale contents of {}.".format(rdDef.Name))
continue
if bInverselyScaleModDefsInsts:
rv = scaleRootLevelInstances(
rdDef,
fScale=1.0/fScale,
bEcho=bEcho,
bDebug=bDebug)
if bDebug: print(rv)
if rv is None: continue
rdInsts_Scaled.extend(rv)
print("Scaled objects in {} definitions.".format(len(rdDefs_Scaled)))
print("Scaled {} root-level instances.".format(len(rdInsts_Scaled)))
if units_Previous:
ss = []
for unit in set(units_Previous):
ss.append("{} of {}".format(
units_Previous.count(unit), unit))
print("Set block definitions to {}:".format(sc.doc.ModelUnitSystem), ", ".join(ss))
if __name__ == '__main__': main()