/
gui_selectplane.py
545 lines (495 loc) · 23 KB
/
gui_selectplane.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
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
# ***************************************************************************
# * Copyright (c) 2019 Yorik van Havre <yorik@uncreated.net> *
# * *
# * This program is free software; you can redistribute it and/or modify *
# * it under the terms of the GNU Lesser General Public License (LGPL) *
# * as published by the Free Software Foundation; either version 2 of *
# * the License, or (at your option) any later version. *
# * for detail see the LICENCE text file. *
# * *
# * This program is distributed in the hope that it will be useful, *
# * but WITHOUT ANY WARRANTY; without even the implied warranty of *
# * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
# * GNU Library General Public License for more details. *
# * *
# * You should have received a copy of the GNU Library General Public *
# * License along with this program; if not, write to the Free Software *
# * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
# * USA *
# * *
# ***************************************************************************
"""Provides GUI tools to set up the working plane and its grid."""
## @package gui_selectplane
# \ingroup draftguitools
# \brief Provides GUI tools to set up the working plane and its grid.
## \addtogroup draftguitools
# @{
import math
import pivy.coin as coin
import PySide.QtGui as QtGui
from PySide.QtCore import QT_TRANSLATE_NOOP
import FreeCAD
import FreeCADGui
import Draft
import Draft_rc
import DraftVecUtils
import drafttaskpanels.task_selectplane as task_selectplane
from draftutils.todo import todo
from draftutils.messages import _msg
from draftutils.translate import translate
# The module is used to prevent complaints from code checkers (flake8)
True if Draft_rc.__name__ else False
__title__ = "FreeCAD Draft Workbench GUI Tools - Working plane-related tools"
__author__ = ("Yorik van Havre, Werner Mayer, Martin Burbaum, Ken Cline, "
"Dmitry Chigrin")
__url__ = "https://www.freecadweb.org"
class Draft_SelectPlane:
"""The Draft_SelectPlane FreeCAD command definition."""
def __init__(self):
self.ac = "FreeCAD.DraftWorkingPlane.alignToPointAndAxis"
self.param = FreeCAD.ParamGet("User parameter:BaseApp/Preferences/Mod/Draft")
self.states = []
def GetResources(self):
"""Set icon, menu and tooltip."""
_msg = ("Select the face of solid body to create a working plane "
"on which to sketch Draft objects.\n"
"You may also select a three vertices or "
"a Working Plane Proxy.")
d = {'Pixmap': 'Draft_SelectPlane',
'Accel': "W, P",
'MenuText': QT_TRANSLATE_NOOP("Draft_SelectPlane", "SelectPlane"),
'ToolTip': QT_TRANSLATE_NOOP("Draft_SelectPlane", _msg)}
return d
def IsActive(self):
"""Return True when this command should be available."""
if FreeCADGui.ActiveDocument:
return True
else:
return False
def Activated(self):
"""Execute when the command is called."""
# Reset variables
self.view = Draft.get3DView()
self.wpButton = FreeCADGui.draftToolBar.wplabel
FreeCAD.DraftWorkingPlane.setup()
# Write current WP if states are empty
if not self.states:
p = FreeCAD.DraftWorkingPlane
self.states.append([p.u, p.v, p.axis, p.position])
m = translate("draft", "Pick a face, 3 vertices "
"or a WP Proxy to define the drawing plane")
_msg(m)
# Create task panel
FreeCADGui.Control.closeDialog()
self.taskd = task_selectplane.SelectPlaneTaskPanel()
# Fill values
self.taskd.form.checkCenter.setChecked(self.param.GetBool("CenterPlaneOnView", False))
q = FreeCAD.Units.Quantity(self.param.GetFloat("gridSpacing", 1.0), FreeCAD.Units.Length)
self.taskd.form.fieldGridSpacing.setText(q.UserString)
self.taskd.form.fieldGridMainLine.setValue(self.param.GetInt("gridEvery", 10))
self.taskd.form.fieldGridExtension.setValue(self.param.GetInt("gridSize", 100))
self.taskd.form.fieldSnapRadius.setValue(self.param.GetInt("snapRange", 8))
# Set icons
self.taskd.form.setWindowIcon(QtGui.QIcon(":/icons/Draft_SelectPlane.svg"))
self.taskd.form.buttonTop.setIcon(QtGui.QIcon(":/icons/view-top.svg"))
self.taskd.form.buttonFront.setIcon(QtGui.QIcon(":/icons/view-front.svg"))
self.taskd.form.buttonSide.setIcon(QtGui.QIcon(":/icons/view-right.svg"))
self.taskd.form.buttonAlign.setIcon(QtGui.QIcon(":/icons/view-isometric.svg"))
self.taskd.form.buttonAuto.setIcon(QtGui.QIcon(":/icons/view-axonometric.svg"))
self.taskd.form.buttonMove.setIcon(QtGui.QIcon(":/icons/Draft_Move.svg"))
self.taskd.form.buttonCenter.setIcon(QtGui.QIcon(":/icons/view-fullscreen.svg"))
self.taskd.form.buttonPrevious.setIcon(QtGui.QIcon(":/icons/edit-undo.svg"))
# Connect slots
self.taskd.form.buttonTop.clicked.connect(self.onClickTop)
self.taskd.form.buttonFront.clicked.connect(self.onClickFront)
self.taskd.form.buttonSide.clicked.connect(self.onClickSide)
self.taskd.form.buttonAlign.clicked.connect(self.onClickAlign)
self.taskd.form.buttonAuto.clicked.connect(self.onClickAuto)
self.taskd.form.buttonMove.clicked.connect(self.onClickMove)
self.taskd.form.buttonCenter.clicked.connect(self.onClickCenter)
self.taskd.form.buttonPrevious.clicked.connect(self.onClickPrevious)
self.taskd.form.fieldGridSpacing.textEdited.connect(self.onSetGridSize)
self.taskd.form.fieldGridMainLine.valueChanged.connect(self.onSetMainline)
self.taskd.form.fieldGridExtension.valueChanged.connect(self.onSetExtension)
self.taskd.form.fieldSnapRadius.valueChanged.connect(self.onSetSnapRadius)
# Try to find a WP from the current selection
if self.handle():
return
# Try another method
if FreeCAD.DraftWorkingPlane.alignToSelection():
FreeCADGui.Selection.clearSelection()
self.display(FreeCAD.DraftWorkingPlane.axis)
self.finish()
return
# Execute the actual task panel
FreeCADGui.Control.showDialog(self.taskd)
self.call = self.view.addEventCallback("SoEvent", self.action)
def finish(self, close=False):
"""Execute when the command is terminated."""
# Store values
self.param.SetBool("CenterPlaneOnView",
self.taskd.form.checkCenter.isChecked())
# Terminate coin callbacks
if self.call:
try:
self.view.removeEventCallback("SoEvent", self.call)
except RuntimeError:
# The view has been deleted already
pass
self.call = None
# Reset everything else
FreeCADGui.Control.closeDialog()
FreeCAD.DraftWorkingPlane.restore()
FreeCADGui.ActiveDocument.resetEdit()
return True
def reject(self):
"""Execute when clicking the Cancel button."""
self.finish()
return True
def action(self, arg):
"""Set the callbacks for the view."""
if arg["Type"] == "SoKeyboardEvent" and arg["Key"] == "ESCAPE":
self.finish()
if arg["Type"] == "SoMouseButtonEvent":
if (arg["State"] == "DOWN") and (arg["Button"] == "BUTTON1"):
# Coin detection happens before the selection
# got a chance of being updated, so we must delay
todo.delay(self.checkSelection, None)
def checkSelection(self):
"""Check the selection, if there is a handle, finish the command."""
if self.handle():
self.finish()
def handle(self):
"""Build a working plane. Return True if successful."""
sel = FreeCADGui.Selection.getSelectionEx()
if len(sel) == 1:
sel = sel[0]
if hasattr(sel.Object, 'TypeId') and sel.Object.TypeId == 'App::Part':
self.setPlaneFromObjPlacement(sel.Object)
return True
elif Draft.getType(sel.Object) == "Axis":
FreeCAD.DraftWorkingPlane.alignToEdges(sel.Object.Shape.Edges)
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
elif Draft.getType(sel.Object) in ("WorkingPlaneProxy", "BuildingPart"):
self.setPlaneOnWPProxy(sel.Object)
return True
elif Draft.getType(sel.Object) == "SectionPlane":
self.setPlaneFromObjPlacement(sel.Object)
return True
elif sel.HasSubObjects:
if len(sel.SubElementNames) == 1:
# look for a face or a plane
if "Face" in sel.SubElementNames[0]:
FreeCAD.DraftWorkingPlane.alignToFace(sel.SubObjects[0], self.getOffset())
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
elif sel.SubElementNames[0] == "Plane":
FreeCAD.DraftWorkingPlane.setFromPlacement(sel.Object.Placement, rebase=True)
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
elif len(sel.SubElementNames) == 3:
# look for 3 points
if ("Vertex" in sel.SubElementNames[0]) \
and ("Vertex" in sel.SubElementNames[1]) \
and ("Vertex" in sel.SubElementNames[2]):
FreeCAD.DraftWorkingPlane.alignTo3Points(sel.SubObjects[0].Point,
sel.SubObjects[1].Point,
sel.SubObjects[2].Point,
self.getOffset())
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
elif sel.Object.isDerivedFrom("Part::Feature"):
if sel.Object.Shape:
if len(sel.Object.Shape.Faces) == 1:
FreeCAD.DraftWorkingPlane.alignToFace(sel.Object.Shape.Faces[0], self.getOffset())
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
elif hasattr(sel.Object, 'Placement'):
self.setPlaneFromObjPlacement(sel.Object)
return True
elif sel:
# look for 3 points
subs = []
import Part
for s in sel:
for so in s.SubObjects:
if isinstance(so, Part.Vertex):
subs.append(so)
if len(subs) == 3:
FreeCAD.DraftWorkingPlane.alignTo3Points(subs[0].Point,
subs[1].Point,
subs[2].Point,
self.getOffset())
self.display(FreeCAD.DraftWorkingPlane.axis)
return True
return False
def setPlaneFromObjPlacement(self, obj):
"""Called by handle(): set the working plane according to an object placement."""
if hasattr(obj, 'getGlobalPlacement'):
pl = obj.getGlobalPlacement()
else:
pl = obj.Placement
FreeCAD.DraftWorkingPlane.setFromPlacement(pl, rebase=True)
FreeCAD.DraftWorkingPlane.weak = False
self.display(FreeCAD.DraftWorkingPlane.axis)
self.wpButton.setText(obj.Label)
self.wpButton.setToolTip(translate("draft", "Current working plane")+": " + self.wpButton.text())
m = translate("draft", "Working plane aligned to global placement of")
_msg(m + " " + obj.Label + ".\n")
return True
def setPlaneOnWPProxy(self, obj):
"""Called by handle(): set the working plane according to a WorkingPlaneProxy or a BuildingPart.
This method also apply the clipping view according to object properties.
"""
FreeCAD.DraftWorkingPlane.setFromPlacement(obj.Placement, rebase=True)
FreeCAD.DraftWorkingPlane.weak = False
if hasattr(obj.ViewObject, "AutoWorkingPlane"):
if obj.ViewObject.AutoWorkingPlane:
FreeCAD.DraftWorkingPlane.weak = True
if hasattr(obj.ViewObject, "CutView") and hasattr(obj.ViewObject, "AutoCutView"):
if obj.ViewObject.AutoCutView:
obj.ViewObject.CutView = True
if hasattr(obj.ViewObject, "RestoreView"):
if obj.ViewObject.RestoreView:
if hasattr(obj.ViewObject, "ViewData"):
if len(obj.ViewObject.ViewData) >= 12:
d = obj.ViewObject.ViewData
camtype = "orthographic"
if len(obj.ViewObject.ViewData) == 13:
if d[12] == 1:
camtype = "perspective"
c = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
if isinstance(c, coin.SoOrthographicCamera):
if camtype == "perspective":
FreeCADGui.ActiveDocument.ActiveView.setCameraType("Perspective")
elif isinstance(c, coin.SoPerspectiveCamera):
if camtype == "orthographic":
FreeCADGui.ActiveDocument.ActiveView.setCameraType("Orthographic")
c = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
c.position.setValue([d[0], d[1], d[2]])
c.orientation.setValue([d[3], d[4], d[5], d[6]])
c.nearDistance.setValue(d[7])
c.farDistance.setValue(d[8])
c.aspectRatio.setValue(d[9])
c.focalDistance.setValue(d[10])
if camtype == "orthographic":
c.height.setValue(d[11])
else:
c.heightAngle.setValue(d[11])
if hasattr(obj.ViewObject, "RestoreState"):
if obj.ViewObject.RestoreState:
if hasattr(obj.ViewObject, "VisibilityMap"):
if obj.ViewObject.VisibilityMap:
for k,v in obj.ViewObject.VisibilityMap.items():
o = FreeCADGui.ActiveDocument.getObject(k)
if o:
if o.Visibility != (v == "True"):
FreeCADGui.doCommand("FreeCADGui.ActiveDocument.getObject(\""+k+"\").Visibility = "+v)
self.display(FreeCAD.DraftWorkingPlane.axis)
self.wpButton.setText(obj.Label)
self.wpButton.setToolTip(translate("draft", "Current working plane")+": "+self.wpButton.text())
def getCenterPoint(self, x, y, z):
"""Get the center point."""
if not self.taskd.form.checkCenter.isChecked():
return FreeCAD.Vector()
v = FreeCAD.Vector(x, y, z)
view = FreeCADGui.ActiveDocument.ActiveView
camera = view.getCameraNode()
cam1 = FreeCAD.Vector(camera.position.getValue().getValue())
cam2 = FreeCADGui.ActiveDocument.ActiveView.getViewDirection()
vcam1 = DraftVecUtils.project(cam1, v)
a = vcam1.getAngle(cam2)
if a < 0.0001:
return FreeCAD.Vector()
d = vcam1.Length
L = d/math.cos(a)
vcam2 = DraftVecUtils.scaleTo(cam2, L)
cp = cam1.add(vcam2)
return cp
def tostr(self, v):
"""Make a string from a vector or tuple."""
string = "FreeCAD.Vector("
string += str(v[0]) + ", "
string += str(v[1]) + ", "
string += str(v[2]) + ")"
return string
def getOffset(self):
"""Return the offset value as a float in mm."""
try:
o = float(self.taskd.form.fieldOffset.text())
except Exception:
o = FreeCAD.Units.Quantity(self.taskd.form.fieldOffset.text())
o = o.Value
return o
def onClickTop(self):
"""Execute when pressing the top button."""
_cmd = self.ac
_cmd += "("
_cmd += self.tostr(self.getCenterPoint(0, 0, 1)) + ", "
_cmd += self.tostr((0, 0, 1)) + ", "
_cmd += str(self.getOffset())
_cmd += ")"
FreeCADGui.doCommandGui(_cmd)
self.display('Top')
self.finish()
def onClickFront(self):
"""Execute when pressing the front button."""
_cmd = self.ac
_cmd += "("
_cmd += self.tostr(self.getCenterPoint(0, -1, 0)) + ", "
_cmd += self.tostr((0, -1, 0)) + ", "
_cmd += str(self.getOffset())
_cmd += ")"
FreeCADGui.doCommandGui(_cmd)
self.display('Front')
self.finish()
def onClickSide(self):
"""Execute when pressing the side button."""
_cmd = self.ac
_cmd += "("
_cmd += self.tostr(self.getCenterPoint(1, 0, 0)) + ", "
_cmd += self.tostr((1, 0, 0)) + ", "
_cmd += str(self.getOffset())
_cmd += ")"
FreeCADGui.doCommandGui(_cmd)
self.display('Side')
self.finish()
def onClickAlign(self):
"""Execute when pressing the align."""
dir = self.view.getViewDirection().negative()
camera = self.view.getCameraNode()
rot = camera.getField("orientation").getValue()
coin_up = coin.SbVec3f(0, 1, 0)
upvec = FreeCAD.Vector(rot.multVec(coin_up).getValue())
_cmd = self.ac
_cmd += "("
_cmd += self.tostr(self.getCenterPoint(dir.x, dir.y, dir.z)) + ", "
_cmd += self.tostr((dir.x, dir.y, dir.z)) + ", "
_cmd += str(self.getOffset()) + ", "
_cmd += self.tostr(upvec)
_cmd += ")"
FreeCADGui.doCommandGui(_cmd)
self.display(dir)
self.finish()
def onClickAuto(self):
"""Execute when pressing the auto button."""
FreeCADGui.doCommandGui("FreeCAD.DraftWorkingPlane.reset()")
self.display('Auto')
self.finish()
def onClickMove(self):
"""Execute when pressing the move button."""
sel = FreeCADGui.Selection.getSelectionEx()
if sel:
verts = []
import Part
for s in sel:
for so in s.SubObjects:
if isinstance(so, Part.Vertex):
verts.append(so)
if len(verts) == 1:
target = verts[0].Point
FreeCAD.DraftWorkingPlane.position = target
self.display(target)
self.finish()
else:
# move the WP to the center of the current view
c = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
p = FreeCAD.Vector(c.position.getValue().getValue())
d = FreeCADGui.ActiveDocument.ActiveView.getViewDirection()
pp = FreeCAD.DraftWorkingPlane.projectPoint(p, d)
FreeCAD.DraftWorkingPlane.position = pp
self.display(pp)
self.finish()
def onClickCenter(self):
"""Execute when pressing the center button."""
c = FreeCADGui.ActiveDocument.ActiveView.getCameraNode()
r = FreeCAD.DraftWorkingPlane.getRotation().Rotation.Q
c.orientation.setValue(r)
# calculate delta
p = FreeCAD.Vector(c.position.getValue().getValue())
pp = FreeCAD.DraftWorkingPlane.projectPoint(p)
delta = pp.negative() # to bring it above the (0,0) point
np = p.add(delta)
c.position.setValue(tuple(np))
self.finish()
def onClickPrevious(self):
"""Execute when pressing the previous button."""
p = FreeCAD.DraftWorkingPlane
if len(self.states) > 1:
self.states.pop() # discard the last one
s = self.states[-1]
p.u = s[0]
p.v = s[1]
p.axis = s[2]
p.position = s[3]
FreeCADGui.Snapper.setGrid()
self.finish()
def onSetGridSize(self, text):
"""Execute when setting the grid size."""
try:
q = FreeCAD.Units.Quantity(text)
except Exception:
pass
else:
self.param.SetFloat("gridSpacing", q.Value)
if hasattr(FreeCADGui, "Snapper"):
FreeCADGui.Snapper.setGrid()
def onSetMainline(self, i):
"""Execute when setting main line grid spacing."""
if i > 1:
self.param.SetInt("gridEvery", i)
if hasattr(FreeCADGui, "Snapper"):
FreeCADGui.Snapper.setGrid()
def onSetExtension(self, i):
"""Execute when setting grid extension."""
if i > 1:
self.param.SetInt("gridSize", i)
if hasattr(FreeCADGui, "Snapper"):
FreeCADGui.Snapper.setGrid()
def onSetSnapRadius(self, i):
"""Execute when setting the snap radius."""
self.param.SetInt("snapRange", i)
if hasattr(FreeCADGui, "Snapper"):
FreeCADGui.Snapper.showradius()
def display(self, arg):
"""Set the text of the working plane button in the toolbar."""
o = self.getOffset()
if o:
if o > 0:
suffix = ' +O'
else:
suffix = ' -O'
else:
suffix = ''
_vdir = FreeCAD.DraftWorkingPlane.axis
vdir = '('
vdir += str(_vdir.x)[:4] + ','
vdir += str(_vdir.y)[:4] + ','
vdir += str(_vdir.z)[:4]
vdir += ')'
vdir = " " + translate("draft", "Dir") + ": " + vdir
if type(arg).__name__ == 'str':
self.wpButton.setText(arg + suffix)
if o != 0:
o = " " + translate("draft", "Offset") + ": " + str(o)
else:
o = ""
_tool = translate("draft", "Current working plane") + ": "
_tool += self.wpButton.text() + o + vdir
self.wpButton.setToolTip(_tool)
elif type(arg).__name__ == 'Vector':
plv = '('
plv += str(arg.x)[:6] + ','
plv += str(arg.y)[:6] + ','
plv += str(arg.z)[:6]
plv += ')'
self.wpButton.setText(translate("draft", "Custom"))
_tool = translate("draft", "Current working plane")
_tool += ": " + plv + vdir
self.wpButton.setToolTip(_tool)
p = FreeCAD.DraftWorkingPlane
self.states.append([p.u, p.v, p.axis, p.position])
FreeCADGui.doCommandGui("FreeCADGui.Snapper.setGrid()")
FreeCADGui.addCommand('Draft_SelectPlane', Draft_SelectPlane())
## @}