-
Notifications
You must be signed in to change notification settings - Fork 0
/
A_TIN200.py
395 lines (320 loc) · 18.9 KB
/
A_TIN200.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
# Author - Tuva Carey, Maria Sol, Trym Jensen
# Parts of the script is borrowed from Sindre E. Hinderaker
# Description - Generator for creating customized flow-valves
from itertools import product
from logging import root
from multiprocessing import parent_process
import adsk.core, adsk.fusion, adsk.cam, traceback
from math import radians, pi, cos, degrees
# Global design parameters
defaultHoles = 6 # number of screw holes
defaultRH = 3 # screw hole radius
defaultLength = 100
defaultTheta = radians(70) # [deg] angle between sensor-pipe and main-pipe
defaultD = 40 # [cm] pipe/valve diameter
# Global set of event _handlers to keep them referenced for the duration of the command
_handlers = []
app = adsk.core.Application.get()
if app:
ui = app.userInterface
new_comp = None
def createNewComponent():
# Get the active design.
product = app.activeProduct
design = adsk.fusion.Design.cast(product)
root_comp = design.rootComponent
all_occs = root_comp.occurrences
new_occ = all_occs.addNewComponent(adsk.core.Matrix3D.create())
return new_occ.component
class FlowValveCommandExecuteHandler(adsk.core.CommandEventHandler):
"""Event handler that reacts to any changes the user makes to any of the command inputs."""
def __init__(self):
super().__init__()
def notify(self, args: adsk.core.CommandEventArgs):
try:
unitsMgr = app.activeProduct.unitsManager
command: adsk.core.Command = args.firingEvent.sender
inputs = command.commandInputs
flow_valve = FlowValve()
for input in inputs:
if input.id == 'theta':
flow_valve.theta = unitsMgr.evaluateExpression(input.expression, "deg")
elif input.id == 'D':
flow_valve.D = unitsMgr.evaluateExpression(input.expression, "cm")
elif input.id == 'L':
flow_valve.L = unitsMgr.evaluateExpression(input.expression, "cm")
elif input.id == 'RH':
flow_valve.RH = unitsMgr.evaluateExpression(input.expression, "cm")
elif input.id == 'H':
flow_valve.H = unitsMgr.evaluateExpression(input.expression, "pcs")
elif input.id == 'P':
input.formattedText = f'~ {round(flow_valve.P, 2)} cm'
elif input.id == 'WT':
input.formattedText = f'~ {round(flow_valve.WT, 2)} cm'
flow_valve.create_flow_valve()
args.isValidResult = True
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class FlowValveCommandDestroyHandler(adsk.core.CommandEventHandler):
"""Event handler that reacts to when the command is destroyed. This terminates the script."""
def __init__(self):
super().__init__()
def notify(self, args: adsk.core.CommandEventArgs):
try:
# when the command is done, terminate the script
# this will release all globals which will remove all event _handlers
adsk.terminate()
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class FlowValveCommandCreatedHandler(adsk.core.CommandCreatedEventHandler):
"""
Event handler that reacts when the command definition is executed which
results in the command being created and this event being fired.
"""
def __init__(self):
super().__init__()
def notify(self, args: adsk.core.CommandEventArgs):
try:
# Get the command that was created.
cmd = adsk.core.Command.cast(args.command)
# Connect to the command event handler.
onExecute = FlowValveCommandExecuteHandler()
cmd.execute.add(onExecute)
_handlers.append(onExecute) # keep the handler referenced beyond this function
# Connect to the command event handler.
onExecutePreview = FlowValveCommandExecuteHandler()
cmd.executePreview.add(onExecutePreview)
_handlers.append(onExecutePreview) # keep the handler referenced beyond this function
# Connect to the command destroyed event.
onDestroy = FlowValveCommandDestroyHandler()
cmd.destroy.add(onDestroy)
_handlers.append(onDestroy) # keep the handler referenced beyond this function
# Get the CommandInputs collection associated with the command.
inputs = cmd.commandInputs
# Define the command dialog image/illustration
#_imgInput = inputs.addImageCommandInput('FlowValve', 'Flow valve', 'resources/flow_valve.png')
#_imgInput.isFullWidth = True
# Define the value inputs for the command
_initTheta = adsk.core.ValueInput.createByReal(defaultTheta)
inputs.addValueInput('theta', 'Angle (θ)', 'deg', _initTheta)
_initD = adsk.core.ValueInput.createByReal(defaultD)
inputs.addValueInput('D', 'Main Pipe Outer Diameter (D)', 'cm', _initD)
_initL = adsk.core.ValueInput.createByReal(defaultLength)
inputs.addValueInput('L', 'Length (L)', 'cm', _initL)
_initRH = adsk.core.ValueInput.createByReal(defaultRH)
inputs.addValueInput('RH', 'Screw hole radius', 'cm', _initRH)
_initH = adsk.core.ValueInput.createByReal(defaultHoles)
inputs.addValueInput('H', 'Number of screw holes', 'pcs', _initH)
# Define a read-only textbox for the command
_initP = round(defaultD/cos(pi/2-defaultTheta), 2)
inputs.addTextBoxCommandInput('P', 'Transducer distance (P)', f'~ {_initP} cm', 1, True)
_initWT = round(defaultD/2-(defaultD/2-defaultD/10))
inputs.addTextBoxCommandInput('WT', 'Wall thickness (WT)', f'~ {_initWT} cm', 1, True)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))
class FlowValve():
def __init__(self):
# Design parameters
self._H = defaultHoles # number of holes for bolts
self._RH = defaultRH # radius for botls
self._theta = defaultTheta # angle between sensor-pipe and main-pipe
self._D = defaultD # main pipe diameter
self._L = defaultLength
self._WT = self.calculate_WT() # wall thickness of main pipe
self._d = 15 # sensor pipe diameter
# self._P = defaultP # distance between transducers
self._P = self.calculate_P() # distance between transducers
# Properties
@property
def H(self) -> float:
return self._H
@H.setter
def H(self, value: float):
self._H = value
@property
def RH(self) -> float:
return self._RH
@RH.setter
def RH(self, value: float):
self._RH = value
@property
def L(self) -> float:
return self._L
@L.setter
def L(self, value: float):
self._L = value
@property
def theta(self) -> float:
"""Angle between sensor-pipe and main-pipe."""
return self._theta
@theta.setter
def theta(self, value: float):
"""Angle between sensor-pipe and main-pipe."""
self._theta = value
self.calculate_P()
@property
def D(self) -> float:
"""Main-pipe diameter."""
return self._D
@D.setter
def D(self, value: float):
"""Main-pipe diameter."""
self._D = value
self.calculate_P()
@property
def P(self) -> float:
"""Distance between transducers."""
return self._P
@property
def WT(self) -> float:
"""Wall thickness of main-pipe"""
return self._WT
# Methods
def calculate_P(self):
self._P = self._D/cos(pi/2-self._theta)
return self._P
def calculate_WT(self):
self._WT = self._D/2-(self.D/2-self.D/10)
return self._WT
def create_flow_valve(self):
"""Creates and builds the flow valve based on specified property values"""
new_comp = createNewComponent()
if new_comp is None:
ui.messageBox('New component failed to create', 'New Component Failed')
return
new_comp.name = f'Flow-valve (D{self.D}cm θ{degrees(self.theta)}deg)'
# Defining a global center point
center_global = new_comp.originConstructionPoint.geometry
# SENSOR PIPE ------------------------------------------------------------------
# Create angled construction plane
const_plane_sp_input = new_comp.constructionPlanes.createInput()
const_plane_sp_input.setByAngle(linearEntity=new_comp.xConstructionAxis, angle=adsk.core.ValueInput.createByReal(self.theta), planarEntity=new_comp.xYConstructionPlane)
const_plane_sp = new_comp.constructionPlanes.add(const_plane_sp_input)
# Create sketch on angled construction plane and center point for sketch
sketch_sp = new_comp.sketches.add(const_plane_sp)
center_sp = sketch_sp.modelToSketchSpace(center_global)
# Draw circles
circles_sp = sketch_sp.sketchCurves.sketchCircles
# Draw outer circle
circle_sp_o = circles_sp.addByCenterRadius(centerPoint=center_sp, radius=self._d/2)
# Draw inner circle
circle_sp_i = circles_sp.addByCenterRadius(centerPoint=circle_sp_o.centerSketchPoint, radius=self._d/2-self._d/10)
# Extrude (new body)
pipe_sp_profile = sketch_sp.profiles.item(0) # get the pipe profile (profile between inner and outer circle)
ext_pipe_sp_input = new_comp.features.extrudeFeatures.createInput(profile=pipe_sp_profile, operation=adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
ext_pipe_sp_input.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(self.P/2+70))
new_comp.features.extrudeFeatures.add(ext_pipe_sp_input)
# ------------------------------------------------------------------------------
# MAIN PIPE --------------------------------------------------------------------
# Create sketch on xY construction plane and center point for sketch
sketch_mp = new_comp.sketches.add(new_comp.xYConstructionPlane)
center_mp = sketch_mp.modelToSketchSpace(center_global)
# Draw circles
circles_mp = sketch_mp.sketchCurves.sketchCircles
# Draw outer circle
circle_mp_o = circles_mp.addByCenterRadius(centerPoint=center_mp, radius=self.D/2)
# Draw inner circle
circle_mp_i = circles_mp.addByCenterRadius(centerPoint=circle_mp_o.centerSketchPoint, radius=self.D/2-self.D/10)
# Create object collection of profiles and extrude cut
profiles_mp = adsk.core.ObjectCollection.create()
[profiles_mp.add(profile) for profile in sketch_mp.profiles]
ext_pipe_mp_cut_input = new_comp.features.extrudeFeatures.createInput(profile=profiles_mp, operation=adsk.fusion.FeatureOperations.CutFeatureOperation)
# ext_pipe_mp_cut_input.setAllExtent(direction=adsk.fusion.ExtentDirections.SymmetricExtentDirection) # does not extrude symmetric for some reason...
ext_pipe_mp_cut_input.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(self.L/2))
new_comp.features.extrudeFeatures.add(ext_pipe_mp_cut_input)
# Extrude join pipe profile
pipe_mp_profile = sketch_mp.profiles.item(0) # get the pipe profile (profile between inner and outer circle)
ext_pipe_mp_join_input = new_comp.features.extrudeFeatures.createInput(profile=pipe_mp_profile, operation=adsk.fusion.FeatureOperations.JoinFeatureOperation)
ext_pipe_mp_join_input.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(self.L/2))
new_comp.features.extrudeFeatures.add(ext_pipe_mp_join_input)
# ------------------------------------------------------------------------------
# Extrude center profile of SENSOR PIPE, to "open" MAIN PIPE
pipe_sp_profile_i = sketch_sp.profiles.item(1) # get the center profile (profile by inner circle)
ext_pipe_sp_i_input = new_comp.features.extrudeFeatures.createInput(profile=pipe_sp_profile_i, operation=adsk.fusion.FeatureOperations.CutFeatureOperation)
# ext_pipe_sp_i_input.setAllExtent(direction=adsk.fusion.ExtentDirections.SymmetricExtentDirection) # does not extrude symmetric for some reason...
ext_pipe_sp_i_input.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(self.P/2 + 70*3))
new_comp.features.extrudeFeatures.add(ext_pipe_sp_i_input)
#---------------------------------------
# SPOOL PIECE 1:
const_offsetPlane_input = new_comp.constructionPlanes.createInput()
const_offsetPlane_input.setByOffset(planarEntity=new_comp.xYConstructionPlane, offset=adsk.core.ValueInput.createByReal(self.L/2))
const_offsetPlane = new_comp.constructionPlanes.add(const_offsetPlane_input)
sketch_spool = new_comp.sketches.add(const_offsetPlane)
center_spool = sketch_spool.modelToSketchSpace(adsk.core.Point3D.create(0,0,self.L/2))
circle_spool = sketch_spool.sketchCurves.sketchCircles
circle_spool_o = circle_spool.addByCenterRadius(centerPoint=center_spool, radius=self.D) #item(0)
circle_spool_i = circle_spool.addByCenterRadius(centerPoint=circle_spool_o.centerSketchPoint, radius=self.D/2-self.D/10) #item(1)
spool_profile = sketch_spool.profiles.item(0)
ext_spool_input = new_comp.features.extrudeFeatures.createInput(profile=spool_profile, operation=adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
ext_spool_input.setDistanceExtent(isSymmetric=False, distance=adsk.core.ValueInput.createByReal(0.2*self.D))
new_comp.features.extrudeFeatures.add(ext_spool_input)
parent_sketch = sketch_spool.sketchCurves.sketchCircles.addByCenterRadius(centerPoint=adsk.core.Point3D.create(0,self.D-self.D/5,0), radius=self.RH) #item(2)
spool_profile = sketch_spool.profiles.item(2)
ext_spool_hole = new_comp.features.extrudeFeatures.createInput(profile=spool_profile, operation=adsk.fusion.FeatureOperations.CutFeatureOperation)
ext_spool_hole.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(0.2*self.D))
circle_cut = new_comp.features.extrudeFeatures.add(ext_spool_hole)
app = adsk.core.Application.get()
ui = app.userInterface
design = app.activeProduct
#rootComp = adsk.fusion.Component.cast(design.rootComponent)
CircularPatterns = new_comp.features.circularPatternFeatures
inputEntitiesCollection = adsk.core.ObjectCollection.create()
inputEntitiesCollection.add(circle_cut)
inputAxis = new_comp.zConstructionAxis
CircularPatternInput = CircularPatterns.createInput(inputEntitiesCollection, inputAxis)
CircularPatternInput.quantity = adsk.core.ValueInput.createByReal(self.H)
CircularPatternInput.totalAngle = adsk.core.ValueInput.createByString('360 deg')
CircularPatternInput.isSymmetric = False
CircularPattern = CircularPatterns.add(CircularPatternInput)
# SPOOL PIECE 2:
const_offsetPlane_input = new_comp.constructionPlanes.createInput()
const_offsetPlane_input.setByOffset(planarEntity=new_comp.xYConstructionPlane, offset=adsk.core.ValueInput.createByReal(self.L/2))
const_offsetPlane = new_comp.constructionPlanes.add(const_offsetPlane_input)
sketch_spool = new_comp.sketches.add(const_offsetPlane)
center_spool = sketch_spool.modelToSketchSpace(adsk.core.Point3D.create(0,0,-self.L/2))
circle_spool = sketch_spool.sketchCurves.sketchCircles
circle_spool_o = circle_spool.addByCenterRadius(centerPoint=center_spool, radius=self.D) #item(0)
circle_spool_i = circle_spool.addByCenterRadius(centerPoint=circle_spool_o.centerSketchPoint, radius=self.D/2-self.D/10) #item(1)
spool_profile = sketch_spool.profiles.item(0)
ext_spool_input = new_comp.features.extrudeFeatures.createInput(profile=spool_profile, operation=adsk.fusion.FeatureOperations.NewBodyFeatureOperation)
ext_spool_input.setDistanceExtent(isSymmetric=False, distance=adsk.core.ValueInput.createByReal(-0.2*self.D))
new_comp.features.extrudeFeatures.add(ext_spool_input)
parent_sketch_2 = sketch_spool.sketchCurves.sketchCircles.addByCenterRadius(centerPoint=adsk.core.Point3D.create(0,self.D-self.D/5,-self.L), radius=self.RH) #item(2)
spool_profile = sketch_spool.profiles.item(2)
ext_spool_hole = new_comp.features.extrudeFeatures.createInput(profile=spool_profile, operation=adsk.fusion.FeatureOperations.CutFeatureOperation)
ext_spool_hole.setDistanceExtent(isSymmetric=True, distance=adsk.core.ValueInput.createByReal(0.2*self.D))
circle_cut = new_comp.features.extrudeFeatures.add(ext_spool_hole)
app = adsk.core.Application.get()
ui = app.userInterface
design = app.activeProduct
CircularPatterns = new_comp.features.circularPatternFeatures
inputEntitiesCollection = adsk.core.ObjectCollection.create()
inputEntitiesCollection.add(circle_cut)
inputAxis = new_comp.zConstructionAxis
CircularPatternInput = CircularPatterns.createInput(inputEntitiesCollection, inputAxis)
CircularPatternInput.quantity = adsk.core.ValueInput.createByReal(self.H)
CircularPatternInput.totalAngle = adsk.core.ValueInput.createByString('360 deg')
CircularPatternInput.isSymmetric = False
CircularPattern = CircularPatterns.add(CircularPatternInput)
# ------------------------------------------------------------------------------
def run(context):
try:
# Get the existing command definition or create it if it doesn't already exist.
cmdDef = ui.commandDefinitions.itemById('FlowValve')
if not cmdDef:
cmdDef = ui.commandDefinitions.addButtonDefinition('FlowValve', 'Create Flow-Valve', 'Create a customized flow-valve.', './resources') # relative resource file path is specified
# Connect to the command created event.
onCommandCreated = FlowValveCommandCreatedHandler()
cmdDef.commandCreated.add(onCommandCreated)
_handlers.append(onCommandCreated)
inputs = adsk.core.NamedValues.create()
# Execute the command definition.
cmdDef.execute(inputs)
# prevent this module from being terminate when the script returns, because we are waiting for event _handlers to fire
adsk.autoTerminate(False)
except:
if ui:
ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))