-
Notifications
You must be signed in to change notification settings - Fork 0
/
zsDovetail.FCMacro
398 lines (378 loc) · 16.6 KB
/
zsDovetail.FCMacro
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
# -*- coding: utf-8 -*-
__version__ = "0.2024.01.31"
#__version__ = "0.2024.01.31"
#__title__ = "Dovetail Macro"
#__author__ = "Mario Zimmermann"
#__license__ = "LGPL 2.1"
#__doc__ = "Create a dovetail joint."
#__usage__ = '''Select the face and activate the tool, modify properties as desired'''
#
#import Part, FreeCADGui, FreeCAD
#from PySide import QtGui,QtCore
#
#class zsDovetail:
# def __init__(self,obj):
# obj.addProperty("App::PropertyEnumeration","Type", "Dovetail").Type=["Pins","Tails"]
# obj.addProperty("App::PropertyEnumeration","AngleRatio", "Dovetail", "Usually 1:6 for softwood, 1:8 for hardwood.").AngleRatio=["1:6","1:8"]
# obj.addProperty("App::PropertyFloat", "Depth", "Dovetail").Depth = 10.0
# obj.addProperty("App::PropertyFloat", "PinWidth", "Dovetail").PinWidth = 10.0
# obj.addProperty("App::PropertyFloat", "PinHeight", "Dovetail").PinHeight = 10.0
# obj.addProperty("App::PropertyFloat", "Width", "Dovetail", "Distance between first and last pin").Width = 100.0
# obj.addProperty("App::PropertyInteger", "PinCount", "Dovetail").PinCount = 3
# obj.addProperty("App::PropertyBool", "ShowTool", "Dovetail", "Show the cutting tool to help positioning.\nSet to False afterwards.").ShowTool = True
# obj.addProperty("App::PropertyLinkSub","Face", "Dovetail", "Selected face for the joint")
# obj.addProperty("App::PropertyBool","EditFace", "Dovetail", "Trigger, toggle to bring up face editor").EditFace = False
#
# obj.addProperty("App::PropertyFloatConstraint", "AngleX", "Positioning", "Rotation angle (in degrees) about the local X axis").AngleX = (0,-360,360,1)
# obj.addProperty("App::PropertyFloatConstraint", "AngleY", "Positioning", "Rotation angle (in degrees) about the local Y axis").AngleY = (0,-360,360,1)
# obj.addProperty("App::PropertyFloatConstraint", "AngleZ", "Positioning", "Rotation angle (in degrees) about the local Z axis").AngleZ = (0,-360,360,1)
# obj.addProperty("App::PropertyVector", "Position", "Positioning", "XYZ position adjustments (internal coordinate system)")
#
# # defaults
# obj.Type = "Pins"
# obj.AngleRatio = "1:6"
#
# obj.Proxy = self
# self.fpName = obj.Name
# self.editingMode = False
#
# def onChanged(self,fp,prop):
# t = QtCore.QTimer()
#
# if prop == "EditFace" and fp.EditFace == True:
# t.singleShot(50, self.editFace) #avoid warning message about selection changing while committing data
# fp.EditFace = False
# else:
# t.singleShot(50, FreeCAD.ActiveDocument.recompute) #avoid error message about recursive recompute
#
# def editFace(self):
# fp = FreeCAD.ActiveDocument.getObject(self.fpName)
# if not fp.Face:
# return
# object = fp.Face[0]
# if not object:
# return
# if not FreeCADGui.Control.activeDialog():
# panel = TaskEditLinkSubPanel(fp,"Face","Face")
# FreeCADGui.Control.showDialog(panel)
# self.editingMode = True #tells execute() not to hide the linked object
# else:
# self.editingMode=False
# FreeCAD.Console.PrintError("Another task dialog is active. Close that one and try again.\n")
#
# def execute(self, fp):
# fp.Label2 = "(" + fp.Type + ")"
#
# if not fp.Face:
# return
#
# object = fp.Face[0]
# if not object:
# return
#
# face = object.getSubObject(fp.Face[1][0])
#
# shape = self.createShape(fp)
#
# tailRotX = 90 if fp.Type == "Tails" else 0 # Tails are rotated 90 degrees
#
# shape.rotate(FreeCAD.Vector(0,0,0), FreeCAD.Vector(1,0,0), fp.AngleX + tailRotX)
# shape = shape.transformShape(shape.Placement.toMatrix(),True)
# shape.rotate(FreeCAD.Vector(0,0,0), FreeCAD.Vector(0,1,0), fp.AngleY)
# shape = shape.transformShape(shape.Placement.toMatrix(),True)
# shape.rotate(FreeCAD.Vector(0,0,0), FreeCAD.Vector(0,0,1), fp.AngleZ)
# shape = shape.transformShape(shape.Placement.toMatrix(),True)
#
# shape.Placement = FreeCAD.Placement()
# shape.Placement.move(fp.Position)
# shape = shape.transformShape(shape.Placement.toMatrix(),True)
# shape.Placement = FreeCAD.Placement()
#
# x,y,z = face.Surface.Axis
# origin = FreeCAD.Vector(face.BoundBox.XMin, face.BoundBox.YMin, face.BoundBox.ZMin)
# shape.Placement = fp.Placement.multiply(FreeCAD.Placement(origin, FreeCAD.Rotation(FreeCAD.Vector(0,0,1), FreeCAD.Vector(x,y,z))))
#
# if hasattr(fp,"AddSubShape"):
# fp.AddSubShape = shape
# if hasattr(fp,"BaseFeature") and fp.BaseFeature:
# full_shape = fp.BaseFeature.Shape.fuse(shape) if fp.ShowTool else fp.BaseFeature.Shape.cut(shape)
# full_shape.transformShape(fp.Placement.inverse().toMatrix(),True)
# # fp.Shape = full_shape.removeSplitter() if fp.Refine else full_shape
# fp.Shape = full_shape
# else:
# fp.Shape = shape
#
# if not self.editingMode:
# object.ViewObject.Visibility = False if shape else True
#
# def createShape(self, fp):
# x = 0
# xdiff = (fp.Width-fp.PinWidth) / (fp.PinCount - 1) if fp.PinCount > 1 else 0
#
# # make the pins
# pins = []
# for n in range(0, fp.PinCount):
# pins.append(self.makePin(fp,x))
# x += xdiff
#
# shape = pins[0].fuse(pins[1:]) if len(pins) > 1 else pins[0]
#
# if fp.Type == "Pins":
# # create the cutout section
# box = Part.makeBox(fp.Width, fp.PinHeight, fp.Depth)
#
# shape = box.cut(shape)
#
# return shape
#
# def makePin(self, fp, x):
# xd = fp.PinHeight / 6 if fp.AngleRatio == "1:6" else fp.PinHeight / 8
#
# # We create 4 points for the 4 corners:
# if fp.Type == "Pins":
# v1 = FreeCAD.Vector(x, 0, 0)
# v2 = FreeCAD.Vector(x+fp.PinWidth, 0, 0)
# v3 = FreeCAD.Vector(x+fp.PinWidth-xd, fp.PinHeight, 0)
# v4 = FreeCAD.Vector(x+xd, fp.PinHeight, 0)
# else: # Tails
# v1 = FreeCAD.Vector(x+xd, 0, 0)
# v2 = FreeCAD.Vector(x+fp.PinWidth-xd, 0, 0)
# v3 = FreeCAD.Vector(x+fp.PinWidth, fp.PinHeight, 0)
# v4 = FreeCAD.Vector(x, fp.PinHeight, 0)
#
# # We create 4 edges:
# e1 = Part.LineSegment(v1, v2).toShape()
# e2 = Part.LineSegment(v2, v3).toShape()
# e3 = Part.LineSegment(v3, v4).toShape()
# e4 = Part.LineSegment(v4, v1).toShape()
#
# # We create a wire:
# wire = Part.Wire([e1, e2, e3, e4])
#
# # We create a face:
# f = Part.Face(wire)
#
# shape = f.extrude(FreeCAD.Vector(0,0,fp.Depth))
#
# return shape
#
#class TaskEditLinkSubPanel: #simple editor for App::PropertyLinkSub
# def __init__(self, obj, linkSubName, subNames,):
# self.obj = obj
# self.subNames = subNames
# self.linkSubName = linkSubName #entire LinkSub property
# self.linkObj = getattr(self.obj,linkSubName)[0]
# self.subObjects = getattr(self.obj,linkSubName)[1]
# self.form = QtGui.QWidget()
# self.label1 = QtGui.QLabel("Select the "+self.subNames+" subobjects to use and click OK.\nThe ones already being utilized have been selected for you.")
# layout=QtGui.QHBoxLayout()
# layout.addWidget(self.label1)
# self.form.setLayout(layout)
# self.form.setWindowTitle('Edit '+self.subNames)
# self.obj.ViewObject.Visibility = False
# self.linkObj.ViewObject.Visibility = True
# FreeCADGui.Selection.clearSelection()
# for f in self.subObjects:
# FreeCADGui.Selection.addSelection(FreeCAD.ActiveDocument.Name,self.linkObj.Name,f)
# self.obj.Proxy.editingMode = True
#
# def reject(self):
# FreeCADGui.Control.closeDialog()
# fp = self.obj
# self.linkObj.ViewObject.Visibility = False
# fp.ViewObject.Visibility = True
# self.obj.Proxy.editingMode = False #self.obj.Proxy is the Joint class object (self in that class)
# FreeCADGui.activeDocument().resetEdit()
# FreeCAD.ActiveDocument.recompute()
#
# def accept(self):
# FreeCADGui.ActiveDocument.resetEdit()
# FreeCADGui.Control.closeDialog()
# fp = self.obj
# if not fp: #user deleted or closed document perhaps
# return
# selx = FreeCADGui.Selection.getSelectionEx()
# if not selx:
# FreeCAD.Console.PrintWarning("Nothing selected, leaving "+self.linkObj.Name+" unmodified.")
# return
# seNames = [sen for sen in selx[0].SubElementNames]
# setattr(self.obj,self.linkSubName,(selx[0].Object,seNames)) #allow user to select diffent object
# self.linkObj = selx[0].Object
# if hasattr(fp,"_Body") and fp._Body and self.linkObj not in fp._Body.Group:
# fp._Body.Group += [self.linkObj]
# if not self.linkObj.isDerivedFrom("PartDesign::Feature"):
# fp.ClaimChildren = True
# self.linkObj.ViewObject.Visibility = False
# fp.ViewObject.Visibility = True
# if hasattr(fp.Proxy,"editingMode"):
# fp.Proxy.editingMode = False
# FreeCAD.ActiveDocument.recompute()
#
#
#class zsDovetailVP:
# def __init__(self, obj):
# '''Set this object to the proxy object of the actual view provider'''
# obj.Proxy = self
#
# def attach(self, obj):
# '''Setup the scene sub-graph of the view provider, this method is mandatory'''
# self.Object = obj.Object
#
# def updateData(self, fp, prop):
# '''If a property of the handled feature has changed we have the chance to handle this here'''
# # fp is the handled feature, prop is the name of the property that has changed
# pass
#
# def getDisplayModes(self,obj):
# '''Return a list of display modes.'''
# modes=[]
# modes.append("Flat Lines")
# return modes
#
# def getDefaultDisplayMode(self):
# '''Return the name of the default display mode. It must be defined in getDisplayModes.'''
# return "Flat Lines"
#
# def setDisplayMode(self,mode):
# '''Map the display mode defined in attach with those defined in getDisplayModes.\
# Since they have the same names nothing needs to be done. This method is optional'''
# return mode
#
# def onChanged(self, vp, prop):
# '''Here we can do something when a single property got changed'''
# #FreeCAD.Console.PrintMessage("Change property: " + str(prop) + ""+chr(10))
# pass
#
# def claimChildren(self):
# return []
#
# def setupContextMenu(self, vobj, menu):
# pass
#
# def setEdit(self,vp,modNum):
# pass
#
# def onDelete(self, vobj, subelements):
# if vobj.Object.Face:
# vobj.Object.Face[0].ViewObject.Visibility = True
# if hasattr(vobj.Object,"_Body"): #do this only when the object is in a PD body
# #need to ensure the next feature in the tree's BaseFeature property points to our BaseFeature
# solids = [feat for feat in vobj.Object._Body.Group if feat.isDerivedFrom("PartDesign::Feature") and feat.BaseFeature == vobj.Object]
# if len(solids) == 1: #found previous solid feature
# solids[0].BaseFeature = vobj.Object.BaseFeature
# return True
#
# def __getstate__(self):
# '''When saving the document this object gets stored using Python's json module.\
# Since we have some un-serializable parts here -- the Coin stuff -- we must define this method\
# to return a tuple of all serializable objects or None.'''
# return None
#
# def __setstate__(self,state):
# '''When restoring the serialized object from document we have the chance to set some internals here.\
# Since no data were serialized nothing needs to be done here.'''
# return None
#
#
#if __name__ == "__main__":
# FreeCAD.Console.PrintError("Please run zsDovetail.FCMacro rather than this file.\n")
#
#CODE_ENDS_HERE
BASENAME = 'zsDovetail'
def getBody(feature):
doc = FreeCAD.ActiveDocument
bodies = [obj for obj in doc.Objects if obj.TypeId == "PartDesign::Body"]
for bod in bodies:
if feature in bod.Group:
return bod
return None
def makeObject(FP):
import DraftGeomUtils as DGU
doc = FreeCAD.ActiveDocument
body=None
selobjs = FreeCADGui.Selection.getSelectionEx()
if doc:
doc.openTransaction("Create zsDovetail")
if selobjs:
for selobj in selobjs:
body = getBody(selobj.Object)
if body:
joint = body.newObject("PartDesign::FeatureSubtractivePython", "Dovetail")
else:
joint = doc.addObject("Part::FeaturePython","Dovetail")
FP.zsDovetail(joint)
FP.zsDovetailVP(joint.ViewObject)
joint.Proxy.execute(joint)
FreeCADGui.Selection.clearSelection()
FreeCADGui.Selection.addSelection(joint)
if selobj.HasSubObjects:
faces = [name for name in selobj.SubElementNames if "Face" in name]
if faces and len(faces) == 1 and DGU.isPlanar(selobj.Object.getSubObject(faces[0])):
joint.Face = (selobj.Object,faces)
else:
FreeCAD.Console.PrintError("Select 1 (planar) face of an object. Using Face1\n")
joint.Face = (selobj.Object, ["Face1"])
else:
joint.Face = (selobj.Object, ["Face1"])
FreeCAD.Console.PrintError("Select 1 (planar) face of an object.\n")
else:
FreeCAD.Console.PrintError("No face selected to make a joint on.\n")
doc.commitTransaction()
doc.recompute()
def writeFile():
with open(py_file,"w") as outfile:
for line in code.splitlines():
if "#CODE_ENDS_HERE" in line:
break
if line.startswith('#'):
if line == "# -*- coding: utf-8 -*-":
line = "#" + line
outfile.write(line[1:]+"\n") #skip first character (#)
if __name__ == "__main__":
import os
fin = open(__file__, 'r')
code = fin.read()
fin.close()
version = code.splitlines()[1][16:]
real_path = os.path.realpath(__file__)
dir_path = os.path.dirname(real_path)
py_file = real_path.replace(".FCMacro",".py")
bHasFile = os.path.exists(py_file)
noImport = False #user elects not to save import file
if not bHasFile:
from PySide import QtCore,QtGui
window = QtGui.QApplication.activeWindow()
items = ["Yes, go ahead and create the file.", "No, do not create the file.","Cancel"]
caption = "In order for "+BASENAME+" objects to be parametric after saving and reloading file\n\
we need to create another file on this computer. File to be created will be: \n\n"+py_file+"\n\n\
This makes it available to the system upon restarting FreeCAD and loading documents containing the \n\
"+BASENAME+" feature python objects. May we proceed?\n\n"
item,ok = QtGui.QInputDialog.getItem(window,"One time installation",caption,items)
if ok and item == items[0]:
writeFile()
QtGui.QMessageBox.information(window,"Success","File successfully created. Please note: if you uninstall "+BASENAME+" macro you need to manually remove this file, too.\n")
else:
new_lines = []
for line in code.splitlines():
if line.startswith('#'):
if "CODE_ENDS_HERE" in line:
break
if line == "# -*- coding: utf-8 -*-":
new_lines.append(line+"\n")
continue
new_lines.append(line[1:]+"\n")
code = "".join(new_lines)
#credit to Mila Nautikus for his answer to a question on stackoverflow, which I modified here
#in this example the filename is bevel.py
#https://stackoverflow.com/questions/5362771/how-to-load-a-module-from-code-in-a-string
##########
import sys, importlib
my_spec = importlib.util.spec_from_loader(BASENAME, loader=None)
zsDovetail = importlib.util.module_from_spec(my_spec)
exec(code, zsDovetail.__dict__)
sys.modules[BASENAME] = zsDovetail
makeObject(zsDovetail)
noImport = True
if not noImport: #don't never use no double negatives
import zsDovetail as FP
makeObject(FP)