summaryrefslogtreecommitdiffstats
path: root/src/animation/backend/animationutils_p.h
blob: 6750e1ad8a5a1117982d41b23073ef0d4060d781 (plain)
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
/****************************************************************************
**
** Copyright (C) 2017 Klaralvdalens Datakonsult AB (KDAB).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt3D module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:COMM$
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** $QT_END_LICENSE$
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
**
****************************************************************************/

#ifndef QT3DANIMATION_ANIMATION_ANIMATIONUTILS_P_H
#define QT3DANIMATION_ANIMATION_ANIMATIONUTILS_P_H

//
//  W A R N I N G
//  -------------
//
// This file is not part of the Qt API.  It exists for the convenience
// of other Qt classes.  This header file may change from version to
// version without notice, or even be removed.
//
// We mean it.
//

#include <Qt3DAnimation/private/qt3danimation_global_p.h>
#include <Qt3DAnimation/private/clock_p.h>
#include <Qt3DAnimation/qanimationcallback.h>
#include <Qt3DCore/qnodeid.h>
#include <Qt3DCore/qscenechange.h>
#include <Qt3DCore/private/sqt_p.h>

#include <QtCore/qbitarray.h>
#include <QtCore/qdebug.h>
#include <qmath.h>

QT_BEGIN_NAMESPACE

namespace Qt3DAnimation {
class QAnimationCallback;
namespace Animation {

struct Channel;
class BlendedClipAnimator;
class Handler;
class AnimationClip;
class ChannelMapper;
class ChannelMapping;

typedef QVector<int> ComponentIndices;

enum JointTransformComponent {
    NoTransformComponent = 0,
    Scale,
    Rotation,
    Translation
};

struct MappingData
{
    Qt3DCore::QNodeId targetId;
    Skeleton *skeleton = nullptr;
    int jointIndex = -1;
    JointTransformComponent jointTransformComponent = NoTransformComponent;
    const char *propertyName;
    QAnimationCallback *callback = nullptr;
    QAnimationCallback::Flags callbackFlags;
    int type;
    ComponentIndices channelIndices;
};

#ifndef QT_NO_DEBUG_STREAM
inline QDebug operator<<(QDebug dbg, const MappingData &mapping)
{
    QDebugStateSaver saver(dbg);
    dbg << "targetId =" << mapping.targetId << Qt::endl
        << "jointIndex =" << mapping.jointIndex << Qt::endl
        << "jointTransformComponent: " << mapping.jointTransformComponent << Qt::endl
        << "propertyName:" << mapping.propertyName << Qt::endl
        << "channelIndices:" << mapping.channelIndices;
    return dbg;
}
#endif

struct AnimatorEvaluationData
{
    double elapsedTime;
    double currentTime;
    int loopCount;
    int currentLoop;
    double playbackRate;
    float normalizedLocalTime;
};

struct ClipEvaluationData
{
    int currentLoop;
    float normalizedLocalTime;
    double localTime;
    bool isFinalFrame;
};

typedef QVector<float> ClipResults;

struct ChannelNameAndType
{
    QString jointName;
    QString name;
    int type;
    int jointIndex;
    Qt3DCore::QNodeId mappingId;
    JointTransformComponent jointTransformComponent;
    int componentCount;

    static const int invalidIndex = -1;

    ChannelNameAndType()
        : jointName()
        , name()
        , type(-1)
        , jointIndex(-1)
        , mappingId()
        , jointTransformComponent(NoTransformComponent)
        , componentCount(-1)
    {}

    ChannelNameAndType(const QString &_name,
                       int _type,
                       int componentCount,
                       Qt3DCore::QNodeId _mappingId = Qt3DCore::QNodeId(),
                       int _jointIndex = invalidIndex)
        : jointName()
        , name(_name)
        , type(_type)
        , jointIndex(_jointIndex)
        , mappingId(_mappingId)
        , jointTransformComponent(NoTransformComponent)
        , componentCount(componentCount)
    {}

    ChannelNameAndType(const QString &_name,
                       int _type,
                       JointTransformComponent _jointTransformComponent)
        : jointName()
        , name(_name)
        , type(_type)
        , jointIndex(invalidIndex)
        , mappingId()
        , jointTransformComponent(_jointTransformComponent)
        , componentCount(-1)
    {
        switch (_jointTransformComponent) {
        case  NoTransformComponent:
            break;
        case Scale:
        case Translation:
            componentCount = 3;
            break;
        case Rotation:
            componentCount = 4;
            break;
        }
    }

    bool operator==(const ChannelNameAndType &rhs) const
    {
        return name == rhs.name
            && type == rhs.type
            && jointIndex == rhs.jointIndex
            && mappingId == rhs.mappingId
            && jointTransformComponent == rhs.jointTransformComponent
            && componentCount == rhs.componentCount;
    }
};

#ifndef QT_NO_DEBUG_STREAM
inline QDebug operator<<(QDebug dbg, const ChannelNameAndType &nameAndType)
{
    QDebugStateSaver saver(dbg);
    dbg << "name =" << nameAndType.name
        << "type =" << nameAndType.type
        << "mappingId =" << nameAndType.mappingId
        << "jointIndex =" << nameAndType.jointIndex
        << "jointName =" << nameAndType.jointName
        << "jointTransformComponent =" << nameAndType.jointTransformComponent
        << "componentCount =" << nameAndType.componentCount;
    return dbg;
}
#endif

struct ComponentValue
{
    int componentIndex;
    float value;
};
QT3D_DECLARE_TYPEINFO_2(Qt3DAnimation, Animation, ComponentValue, Q_PRIMITIVE_TYPE)

struct ClipFormat
{
    // TODO: Remove the mask and store both the sourceClipIndices and
    // formattedComponentIndices in flat vectors. This will require a
    // way to look up the offset and number of elements for each channel.
    ComponentIndices sourceClipIndices;
    QVector<QBitArray> sourceClipMask;
    QVector<ComponentIndices> formattedComponentIndices;
    QVector<ChannelNameAndType> namesAndTypes;
    QVector<ComponentValue> defaultComponentValues;
};

#ifndef QT_NO_DEBUG_STREAM
inline QDebug operator<<(QDebug dbg, const ClipFormat &format)
{
    QDebugStateSaver saver(dbg);
    int sourceIndex = 0;
    for (int i = 0; i < format.namesAndTypes.size(); ++i) {
        dbg << i
            << format.namesAndTypes[i].jointIndex
            << format.namesAndTypes[i].jointName
            << format.namesAndTypes[i].name
            << format.namesAndTypes[i].type
            << "formatted results dst indices =" << format.formattedComponentIndices[i];
        const int componentCount = format.formattedComponentIndices[i].size();

        dbg << "clip src indices =";
        for (int j = sourceIndex; j < sourceIndex + componentCount; ++j)
            dbg << format.sourceClipIndices[j] << "";

        dbg << "src clip mask =" << format.sourceClipMask[i];
        dbg << Qt::endl;
        sourceIndex += componentCount;
    }
    return dbg;
}
#endif

struct AnimationCallbackAndValue
{
    QAnimationCallback *callback;
    QAnimationCallback::Flags flags;
    QVariant value;
};

struct AnimationRecord {
    struct TargetChange {
        TargetChange(Qt3DCore::QNodeId id, const char *name, QVariant v)
            : targetId(id), propertyName(name), value(v) {

        }

        Qt3DCore::QNodeId targetId;
        const char *propertyName = nullptr;
        QVariant value;
    };

