aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/skotty/SkottyAnimator.h
blob: 1b519c9aa66e515c9fbe0de8a37cc7e95b0d3b66 (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
/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#ifndef SkottyAnimator_DEFINED
#define SkottyAnimator_DEFINED

#include "SkCubicMap.h"
#include "SkMakeUnique.h"
#include "SkottyPriv.h"
#include "SkottyProperties.h"
#include "SkTArray.h"
#include "SkTypes.h"

#include <functional>
#include <memory>

namespace skotty {

class AnimatorBase : public SkNoncopyable {
public:
    virtual ~AnimatorBase() = default;

    virtual void tick(SkMSec) = 0;

protected:
    AnimatorBase() = default;

    // Compute a cubic-Bezier-interpolated t relative to [t0..t1].
    static float ComputeLocalT(float t, float t0, float t1,
                               const SkCubicMap*);
};

// Describes a keyframe interpolation interval (v0@t0) -> (v1@t1).
// TODO: add interpolation params.
template <typename T>
struct KeyframeInterval {
    // Start/end values.
    T       fV0,
            fV1;

    // Start/end times.
    float   fT0 = 0,
            fT1 = 0;

    // Initialized for non-linear lerp.
    std::unique_ptr<SkCubicMap> fCubicMap;

    // Parse the current interval AND back-fill prev interval t1.
    bool parse(const Json::Value& k, KeyframeInterval* prev) {
        SkASSERT(k.isObject());

        fT0 = fT1 = ParseScalar(k["t"], SK_ScalarMin);
        if (fT0 == SK_ScalarMin) {
            return false;
        }

        if (prev) {
            if (prev->fT1 >= fT0) {
                LOG("!! Dropping out-of-order key frame (t: %f < t: %f)\n", fT0, prev->fT1);
                return false;
            }
            // Back-fill t1 in prev interval.  Note: we do this even if we end up discarding
            // the current interval (to support "t"-only final frames).
            prev->fT1 = fT0;
        }

        if (!T::Parse(k["s"], &fV0) ||
            !T::Parse(k["e"], &fV1) ||
            fV0.cardinality() != fV1.cardinality() ||
            (prev && fV0.cardinality() != prev->fV0.cardinality())) {
            return false;
        }

        // default is linear lerp
        static constexpr SkPoint kDefaultC0 = { 0, 0 },
                                 kDefaultC1 = { 1, 1 };
        const auto c0 = ParsePoint(k["i"], kDefaultC0),
                   c1 = ParsePoint(k["o"], kDefaultC1);

        if (c0 != kDefaultC0 || c1 != kDefaultC1) {
            fCubicMap = skstd::make_unique<SkCubicMap>();
            // TODO: why do we have to plug these inverted?
            fCubicMap->setPts(c1, c0);
        }

        return true;
    }

    void lerp(float t, T*) const;
};

// Binds an animated/keyframed property to a node attribute.
template <typename ValT, typename AttrT, typename NodeT>
class Animator : public AnimatorBase {
public:
    static std::unique_ptr<Animator> Make(const Json::Value& frames, sk_sp<NodeT> node,
        std::function<void(const sk_sp<NodeT>&, const AttrT&)> applyFunc);

    void tick(SkMSec t) override {
        const auto& frame = this->findInterval(t);

        ValT val;
        frame.lerp(ComputeLocalT(t, frame.fT0, frame.fT1, frame.fCubicMap.get()), &val);

        fFunc(fTarget, val.template as<AttrT>());
    }

private:
    Animator(SkTArray<KeyframeInterval<ValT>>&& intervals, sk_sp<NodeT> node,
             std::function<void(const sk_sp<NodeT>&, const AttrT&)> applyFunc)
        : fIntervals(std::move(intervals))
        , fTarget(std::move(node))
        , fFunc(std::move(applyFunc)) {}

    const KeyframeInterval<ValT>& findInterval(float t) const;

    const SkTArray<KeyframeInterval<ValT>>                 fIntervals;
    sk_sp<NodeT>                                           fTarget;
    std::function<void(const sk_sp<NodeT>&, const AttrT&)> fFunc;
};

template <typename ValT, typename AttrT, typename NodeT>
std::unique_ptr<Animator<ValT, AttrT, NodeT>>
Animator<ValT, AttrT, NodeT>::Make(const Json::Value& frames,
    sk_sp<NodeT> node, std::function<void(const sk_sp<NodeT>&, const AttrT&)> applyFunc) {

    if (!frames.isArray())
        return nullptr;

    SkTArray<KeyframeInterval<ValT>> intervals;
    intervals.reserve(frames.size());

    for (const auto& frame : frames) {
        if (!frame.isObject())
            return nullptr;

        auto& curr_interval = intervals.push_back();
        auto* prev_interval = intervals.count() > 1 ? &intervals.fromBack(1) : nullptr;
        if (!curr_interval.parse(frame, prev_interval)) {
            // Invalid frame, or "t"-only frame.
            intervals.pop_back();
            continue;
        }
    }

    // If we couldn't determine a t1 for the last interval, discard it.
    if (!intervals.empty() && intervals.back().fT0 == intervals.back().fT1) {
        intervals.pop_back();
    }

    if (intervals.empty()) {
        return nullptr;
    }

    return std::unique_ptr<Animator>(
        new Animator(std::move(intervals), node, std::move(applyFunc)));
}

template <typename ValT, typename AttrT, typename NodeT>
const KeyframeInterval<ValT>& Animator<ValT, AttrT, NodeT>::findInterval(float t) const {
    SkASSERT(!fIntervals.empty());

    // TODO: cache last/current frame?

    auto f0 = fIntervals.begin(),
         f1 = fIntervals.end() - 1;

    SkASSERT(f0->fT0 < f0->fT1);
    SkASSERT(f1->fT0 < f1->fT1);

    if (t < f0->fT0) {
        return *f0;
    }

    if (t > f1->fT1) {
        return *f1;
    }

    while (f0 != f1) {
        SkASSERT(f0 < f1);
        SkASSERT(t >= f0->fT0 && t <= f1->fT1);

        const auto f = f0 + (f1 - f0) / 2;
        SkASSERT(f->fT0 < f->fT1);

        if (t > f->fT1) {
            f0 = f + 1;
        } else {
            f1 = f;
        }
    }

    SkASSERT(f0 == f1);
    SkASSERT(t >= f0->fT0 && t <= f1->fT1);
    return *f0;
}

} // namespace skotty

#endif // SkottyAnimator_DEFINED