-
Notifications
You must be signed in to change notification settings - Fork 0
/
gui.py
221 lines (182 loc) · 6.42 KB
/
gui.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
#!/usr/bin/env python3
import importlib
import os
import sys
import time
import warnings
from PyQt5.QtCore import (
QSize, QTimer, Qt, QByteArray, QBuffer, QIODevice
)
from PyQt5.QtGui import (
QPalette, QColor
)
from PyQt5.QtWidgets import (
QWidget, QVBoxLayout, QSizePolicy, QApplication, QPushButton, QFileDialog,
QMessageBox, QProgressDialog
)
from anistate import AniState
try:
import imageio
except ImportError:
imageio = None
warnings.warn('Export as video feature disabled, imageio module missing')
try:
import watchdog.observers
import watchdog.events
except ImportError:
watchdog = None
warnings.warn('Hot reload feature disabled, watchdog module missing')
FPS = 60 # Frames Per Second at which to render the animation
DURATION = 60 # In seconds
CENTER = False # Should everything be translated to the center?
BACKGROUND = QColor('#fff')
class CanvasWidget(QWidget):
def __init__(self):
super().__init__()
pal = QPalette()
pal.setColor(QPalette.Background, BACKGROUND)
self.setPalette(pal)
self.setAutoFillBackground(True)
self.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
self.start = lambda: None
self.callback = lambda a: None
self.duration = DURATION
self.frame_no = self.start_time = self.last_time = None
self.restart()
def restart(self):
self.frame_no = 0
self.start_time = self.last_time = time.time()
self.start()
def minimumSizeHint(self):
return QSize(50, 50)
def sizeHint(self):
return QSize(400, 400)
def next_animation_frame(self):
self.update()
self.frame_no += 1
if time.time() - self.start_time > self.duration:
self.restart()
def export_video(self):
if not imageio:
return QMessageBox(
QMessageBox.Information, 'Export not available',
'imageio and ffmpeg must be installed to export videos'
).exec()
location = QFileDialog.getSaveFileName(
self, 'Choose export location', filter='Video (*.mp4)'
)[0]
if not location:
return
if not location.endswith('.mp4'):
location += '.mp4'
frame_count = int(self.duration * FPS)
progress_box = QProgressDialog(
'Recording and exporting video...', 'Cancel', 1, frame_count, self
)
progress_box.setWindowModality(Qt.WindowModal)
with imageio.get_writer(location, format='mp4', mode='I',
fps=FPS, quality=6) as writer:
frame = 0
stopped = False
def new_event(*args):
nonlocal frame, stopped
try:
self.callback(AniState(self,
frame=frame,
time=frame / FPS,
dt=1 / FPS))
frame += 1
except StopIteration:
stopped = True
old = self.paintEvent
self.paintEvent = new_event
self.start()
self.frame_no = 0
for i in range(frame_count):
progress_box.setValue(i)
if progress_box.wasCanceled():
os.remove(location)
return
im_bytes = QByteArray()
buf = QBuffer(im_bytes)
buf.open(QIODevice.WriteOnly)
self.grab().save(buf, 'PNG', 100) # Triggers paintEvent
self.frame_no += 1
writer.append_data(imageio.imread(im_bytes.data(), 'png'))
if stopped:
break
progress_box.setValue(progress_box.maximum())
self.paintEvent = old
return QMessageBox(
QMessageBox.Information, 'Completed',
'Export finished! Saved to {}'.format(location)
).exec()
def paintEvent(self, *args):
now = time.time()
try:
self.callback(AniState(self,
frame=self.frame_no,
time=now - self.start_time,
dt=now - self.last_time))
self.last_time = now
except StopIteration:
self.restart()
class Animake(QWidget):
def __init__(self):
super().__init__(None)
self.setWindowTitle("Animake")
self.setWindowFlags(Qt.Dialog)
layout = QVBoxLayout(self)
self.canvas = CanvasWidget()
self.canvas.timer = QTimer(self)
self.canvas.timer.timeout.connect(self.canvas.next_animation_frame)
layout.addWidget(self.canvas)
export_button = QPushButton("Export a video")
export_button.pressed.connect(self.canvas.export_video)
layout.addWidget(export_button)
self.canvas.timer.start(int((1000 + FPS - 1) / FPS))
class ModLoader(watchdog.events.FileSystemEventHandler):
def __init__(self, canvas, name):
self.canvas = canvas
self.filename = name.replace('.', '/') + '.py'
self.mod = importlib.import_module(name)
self.mod_updated()
def on_modified(self, event):
if event.src_path == self.filename:
try:
importlib.reload(self.mod)
self.mod_updated()
except Exception as e:
warnings.warn('Failed to hot reload %s:\n%s' % (self.name, e))
def mod_updated(self):
if hasattr(self.mod, 'start'):
self.canvas.start = self.mod.start
self.canvas.callback = self.mod.callback
self.canvas.duration = getattr(self.mod, 'DURATION', DURATION)
if not self.canvas.duration:
self.canvas.duration = float('inf')
self.canvas.restart()
def main(args):
app = QApplication([])
win = Animake()
if args:
mod = args[0]
if not mod.startswith('scenes.'):
mod = 'scenes.' + mod
else:
mod = 'scenes.example'
loader = ModLoader(win.canvas, mod)
if watchdog:
observer = watchdog.observers.Observer()
observer.schedule(loader, 'scenes/')
observer.start()
else:
observer = None
win.show()
ret_val = app.exec()
if observer:
observer.stop()
observer.join()
return ret_val
if __name__ == '__main__':
main(sys.argv[1:])