-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoMortise.py
More file actions
447 lines (369 loc) · 15.5 KB
/
AutoMortise.py
File metadata and controls
447 lines (369 loc) · 15.5 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
# Author-dymk
# Description-Create various joints
import adsk.core
import adsk.fusion
import adsk.cam
import traceback
import logging
import sys
import itertools
from . import ids
from . import geom
from .boundary import boundary
import timeit
EPS = 0.00001
DEBUGGING_GRAPHICS = False
MOAR_DEBUG = False
handlers = []
def createHandler(klass, method, name):
class _Handler(klass):
def __init__(self):
super().__init__()
print("initialized {} handler".format(name))
def notify(self, arg):
print("handler {} called".format(name))
method(arg)
handler = _Handler()
handlers.append(handler)
return handler
class AutoMortiseCommand:
def __init__(self, createHandler):
self._createHandler = createHandler
@boundary("onCreate")
def onCreate(self, args: adsk.core.CommandCreatedEventArgs):
command = args.command
inputs = command.commandInputs
self._bodies: List[adsk.fusion.BRepBody] = []
selectBodiesInput = inputs.addSelectionInput(
ids.BODIES_SELECT, "Bodies", "Select bodies to generate tabs between"
)
selectBodiesInput.addSelectionFilter("SolidBodies")
selectBodiesInput.setSelectionLimits(2, 0)
self._tabMaxSizeInput = inputs.addValueInput(
ids.TAB_MAX_SIZE,
"Max Tab Width",
"cm",
adsk.core.ValueInput.createByReal(3),
)
command.inputChanged.add(
self._createHandler(
adsk.core.InputChangedEventHandler, self.onChange, "onChange"
)
)
command.validateInputs.add(
self._createHandler(
adsk.core.ValidateInputsEventHandler, self.onValidate, "onValidate"
)
)
command.execute.add(
self._createHandler(
adsk.core.CommandEventHandler, self.onExecute, "onExecute"
)
)
@boundary("onChange")
def onChange(self, args: adsk.core.InputChangedEventArgs):
input_ = adsk.core.SelectionCommandInput.cast(args.input)
if input_.id == ids.BODIES_SELECT:
entities = [
input_.selection(idx).entity for idx in range(input_.selectionCount)
]
self._bodies = entities
print("{} bodies selected".format(len(entities)))
@boundary("onValidate")
def onValidate(self, args: adsk.core.ValidateInputsEventArgs):
if len(self._bodies) < 2:
return False
if not self._tabMaxSizeInput.isValidExpression:
return False
return True
def app(self):
return adsk.core.Application.get()
def design(self):
return adsk.fusion.Design.cast(self.app().activeProduct)
def rootComponent(self):
return self.design().rootComponent
@boundary("onExecute")
def onExecute(self, args: adsk.core.CommandEventArgs):
pairsOfBodies = list(itertools.combinations(self._bodies, 2))
print("{} combinations of bodies".format(len(pairsOfBodies)))
# for now, remove any existing history groups generated by this script
existingGroups = geom.adskList(
self.design().timeline.timelineGroups, adsk.fusion.TimelineGroup
)
for g in existingGroups:
if g.name == ids.TAB_TIMELINE_GROUP:
g.deleteMe(True)
tlstart = self.design().timeline.markerPosition
startTimeFindCandidates = timeit.default_timer()
tabsToExtrude = []
for bodyPair in pairsOfBodies:
for facePair in self.getCandidateFacePairs(*bodyPair):
tabToExtrude = self.tryPlacingTabProfiles(*facePair)
if tabToExtrude is not None:
tabsToExtrude.append(tabToExtrude)
endTimeFindCandidates = timeit.default_timer()
startTimeExtrude = timeit.default_timer()
for tabToExtrude in tabsToExtrude:
self.extrudeTabs(*tabToExtrude)
endTimeExtrude = timeit.default_timer()
def timeFmt(dur):
return "{} seconds".format(round(dur, 2))
print(
"duration to get candidate pairs: {}".format(
timeFmt(endTimeFindCandidates - startTimeFindCandidates)
)
)
print(
"duration to extrude profiles: {}".format(
timeFmt(endTimeExtrude - startTimeExtrude)
)
)
tlend = self.design().timeline.markerPosition - 1
if (tlend - tlstart) > 0:
group = self.design().timeline.timelineGroups.add(tlstart, tlend)
group.name = ids.TAB_TIMELINE_GROUP
# tries to extrude tabs from fromFace into toFace
# If the operation fails, then returns None
# If it works, returns information about how to extrude the tab later
def tryPlacingTabProfiles(
self, fromFace: adsk.fusion.BRepFace, toFace: adsk.fusion.BRepFace
):
fromComponent = self.getComponentOrRoot(fromFace)
toComponent = self.getComponentOrRoot(toFace)
prettyName = "{}.{} -> {}.{}".format(
fromComponent.name, fromFace.body.name, toComponent.name, toFace.body.name
)
print(
"Checking if candidate pair of faces between {} is valid".format(prettyName)
)
sketchName = ids.TAB_SKETCH_PREFIX + prettyName + " (from)"
fromSketch: adsk.fusion.Sketch = fromComponent.sketches.addWithoutEdges(
fromFace
)
fromSketch.name = sketchName
fromSketch.isComputeDeferred = True
toEvaluator = toFace.evaluator
for vertex in geom.adskList(fromFace.vertices, adsk.fusion.BRepVertex):
success, vertexParam = toEvaluator.getParameterAtPoint(vertex.geometry)
if not success or not toEvaluator.isParameterOnFace(vertexParam):
print(
"({}, {}) does not lie on the target surface".format(
*[round(i, 2) for i in [vertex.geometry.x, vertex.geometry.y]]
)
)
fromSketch.deleteMe()
return None
# check that the face is some sort of rectangle - and get the basis vector for its
# orientation
fromEdges = geom.adskList(fromFace.edges, adsk.fusion.BRepEdge)
for edge in fromEdges:
if edge.geometry.curveType != adsk.core.Curve3DTypes.Line3DCurveType:
print("Face between {} contains a non-straight line".format(prettyName))
fromSketch.deleteMe()
return None
fromSketch.isComputeDeferred = False
fromEdgesOnSketch = []
for edge in fromEdges:
collection = fromSketch.project(edge)
for i in range(collection.count):
sketchCurve = collection.item(i)
sketchCurve.isConstruction = True
fromEdgesOnSketch.append(sketchCurve)
fromSketch.isComputeDeferred = True
edgeDirs = []
edgeGroups = []
fromEdgesOnSketch.sort(key=geom.edgeDirectionForComparison)
for edgeDir, edges in itertools.groupby(
fromEdgesOnSketch, key=geom.edgeDirectionForComparison
):
edgeDirs.append(edgeDir)
edgeGroups.append(list(edges))
if len(edgeDirs) != 2:
print(
"Face must be a rectangle ({} edge directions detected: {})".format(
len(edgeDirs), edgeDirs
)
)
fromSketch.deleteMe()
return None
if (
abs(
geom.edgeDirection(edgeGroups[0][0]).dotProduct(
geom.edgeDirection(edgeGroups[1][0])
)
)
>= EPS
):
print("Face must be a rectangle (nonorthonal edge directions detected)")
fromSketch.deleteMe()
return None
# find all the coplanar faces on the body being extruded into,
# and find the farthest one from fromFace
toBodyFaces = sorted(
[
face
for face in geom.adskList(toFace.body.faces, adsk.fusion.BRepFace)
if not toFace == face and geom.arePlanesParallel(toFace, face)
],
key=lambda face: -geom.distBetweenFaces(fromFace, face),
)
if len(toBodyFaces) == 0:
print("body to extrude into has no good candidate ending plane")
fromSketch.deleteMe()
return None
toBodyTargetFace = toBodyFaces[0]
# find the longer of the edges
longEdges: List[adsk.fusion.SketchLine] = max(
edgeGroups, key=lambda group: geom.sketchLineLength(group[0])
)
# start / end points of the two long sides
e1points = [longEdges[0].geometry.startPoint, longEdges[0].geometry.endPoint]
e2points = [longEdges[1].geometry.startPoint, longEdges[1].geometry.endPoint]
# the start / end points might be swapped - starting points should be closer to each other
if geom.distToPoint(e1points[0], e2points[0]) > geom.distToPoint(
e1points[0], e2points[1]
):
e2points.reverse()
def drawRectFrom(lower, upper):
# points of a polygon representing a rectangle
rectPoints = [
geom.lerp(e1points[0], e1points[1], lower),
geom.lerp(e1points[0], e1points[1], upper),
geom.lerp(e2points[0], e2points[1], upper),
geom.lerp(e2points[0], e2points[1], lower),
]
for idx, p1 in enumerate(rectPoints):
p2 = rectPoints[(idx + 1) % len(rectPoints)]
fromSketch.sketchCurves.sketchLines.addByTwoPoints(p1, p2)
# start with splitting into 3 sections - two detents on the
# outer edges, one tab in the middle, all of equal size
# keep adding more sections until we're under "max tab size"
longEdgeLength = geom.edgeLength(longEdges[0])
numSections = 3
maxTabSize = self._tabMaxSizeInput.value
while (longEdgeLength / numSections) > maxTabSize:
# add another pair of tabs / detents
numSections += 2
print(
"computed tab size to be {}".format(round(longEdgeLength / numSections, 2))
)
# the odd numbered sections are the tabs, evens are detents
for section in (i for i in range(numSections) if i % 2 == 1):
start = float(section) / numSections
end = float(section + 1) / numSections
drawRectFrom(start, end)
fromSketch.isComputeDeferred = False
print("{} sketch profiles generated".format(fromSketch.profiles.count))
fromTabProfiles = adsk.core.ObjectCollection.create()
for profile in geom.adskList(fromSketch.profiles, adsk.fusion.Profile):
fromTabProfiles.add(profile)
tabDist = geom.distBetweenFaces(fromFace, toBodyTargetFace)
# The plane to extrude from, the tab profiles to extrude, the distance to extrude the tabs
# and the two faces that will be extrude from / into
return (fromFace, toFace, fromTabProfiles, tabDist)
def extrudeTabs(
self,
fromFace: adsk.fusion.BRepFace,
toFace: adsk.fusion.BRepFace,
fromtabProfiles: adsk.core.ObjectCollection,
tabDist: float,
):
fromBody = fromFace.body
toBody = toFace.body
fromComponent = self.getComponentOrRoot(fromFace)
toComponent = self.getComponentOrRoot(toBody)
# perform the tab extrude (only on the body that contains the fromFace)
tabFeatureInput = fromComponent.features.extrudeFeatures.createInput(
fromtabProfiles, adsk.fusion.FeatureOperations.JoinFeatureOperation
)
tabFeatureInput.participantBodies = [fromBody]
tabFeatureInput.setDistanceExtent(
False, adsk.core.ValueInput.createByReal(tabDist)
)
fromComponent.features.extrudeFeatures.add(tabFeatureInput)
# Cut out the tabs via body combine
combineFeatures = toComponent.features.combineFeatures
fromBodies = adsk.core.ObjectCollection.create()
fromBodies.add(fromBody)
cutInput = combineFeatures.createInput(toBody, fromBodies)
cutInput.operation = adsk.fusion.FeatureOperations.CutFeatureOperation
cutInput.isKeepToolBodies = True
combineFeatures.add(cutInput)
def getComponentOrRoot(self, objWithAssemblyContext) -> adsk.fusion.Component:
ac = objWithAssemblyContext.assemblyContext
if ac:
return ac.component
else:
return self.rootComponent()
def getCandidateFacePairs(
self, body1: adsk.fusion.BRepBody, body2: adsk.fusion.BRepBody
) -> (adsk.fusion.BRepFace, adsk.fusion.BRepFace):
def doFaceEachOther(f1, f2):
# if n1+n2 == 0, they're complementary vectors
v1 = geom.faceNormal(f1)
v2 = geom.faceNormal(f2)
v1.add(v2)
return v1.length < EPS
# [0] - the smaller brep face (gets notches extruded from)
# [1] - the larger brep face (gets cut into)
candidatePairs: (adsk.fusion.BRepFace, adsk.fusion.BRepFace) = []
for f1 in body1.faces:
for f2 in body2.faces:
coplanar = geom.areFacesCoplanar(f1, f2)
if coplanar and MOAR_DEBUG:
print(
"these planes are coplanar: {}, {}".format(
f1.tempId, f2.tempId
)
)
faceEachOther = doFaceEachOther(f1, f2)
if faceEachOther and MOAR_DEBUG:
print(
"these planes face each other: {}, {}".format(
f1.tempId, f2.tempId
)
)
if coplanar and faceEachOther:
candidatePairs.append((f1, f2) if f1.area < f2.area else (f2, f1))
return candidatePairs
def tryRemove():
app = adsk.core.Application.get()
ui = app.userInterface
cmdDef = ui.commandDefinitions.itemById(ids.MAIN_BUTTON_ID)
if cmdDef:
cmdDef.deleteMe()
createPanel = ui.allToolbarPanels.itemById("SolidCreatePanel")
cntrl = createPanel.controls.itemById(ids.MAIN_BUTTON_ID)
if cntrl:
cntrl.deleteMe()
root = adsk.fusion.Design.cast(app.activeProduct).rootComponent
if root.customGraphicsGroups.count > 0:
root.customGraphicsGroups.item(0).deleteMe()
app.activeViewport.refresh()
print("removed def: {}".format(cmdDef is not None))
print("removed ctrl: {}".format(cntrl is not None))
@boundary("run")
def run(context):
tryRemove()
app = adsk.core.Application.get()
ui = app.userInterface
command = AutoMortiseCommand(createHandler)
handlers.append(command)
button = ui.commandDefinitions.addButtonDefinition(
ids.MAIN_BUTTON_ID, "AutoMortise", "Generate mortise&tenon / box joints", "res"
)
button.commandCreated.add(
createHandler(
adsk.core.CommandCreatedEventHandler, command.onCreate, "onCreate"
)
)
createPanel = ui.allToolbarPanels.itemById("SolidCreatePanel")
buttonControl = createPanel.controls.addCommand(button, ids.MAIN_BUTTON_ID)
# Make the button available in the panel.
buttonControl.isPromotedByDefault = True
buttonControl.isPromoted = True
print("started addin")
@boundary("stop")
def stop(context):
tryRemove()
print("stopped addin")