forked from Zolko-123/FreeCAD_Assembly4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAnimationLib.py
399 lines (325 loc) · 13.7 KB
/
AnimationLib.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
#!/usr/bin/env python3
# coding: utf-8
#
# LGPL
# Copyright HUBERT Zoltán
#
# AnimationLib.py
import os, time
from PySide import QtGui, QtCore
from enum import Enum
import FreeCADGui as Gui
import FreeCAD as App
import libAsm4 as Asm4
"""
+-----------------------------------------------+
| main class |
+-----------------------------------------------+
"""
class animateVariable():
"""
+-----------------------------------------------+
| State and Transition Enums |
+-----------------------------------------------+
"""
class AnimationState(Enum):
STOPPED = 0
RUNNING = 1
class AnimationRequest(Enum):
NONE = 0
START = 1
STOP = 2
"""
+-----------------------------------------------+
| Initialization and Registration |
+-----------------------------------------------+
"""
def __init__(self):
super(animateVariable,self).__init__()
self.UI = QtGui.QDialog()
self.drawUI()
def GetResources(self):
return {"MenuText": "Animate Assembly",
"ToolTip": "Animate Assembly",
"Pixmap" : os.path.join( Asm4.iconPath , 'Asm4_GearsAnimate.svg')
}
def IsActive(self):
# is there an active document ?
if Asm4.checkModel() and App.ActiveDocument.getObject('Variables'):
return True
return False
"""
+-----------------------------------------------+
| the real stuff |
+-----------------------------------------------+
"""
def Activated(self):
# grab the Variables container
self.Variables = App.ActiveDocument.getObject('Variables')
self.Model = App.ActiveDocument.getObject('Model')
# Initialize States and timing logic.
self.RunState = self.AnimationState.STOPPED
self.reverseAnimation = False # True flags when the animation is "in reverse" for the pendulum mode.
self.ForceGUIUpdate = False # True Forces GUI to update on every step of the animation.
self.timer = QtCore.QTimer()
self.timer.timeout.connect(self.onTimerTick)
# Now we can draw the UI
self.UI.show()
# select the Float variables that are in the "Variables" group
self.varList.clear()
for prop in self.Variables.PropertiesList:
if self.Variables.getGroupOfProperty(prop)=='Variables' :
if self.Variables.getTypeIdOfProperty(prop)=='App::PropertyFloat' :
self.varList.addItem(prop)
"""
+------------------------------------------------+
| fill default values when selecting a variable |
+------------------------------------------------+
"""
def onSelectVar(self):
# the currently selected variable
selectedVar = self.varList.currentText()
# if it's indeed a property in the Variables object (one never knows)
if selectedVar in self.Variables.PropertiesList:
# get its value
selectedVarValue = self.Variables.getPropertyByName(selectedVar)
# initialise the Begin and End values with it
self.beginValue.setValue(selectedVarValue)
self.endValue.setValue(selectedVarValue)
return
"""
+-----------------------------------------------+
| Animation Tick Functions |
+-----------------------------------------------+
"""
def initAnimation(self):
# Set GUI-state, initial value and start the timer
self.RunButton.setEnabled(False)
self.StopButton.setEnabled(True)
self.setVarValue(self.varList.currentText(), self.beginValue.value())
sleep = self.sleepValue.value() * 1000.0
self.timer.start(sleep)
self.reverseAnimation = False
def nextStep(self, reverse):
# Calculate the next variable increment/decrement
begin = self.beginValue.value()
end = self.endValue.value()
step = abs(self.stepValue.value())
varName = self.varList.currentText()
varValue = self.Variables.getPropertyByName(varName)
if reverse:
begin, end = end, begin
if begin < end:
varValue += step
elif begin > end:
varValue -= step
# Assert varValue is in currently set range (range can now update with the animation running)
varValue = min(varValue, max(begin, end))
varValue = max(varValue, min(begin, end))
# Update document variable and slider
self.setVarValue(varName, varValue)
self.slider.setValue(varValue)
# Flag when the end of one sweep is reached
return (varValue == begin) or (varValue == end)
def update(self, req):
# STOPPED STATE; NO ANIMATION RUNNING
if self.RunState == self.AnimationState.STOPPED:
if req == self.AnimationRequest.START:
self.RunState = self.AnimationState.RUNNING
self.initAnimation()
# RUNNING STATE
elif self.RunState == self.AnimationState.RUNNING:
endOfCycle = self.nextStep(self.reverseAnimation)
stop = (req == self.AnimationRequest.STOP)
stop |= endOfCycle and not (self.Pendulum.isChecked() or self.Loop.isChecked())
sleep = self.sleepValue.value() * 1000.0
self.timer.setInterval(sleep)
if stop:
self.RunButton.setEnabled(True)
self.StopButton.setEnabled(False)
self.timer.stop()
self.RunState = self.AnimationState.STOPPED
elif endOfCycle:
if self.Loop.isChecked():
self.initAnimation()
elif self.Pendulum.isChecked():
self.reverseAnimation = not self.reverseAnimation
# SANITY CHECK
else:
print("Unknown State/Transition")
def onTimerTick(self):
self.update(self.AnimationRequest.NONE)
def setVarValue(self,name,value):
setattr( self.Variables, name, value )
App.ActiveDocument.Model.recompute('True')
self.variableValue.setText('{:.2f}'.format(value))
if self.ForceGUIUpdate:
Gui.updateGui()
"""
+-----------------------------------------------+
| Loop or Pendulum Selector |
+-----------------------------------------------+
"""
def onLoop(self):
if self.Pendulum.isChecked() and self.Loop.isChecked():
self.Pendulum.setChecked(False)
return
def onPendulum(self):
if self.Loop.isChecked() and self.Pendulum.isChecked():
self.Loop.setChecked(False)
return
def onForceRender(self):
self.ForceGUIUpdate = self.ForceRender.isChecked()
"""
+-----------------------------------------------+
| Slider |
+-----------------------------------------------+
"""
def sliderMoved(self):
# Stop the animation when the user grabs the slider
self.update(self.AnimationRequest.STOP)
varName = self.varList.currentText()
varValue = self.slider.value()
self.setVarValue(varName, varValue)
return
def onValuesChanged(self):
minVal = min(self.beginValue.value(), self.endValue.value())
maxVal = max(self.beginValue.value(), self.endValue.value())
self.sliderLeftValue.setText(str(minVal))
self.sliderRightValue.setText(str(maxVal))
self.slider.setRange(minVal, maxVal)
self.slider.setSingleStep(self.stepValue.value())
return
"""
+-----------------------------------------------+
| Star/Stop/Close |
+-----------------------------------------------+
"""
def onRun(self):
self.update(self.AnimationRequest.START)
def onStop(self):
self.update(self.AnimationRequest.STOP)
return
def onClose(self):
self.update(self.AnimationRequest.STOP)
self.UI.close()
"""
+-----------------------------------------------+
| defines the UI, only static elements |
+-----------------------------------------------+
"""
def drawUI(self):
# Our main window will be a QDialog
# make this dialog stay above the others, always visible
self.UI.setWindowFlags( QtCore.Qt.WindowStaysOnTopHint )
self.UI.setWindowTitle('Animate Assembly')
self.UI.setWindowIcon( QtGui.QIcon( os.path.join( Asm4.iconPath , 'FreeCad.svg' ) ) )
self.UI.setMinimumWidth(470)
self.UI.setModal(False)
# set main window widgets
self.mainLayout = QtGui.QVBoxLayout(self.UI)
# Define the fields for the form ( label + widget )
self.formLayout = QtGui.QFormLayout()
# select Variable
self.varList = QtGui.QComboBox()
self.formLayout.addRow(QtGui.QLabel('Select Variable'),self.varList)
# Range Minimum
self.beginValue = QtGui.QDoubleSpinBox()
self.beginValue.setRange(-1000000.0, 1000000.0)
self.formLayout.addRow(QtGui.QLabel('Range Begin'), self.beginValue)
# Maximum
self.endValue = QtGui.QDoubleSpinBox()
self.endValue.setRange(-1000000.0, 1000000.0)
self.formLayout.addRow(QtGui.QLabel('Range End'), self.endValue)
# Step
self.stepValue = QtGui.QDoubleSpinBox()
self.stepValue.setRange( -10000.0, 10000.0 )
self.stepValue.setValue( 1.0 )
self.formLayout.addRow(QtGui.QLabel('Step Size'),self.stepValue)
# Sleep
self.sleepValue = QtGui.QDoubleSpinBox()
self.sleepValue.setRange( 0.0, 10.0 )
self.sleepValue.setValue( 0.0 )
self.sleepValue.setSingleStep(0.01)
self.formLayout.addRow(QtGui.QLabel('Sleep (s)'),self.sleepValue)
# apply the layout
self.mainLayout.addLayout(self.formLayout)
self.mainLayout.addWidget(QtGui.QLabel())
# Current Variable Value
self.curVarLayout = QtGui.QHBoxLayout()
self.variableValue = QtGui.QLabel('Variable')
self.curVarLayout.addWidget(QtGui.QLabel('Current Value:'))
self.curVarLayout.addStretch()
self.curVarLayout.addWidget(self.variableValue)
self.mainLayout.addLayout(self.curVarLayout)
# slider
self.sliderLayout = QtGui.QHBoxLayout()
self.slider = QtGui.QSlider()
self.slider.setOrientation(QtCore.Qt.Orientation.Horizontal)
self.slider.setRange(0, 10)
self.slider.setTickInterval(0)
self.sliderLeftValue = QtGui.QLabel('Begin')
self.sliderRightValue = QtGui.QLabel('End')
self.sliderLayout.addWidget(self.sliderLeftValue)
self.sliderLayout.addWidget(self.slider)
self.sliderLayout.addWidget(self.sliderRightValue)
self.mainLayout.addLayout(self.sliderLayout)
# ForceUpdate, loop and pendulum tick-boxes
self.ForceRender = QtGui.QCheckBox()
self.ForceRender.setLayoutDirection(QtCore.Qt.LeftToRight)
self.ForceRender.setToolTip("Force GUI to update on every step.")
self.ForceRender.setText("Force-render every step")
self.ForceRender.setChecked(False)
self.Loop = QtGui.QCheckBox()
self.Loop.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Loop.setToolTip("Infinite Loop")
self.Loop.setText("Loop")
self.Loop.setChecked(False)
self.Pendulum = QtGui.QCheckBox()
self.Pendulum.setLayoutDirection(QtCore.Qt.RightToLeft)
self.Pendulum.setToolTip("Back-and-forth pendulum")
self.Pendulum.setText("Pendulum")
self.Pendulum.setChecked(False)
self.mainLayout.addWidget(self.Loop)
self.cbLayout = QtGui.QFormLayout()
self.cbLayout.addRow(self.ForceRender, self.Pendulum)
self.mainLayout.addLayout(self.cbLayout)
self.mainLayout.addWidget(QtGui.QLabel())
self.mainLayout.addStretch()
# the button row definition
self.buttonLayout = QtGui.QHBoxLayout()
# Close button
self.CloseButton = QtGui.QPushButton('Close')
self.buttonLayout.addWidget(self.CloseButton)
self.buttonLayout.addStretch()
# Stop button
self.StopButton = QtGui.QPushButton('Stop')
self.buttonLayout.addWidget(self.StopButton)
self.buttonLayout.addStretch()
self.StopButton.setEnabled(False)
# Run button
self.RunButton = QtGui.QPushButton('Run')
self.RunButton.setDefault(True)
self.buttonLayout.addWidget(self.RunButton)
# add buttons to layout
self.mainLayout.addLayout(self.buttonLayout)
# finally, apply the layout to the main window
self.UI.setLayout(self.mainLayout)
# Actions
self.varList.currentIndexChanged.connect( self.onSelectVar )
self.slider.sliderMoved.connect( self.sliderMoved)
self.beginValue.valueChanged.connect(self.onValuesChanged)
self.endValue.valueChanged.connect(self.onValuesChanged)
self.stepValue.valueChanged.connect( self.onValuesChanged )
self.Loop.toggled.connect( self.onLoop )
self.Pendulum.toggled.connect( self.onPendulum )
self.ForceRender.toggled.connect(self.onForceRender)
self.CloseButton.clicked.connect( self.onClose )
self.StopButton.clicked.connect(self.onStop)
self.RunButton.clicked.connect( self.onRun )
"""
+-----------------------------------------------+
| add the command to the workbench |
+-----------------------------------------------+
"""
Gui.addCommand( 'Asm4_Animate', animateVariable() )