-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAnimationControlController.cpp
More file actions
1731 lines (1539 loc) · 71.9 KB
/
AnimationControlController.cpp
File metadata and controls
1731 lines (1539 loc) · 71.9 KB
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
#include "AnimationControlController.h"
#include "SelectionSet.h"
#include "Manager.h"
#include "SentryReporter.h"
#include "UndoManager.h"
#include "commands/MoveKeyframeCommand.h"
#include "commands/BulkKeyframeCommands.h"
#include "commands/SetKeyframeValueCommand.h"
#include "commands/ResampleCurveCommand.h"
#include "commands/CurveEditModelChangeCommand.h"
#include "commands/DecimateTrackCommand.h"
#include "CurveEditModel.h"
#include "commands/AddKeyframeCommand.h"
#include "commands/DeleteKeyframeCommand.h"
#include <QApplication>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QPalette>
#include <QSet>
#include <QTimer>
#include <QVariantMap>
#include <algorithm>
#include <cmath>
#include <limits>
#include <optional>
#include <Ogre.h>
AnimationControlController* AnimationControlController::m_pSingleton = nullptr;
AnimationControlController* AnimationControlController::instance()
{
if (!m_pSingleton)
m_pSingleton = new AnimationControlController();
return m_pSingleton;
}
AnimationControlController* AnimationControlController::qmlInstance(QQmlEngine* engine, QJSEngine* scriptEngine)
{
Q_UNUSED(engine); Q_UNUSED(scriptEngine);
auto* inst = instance();
QQmlEngine::setObjectOwnership(inst, QQmlEngine::CppOwnership);
return inst;
}
void AnimationControlController::kill()
{
delete m_pSingleton;
m_pSingleton = nullptr;
}
AnimationControlController::AnimationControlController()
: QObject(nullptr)
{
connect(SelectionSet::getSingleton(), &SelectionSet::selectionChanged,
this, &AnimationControlController::updateAnimationTree);
connect(qApp, &QApplication::paletteChanged, this, [this]() {
emit themeChanged();
});
m_pollTimer = new QTimer(this);
connect(m_pollTimer, &QTimer::timeout, this, [this]() {
if (!m_selectedEntity || m_selectedAnimation.empty()) return;
if (!m_selectedEntity->hasAnimationState(m_selectedAnimation)) return;
Ogre::AnimationState* state = m_selectedEntity->getAnimationState(m_selectedAnimation);
int newMs = static_cast<int>(state->getTimePosition() * 1000);
if (newMs != m_sliderValue) {
m_sliderValue = newMs;
emit sliderValueChanged();
setAnimationFrame(newMs);
}
});
m_pollTimer->start(16);
}
// ── Theme colors ──────────────────────────────────────────────────────────────
QColor AnimationControlController::panelColor() const
{ return QApplication::palette().color(QPalette::Window); }
QColor AnimationControlController::headerColor() const
{ return QApplication::palette().color(QPalette::Window).darker(110); }
QColor AnimationControlController::textColor() const
{ return QApplication::palette().color(QPalette::WindowText); }
QColor AnimationControlController::borderColor() const
{ return QApplication::palette().color(QPalette::Mid); }
QColor AnimationControlController::inputColor() const
{ return QApplication::palette().color(QPalette::Base); }
QColor AnimationControlController::highlightColor() const
{ return QApplication::palette().color(QPalette::Highlight); }
QColor AnimationControlController::buttonColor() const
{ return QApplication::palette().color(QPalette::Button); }
QColor AnimationControlController::buttonTextColor() const
{ return QApplication::palette().color(QPalette::ButtonText); }
QColor AnimationControlController::disabledTextColor() const
{ return QApplication::palette().color(QPalette::Disabled, QPalette::WindowText); }
// ── Animation tree ────────────────────────────────────────────────────────────
void AnimationControlController::updateAnimationTree()
{
// Save current selection to restore after rebuild
QString prevEntity = QString::fromStdString(m_selectedEntityName);
QString prevAnim = QString::fromStdString(m_selectedAnimation);
QVariantList newTree;
for (Ogre::Entity* entity : SelectionSet::getSingleton()->getResolvedEntities()) {
Ogre::AnimationStateSet* set = entity->getAllAnimationStates();
if (!set) continue;
QStringList animNames;
for (const auto& pair : set->getAnimationStates())
animNames << QString::fromStdString(pair.first);
if (animNames.isEmpty()) continue;
QVariantMap group;
group["entity"] = QString::fromStdString(entity->getName());
group["animations"] = animNames;
newTree.append(group);
}
// Early-out when the tree hasn't actually changed AFTER it's been
// built once: the connected signal (SelectionSet::selectionChanged)
// also fires whenever undo commands are pushed (mainwindow re-emits
// it on QUndoStack indexChanged). Without this guard, every
// BoneTransformCommand push would call selectAnimation() and reset
// slider+bone selection. We always run the first call so QML
// listeners get an initial signal, even if the tree is empty.
if (m_animationTreeBuilt && newTree == m_animationTree) return;
m_animationTree = newTree;
m_animationTreeBuilt = true;
emit animationTreeChanged();
// Try to restore selection
if (!prevEntity.isEmpty() && !prevAnim.isEmpty()) {
selectAnimation(prevEntity, prevAnim);
} else if (!m_animationTree.isEmpty()) {
// Auto-select first animation
auto first = m_animationTree.first().toMap();
auto anims = first["animations"].toStringList();
if (!anims.isEmpty())
selectAnimation(first["entity"].toString(), anims.first());
else
selectAnimation("", "");
} else {
selectAnimation("", "");
}
}
void AnimationControlController::selectAnimation(const QString& entityName, const QString& animName)
{
// Reset state
m_selectedEntity = nullptr;
m_selectedSkeleton = nullptr;
m_selectedTrack = nullptr;
m_currentKeyframe = nullptr;
m_selectedEntityName.clear();
m_selectedAnimation.clear();
m_selectedBone.clear();
m_sliderValue = 0;
m_sliderMaximum = 0;
m_selectedTick = -1;
m_boneNames.clear();
m_keyframeTicks.clear();
if (entityName.isEmpty() || animName.isEmpty()) {
emit selectionChanged();
emit boneListChanged();
emit sliderValueChanged();
emit animationLengthChanged();
emit keyframeTicksChanged();
emit currentKeyframeChanged();
return;
}
// Find the entity
for (Ogre::Entity* entity : SelectionSet::getSingleton()->getResolvedEntities()) {
if (entity->getName() == entityName.toStdString()) {
m_selectedEntity = entity;
break;
}
}
if (!m_selectedEntity) {
emit selectionChanged();
return;
}
m_selectedEntityName = entityName.toStdString();
m_selectedAnimation = animName.toStdString();
m_selectedSkeleton = m_selectedEntity->getSkeleton();
if (m_selectedSkeleton && m_selectedSkeleton->hasAnimation(m_selectedAnimation)) {
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
m_sliderMaximum = static_cast<int>(anim->getLength() * 1000);
}
// Reset loop region to span the whole animation whenever a new clip is
// selected — users typically want fresh in/out points per clip.
m_loopStart = 0.0;
m_loopEnd = m_sliderMaximum / 1000.0;
m_loopRegionActive = false;
emit loopRegionChanged();
emit selectionChanged();
emit animationLengthChanged();
emit sliderValueChanged();
refreshBoneList();
}
// ── Bone list ─────────────────────────────────────────────────────────────────
void AnimationControlController::refreshBoneList()
{
m_boneNames.clear();
m_selectedTrack = nullptr;
m_currentKeyframe = nullptr;
m_selectedBone.clear();
if (!m_selectedSkeleton || m_selectedAnimation.empty()) {
emit boneListChanged();
emit keyframeTicksChanged();
emit currentKeyframeChanged();
return;
}
if (!m_selectedSkeleton->hasAnimation(m_selectedAnimation)) {
emit boneListChanged();
emit keyframeTicksChanged();
emit currentKeyframeChanged();
return;
}
// Show every bone in the skeleton — not just the ones that already
// have a track in this animation. Tracks for picked-but-untracked
// bones get created lazily when the user adds a keyframe. Order:
// tracked bones first (so users see what's already animated at the
// top), then the rest in skeleton index order.
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
QSet<QString> trackedNames;
for (const auto& pair : anim->_getNodeTrackList()) {
QString name = QString::fromStdString(pair.second->getAssociatedNode()->getName());
m_boneNames << name;
trackedNames.insert(name);
}
for (unsigned short i = 0; i < m_selectedSkeleton->getNumBones(); ++i) {
QString name = QString::fromStdString(m_selectedSkeleton->getBone(i)->getName());
if (!trackedNames.contains(name))
m_boneNames << name;
}
emit boneListChanged();
if (!m_boneNames.isEmpty())
selectBone(m_boneNames.first());
else {
emit keyframeTicksChanged();
emit currentKeyframeChanged();
}
}
Ogre::Bone* AnimationControlController::selectedBonePtr() const
{
if (!m_selectedSkeleton || m_selectedBone.empty()) return nullptr;
if (!m_selectedSkeleton->hasBone(m_selectedBone)) return nullptr;
return m_selectedSkeleton->getBone(m_selectedBone);
}
bool AnimationControlController::boneCanTranslate(const Ogre::Bone* bone) const
{
if (!bone) return true;
// Skeleton roots → always translatable (these are the "this is the
// character" bones that move the whole rig around — Hips, Pelvis,
// Armature, etc. — and may also have skin weights). Some importers
// wrap the actual root in an additional parent bone, so we check
// both: parentless OR present in Skeleton::getRootBones().
if (!bone->getParent()) return true;
if (m_selectedSkeleton) {
for (Ogre::Bone* root : m_selectedSkeleton->getRootBones())
if (root == bone) return true;
}
if (!m_selectedEntity) return true;
Ogre::MeshPtr mesh = m_selectedEntity->getMesh();
if (!mesh) return true;
// Walk every submesh's vertex-bone-assignment list. If any vertex
// is weighted to this bone's handle, translating it would tear the
// mesh away from the rig.
const auto handle = bone->getHandle();
auto referencesBone = [&](const Ogre::SubMesh::VertexBoneAssignmentList& list) {
for (auto it = list.begin(); it != list.end(); ++it)
if (it->second.boneIndex == handle) return true;
return false;
};
if (referencesBone(mesh->getBoneAssignments())) return false;
for (unsigned short i = 0; i < mesh->getNumSubMeshes(); ++i) {
Ogre::SubMesh* sub = mesh->getSubMesh(i);
if (!sub) continue;
if (referencesBone(sub->getBoneAssignments())) return false;
}
return true;
}
void AnimationControlController::selectBone(const QString& boneName)
{
m_selectedTrack = nullptr;
m_currentKeyframe = nullptr;
m_selectedBone = boneName.toStdString();
// Clear all bone selection highlights
if (m_selectedSkeleton) {
for (unsigned short i = 0; i < m_selectedSkeleton->getNumBones(); ++i)
m_selectedSkeleton->getBone(i)->getUserObjectBindings()
.setUserAny("selected", Ogre::Any(false));
}
// Highlight the picked bone first — independent of whether a track
// exists for it in the current animation. Bones that aren't yet
// rigged into the active clip (no NodeAnimationTrack) should still
// visually select; the keyframe-editing path then no-ops cleanly
// since m_selectedTrack stays null until the user actually adds a
// keyframe (which lazily creates the track).
if (m_selectedSkeleton && !m_selectedBone.empty()
&& m_selectedSkeleton->hasBone(m_selectedBone))
{
m_selectedSkeleton->getBone(m_selectedBone)
->getUserObjectBindings().setUserAny("selected", Ogre::Any(true));
}
// Bind the existing track for this bone, if the animation has one.
if (m_selectedSkeleton && !m_selectedAnimation.empty()
&& m_selectedSkeleton->hasAnimation(m_selectedAnimation))
{
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
for (const auto& pair : anim->_getNodeTrackList()) {
if (pair.second->getAssociatedNode()->getName() == m_selectedBone) {
m_selectedTrack = pair.second;
break;
}
}
}
emit boneListChanged();
refreshSliderTicks();
setAnimationFrame(m_sliderValue);
}
// ── Timeline / slider ─────────────────────────────────────────────────────────
void AnimationControlController::setSliderValue(int ms)
{
if (ms == m_sliderValue && m_selectedEntity) {
// Still call setAnimationFrame to keep Ogre in sync on explicit user drags
}
m_sliderValue = ms;
emit sliderValueChanged();
setAnimationFrame(ms);
}
void AnimationControlController::setAnimationLength(double length)
{
if (!m_selectedSkeleton || m_selectedAnimation.empty()) return;
if (!m_selectedSkeleton->hasAnimation(m_selectedAnimation)) return;
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
anim->setLength(static_cast<float>(length));
m_sliderMaximum = static_cast<int>(length * 1000);
if (m_sliderValue > m_sliderMaximum) {
m_sliderValue = m_sliderMaximum;
emit sliderValueChanged();
}
if (m_selectedEntity && m_selectedEntity->hasAnimationState(m_selectedAnimation)) {
Ogre::AnimationState* state = m_selectedEntity->getAnimationState(m_selectedAnimation);
state->setLength(static_cast<float>(length));
state->setTimePosition(std::min(state->getTimePosition(), static_cast<float>(length)));
m_selectedEntity->getAllAnimationStates()->_notifyDirty();
}
refreshSliderTicks();
emit animationLengthChanged();
}
// ── Playback speed / loop region ──────────────────────────────────────────────
void AnimationControlController::setPlaybackSpeed(double s)
{
if (s < 0.0) s = 0.0;
if (qFuzzyCompare(s, m_playbackSpeed)) return;
m_playbackSpeed = s;
emit playbackSpeedChanged();
}
void AnimationControlController::setLoopStart(double s)
{
if (s < 0.0) s = 0.0;
// Clamp first, then bail out if nothing actually changed — avoids
// emitting loopRegionChanged when the request collapses to the
// existing value after clamping.
if (m_loopEnd > 0.0 && s > m_loopEnd) {
s = m_loopEnd;
}
if (qFuzzyCompare(s, m_loopStart)) return;
m_loopStart = s;
emit loopRegionChanged();
}
void AnimationControlController::setLoopEnd(double s)
{
if (s < 0.0) s = 0.0;
if (qFuzzyCompare(s, m_loopEnd)) return;
m_loopEnd = s;
if (m_loopEnd > 0.0 && m_loopStart > m_loopEnd) {
m_loopStart = m_loopEnd;
}
emit loopRegionChanged();
}
void AnimationControlController::setLoopRegionActive(bool on)
{
if (on == m_loopRegionActive) return;
m_loopRegionActive = on;
emit loopRegionChanged();
}
void AnimationControlController::setAutoKey(bool on)
{
if (on == m_autoKey) return;
m_autoKey = on;
SentryReporter::addBreadcrumb("ui.action",
QString("AutoKey toggled %1").arg(on ? "on" : "off"));
emit autoKeyChanged();
}
void AnimationControlController::autoKeyOnTransform()
{
if (!m_autoKey) return;
// Don't require m_selectedTrack here — addKeyframe lazily creates
// the track for non-rigged bones. Just ensure the bone-level
// identity is set so addKeyframe has something to write into.
if (!m_selectedEntity || m_selectedAnimation.empty()) return;
if (!m_selectedSkeleton || m_selectedBone.empty()) return;
SentryReporter::addBreadcrumb("ui.action", "AutoKey applied keyframe");
addKeyframe();
}
double AnimationControlController::advanceTime(double currentTime, double dt) const
{
double next = currentTime + dt * m_playbackSpeed;
// Apply loop region only when active and the region is well-formed.
if (m_loopRegionActive && m_loopEnd > m_loopStart) {
if (next > m_loopEnd) {
const double span = m_loopEnd - m_loopStart;
double over = next - m_loopEnd;
// Wrap any number of full passes back into the region.
if (span > 0.0) over = std::fmod(over, span);
next = m_loopStart + over;
} else if (next < m_loopStart) {
// Reverse wrap (negative speed); not exposed via UI today but kept
// symmetrical so callers don't trip if they ever get here.
const double span = m_loopEnd - m_loopStart;
double under = m_loopStart - next;
if (span > 0.0) under = std::fmod(under, span);
next = m_loopEnd - under;
}
}
return next;
}
void AnimationControlController::setAnimationFrame(int ms)
{
if (!m_selectedEntity || m_selectedAnimation.empty()) return;
if (!m_selectedEntity->hasAnimationState(m_selectedAnimation)) return;
Ogre::AnimationState* state = m_selectedEntity->getAnimationState(m_selectedAnimation);
state->setTimePosition(ms / 1000.0f);
if (!m_selectedTrack || m_selectedTrack->getNumKeyFrames() == 0) {
if (m_currentKeyframe) {
m_updatingValues = true;
m_currentKeyframe = nullptr;
m_selectedTick = -1;
m_updatingValues = false;
emit keyframeTicksChanged();
emit currentKeyframeChanged();
}
return;
}
Ogre::KeyFrame* kf1 = nullptr;
Ogre::KeyFrame* kf2 = nullptr;
m_selectedTrack->getKeyFramesAtTime(ms / 1000.0f, &kf1, &kf2);
Ogre::TransformKeyFrame* closest = nullptr;
if (kf1 && kf2) {
float d1 = std::fabs(kf1->getTime() - ms / 1000.0f);
float d2 = std::fabs(kf2->getTime() - ms / 1000.0f);
closest = static_cast<Ogre::TransformKeyFrame*>(d1 <= d2 ? kf1 : kf2);
} else if (kf1) {
closest = static_cast<Ogre::TransformKeyFrame*>(kf1);
} else if (kf2) {
closest = static_cast<Ogre::TransformKeyFrame*>(kf2);
}
bool tickChanged = (closest != m_currentKeyframe);
m_currentKeyframe = closest;
if (m_currentKeyframe) {
int newTick = static_cast<int>(m_currentKeyframe->getTime() * 1000);
if (newTick != m_selectedTick) {
m_selectedTick = newTick;
tickChanged = true;
}
} else {
m_selectedTick = -1;
tickChanged = true;
}
if (tickChanged) emit keyframeTicksChanged();
if (m_currentKeyframe) pushKeyframeValues();
}
void AnimationControlController::refreshSliderTicks()
{
m_keyframeTicks.clear();
m_selectedTick = -1;
if (m_selectedTrack) {
for (unsigned short i = 0; i < m_selectedTrack->getNumKeyFrames(); ++i)
m_keyframeTicks.append(static_cast<int>(m_selectedTrack->getKeyFrame(i)->getTime() * 1000));
if (m_currentKeyframe)
m_selectedTick = static_cast<int>(m_currentKeyframe->getTime() * 1000);
}
emit keyframeTicksChanged();
// Dope-sheet view re-queries rows on the same signals as track-level
// changes (add/delete/move/select).
emit boneRowsChanged();
}
void AnimationControlController::onUndoRedoCommandApplied()
{
// Structural undo/redo (track destroy, keyframe add/remove) can
// invalidate cached pointers we hold. Drop them and re-resolve
// against the current skeleton state — but preserve the user's
// current bone selection (refreshBoneList would reset to the
// first bone, which is jarring).
m_selectedTrack = nullptr;
m_currentKeyframe = nullptr;
m_selectedTick = -1;
// Re-resolve m_selectedTrack from the active animation + bone, if
// both are still valid (the track may have been destroyed by an
// AddKeyframeCommand undo on a lazy-created track).
if (m_selectedSkeleton && !m_selectedAnimation.empty()
&& m_selectedSkeleton->hasAnimation(m_selectedAnimation)
&& !m_selectedBone.empty()
&& m_selectedSkeleton->hasBone(m_selectedBone))
{
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
for (const auto& pair : anim->_getNodeTrackList()) {
if (pair.second->getAssociatedNode()->getName() == m_selectedBone) {
m_selectedTrack = pair.second;
break;
}
}
}
refreshSliderTicks();
setAnimationFrame(m_sliderValue);
// The dope sheet + curve editor read keyTimes from allBoneRows(),
// which they refresh on boneRowsChanged. Without this emit, undo
// of a Bake leaves the QML views showing stale dense keyframes
// even though the underlying track has been reverted.
emit boneRowsChanged();
}
// ── Keyframe editing ──────────────────────────────────────────────────────────
bool AnimationControlController::hasPrevKeyframe() const
{
if (!m_selectedTrack || m_selectedTrack->getNumKeyFrames() == 0) return false;
float time = m_sliderValue / 1000.0f;
for (int i = static_cast<int>(m_selectedTrack->getNumKeyFrames()) - 1; i >= 0; --i) {
if (m_selectedTrack->getKeyFrame(i)->getTime() < time - 0.001f) return true;
}
return false;
}
bool AnimationControlController::hasNextKeyframe() const
{
if (!m_selectedTrack || m_selectedTrack->getNumKeyFrames() == 0) return false;
float time = m_sliderValue / 1000.0f;
for (unsigned short i = 0; i < m_selectedTrack->getNumKeyFrames(); ++i) {
if (m_selectedTrack->getKeyFrame(i)->getTime() > time + 0.001f) return true;
}
return false;
}
void AnimationControlController::prevKeyframe()
{
if (!m_selectedTrack || m_selectedTrack->getNumKeyFrames() == 0) return;
float time = m_sliderValue / 1000.0f;
Ogre::TransformKeyFrame* target = nullptr;
for (int i = static_cast<int>(m_selectedTrack->getNumKeyFrames()) - 1; i >= 0; --i) {
auto* kf = static_cast<Ogre::TransformKeyFrame*>(m_selectedTrack->getKeyFrame(i));
if (kf->getTime() < time - 0.001f) { target = kf; break; }
}
if (!target)
target = static_cast<Ogre::TransformKeyFrame*>(m_selectedTrack->getKeyFrame(0));
setSliderValue(static_cast<int>(target->getTime() * 1000));
}
void AnimationControlController::nextKeyframe()
{
if (!m_selectedTrack || m_selectedTrack->getNumKeyFrames() == 0) return;
float time = m_sliderValue / 1000.0f;
Ogre::TransformKeyFrame* target = nullptr;
for (unsigned short i = 0; i < m_selectedTrack->getNumKeyFrames(); ++i) {
auto* kf = static_cast<Ogre::TransformKeyFrame*>(m_selectedTrack->getKeyFrame(i));
if (kf->getTime() > time + 0.001f) { target = kf; break; }
}
if (!target)
target = static_cast<Ogre::TransformKeyFrame*>(
m_selectedTrack->getKeyFrame(m_selectedTrack->getNumKeyFrames() - 1));
setSliderValue(static_cast<int>(target->getTime() * 1000));
}
void AnimationControlController::addKeyframe()
{
if (!m_selectedEntity || m_selectedAnimation.empty()) return;
if (!m_selectedSkeleton || m_selectedBone.empty()) return;
if (!m_selectedSkeleton->hasBone(m_selectedBone)) return;
if (!m_selectedSkeleton->hasAnimation(m_selectedAnimation)) return;
// Determine the operation mode for undo: track-create vs.
// keyframe-create vs. keyframe-update.
const bool trackExisted = (m_selectedTrack != nullptr);
AddKeyframeCommand::Mode mode = AddKeyframeCommand::Mode::TrackCreated;
// Lazily create an animation track for this bone if it doesn't have
// one yet (non-rigged bones, or bones the imported animation didn't
// touch). Without this, the user's edit would be a runtime-only
// pose that vanishes on export.
if (!m_selectedTrack) {
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
Ogre::Bone* bone = m_selectedSkeleton->getBone(m_selectedBone);
m_selectedTrack = anim->createNodeTrack(bone->getHandle(), bone);
// Re-include this bone in the bone-list and rebuild the panel
// so subsequent +KF / dope-sheet operations see the new track.
QString boneNameStr = QString::fromStdString(m_selectedBone);
if (!m_boneNames.contains(boneNameStr))
m_boneNames << boneNameStr;
emit boneListChanged();
}
if (!m_selectedTrack) return;
const float time = m_sliderValue / 1000.0f;
// Reuse a keyframe at the same time if one already exists — the rest of
// this controller treats same-time collisions as invalid, and auto-key
// would otherwise stack duplicates on every drag-end at the same scrub
// time. Match the same epsilon used by deleteKeyframe (1 ms).
Ogre::TransformKeyFrame* existingKf = nullptr;
constexpr float kKeyframeEpsilon = 0.001f;
for (unsigned short i = 0; i < m_selectedTrack->getNumKeyFrames(); ++i) {
auto* existing = static_cast<Ogre::TransformKeyFrame*>(m_selectedTrack->getKeyFrame(i));
if (std::fabs(existing->getTime() - time) <= kKeyframeEpsilon) {
existingKf = existing;
break;
}
}
// Capture before-TRS so undo restores the keyframe's pre-edit state.
// Defaults are identity for the create paths (the keyframe didn't
// exist; undo will remove it instead of restoring values).
Ogre::Vector3 beforeT = Ogre::Vector3::ZERO;
Ogre::Quaternion beforeR = Ogre::Quaternion::IDENTITY;
Ogre::Vector3 beforeS = Ogre::Vector3::UNIT_SCALE;
if (existingKf) {
beforeT = existingKf->getTranslate();
beforeR = existingKf->getRotation();
beforeS = existingKf->getScale();
mode = AddKeyframeCommand::Mode::KeyframeUpdated;
} else if (trackExisted) {
mode = AddKeyframeCommand::Mode::KeyframeCreated;
}
// else: trackExisted == false → Mode::TrackCreated (already set above).
// Compute the after-TRS from the bone's current local pose
// (relative to its initial bind pose, the format
// TransformKeyFrame stores). Previously this used
// getInterpolatedKeyFrame, which samples the existing animation
// curve at `time` and produces an identity-ish keyframe whenever
// the curve is flat there — the user-visible "blank registry"
// bug. With this change, hitting +KF after dragging the scene
// node (or, via the bone gizmo, the bone directly) captures the
// actual pose under the cursor at that scrub time.
const Ogre::Bone* bone = m_selectedSkeleton->getBone(m_selectedBone);
const Ogre::Vector3 afterT = bone->getPosition() - bone->getInitialPosition();
const Ogre::Quaternion afterR = bone->getInitialOrientation().Inverse() * bone->getOrientation();
const Ogre::Vector3 afterS = bone->getScale() / bone->getInitialScale();
// QUndoStack::push() executes redo() immediately, which performs the
// actual write. Pushing the command both creates the keyframe and
// makes it undoable.
auto* cmd = new AddKeyframeCommand( // NOSONAR — QUndoStack owns
m_selectedEntityName,
m_selectedAnimation,
m_selectedBone,
time,
mode,
beforeT, beforeR, beforeS,
afterT, afterR, afterS);
UndoManager::getSingleton()->push(cmd);
refreshSliderTicks();
setAnimationFrame(m_sliderValue);
}
void AnimationControlController::deleteKeyframe()
{
if (!m_selectedTrack || !m_currentKeyframe) return;
// Capture the keyframe's TRS so the undo path can restore it.
const float t = m_currentKeyframe->getTime();
const Ogre::Vector3 keyT = m_currentKeyframe->getTranslate();
const Ogre::Quaternion keyR = m_currentKeyframe->getRotation();
const Ogre::Vector3 keyS = m_currentKeyframe->getScale();
// Push the command — its redo() removes the keyframe. Drop our
// cached pointer first since the command will invalidate it.
m_currentKeyframe = nullptr;
m_selectedTick = -1;
auto* cmd = new DeleteKeyframeCommand( // NOSONAR — QUndoStack owns
m_selectedEntityName,
m_selectedAnimation,
m_selectedBone,
t, keyT, keyR, keyS);
UndoManager::getSingleton()->push(cmd);
refreshSliderTicks();
setAnimationFrame(m_sliderValue);
}
void AnimationControlController::pushKeyframeValues()
{
if (!m_currentKeyframe) return;
m_updatingValues = true;
Ogre::Vector3 t = m_currentKeyframe->getTranslate();
Ogre::Vector3 s = m_currentKeyframe->getScale();
Ogre::Quaternion r = m_currentKeyframe->getRotation();
m_kfTransX = t.x; m_kfTransY = t.y; m_kfTransZ = t.z;
m_kfScaleX = s.x; m_kfScaleY = s.y; m_kfScaleZ = s.z;
m_kfRotW = r.w; m_kfRotX = r.x; m_kfRotY = r.y; m_kfRotZ = r.z;
m_updatingValues = false;
emit currentKeyframeChanged();
}
void AnimationControlController::notifyOgreUpdate()
{
if (!m_selectedEntity || m_selectedAnimation.empty()) return;
m_selectedEntity->getAllAnimationStates()->_notifyDirty();
auto* state = m_selectedEntity->getAnimationState(m_selectedAnimation);
state->setTimePosition(state->getTimePosition());
}
// ── Keyframe value setters ────────────────────────────────────────────────────
#define KF_SET_TRANS(AXIS, FIELD) \
void AnimationControlController::setKfTrans##AXIS(double v) { \
if (m_updatingValues || !m_currentKeyframe) return; \
Ogre::Vector3 t = m_currentKeyframe->getTranslate(); \
t.FIELD = static_cast<float>(v); \
m_currentKeyframe->setTranslate(t); \
m_kfTrans##AXIS = v; \
notifyOgreUpdate(); \
}
#define KF_SET_SCALE(AXIS, FIELD) \
void AnimationControlController::setKfScale##AXIS(double v) { \
if (m_updatingValues || !m_currentKeyframe) return; \
Ogre::Vector3 s = m_currentKeyframe->getScale(); \
s.FIELD = static_cast<float>(v); \
m_currentKeyframe->setScale(s); \
m_kfScale##AXIS = v; \
notifyOgreUpdate(); \
}
#define KF_SET_ROT(AXIS, FIELD) \
void AnimationControlController::setKfRot##AXIS(double v) { \
if (m_updatingValues || !m_currentKeyframe) return; \
Ogre::Quaternion r = m_currentKeyframe->getRotation(); \
r.FIELD = static_cast<float>(v); \
m_currentKeyframe->setRotation(r); \
m_kfRot##AXIS = v; \
notifyOgreUpdate(); \
}
KF_SET_TRANS(X, x)
KF_SET_TRANS(Y, y)
KF_SET_TRANS(Z, z)
KF_SET_SCALE(X, x)
KF_SET_SCALE(Y, y)
KF_SET_SCALE(Z, z)
KF_SET_ROT(W, w)
KF_SET_ROT(X, x)
KF_SET_ROT(Y, y)
KF_SET_ROT(Z, z)
// ── Dope sheet API (slice C) ──────────────────────────────────────────────────
namespace {
// A channel is "active" on a track if any keyframe's value differs from the
// channel's identity (translate.x = 0, rotation = 1+0i+0j+0k, scale = 1) by
// more than this epsilon. Tighter than kBulkEpsilon since these are values,
// not times — a 1mm translate is meaningful.
constexpr float kChannelEpsilon = 1e-4f;
// Returns the 9 boolean channel flags for a track in TRS order:
// {tx, ty, tz, rw, rx, ry, rz, sx, sy, sz}.
// Only flags whose values deviate from identity are set.
//
// Rotation identity covers BOTH (+1, 0, 0, 0) AND (-1, 0, 0, 0) — a
// quaternion and its negative encode the same rotation. Naive component-
// wise comparison would flag rw as active for a sign-flipped identity,
// producing bogus chevrons. We compare against the absolute values
// instead: |w| ≈ 1, |x| ≈ |y| ≈ |z| ≈ 0 means identity regardless of sign.
QVariantMap collectActiveChannels(const Ogre::NodeAnimationTrack* track)
{
bool tx = false, ty = false, tz = false;
bool rw = false, rx = false, ry = false, rz = false;
bool sx = false, sy = false, sz = false;
for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) {
const auto* kf = static_cast<const Ogre::TransformKeyFrame*>(track->getKeyFrame(i));
const Ogre::Vector3 t = kf->getTranslate();
const Ogre::Quaternion r = kf->getRotation();
const Ogre::Vector3 s = kf->getScale();
if (std::fabs(t.x) > kChannelEpsilon) tx = true;
if (std::fabs(t.y) > kChannelEpsilon) ty = true;
if (std::fabs(t.z) > kChannelEpsilon) tz = true;
// Sign-agnostic rotation identity check — see header comment.
if (std::fabs(std::fabs(r.w) - 1.0f) > kChannelEpsilon) rw = true;
if (std::fabs(r.x) > kChannelEpsilon) rx = true;
if (std::fabs(r.y) > kChannelEpsilon) ry = true;
if (std::fabs(r.z) > kChannelEpsilon) rz = true;
// Scale identity = (1, 1, 1).
if (std::fabs(s.x - 1.0f) > kChannelEpsilon) sx = true;
if (std::fabs(s.y - 1.0f) > kChannelEpsilon) sy = true;
if (std::fabs(s.z - 1.0f) > kChannelEpsilon) sz = true;
}
QVariantMap m;
m[QStringLiteral("tx")] = tx; m[QStringLiteral("ty")] = ty; m[QStringLiteral("tz")] = tz;
m[QStringLiteral("rw")] = rw; m[QStringLiteral("rx")] = rx;
m[QStringLiteral("ry")] = ry; m[QStringLiteral("rz")] = rz;
m[QStringLiteral("sx")] = sx; m[QStringLiteral("sy")] = sy; m[QStringLiteral("sz")] = sz;
return m;
}
} // namespace
QVariantList AnimationControlController::allBoneRows() const
{
QVariantList rows;
if (!m_selectedSkeleton || m_selectedAnimation.empty()) return rows;
if (!m_selectedSkeleton->hasAnimation(m_selectedAnimation)) return rows;
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
for (const auto& [handle, track] : anim->_getNodeTrackList()) {
Ogre::Node* node = track->getAssociatedNode();
if (!node) continue;
QVariantList keyTimes;
keyTimes.reserve(static_cast<int>(track->getNumKeyFrames()));
for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) {
keyTimes.append(static_cast<double>(track->getKeyFrame(i)->getTime()));
}
QVariantMap row;
row[QStringLiteral("bone")] = QString::fromStdString(node->getName());
row[QStringLiteral("keyTimes")] = keyTimes;
row[QStringLiteral("channels")] = collectActiveChannels(track);
rows.append(row);
}
return rows;
}
QVariantList AnimationControlController::allMorphRows() const
{
QVariantList rows;
auto* sel = SelectionSet::getSingleton();
if (!sel) return rows;
const auto entities = sel->getResolvedEntities();
if (entities.isEmpty() || !entities.first()) return rows;
Ogre::Entity* entity = entities.first();
if (!entity) return rows;
Ogre::MeshPtr mesh = entity->getMesh();
if (!mesh) return rows;
const Ogre::PoseList& poseList = mesh->getPoseList();
if (poseList.empty()) return rows;
// Each pose has a matching `Ogre::Animation` (see MeshProcessor:
// import-time one-animation-per-pose pattern). Read the keyframe
// times off the animation's VAT_POSE track; in A1 every animation
// carries a single t=0 keyframe, but future slices may add more.
for (const Ogre::Pose* pose : poseList) {
if (!pose) continue;
const Ogre::String poseName = pose->getName();
if (poseName.empty()) continue;
QVariantList keyTimes;
if (mesh->hasAnimation(poseName)) {
// The importer (MeshProcessor) groups same-named poses
// across submeshes into a single Animation with one
// VAT_POSE track per submesh. Pull only the track
// matching this pose's target handle — otherwise a
// shape that appears on body + head would show its
// diamonds twice in the dope sheet.
Ogre::Animation* anim = mesh->getAnimation(poseName);
const unsigned short handle = pose->getTarget();
if (anim->hasVertexTrack(handle)) {
Ogre::VertexAnimationTrack* track = anim->getVertexTrack(handle);
if (track && track->getAnimationType() == Ogre::VAT_POSE) {
for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i)
keyTimes.append(static_cast<double>(track->getKeyFrame(i)->getTime()));
}
}
}
QVariantMap row;
row[QStringLiteral("name")] = QString::fromStdString(poseName);
row[QStringLiteral("keyTimes")] = keyTimes;
rows.append(row);
}
return rows;
}
bool AnimationControlController::moveKeyframe(const QString& boneName,
double oldTime, double newTime)
{
if (boneName.isEmpty()) return false;
if (!m_selectedSkeleton || m_selectedAnimation.empty()) return false;
if (!m_selectedSkeleton->hasAnimation(m_selectedAnimation)) return false;
if (qFuzzyCompare(oldTime + 1.0, newTime + 1.0)) return false;
// Validate up-front so we never push a no-op onto the undo stack.
// The command's internal validation is the source of truth, but
// duplicating the find-source-keyframe + collision-check here lets
// us return false without polluting the undo history.
Ogre::Animation* anim = m_selectedSkeleton->getAnimation(m_selectedAnimation);
const std::string boneStd = boneName.toStdString();
if (!m_selectedSkeleton->hasBone(boneStd)) return false;
Ogre::Bone* bone = m_selectedSkeleton->getBone(boneStd);
if (!bone || !anim->hasNodeTrack(bone->getHandle())) return false;
Ogre::NodeAnimationTrack* track = anim->getNodeTrack(bone->getHandle());
constexpr float kEpsilon = 0.001f;
int sourceIdx = -1;
for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) {
if (std::fabs(track->getKeyFrame(i)->getTime() - static_cast<float>(oldTime)) <= kEpsilon) {
sourceIdx = static_cast<int>(i);
break;
}
}
if (sourceIdx < 0) return false; // no keyframe at oldTime
for (unsigned short i = 0; i < track->getNumKeyFrames(); ++i) {
if (static_cast<int>(i) == sourceIdx) continue;
if (std::fabs(track->getKeyFrame(i)->getTime() - static_cast<float>(newTime)) <= kEpsilon) {
return false; // collision with another existing keyframe
}
}
// QUndoStack::push() takes ownership of the command — this raw new is
// the standard QUndoCommand idiom (mirrors TransformCommands callers).
auto* cmd = new MoveKeyframeCommand(m_selectedEntityName, // NOSONAR — QUndoStack owns
m_selectedAnimation,
boneStd,
static_cast<float>(oldTime),
static_cast<float>(newTime));
UndoManager::getSingleton()->push(cmd);
// The command's redo() ran inside push(); refresh the slider ticks for
// the currently-edited bone and signal QML views to re-read rows.
refreshSliderTicks();
emit boneRowsChanged();
return true;