-
-
Notifications
You must be signed in to change notification settings - Fork 91
/
keyframes.py
1298 lines (1012 loc) · 45.9 KB
/
keyframes.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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# (C) 2021 Minoru Akagi
# SPDX-License-Identifier: GPL-2.0-or-later
# begin: 2021-11-10
from PyQt5.QtCore import Qt, QSize, QUrl
from PyQt5.QtGui import QCursor, QIcon
from PyQt5.QtWidgets import (QAbstractItemView, QAction, QButtonGroup, QDialog, QInputDialog, QMenu,
QMessageBox, QTreeWidget, QTreeWidgetItem, QWidget)
from qgis.core import Qgis, QgsApplication, QgsFieldProxyModel
from .conf import DEBUG_MODE, DEF_SETS, PLUGIN_NAME
from .q3dconst import DEMMtlType, LayerType, ATConst
from .q3dcore import Layer
from .utils import createUid, selectImageFile, js_bool, logMessage, parseInt, pluginDir
from .ui.animationpanel import Ui_AnimationPanel
from .ui.keyframedialog import Ui_KeyframeDialog
class AnimationPanel(QWidget):
def __init__(self, parent=None):
QWidget.__init__(self, parent)
self.isAnimating = False
self.ui = Ui_AnimationPanel()
self.ui.setupUi(self)
self.ui.treeWidgetAnimation = AnimationTreeWidget(self)
self.ui.treeWidgetAnimation.setObjectName("treeWidgetAnimation")
self.ui.verticalLayout.addWidget(self.ui.treeWidgetAnimation)
self.tree = self.ui.treeWidgetAnimation
self.iconPlay = QIcon(pluginDir("svg", "play.svg")) # QgsApplication.getThemeIcon("temporal_navigation/forward.svg")
self.iconStop = QIcon(pluginDir("svg", "stop.svg")) # QgsApplication.getThemeIcon("temporal_navigation/stop.svg")
self.iconNarration = QgsApplication.getThemeIcon("mIconInfo.svg")
self.iconEasing = {}
def setup(self, wnd, settings):
self.wnd = wnd
self.webPage = wnd.webPage
self.ui.toolButtonAdd.setIcon(QgsApplication.getThemeIcon("symbologyAdd.svg"))
self.ui.toolButtonEdit.setIcon(QgsApplication.getThemeIcon("symbologyEdit.svg"))
self.ui.toolButtonRemove.setIcon(QgsApplication.getThemeIcon("symbologyRemove.svg"))
self.ui.toolButtonPlay.setIcon(self.iconPlay)
self.ui.toolButtonAdd.clicked.connect(self.tree.addNewItem)
self.ui.toolButtonEdit.clicked.connect(self.tree.onItemEdit)
self.ui.toolButtonRemove.clicked.connect(self.tree.removeSelectedItems)
self.ui.toolButtonPlay.clicked.connect(self.playButtonClicked)
self.tree.setup(wnd, settings)
self.setData(settings.animationData())
if self.webPage:
self.tree.currentItemChanged.connect(self.currentItemChanged)
self.currentItemChanged(None, None)
self.webPage.bridge.animationStopped.connect(self.animationStopped)
else:
self.setEnabled(False) # animation panel gets disabled when exporter has no preview.
def data(self):
d = self.tree.data()
d["repeat"] = self.ui.checkBoxLoop.isChecked()
return d
def setData(self, data):
self.ui.checkBoxLoop.setChecked(data.get("repeat", False))
self.tree.setData(data)
def playButtonClicked(self, _):
if self.isAnimating:
self.stopAnimation()
else:
self.playAnimation(repeat=self.ui.checkBoxLoop.isChecked())
def playAnimation(self, items=None, repeat=False):
self.wnd.settings.setAnimationData(self.data())
self._warnings = []
dataList = []
if items is None:
for group in self.wnd.settings.enabledValidKeyframeGroups(warning_log=self._log):
layerId = group.get("layerId")
if layerId is None:
dataList.append(group)
else:
layer = self.wnd.settings.getLayerByJSLayerId(layerId)
if layer:
t = group.get("type")
if t in (ATConst.ITEM_GRP_TEXTURE, ATConst.ITEM_GRP_GROWING_LINE):
self._updateLayer(layer, t)
dataList.append(group)
else:
for item in items:
t = item.type()
if t in (ATConst.ITEM_GRP_TEXTURE, ATConst.ITEM_GRP_GROWING_LINE):
mapLayerId = item.parent().data(0, ATConst.DATA_LAYER_ID)
elif t in (ATConst.ITEM_TEXTURE, ATConst.ITEM_GROWING_LINE):
mapLayerId = item.parent().parent().data(0, ATConst.DATA_LAYER_ID)
else:
mapLayerId = None
if mapLayerId:
layer = self.wnd.settings.getLayer(mapLayerId)
self._updateLayer(layer, t)
data = self.tree.transitionData(item, exclude_narration=bool(t & ATConst.ITEM_MBR))
if data:
dataList.append(data)
msg = ""
timeout_ms = 5000
if self._warnings:
msg = "Animation warning{}:<br><ul>".format("s" if len(self._warnings) > 1 else "")
for w in self._warnings:
msg += "<li>" + w + "</li>"
msg += "</ul>"
timeout_ms = 0
if len(dataList):
if DEBUG_MODE:
logMessage("Play: " + str(dataList))
self.wnd.iface.requestRunScript("startAnimation(pyData(), {})".format(js_bool(repeat)), data=dataList)
self.ui.toolButtonPlay.setIcon(self.iconStop)
self.ui.checkBoxLoop.setEnabled(False)
self.isAnimating = True
else:
if not msg:
msg = "Animation: "
msg += "There are no keyframe groups to play."
self.ui.toolButtonPlay.setChecked(False)
if msg:
self.wnd.webPage.showMessageBar(msg, timeout_ms, warning=True)
def _updateLayer(self, layer, groupType):
if groupType in (ATConst.ITEM_GRP_TEXTURE, ATConst.ITEM_TEXTURE):
layer = layer.clone()
layer.opt.onlyMaterial = True
layer.opt.allMaterials = True
self.wnd.iface.requestRunScript("preview.renderEnabled = false;")
self.wnd.iface.buildLayerRequest.emit(layer)
self.wnd.iface.requestRunScript("preview.renderEnabled = true;")
def _log(self, msg):
self._warnings.append(msg)
logMessage("Animation: " + msg)
def stopAnimation(self):
self.webPage.runScript("stopAnimation()")
# @pyqtSlot()
def animationStopped(self):
self.ui.toolButtonPlay.setIcon(self.iconPlay)
self.ui.toolButtonPlay.setChecked(False)
self.ui.checkBoxLoop.setEnabled(True)
self.isAnimating = False
def updateKeyframeView(self):
view = self.webPage.cameraState(flat=True)
msg = "Are you sure you want to update the camera position and focal point of this keyframe?"
if QMessageBox.question(self, PLUGIN_NAME, msg) == QMessageBox.Yes:
item = self.tree.currentItem()
item.setData(0, ATConst.DATA_CAMERA, view)
def currentItemChanged(self, current, previous):
self.ui.toolButtonAdd.setEnabled(bool(current))
b = bool(current and not (current.type() & ATConst.ITEM_TOPLEVEL))
self.ui.toolButtonEdit.setEnabled(b)
self.ui.toolButtonRemove.setEnabled(b)
def showNarrativeBox(self, content):
self.webPage.runScript("showNarrativeBox(pyData())", data=content)
class AnimationTreeWidget(QTreeWidget):
def __init__(self, parent):
QTreeWidget.__init__(self, parent)
self.panel = parent
self.dialog = None
root = self.invisibleRootItem()
root.setFlags(root.flags() & ~Qt.ItemIsDropEnabled)
self.header().setVisible(False)
self.setDragDropMode(QAbstractItemView.InternalMove)
self.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.setExpandsOnDoubleClick(False)
def setup(self, wnd, settings):
self.wnd = wnd
self.webPage = wnd.webPage
self.settings = settings
self.icons = wnd.icons
self.cameraIcon = QgsApplication.getThemeIcon("mIconCamera.svg") if Qgis.QGIS_VERSION_INT >= 31600 else QIcon(pluginDir("svg", "camera.svg"))
self.keyframeIcon = QIcon(pluginDir("svg", "keyframe.svg"))
self.effectIcon = QgsApplication.getThemeIcon("mLayoutItemPolyline.svg")
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.customContextMenuRequested.connect(self.contextMenu)
self.currentItemChanged.connect(self.currentTreeItemChanged)
self.itemDoubleClicked.connect(self.onItemDoubleClicked)
# context menu
self.actionAdd = QAction("Add", self) # NOTE: may be hidden
self.actionAdd.triggered.connect(self.addNewItem)
self.actionRemove = QAction("Remove...", self)
self.actionRemove.triggered.connect(self.removeSelectedItems)
self.actionEdit = QAction("Edit...", self)
self.actionEdit.triggered.connect(self.onItemEdit)
self.actionRename = QAction("Rename...", self)
self.actionRename.triggered.connect(self.renameGroup)
self.actionPlay = QAction("Play", self)
self.actionPlay.triggered.connect(self.playAnimation)
self.actionShowNarBox = QAction("Preview narrative content", self)
self.actionShowNarBox.triggered.connect(self.showNarrativeBox)
self.actionUpdateView = QAction("Set current view to this keyframe...", self)
self.actionUpdateView.triggered.connect(self.panel.updateKeyframeView)
self.actionOpacity = QAction("Change opacity...", self)
self.actionOpacity.triggered.connect(self.addOpacityItem)
self.actionTexture = QAction("Change texture...", self)
self.actionTexture.triggered.connect(self.addTextureItem)
self.actionGrowLine = QAction("Growing line...", self)
self.actionGrowLine.triggered.connect(self.addGrowLineItem)
self.actionProperties = QAction("Properties...", self)
self.actionProperties.triggered.connect(self.showDialog)
self.ctxMenuKeyframeGroup = QMenu(self)
self.ctxMenuKeyframeGroup.addAction(self.actionPlay)
self.ctxMenuKeyframeGroup.addAction(self.actionRename)
self.ctxMenuKeyframeGroup.addSeparator()
self.ctxMenuKeyframeGroup.addAction(self.actionAdd)
self.ctxMenuKeyframeGroup.addAction(self.actionEdit)
self.ctxMenuKeyframeGroup.addSeparator()
self.ctxMenuKeyframeGroup.addAction(self.actionRemove)
self.ctxMenuKeyframe = QMenu(self)
self.ctxMenuKeyframe.addAction(self.actionShowNarBox)
self.ctxMenuKeyframe.addAction(self.actionPlay)
self.ctxMenuKeyframe.addSeparator()
self.ctxMenuKeyframe.addAction(self.actionEdit)
self.ctxMenuKeyframe.addAction(self.actionUpdateView)
self.ctxMenuKeyframe.addSeparator()
self.ctxMenuKeyframe.addAction(self.actionRemove)
self.ctxMenuLayerAdd = QMenu(self)
self.ctxMenuLayerAdd.addActions([self.actionOpacity, self.actionTexture, self.actionGrowLine])
self.ctxMenuLayer = QMenu(self)
self.ctxMenuLayer.addMenu("Add").addActions(self.ctxMenuLayerAdd.actions())
self.ctxMenuLayer.addSeparator()
self.ctxMenuLayer.addAction(self.actionProperties)
def dropEvent(self, event):
items = self.selectedItems()
p = items[0].parent()
dp = False
for item in items[1:]:
if item.parent() != p:
dp = True
item = items[0]
dest = self.itemAt(event.pos())
accept = False
if dest and item.type() & ATConst.ITEM_MBR and not dp:
if item.type() == dest.type():
if item.parent().parent() == item.parent().parent():
accept = True
elif item.parent().type() == dest.type():
if item.parent().parent() == dest.parent():
accept = True
if item.type() == ATConst.ITEM_GROWING_LINE:
accept = False
if not accept:
event.setDropAction(Qt.IgnoreAction)
self.wnd.ui.statusbar.showMessage("Cannot move item(s) there.", 3000)
return QTreeWidget.dropEvent(self, event)
def initTree(self):
self.clear()
def addLayer(self, id_layer):
if isinstance(id_layer, Layer):
layer = id_layer
layerId = id_layer.layerId
else:
layerId = id_layer
layer = self.settings.getLayer(layerId)
if not layer:
return
item = QTreeWidgetItem(self, [layer.name], ATConst.ITEM_TL_LAYER)
item.setData(0, ATConst.DATA_LAYER_ID, layerId)
item.setFlags(Qt.ItemIsEnabled)
item.setIcon(0, self.icons[layer.type])
item.setExpanded(True)
return item
def checkedGroups(self):
groups = []
root = self.invisibleRootItem()
for i in range(root.childCount()):
top_level = root.child(i)
if top_level.isHidden():
continue
for j in range(top_level.childCount()):
g = top_level.child(j)
if g.checkState(0):
groups.append(g)
return groups
def currentLayer(self):
item = self.currentItem()
if item:
while item.parent():
item = item.parent()
return self.getLayerFromLayerItem(item)
def getLayerFromLayerItem(self, item):
layerId = item.data(0, ATConst.DATA_LAYER_ID)
return self.settings.getLayer(layerId)
def findLayerItem(self, layerId):
root = self.invisibleRootItem()
for i in range(root.childCount()):
item = root.child(i)
if item.type() == ATConst.ITEM_TL_LAYER and item.data(0, ATConst.DATA_LAYER_ID) == layerId:
return item
def setLayerHidden(self, layerId, b=True):
item = self.findLayerItem(layerId)
if item:
item.setHidden(b)
def addNewItem(self):
item = self.currentItem()
if item is None:
return
typ = item.type()
parent = None
if typ & ATConst.ITEM_TOPLEVEL:
if typ == ATConst.ITEM_TL_CAMERA:
parent = self.addKeyframeGroupItem(item, ATConst.ITEM_GRP_CAMERA)
child = self.addKeyframeItem(parent)
self.setCurrentItem(child)
self.wnd.ui.statusbar.showMessage("A new keyframe group and a keyframe have been added.", 5000)
else:
layer = self.getLayerFromLayerItem(item)
self.actionTexture.setVisible(layer.type == LayerType.DEM)
self.actionGrowLine.setVisible(layer.type == LayerType.LINESTRING)
self.ctxMenuLayerAdd.popup(QCursor.pos())
return
gt = typ if typ & ATConst.ITEM_GRP else typ - ATConst.ITEM_MBR + ATConst.ITEM_GRP
if gt == ATConst.ITEM_GRP_CAMERA:
added = self.addKeyframeItem()
self.setCurrentItem(added)
elif gt == ATConst.ITEM_GRP_OPACITY:
self.addOpacityItem()
elif gt == ATConst.ITEM_GRP_TEXTURE:
self.addTextureItem()
elif gt == ATConst.ITEM_GRP_GROWING_LINE:
if typ == ATConst.ITEM_GRP_GROWING_LINE and item.childCount() == 0:
self.addGrowLineItem()
else:
QMessageBox.warning(self, PLUGIN_NAME, "This group can't have more than one item.")
def removeSelectedItems(self):
items = self.selectedItems() or [self.currentItem()]
if len(items) == 0:
return
elif len(items) == 1:
msg = "Are you sure you want to remove '{}'?".format(items[0].text(0))
else:
msg = "Are you sure you want to remove {} items?".format(len(items))
if QMessageBox.question(self, PLUGIN_NAME, msg) != QMessageBox.Yes:
return
for item in items:
item.parent().removeChild(item)
def uniqueChildName(self, parent, base_name, omit_one=True):
n = parent.childCount()
names = [parent.child(i).text(0) for i in range(n)]
for i in range(n + 1):
name = base_name
if i or not omit_one:
name += " {}".format(i + 1)
if name not in names:
return name
def addKeyframeGroupItem(self, parent, typ, name=None, enabled=True):
name = name or self.uniqueChildName(parent, ATConst.defaultName(typ))
item = QTreeWidgetItem(typ)
item.setText(0, name)
item.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled | Qt.ItemIsUserCheckable)
item.setCheckState(0, Qt.Checked if enabled else Qt.Unchecked)
parent.addChild(item)
item.setExpanded(True)
return item
def addKeyframeItem(self, parent=None, keyframe=None):
if parent is None:
item = self.currentItem()
if not item:
return
t = item.type()
if t & ATConst.ITEM_MBR:
parent = item.parent()
iidx = parent.indexOfChild(item) + 1
elif t & ATConst.ITEM_GRP:
parent = item
iidx = 0
elif keyframe:
pass
else:
return
else:
iidx = 0
keyframe = keyframe or {}
typ = keyframe.get("type", parent.type() - ATConst.ITEM_GRP + ATConst.ITEM_MBR)
name = keyframe.get("name") or self.uniqueChildName(parent, "keyframe", omit_one=False)
item = QTreeWidgetItem(typ)
item.setText(0, name)
item.setData(0, ATConst.DATA_EASING, keyframe.get("easing", ATConst.EASING_LINEAR))
item.setData(0, ATConst.DATA_DURATION, keyframe.get("duration", DEF_SETS.ANM_DURATION))
item.setData(0, ATConst.DATA_DELAY, keyframe.get("delay", 0))
icon = None
if typ == ATConst.ITEM_CAMERA:
item.setData(0, ATConst.DATA_CAMERA, keyframe.get("camera") or self.webPage.cameraState(flat=True))
elif typ == ATConst.ITEM_OPACITY:
item.setData(0, ATConst.DATA_OPACITY, keyframe.get("opacity", 1))
elif typ == ATConst.ITEM_TEXTURE:
item.setData(0, ATConst.DATA_MTL_ID, keyframe.get("mtlId", ""))
item.setData(0, ATConst.DATA_EFFECT, keyframe.get("effect", 0))
elif typ == ATConst.ITEM_GROWING_LINE:
item.setData(0, ATConst.DATA_SEQ, keyframe.get("sequential", False))
icon = self.effectIcon
nar = keyframe.get("narration")
if nar:
item.setData(0, ATConst.DATA_NARRATION, {"id": nar["id"], "text": nar["text"]})
icon = self.panel.iconNarration
item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsDragEnabled | Qt.ItemIsEnabled)
item.setIcon(0, icon if icon else self.keyframeIcon)
if iidx:
parent.insertChild(iidx, item)
else:
parent.addChild(item)
return item
def keyframe(self, item=None):
item = item or self.currentItem()
if not item or not (item.type() & ATConst.ITEM_MBR):
return
typ = item.type()
k = {
"type": typ,
"name": item.text(0)
}
easing = item.data(0, ATConst.DATA_EASING)
if easing:
k["easing"] = easing
k["delay"] = item.data(0, ATConst.DATA_DELAY)
k["duration"] = item.data(0, ATConst.DATA_DURATION)
n = item.data(0, ATConst.DATA_NARRATION)
if n:
k["narration"] = n
if typ == ATConst.ITEM_CAMERA:
k["camera"] = item.data(0, ATConst.DATA_CAMERA)
elif typ == ATConst.ITEM_OPACITY:
k["opacity"] = item.data(0, ATConst.DATA_OPACITY)
elif typ == ATConst.ITEM_TEXTURE:
layer = self.getLayerFromLayerItem(item.parent().parent())
if layer:
id = item.data(0, ATConst.DATA_MTL_ID)
k["mtlId"] = id
k["mtlIndex"] = layer.mtlIndex(id)
k["effect"] = item.data(0, ATConst.DATA_EFFECT)
elif typ == ATConst.ITEM_GROWING_LINE:
k["sequential"] = item.data(0, ATConst.DATA_SEQ)
return k
def keyframeGroupData(self, item):
if not item:
return {}
typ = item.type()
if typ & ATConst.ITEM_GRP:
group = item
elif typ & ATConst.ITEM_MBR:
group = item.parent()
else:
return {}
items = [group.child(i) for i in range(group.childCount())]
d = {
"type": group.type(),
"name": group.text(0),
"enabled": bool(group.checkState(0)),
"keyframes": [self.keyframe(item) for item in items]
}
if group.parent().type() == ATConst.ITEM_TL_LAYER:
layer = self.settings.getLayer(group.parent().data(0, ATConst.DATA_LAYER_ID))
if layer:
d["layerId"] = layer.jsLayerId
else:
logMessage("[KeyframeGroup] Layer not found in export settings.", error=True)
return d
def layerData(self, layer=None):
if not layer:
return {}
layerItem = layer if isinstance(layer, QTreeWidgetItem) else self.findLayerItem(layer)
if layerItem is None:
return {}
items = [layerItem.child(i) for i in range(layerItem.childCount())]
return {
"enabled": not layerItem.isDisabled(),
"groups": [self.keyframeGroupData(item) for item in items]
}
def setLayerData(self, layerId, data):
if layerId is None:
return
layerItem = self.findLayerItem(layerId) or self.addLayer(layerId)
if layerItem is None:
return
for _ in range(layerItem.childCount()):
layerItem.removeChild(layerItem.child(0))
for group in data.get("groups", []):
parent = self.addKeyframeGroupItem(layerItem, group.get("type"), group.get("name"), group.get("enabled", True))
for keyframe in group.get("keyframes", []):
self.addKeyframeItem(parent, keyframe)
def data(self):
root = self.invisibleRootItem()
parent = root.child(0) # camera motion
d = {
"camera": {
"groups": [self.keyframeGroupData(parent.child(i)) for i in range(parent.childCount())]
}
}
layers = {}
for item in [root.child(i) for i in range(1, root.childCount())]:
layers[item.data(0, ATConst.DATA_LAYER_ID)] = self.layerData(item)
if layers:
d["layers"] = layers
return d
def transitionData(self, item=None, exclude_narration=False):
item = item or self.currentItem()
if not item:
return
typ = item.type()
if typ & ATConst.ITEM_MBR:
isKF = (typ != ATConst.ITEM_GROWING_LINE)
c = 2 if isKF else 1
p = item.parent()
iidx = p.indexOfChild(item)
if isKF and iidx == p.childCount() - 1:
return
d = self.keyframeGroupData(p)
kfs = d["keyframes"][iidx:iidx + c]
if exclude_narration:
kfs[0].pop("narration", None)
if c == 2:
kfs[1].pop("narration", None)
d["keyframes"] = kfs
return d
elif typ & ATConst.ITEM_GRP: # NOTE: exclude_narration is ignored
return self.keyframeGroupData(item)
def setData(self, data):
self.initTree()
# camera motion
item = QTreeWidgetItem(self, ["Camera Motion"], ATConst.ITEM_TL_CAMERA)
item.setFlags(Qt.ItemIsEnabled)
item.setIcon(0, self.cameraIcon)
item.setExpanded(True)
self.cameraTLItem = item
for s in data.get("camera", {}).get("groups", []):
parent = self.addKeyframeGroupItem(item, ATConst.ITEM_GRP_CAMERA, s.get("name"), s.get("enabled", True))
for k in s.get("keyframes", []):
self.addKeyframeItem(parent, k)
# layers
dp = data.get("layers", {})
for layer in self.settings.layers():
id = layer.layerId
self.addLayer(layer)
d = dp.get(id)
if d:
self.setLayerData(id, d)
self.setLayerHidden(id, not layer.visible)
def currentItemView(self):
item = self.currentItem()
if item and item.type() == ATConst.ITEM_CAMERA:
return item.data(0, ATConst.DATA_CAMERA)
def contextMenu(self, pos):
item = self.itemAt(pos)
if item is None:
# blank space
return
m = None
typ = item.type()
if typ & ATConst.ITEM_TOPLEVEL:
if typ == ATConst.ITEM_TL_LAYER:
m = self.ctxMenuLayer
layer = self.getLayerFromLayerItem(item)
self.actionTexture.setVisible(layer.type == LayerType.DEM)
self.actionGrowLine.setVisible(layer.type == LayerType.LINESTRING)
else:
if typ & ATConst.ITEM_GRP:
m = self.ctxMenuKeyframeGroup
self.actionAdd.setText("Add" if typ == ATConst.ITEM_GRP_CAMERA else "Add...")
self.actionAdd.setVisible(bool(typ != ATConst.ITEM_GRP_GROWING_LINE))
elif typ & ATConst.ITEM_MBR:
m = self.ctxMenuKeyframe
self.actionShowNarBox.setVisible(bool(item.data(0, ATConst.DATA_NARRATION)))
self.actionUpdateView.setVisible(bool(typ == ATConst.ITEM_CAMERA))
if m:
m.exec_(self.mapToGlobal(pos))
def currentTreeItemChanged(self, current, previous=None):
if not current:
return
typ = current.type()
if not (typ & ATConst.ITEM_MBR):
return
if typ == ATConst.ITEM_CAMERA:
# restore the view of current keyframe
k = self.keyframe()
if k:
self.webPage.setCameraState(k.get("camera") or {})
elif typ == ATConst.ITEM_OPACITY:
layerId = current.parent().parent().data(0, ATConst.DATA_LAYER_ID)
layer = self.settings.getLayer(layerId)
if layer:
opacity = current.data(0, ATConst.DATA_OPACITY)
self.webPage.runScript("setLayerOpacity({}, {})".format(layer.jsLayerId, opacity))
elif typ == ATConst.ITEM_TEXTURE:
layerId = current.parent().parent().data(0, ATConst.DATA_LAYER_ID)
layer = self.settings.getLayer(layerId)
if layer:
layer = layer.clone()
layer.properties["mtlId"] = current.data(0, ATConst.DATA_MTL_ID)
layer.opt.onlyMaterial = True
self.wnd.iface.buildLayerRequest.emit(layer)
def onItemDoubleClicked(self, item=None, column=0):
item = item or self.currentItem()
t = item.type()
if t != ATConst.ITEM_TL_CAMERA:
self.showDialog(item)
def onItemEdit(self):
item = self.currentItem()
if item:
t = item.type()
if t & ATConst.ITEM_MBR:
self.showDialog(item)
elif t & ATConst.ITEM_GRP:
if item.childCount() > 0:
self.showDialog(item.child(0))
def renameGroup(self, item=None):
item = item or self.currentItem()
if item:
name, ok = QInputDialog.getText(self, "Rename group", "Group name", text=item.text(0))
if ok:
item.setText(0, name)
def addOpacityItem(self):
item = self.currentItem()
if not item:
return
val, ok = QInputDialog.getDouble(self, "Layer Opacity", "Opacity (0 - 1)", 1, 0, 1, 2)
if ok:
parent = None
if item.type() == ATConst.ITEM_TL_LAYER:
parent = self.addKeyframeGroupItem(item, ATConst.ITEM_GRP_OPACITY)
added = self.addKeyframeItem(parent, {
"type": ATConst.ITEM_OPACITY,
"name": "opacity '{}'".format(val),
"opacity": val
})
self.setCurrentItem(added)
def addTextureItem(self):
item = self.currentItem()
layer = self.currentLayer()
if not item or not layer:
return
mtlNames = ["[{}] {}".format(i, mtl.get("name", "")) for i, mtl in enumerate(layer.properties.get("materials", [])) if mtl.get("type") != DEMMtlType.COLOR]
if not mtlNames:
QMessageBox.warning(self, "Texture", "The layer has no textures.")
return
val, ok = QInputDialog.getItem(self, "Texture", "Select a material with texture", mtlNames, 0, False)
if ok:
mtlIdx = int(val.split("]")[0][1:])
mtl = layer.properties["materials"][mtlIdx]
parent = None
if item.type() == ATConst.ITEM_TL_LAYER:
parent = self.addKeyframeGroupItem(item, ATConst.ITEM_GRP_TEXTURE)
added = self.addKeyframeItem(parent, {
"type": ATConst.ITEM_TEXTURE,
"name": mtl.get("name", "no name"),
"mtlId": mtl.get("id")
})
self.setCurrentItem(added)
def addGrowLineItem(self):
item = self.currentItem()
layer = self.currentLayer()
if not item or not layer:
return
parent = None
if item.type() == ATConst.ITEM_TL_LAYER:
parent = self.addKeyframeGroupItem(item, ATConst.ITEM_GRP_GROWING_LINE)
added = self.addKeyframeItem(parent, {
"type": ATConst.ITEM_GROWING_LINE,
"name": "Growing line"
})
self.setCurrentItem(added)
def showDialog(self, item=None):
item = item or self.currentItem()
if item is None:
return
t = item.type()
if t == ATConst.ITEM_TL_LAYER:
layerId = item.data(0, ATConst.DATA_LAYER_ID)
layer = self.settings.getLayer(layerId)
self.wnd.showLayerPropertiesDialog(layer)
return
elif t == ATConst.ITEM_TL_CAMERA:
return
if t & ATConst.ITEM_GRP:
item = item.child(0)
if item is None:
isKF = (t != ATConst.ITEM_GRP_GROWING_LINE)
msg = "This group has no items. Please add {}.".format("at least two keyframe items" if isKF else "an item")
QMessageBox.warning(self, PLUGIN_NAME, msg)
return
t = item.type()
isKF = (t != ATConst.ITEM_GROWING_LINE)
if isKF:
if item.parent().childCount() < 2:
QMessageBox.warning(self, PLUGIN_NAME, "Two or more keyframes are necessary for animation to work. Please add a keyframe.")
return
else:
# line growing doesn't work if group item is not checked
item.parent().setCheckState(0, Qt.Checked)
top_level = item.parent().parent()
layer = None
if top_level.type() == ATConst.ITEM_TL_LAYER:
layerId = top_level.data(0, ATConst.DATA_LAYER_ID)
layer = self.settings.getLayer(layerId)
self.panel.setEnabled(False)
self.dialog = KeyframeDialog(self)
self.dialog.setup(item, layer)
self.dialog.finished.connect(self.dialogClosed)
self.dialog.show()
self.dialog.exec_()
def dialogClosed(self, result):
self.panel.setEnabled(True)
self.dialog = None
def playAnimation(self):
item = self.currentItem()
if item:
self.panel.playAnimation([item])
def showNarrativeBox(self):
item = self.currentItem()
if item:
nar = item.data(0, ATConst.DATA_NARRATION)
if nar:
self.panel.showNarrativeBox(nar["text"])
def materialChanged(self, layer):
layerItem = self.findLayerItem(layer.layerId)
if not layerItem:
return
mtls = {mtl["id"]: mtl for mtl in layer.properties.get("materials", [])}
for i in range(layerItem.childCount()):
group = layerItem.child(i)
if group.type() != ATConst.ITEM_GRP_TEXTURE:
continue
for idx in reversed(range(group.childCount())):
item = group.child(idx)
mtl = mtls.get(item.data(0, ATConst.DATA_MTL_ID))
if mtl:
item.setText(0, mtl["name"])
else:
logMessage("The material '{}' was removed.".format(item.text(0)))
group.removeChild(item)
class KeyframeDialog(QDialog):
def __init__(self, parent):
QDialog.__init__(self, parent)
self.setAttribute(Qt.WA_DeleteOnClose)
self.ui = Ui_KeyframeDialog()
self.ui.setupUi(self)
self.easingButtons = {
ATConst.EASING_NONE: self.ui.toolButtonNone,
ATConst.EASING_LINEAR: self.ui.toolButtonLinear,
ATConst.EASING_EASE_INOUT: self.ui.toolButtonEaseInOut,
ATConst.EASING_EASE_IN: self.ui.toolButtonEaseIn,
ATConst.EASING_EASE_OUT: self.ui.toolButtonEaseOut
}
self.ui.buttonGroup = QButtonGroup(self)
self.ui.buttonGroup.setObjectName("buttonGroup")
for id, btn in self.easingButtons.items():
self.ui.buttonGroup.addButton(btn, id)
self.panel = parent.panel
self.narId = None
self.isPlaying = self.isPlayingAll = False
parent.webPage.bridge.tweenStarted.connect(self.tweenStarted)
parent.webPage.bridge.animationStopped.connect(self.animationStopped)
def setup(self, item, layer=None):
self.type = t = item.type()
if not self.type & ATConst.ITEM_MBR:
return
self.item = item
self.currentItem = None
self.isKF = (t != ATConst.ITEM_GROWING_LINE)
self.layer = layer
group = item.parent()
self.kfCount = group.childCount()
self.setWindowTitle("{} - {}".format(item.parent().text(0), layer.name if layer else "Camera Motion"))
# set up widgets
self.ui.toolButtonPlay.setIcon(self.panel.iconPlay)
self.ui.pushButtonPlayAll.setIcon(self.panel.iconPlay)
self.ui.toolButtonAddImage.setIcon(QgsApplication.getThemeIcon("mActionAddImage.svg"))
self.ui.toolButtonPreview.setIcon(self.panel.iconNarration)
if not self.panel.iconEasing:
names = {
ATConst.EASING_LINEAR: "linear",
ATConst.EASING_EASE_INOUT: "inout",
ATConst.EASING_EASE_IN: "in",
ATConst.EASING_EASE_OUT: "out",
ATConst.EASING_NONE: "none"
}
for id, name in names.items():
self.panel.iconEasing[id] = QIcon(pluginDir("svg", "ease_{}.svg".format(name)))
size = QSize(25, 18)
for id, btn in self.easingButtons.items():
btn.setIconSize(size)
btn.setIcon(self.panel.iconEasing[id])
if t == ATConst.ITEM_TEXTURE:
self.ui.labelComboBox1.setText("Texture")
for mtl in self.layer.properties.get("materials", []):
if mtl.get("type") != DEMMtlType.COLOR:
name, id = (mtl.get("name", ""), mtl.get("id"))
self.ui.comboBox1.addItem(name, id)
self.ui.labelComboBox2.setText("Effect")
self.ui.comboBox2.addItem("Fade in", 0)
elif t == ATConst.ITEM_GROWING_LINE:
self.ui.labelComboBox1.setText("Animate")
self.ui.comboBox1.addItem("all lines at once", False)
self.ui.comboBox1.addItem("each line sequentially", True)
self.ui.comboBox1.currentIndexChanged.connect(self.modeChanged)
for w in [self.ui.expressionDelay, self.ui.expressionDuration]: