summaryrefslogtreecommitdiffstats
path: root/src/animation/backend/animationutils.cpp
blob: 65a4551449d898530cb2955d881e00229d7ad13e (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
/****************************************************************************
**
** 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:LGPL3$
** 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 http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or later as published by the Free
** Software Foundation and appearing in the file LICENSE.GPL included in
** the packaging of this file. Please review the following information to
** ensure the GNU General Public License version 2.0 requirements will be
** met: http://www.gnu.org/licenses/gpl-2.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "animationutils_p.h"
#include <Qt3DAnimation/private/handler_p.h>
#include <Qt3DAnimation/private/managers_p.h>
#include <Qt3DCore/qpropertyupdatedchange.h>
#include <Qt3DCore/private/qpropertyupdatedchangebase_p.h>
#include <QtGui/qvector2d.h>
#include <QtGui/qvector3d.h>
#include <QtGui/qvector4d.h>
#include <QtGui/qquaternion.h>
#include <QtCore/qvariant.h>
#include <Qt3DAnimation/private/animationlogging_p.h>

QT_BEGIN_NAMESPACE

namespace Qt3DAnimation {
namespace Animation {

double AnimationUtils::localTimeFromGlobalTime(double t_global,
                                               double t_start_global,
                                               double playbackRate,
                                               double duration,
                                               int loopCount,
                                               int &currentLoop)
{
    double t_local = playbackRate * (t_global - t_start_global);
    double loopNumber = 0;
    if (loopCount == 1) {
        t_local = qBound(0.0, t_local, duration);
    } else if (loopCount == 0) {
        // Loops forever
        (void) std::modf(t_local / duration, &loopNumber);
        t_local = std::fmod(t_local, duration);
    } else {
        // N loops
        t_local = qBound(0.0, t_local, double(loopCount) * duration);
        (void) std::modf(t_local / duration, &loopNumber);
        t_local = std::fmod(t_local, duration);

        // Ensure we clamp to end of final loop
        if (loopNumber == loopCount) {
            loopNumber = loopCount - 1;
            t_local = duration;
        }
    }

    qCDebug(Jobs) << "t_global - t_start =" << t_global - t_start_global
                  << "current loop =" << loopNumber
                  << "t =" << t_local
                  << "duration =" << duration;

    currentLoop = loopNumber;

    return t_local;
}

QVector<int> AnimationUtils::channelsToIndices(const ChannelGroup &channelGroup, int dataType, int offset)
{
    static const QStringList standardSuffixes = (QStringList()
                                                 << QLatin1String("x")
                                                 << QLatin1String("y")
                                                 << QLatin1String("z")
                                                 << QLatin1String("w"));
    static const QStringList quaternionSuffixes = (QStringList()
                                                   << QLatin1String("w")
                                                   << QLatin1String("x")
                                                   << QLatin1String("y")
                                                   << QLatin1String("z"));

    if (dataType != QVariant::Quaternion)
        return channelsToIndicesHelper(channelGroup, dataType, offset, standardSuffixes);
    else
        return channelsToIndicesHelper(channelGroup, dataType, offset, quaternionSuffixes);

}

QVector<int> AnimationUtils::channelsToIndicesHelper(const ChannelGroup &channelGroup, int dataType, int offset, const QStringList &suffixes)
{
    int expectedChannelCount = 1;
    switch (dataType) {
    case QVariant::Double:
        expectedChannelCount = 1;
        break;

    case QVariant::Vector2D:
        expectedChannelCount = 2;
        break;

    case QVariant::Vector3D:
        expectedChannelCount = 3;
        break;

    case QVariant::Vector4D:
    case QVariant::Quaternion:
        expectedChannelCount = 4;
        break;

    default:
        qWarning() << "Unhandled animation type";
    }

    const int foundChannelCount = channelGroup.channels.size();
    if (foundChannelCount != expectedChannelCount) {
        qWarning() << "Data type expects" << expectedChannelCount
                   << "but found" << foundChannelCount << "channels in the animation clip";
    }

    QVector<int> indices(expectedChannelCount);
    for (int i = 0; i < expectedChannelCount; ++i) {
        int index = suffixes.indexOf(channelGroup.channels[i].name);
        if (index != -1)
            indices[i] = index + offset;
        else
            indices[i] = -1;
    }
    return indices;
}

QVector<float> AnimationUtils::evaluateAtGlobalTime(AnimationClip *clip,
                                                    qint64 globalTime,
                                                    qint64 startTime,
                                                    int loopCount,
                                                    int &currentLoop,
                                                    bool &finalFrame)
{
    // Calculate local time from global time
    const double t_global = double(globalTime) / 1.0e9;
    const double t_start_global = double(startTime) / 1.0e9;
    const double playbackRate = 1.0; // Assume standard playback rate for now
    const double duration = clip->duration();

    const double localTime = localTimeFromGlobalTime(t_global, t_start_global,
                                                     playbackRate, duration,
                                                     loopCount, currentLoop);
    return AnimationUtils::evaluateAtLocalTime(clip, localTime,
                                               currentLoop, loopCount,
                                               finalFrame);
}

QVector<float> AnimationUtils::evaluateAtLocalTime(AnimationClip *clip, float localTime,
                                                   int currentLoop, int loopCount,
                                                   bool &finalFrame)
{
    QVector<float> channelResults;
    Q_ASSERT(clip);

    // TODO: Uncomment when we add loopCount property
    if (localTime >= clip->duration()
            && loopCount != 0
            && currentLoop == loopCount - 1)
        finalFrame = true;

    // Ensure we have enough storage to hold the evaluations
    channelResults.resize(clip->channelCount());

    // Iterate over channels and evaluate the fcurves
    const QVector<ChannelGroup> &channelGroups = clip->channelGroups();
    int i = 0;
    for (const ChannelGroup &channelGroup : channelGroups) {
        for (const auto channel : qAsConst(channelGroup.channels))
            channelResults[i++] = channel.fcurve.evaluateAtTime(localTime);
    }
    return channelResults;
}

QVector<Qt3DCore::QSceneChangePtr> AnimationUtils::preparePropertyChanges(Qt3DCore::QNodeId peerId,
                                                                          const QVector<MappingData> &mappingDataVec,
                                                                          const QVector<float> &channelResults,
                                                                          bool finalFrame)
{
    QVector<Qt3DCore::QSceneChangePtr> changes;
    // Iterate over the mappings
    for (const MappingData &mappingData : mappingDataVec) {
        // Construct a property update change, set target, property and delivery options
        auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(mappingData.targetId);
        e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll);
        e->setPropertyName(mappingData.propertyName);

        // Handle intermediate updates vs final flag properly
        Qt3DCore::QPropertyUpdatedChangeBasePrivate::get(e.data())->m_isFinal = finalFrame;

        // Build the new value from the channel/fcurve evaluation results
        QVariant v;
        switch (mappingData.type) {
        case QVariant::Double: {
            v = QVariant::fromValue(channelResults[mappingData.channelIndices[0]]);
            break;
        }

        case QVariant::Vector2D: {
            const QVector2D vector(channelResults[mappingData.channelIndices[0]],
                    channelResults[mappingData.channelIndices[1]]);
            v = QVariant::fromValue(vector);
            break;
        }

        case QVariant::Vector3D: {
            const QVector3D vector(channelResults[mappingData.channelIndices[0]],
                    channelResults[mappingData.channelIndices[1]],
                    channelResults[mappingData.channelIndices[2]]);
            v = QVariant::fromValue(vector);
            break;
        }

        case QVariant::Vector4D: {
            const QVector4D vector(channelResults[mappingData.channelIndices[0]],
                    channelResults[mappingData.channelIndices[1]],
                    channelResults[mappingData.channelIndices[2]],
                    channelResults[mappingData.channelIndices[3]]);
            v = QVariant::fromValue(vector);
            break;
        }

        case QVariant::Quaternion: {
            QQuaternion q(channelResults[mappingData.channelIndices[0]],
                    channelResults[mappingData.channelIndices[1]],
                    channelResults[mappingData.channelIndices[2]],
                    channelResults[mappingData.channelIndices[3]]);
            q.normalize();
            v = QVariant::fromValue(q);
            break;
        }

        default:
            qWarning() << "Unhandled animation type";
            continue;
        }

        // Assign new value and send
        e->setValue(v);
        changes.push_back(e);
    }


    // If it's the final frame, notify the frontend that we've stopped
    if (finalFrame) {
        auto e = Qt3DCore::QPropertyUpdatedChangePtr::create(peerId);
        e->setDeliveryFlags(Qt3DCore::QSceneChange::DeliverToAll);
        e->setPropertyName("running");
        e->setValue(false);
        Qt3DCore::QPropertyUpdatedChangeBasePrivate::get(e.data())->m_isFinal = true;
        changes.push_back(e);
    }
    return changes;
}

QVector<AnimationUtils::MappingData> AnimationUtils::buildPropertyMappings(Handler *handler, const AnimationClip *clip, const ChannelMapper *mapper)
{
    QVector<MappingData> mappingDataVec;
    ChannelMappingManager *mappingManager = handler->channelMappingManager();
    const QVector<ChannelGroup> &channelGroups = clip->channelGroups();

    // Iterate over the mappings in the mapper object
    for (const Qt3DCore::QNodeId mappingId : mapper->mappingIds()) {
        // Get the mapping object
        ChannelMapping *mapping = mappingManager->lookupResource(mappingId);
        Q_ASSERT(mapping);

        // Populate the data we need, easy stuff first
        MappingData mappingData;
        mappingData.targetId = mapping->targetId();
        mappingData.propertyName = mapping->propertyName();
        mappingData.type = mapping->type();

        if (mappingData.type == static_cast<int>(QVariant::Invalid)) {
            qWarning() << "Unknown type for node id =" << mappingData.targetId
                       << "and property =" << mapping->property();
            continue;
        }

        // Now the tricky part. Mapping the channel indices onto the property type.
        // Try to find a ChannelGroup with matching name
        const QString channelName = mapping->channelName();
        int channelGroupIndex = 0;
        bool foundMatch = false;
        for (const ChannelGroup &channelGroup : channelGroups) {
            if (channelGroup.name == channelName) {
                foundMatch = true;
                const int channelBaseIndex = clip->channelBaseIndex(channelGroupIndex);

                // Within this group, match channel names with index ordering
                mappingData.channelIndices = channelsToIndices(channelGroup, mappingData.type, channelBaseIndex);

                // Store the mapping data
                mappingDataVec.push_back(mappingData);

                if (foundMatch)
                    break;
            }

            ++channelGroupIndex;
        }
    }

    return mappingDataVec;
}


} // Animation
} // Qt3DAnimation

QT_END_NAMESPACE