    Qt3DCore::QNodeId animatorId;
    QVector<TargetChange> targetChanges;
    QVector<QPair<Qt3DCore::QNodeId, QVector<Qt3DCore::Sqt>>> skeletonChanges;
    float normalizedTime = -1.f;
    bool finalFrame = false;
};

Q_AUTOTEST_EXPORT
AnimationRecord prepareAnimationRecord(Qt3DCore::QNodeId animatorId,
                                       const QVector<MappingData> &mappingDataVec,
                                       const QVector<float> &channelResults,
                                       bool finalFrame,
                                       float normalizedLocalTime);

inline constexpr double toSecs(qint64 nsecs) { return nsecs / 1.0e9; }
inline qint64 toNsecs(double seconds) { return qRound64(seconds * 1.0e9); }

template<typename Animator>
AnimatorEvaluationData evaluationDataForAnimator(Animator animator,
                                                 Clock* clock,
                                                 qint64 nsSincePreviousFrame)
{
    const bool seeking = animator->isSeeking();
    AnimatorEvaluationData data;
    data.loopCount = animator->loops();
    data.currentLoop = animator->currentLoop();
    // The playback-rate is always 1.0 when seeking
    data.playbackRate = ((clock != nullptr) && !seeking) ? clock->playbackRate() : 1.0;
    // Convert global time from nsec to sec
    data.elapsedTime = toSecs(nsSincePreviousFrame);
    // When seeking we base it on the current time being at the start of the clip
    data.currentTime = seeking ? 0.0 : animator->lastLocalTime();
    // If we're not seeking the local normalized time will be calculate in
    // evaluationDataForClip().
    data.normalizedLocalTime = seeking ? animator->normalizedLocalTime() : -1.0;
    return data;
}

inline bool isFinalFrame(double localTime,
                         double duration,
                         int currentLoop,
                         int loopCount,
                         double playbackRate)
{
    // We must be on the final loop and
    // - if playing forward, localTime must be equal or above the duration
    // - if playing backward, localTime must be equal or below 0
    if (playbackRate >= 0.0)
        return (loopCount != 0 && currentLoop >= loopCount - 1 && localTime >= duration);
    return (loopCount != 0  && currentLoop <= 0 && localTime <= 0);
}

inline bool isValidNormalizedTime(float t)
{
    return !(t < 0.0f) && !(t > 1.0f);
}

Q_AUTOTEST_EXPORT
ClipEvaluationData evaluationDataForClip(AnimationClip *clip,
                                         const AnimatorEvaluationData &animatorData);

Q_AUTOTEST_EXPORT
ComponentIndices channelComponentsToIndices(const Channel &channel,
                                            int dataType,
                                            int expectedComponentCount,
                                            int offset);

Q_AUTOTEST_EXPORT
ComponentIndices channelComponentsToIndicesHelper(const Channel &channelGroup,
                                                  int expectedComponentCount,
                                                  int offset,
                                                  const QVector<char> &suffixes);

Q_AUTOTEST_EXPORT
ClipResults evaluateClipAtLocalTime(AnimationClip *clip,
                                    float localTime);

Q_AUTOTEST_EXPORT
ClipResults evaluateClipAtPhase(AnimationClip *clip,
                                float phase);

Q_AUTOTEST_EXPORT
QVector<AnimationCallbackAndValue> prepareCallbacks(const QVector<MappingData> &mappingDataVec,
                                                    const QVector<float> &channelResults);

Q_AUTOTEST_EXPORT
QVector<MappingData> buildPropertyMappings(const QVector<ChannelMapping *> &channelMappings,
                                           const QVector<ChannelNameAndType> &channelNamesAndTypes,
                                           const QVector<ComponentIndices> &channelComponentIndices,
                                           const QVector<QBitArray> &sourceClipMask);

Q_AUTOTEST_EXPORT
QVector<ChannelNameAndType> buildRequiredChannelsAndTypes(Handler *handler,
                                                          const ChannelMapper *mapper);

Q_AUTOTEST_EXPORT
QVector<ComponentIndices> assignChannelComponentIndices(const QVector<ChannelNameAndType> &namesAndTypes);

Q_AUTOTEST_EXPORT
double localTimeFromElapsedTime(double t_current_local, double t_elapsed_global,
                                double playbackRate, double duration,
                                int loopCount, int &currentLoop);

Q_AUTOTEST_EXPORT
double phaseFromElapsedTime(double t_current_local, double t_elapsed_global,
                           double playbackRate, double duration,
                           int loopCount, int &currentLoop);

Q_AUTOTEST_EXPORT
QVector<Qt3DCore::QNodeId> gatherValueNodesToEvaluate(Handler *handler,
                                                      Qt3DCore::QNodeId blendTreeRootId);

Q_AUTOTEST_EXPORT
ClipFormat generateClipFormatIndices(const QVector<ChannelNameAndType> &targetChannels,
                                     const QVector<ComponentIndices> &targetIndices,
                                     const AnimationClip *clip);

Q_AUTOTEST_EXPORT
ClipResults formatClipResults(const ClipResults &rawClipResults,
                              const ComponentIndices &format);

Q_AUTOTEST_EXPORT
ClipResults evaluateBlendTree(Handler *handler,
                              BlendedClipAnimator *animator,
                              Qt3DCore::QNodeId blendNodeId);

Q_AUTOTEST_EXPORT
QVector<float> defaultValueForChannel(Handler *handler, const ChannelNameAndType &channelDescription);

Q_AUTOTEST_EXPORT
void applyComponentDefaultValues(const QVector<ComponentValue> &componentDefaults,
                                 ClipResults &formattedClipResults);

} // Animation
} // Qt3DAnimation

QT_END_NAMESPACE

Q_DECLARE_METATYPE(Qt3DAnimation::Animation::AnimationRecord) // LCOV_EXCL_LINE


#endif // QT3DANIMATION_ANIMATION_ANIMATIONUTILS_P_H