• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "modules/skottie/include/Skottie.h"
9 
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkData.h"
12 #include "include/core/SkFontMgr.h"
13 #include "include/core/SkImage.h"
14 #include "include/core/SkPaint.h"
15 #include "include/core/SkPoint.h"
16 #include "include/core/SkStream.h"
17 #include "include/private/SkTArray.h"
18 #include "include/private/SkTo.h"
19 #include "modules/skottie/include/SkottieProperty.h"
20 #include "modules/skottie/src/SkottieAdapter.h"
21 #include "modules/skottie/src/SkottieJson.h"
22 #include "modules/skottie/src/SkottiePriv.h"
23 #include "modules/skottie/src/SkottieValue.h"
24 #include "modules/skottie/src/text/TextAdapter.h"
25 #include "modules/sksg/include/SkSGInvalidationController.h"
26 #include "modules/sksg/include/SkSGOpacityEffect.h"
27 #include "modules/sksg/include/SkSGPaint.h"
28 #include "modules/sksg/include/SkSGPath.h"
29 #include "modules/sksg/include/SkSGRenderEffect.h"
30 #include "modules/sksg/include/SkSGScene.h"
31 #include "modules/sksg/include/SkSGTransform.h"
32 #include "src/core/SkTraceEvent.h"
33 
34 #include <chrono>
35 #include <cmath>
36 
37 #include "stdlib.h"
38 
39 namespace skottie {
40 
41 namespace internal {
42 
log(Logger::Level lvl,const skjson::Value * json,const char fmt[],...) const43 void AnimationBuilder::log(Logger::Level lvl, const skjson::Value* json,
44                            const char fmt[], ...) const {
45     if (!fLogger) {
46         return;
47     }
48 
49     char buff[1024];
50     va_list va;
51     va_start(va, fmt);
52     const auto len = vsnprintf(buff, sizeof(buff), fmt, va);
53     va_end(va);
54 
55     if (len < 0) {
56         SkDebugf("!! Could not format log message !!\n");
57         return;
58     }
59 
60     if (len >= SkToInt(sizeof(buff))) {
61         static constexpr char kEllipsesStr[] = "...";
62         strcpy(buff + sizeof(buff) - sizeof(kEllipsesStr), kEllipsesStr);
63     }
64 
65     SkString jsonstr = json ? json->toString() : SkString();
66 
67     fLogger->log(lvl, buff, jsonstr.c_str());
68 }
69 
attachMatrix2D(const skjson::ObjectValue & t,sk_sp<sksg::Transform> parent) const70 sk_sp<sksg::Transform> AnimationBuilder::attachMatrix2D(const skjson::ObjectValue& t,
71                                                         sk_sp<sksg::Transform> parent) const {
72     static const VectorValue g_default_vec_0   = {  0,   0},
73                              g_default_vec_100 = {100, 100};
74 
75     auto matrix = sksg::Matrix<SkMatrix>::Make(SkMatrix::I());
76     auto adapter = sk_make_sp<TransformAdapter2D>(matrix);
77 
78     auto bound = this->bindProperty<VectorValue>(t["a"],
79             [adapter](const VectorValue& a) {
80                 adapter->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
81             }, g_default_vec_0);
82     bound |= this->bindProperty<VectorValue>(t["p"],
83             [adapter](const VectorValue& p) {
84                 adapter->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
85             }, g_default_vec_0);
86     bound |= this->bindProperty<VectorValue>(t["s"],
87             [adapter](const VectorValue& s) {
88                 adapter->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
89             }, g_default_vec_100);
90 
91     const auto* jrotation = &t["r"];
92     if (jrotation->is<skjson::NullValue>()) {
93         // 3d rotations have separate rx,ry,rz components.  While we don't fully support them,
94         // we can still make use of rz.
95         jrotation = &t["rz"];
96     }
97     bound |= this->bindProperty<ScalarValue>(*jrotation,
98             [adapter](const ScalarValue& r) {
99                 adapter->setRotation(r);
100             }, 0.0f);
101     bound |= this->bindProperty<ScalarValue>(t["sk"],
102             [adapter](const ScalarValue& sk) {
103                 adapter->setSkew(sk);
104             }, 0.0f);
105     bound |= this->bindProperty<ScalarValue>(t["sa"],
106             [adapter](const ScalarValue& sa) {
107                 adapter->setSkewAxis(sa);
108             }, 0.0f);
109 
110     const auto dispatched = this->dispatchTransformProperty(adapter);
111 
112     return (bound || dispatched)
113         ? sksg::Transform::MakeConcat(std::move(parent), std::move(matrix))
114         : parent;
115 }
116 
attachMatrix3D(const skjson::ObjectValue & t,sk_sp<sksg::Transform> parent,sk_sp<TransformAdapter3D> adapter,bool precompose_parent) const117 sk_sp<sksg::Transform> AnimationBuilder::attachMatrix3D(const skjson::ObjectValue& t,
118                                                         sk_sp<sksg::Transform> parent,
119                                                         sk_sp<TransformAdapter3D> adapter,
120                                                         bool precompose_parent) const {
121     static const VectorValue g_default_vec_0   = {  0,   0,   0},
122                              g_default_vec_100 = {100, 100, 100};
123 
124     if (!adapter) {
125         // Default to TransformAdapter3D (we only use external adapters for cameras).
126         adapter = sk_make_sp<TransformAdapter3D>();
127     }
128 
129     auto bound = this->bindProperty<VectorValue>(t["a"],
130             [adapter](const VectorValue& a) {
131                 adapter->setAnchorPoint(TransformAdapter3D::Vec3(a));
132             }, g_default_vec_0);
133     bound |= this->bindProperty<VectorValue>(t["p"],
134             [adapter](const VectorValue& p) {
135                 adapter->setPosition(TransformAdapter3D::Vec3(p));
136             }, g_default_vec_0);
137     bound |= this->bindProperty<VectorValue>(t["s"],
138             [adapter](const VectorValue& s) {
139                 adapter->setScale(TransformAdapter3D::Vec3(s));
140             }, g_default_vec_100);
141 
142     // Orientation and rx/ry/rz are mapped to the same rotation property -- the difference is
143     // in how they get interpolated (vector vs. scalar/decomposed interpolation).
144     bound |= this->bindProperty<VectorValue>(t["or"],
145             [adapter](const VectorValue& o) {
146                 adapter->setRotation(TransformAdapter3D::Vec3(o));
147             }, g_default_vec_0);
148 
149     bound |= this->bindProperty<ScalarValue>(t["rx"],
150             [adapter](const ScalarValue& rx) {
151                 const auto& r = adapter->getRotation();
152                 adapter->setRotation(TransformAdapter3D::Vec3({rx, r.fY, r.fZ}));
153             }, 0.0f);
154 
155     bound |= this->bindProperty<ScalarValue>(t["ry"],
156             [adapter](const ScalarValue& ry) {
157                 const auto& r = adapter->getRotation();
158                 adapter->setRotation(TransformAdapter3D::Vec3({r.fX, ry, r.fZ}));
159             }, 0.0f);
160 
161     bound |= this->bindProperty<ScalarValue>(t["rz"],
162             [adapter](const ScalarValue& rz) {
163                 const auto& r = adapter->getRotation();
164                 adapter->setRotation(TransformAdapter3D::Vec3({r.fX, r.fY, rz}));
165             }, 0.0f);
166 
167     // TODO: dispatch 3D transform properties
168 
169     if (!bound) {
170         return parent;
171     }
172 
173     return precompose_parent
174         ? sksg::Transform::MakeConcat(adapter->refTransform(), std::move(parent))
175         : sksg::Transform::MakeConcat(std::move(parent), adapter->refTransform());
176 }
177 
attachOpacity(const skjson::ObjectValue & jtransform,sk_sp<sksg::RenderNode> childNode) const178 sk_sp<sksg::RenderNode> AnimationBuilder::attachOpacity(const skjson::ObjectValue& jtransform,
179                                                         sk_sp<sksg::RenderNode> childNode) const {
180     if (!childNode)
181         return nullptr;
182 
183     auto opacityNode = sksg::OpacityEffect::Make(childNode);
184 
185     const auto bound = this->bindProperty<ScalarValue>(jtransform["o"],
186         [opacityNode](const ScalarValue& o) {
187             // BM opacity is [0..100]
188             opacityNode->setOpacity(o * 0.01f);
189         }, 100.0f);
190     const auto dispatched = this->dispatchOpacityProperty(opacityNode);
191 
192     // We can ignore constant full opacity.
193     return (bound || dispatched) ? std::move(opacityNode) : childNode;
194 }
195 
196 namespace  {
197 
GetBlendMode(const skjson::ObjectValue & jobject,const AnimationBuilder * abuilder)198 static SkBlendMode GetBlendMode(const skjson::ObjectValue& jobject,
199                                 const AnimationBuilder* abuilder) {
200     static constexpr SkBlendMode kBlendModeMap[] = {
201         SkBlendMode::kSrcOver,    // 0:'normal'
202         SkBlendMode::kMultiply,   // 1:'multiply'
203         SkBlendMode::kScreen,     // 2:'screen'
204         SkBlendMode::kOverlay,    // 3:'overlay
205         SkBlendMode::kDarken,     // 4:'darken'
206         SkBlendMode::kLighten,    // 5:'lighten'
207         SkBlendMode::kColorDodge, // 6:'color-dodge'
208         SkBlendMode::kColorBurn,  // 7:'color-burn'
209         SkBlendMode::kHardLight,  // 8:'hard-light'
210         SkBlendMode::kSoftLight,  // 9:'soft-light'
211         SkBlendMode::kDifference, // 10:'difference'
212         SkBlendMode::kExclusion,  // 11:'exclusion'
213         SkBlendMode::kHue,        // 12:'hue'
214         SkBlendMode::kSaturation, // 13:'saturation'
215         SkBlendMode::kColor,      // 14:'color'
216         SkBlendMode::kLuminosity, // 15:'luminosity'
217         SkBlendMode::kPlus,       // 16:'add'
218     };
219 
220     const auto bm_index = ParseDefault<size_t>(jobject["bm"], 0);
221     if (bm_index >= SK_ARRAY_COUNT(kBlendModeMap)) {
222             abuilder->log(Logger::Level::kWarning, &jobject,
223                           "Unsupported blend mode %lu\n", bm_index);
224             return SkBlendMode::kSrcOver;
225     }
226 
227     return kBlendModeMap[bm_index];
228 }
229 
230 } // namespace
231 
attachBlendMode(const skjson::ObjectValue & jobject,sk_sp<sksg::RenderNode> child) const232 sk_sp<sksg::RenderNode> AnimationBuilder::attachBlendMode(const skjson::ObjectValue& jobject,
233                                                           sk_sp<sksg::RenderNode> child) const {
234     const auto bm = GetBlendMode(jobject, this);
235     if (bm != SkBlendMode::kSrcOver) {
236         fHasNontrivialBlending = true;
237         child = sksg::BlendModeEffect::Make(std::move(child), bm);
238     }
239 
240     return child;
241 }
242 
attachPath(const skjson::Value & jpath) const243 sk_sp<sksg::Path> AnimationBuilder::attachPath(const skjson::Value& jpath) const {
244     auto path_node = sksg::Path::Make();
245     return this->bindProperty<ShapeValue>(jpath,
246         [path_node](const ShapeValue& p) {
247             // FillType is tracked in the SG node, not in keyframes -- make sure we preserve it.
248             auto path = ValueTraits<ShapeValue>::As<SkPath>(p);
249             path.setFillType(path_node->getFillType());
250             path_node->setPath(path);
251         })
252         ? path_node
253         : nullptr;
254 }
255 
attachColor(const skjson::ObjectValue & jcolor,const char prop_name[]) const256 sk_sp<sksg::Color> AnimationBuilder::attachColor(const skjson::ObjectValue& jcolor,
257                                                  const char prop_name[]) const {
258     auto color_node = sksg::Color::Make(SK_ColorBLACK);
259 
260     this->bindProperty<VectorValue>(jcolor[prop_name],
261         [color_node](const VectorValue& c) {
262             color_node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
263         });
264     this->dispatchColorProperty(color_node);
265 
266     return color_node;
267 }
268 
AnimationBuilder(sk_sp<ResourceProvider> rp,sk_sp<SkFontMgr> fontmgr,sk_sp<PropertyObserver> pobserver,sk_sp<Logger> logger,sk_sp<MarkerObserver> mobserver,Animation::Builder::Stats * stats,const SkSize & size,float duration,float framerate)269 AnimationBuilder::AnimationBuilder(sk_sp<ResourceProvider> rp, sk_sp<SkFontMgr> fontmgr,
270                                    sk_sp<PropertyObserver> pobserver, sk_sp<Logger> logger,
271                                    sk_sp<MarkerObserver> mobserver,
272                                    Animation::Builder::Stats* stats,
273                                    const SkSize& size, float duration, float framerate)
274     : fResourceProvider(std::move(rp))
275     , fLazyFontMgr(std::move(fontmgr))
276     , fPropertyObserver(std::move(pobserver))
277     , fLogger(std::move(logger))
278     , fMarkerObserver(std::move(mobserver))
279     , fStats(stats)
280     , fSize(size)
281     , fDuration(duration)
282     , fFrameRate(framerate)
283     , fHasNontrivialBlending(false) {}
284 
parse(const skjson::ObjectValue & jroot)285 std::unique_ptr<sksg::Scene> AnimationBuilder::parse(const skjson::ObjectValue& jroot) {
286     this->dispatchMarkers(jroot["markers"]);
287 
288     this->parseAssets(jroot["assets"]);
289     this->parseFonts(jroot["fonts"], jroot["chars"]);
290 
291     AutoScope ascope(this);
292     auto root = this->attachComposition(jroot);
293 
294     auto animators = ascope.release();
295     fStats->fAnimatorCount = animators.size();
296 
297     return sksg::Scene::Make(std::move(root), std::move(animators));
298 }
299 
parseAssets(const skjson::ArrayValue * jassets)300 void AnimationBuilder::parseAssets(const skjson::ArrayValue* jassets) {
301     if (!jassets) {
302         return;
303     }
304 
305     for (const skjson::ObjectValue* asset : *jassets) {
306         if (asset) {
307             fAssets.set(ParseDefault<SkString>((*asset)["id"], SkString()), { asset, false });
308         }
309     }
310 }
311 
dispatchMarkers(const skjson::ArrayValue * jmarkers) const312 void AnimationBuilder::dispatchMarkers(const skjson::ArrayValue* jmarkers) const {
313     if (!fMarkerObserver || !jmarkers) {
314         return;
315     }
316 
317     // For frame-number -> t conversions.
318     const auto frameRatio = 1 / (fFrameRate * fDuration);
319 
320     for (const skjson::ObjectValue* m : *jmarkers) {
321         if (!m) continue;
322 
323         const skjson::StringValue* name = (*m)["cm"];
324         const auto time = ParseDefault((*m)["tm"], -1.0f),
325                duration = ParseDefault((*m)["dr"], -1.0f);
326 
327         if (name && time >= 0 && duration >= 0) {
328             fMarkerObserver->onMarker(
329                         name->begin(),
330                         // "tm" is in frames
331                         time * frameRatio,
332                         // ... as is "dr"
333                         (time + duration) * frameRatio
334             );
335         } else {
336             this->log(Logger::Level::kWarning, m, "Ignoring unexpected marker.");
337         }
338     }
339 }
340 
dispatchColorProperty(const sk_sp<sksg::Color> & c) const341 bool AnimationBuilder::dispatchColorProperty(const sk_sp<sksg::Color>& c) const {
342     bool dispatched = false;
343 
344     if (fPropertyObserver) {
345         fPropertyObserver->onColorProperty(fPropertyObserverContext,
346             [&]() {
347                 dispatched = true;
348                 return std::unique_ptr<ColorPropertyHandle>(new ColorPropertyHandle(c));
349             });
350     }
351 
352     return dispatched;
353 }
354 
dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect> & o) const355 bool AnimationBuilder::dispatchOpacityProperty(const sk_sp<sksg::OpacityEffect>& o) const {
356     bool dispatched = false;
357 
358     if (fPropertyObserver) {
359         fPropertyObserver->onOpacityProperty(fPropertyObserverContext,
360             [&]() {
361                 dispatched = true;
362                 return std::unique_ptr<OpacityPropertyHandle>(new OpacityPropertyHandle(o));
363             });
364     }
365 
366     return dispatched;
367 }
368 
dispatchTextProperty(const sk_sp<TextAdapter> & t) const369 bool AnimationBuilder::dispatchTextProperty(const sk_sp<TextAdapter>& t) const {
370     bool dispatched = false;
371 
372     if (fPropertyObserver) {
373         fPropertyObserver->onTextProperty(fPropertyObserverContext,
374             [&]() {
375                 dispatched = true;
376                 return std::unique_ptr<TextPropertyHandle>(new TextPropertyHandle(t));
377             });
378     }
379 
380     return dispatched;
381 }
382 
dispatchTransformProperty(const sk_sp<TransformAdapter2D> & t) const383 bool AnimationBuilder::dispatchTransformProperty(const sk_sp<TransformAdapter2D>& t) const {
384     bool dispatched = false;
385 
386     if (fPropertyObserver) {
387         fPropertyObserver->onTransformProperty(fPropertyObserverContext,
388             [&]() {
389                 dispatched = true;
390                 return std::unique_ptr<TransformPropertyHandle>(new TransformPropertyHandle(t));
391             });
392     }
393 
394     return dispatched;
395 }
396 
updateContext(PropertyObserver * observer,const skjson::ObjectValue & obj)397 void AnimationBuilder::AutoPropertyTracker::updateContext(PropertyObserver* observer,
398                                                           const skjson::ObjectValue& obj) {
399 
400     const skjson::StringValue* name = obj["nm"];
401 
402     fBuilder->fPropertyObserverContext = name ? name->begin() : nullptr;
403 }
404 
405 } // namespace internal
406 
load(const char[],const char[]) const407 sk_sp<SkData> ResourceProvider::load(const char[], const char[]) const {
408     return nullptr;
409 }
410 
loadImageAsset(const char path[],const char name[],const char id[]) const411 sk_sp<ImageAsset> ResourceProvider::loadImageAsset(const char path[], const char name[],
412                                                    const char id[]) const {
413     return nullptr;
414 }
415 
loadFont(const char[],const char[]) const416 sk_sp<SkData> ResourceProvider::loadFont(const char[], const char[]) const {
417     return nullptr;
418 }
419 
log(Level,const char[],const char *)420 void Logger::log(Level, const char[], const char*) {}
421 
422 Animation::Builder::Builder()  = default;
423 Animation::Builder::~Builder() = default;
424 
setResourceProvider(sk_sp<ResourceProvider> rp)425 Animation::Builder& Animation::Builder::setResourceProvider(sk_sp<ResourceProvider> rp) {
426     fResourceProvider = std::move(rp);
427     return *this;
428 }
429 
setFontManager(sk_sp<SkFontMgr> fmgr)430 Animation::Builder& Animation::Builder::setFontManager(sk_sp<SkFontMgr> fmgr) {
431     fFontMgr = std::move(fmgr);
432     return *this;
433 }
434 
setPropertyObserver(sk_sp<PropertyObserver> pobserver)435 Animation::Builder& Animation::Builder::setPropertyObserver(sk_sp<PropertyObserver> pobserver) {
436     fPropertyObserver = std::move(pobserver);
437     return *this;
438 }
439 
setLogger(sk_sp<Logger> logger)440 Animation::Builder& Animation::Builder::setLogger(sk_sp<Logger> logger) {
441     fLogger = std::move(logger);
442     return *this;
443 }
444 
setMarkerObserver(sk_sp<MarkerObserver> mobserver)445 Animation::Builder& Animation::Builder::setMarkerObserver(sk_sp<MarkerObserver> mobserver) {
446     fMarkerObserver = std::move(mobserver);
447     return *this;
448 }
449 
make(SkStream * stream)450 sk_sp<Animation> Animation::Builder::make(SkStream* stream) {
451     if (!stream->hasLength()) {
452         // TODO: handle explicit buffering?
453         if (fLogger) {
454             fLogger->log(Logger::Level::kError, "Cannot parse streaming content.\n");
455         }
456         return nullptr;
457     }
458 
459     auto data = SkData::MakeFromStream(stream, stream->getLength());
460     if (!data) {
461         if (fLogger) {
462             fLogger->log(Logger::Level::kError, "Failed to read the input stream.\n");
463         }
464         return nullptr;
465     }
466 
467     return this->make(static_cast<const char*>(data->data()), data->size());
468 }
469 
make(const char * data,size_t data_len)470 sk_sp<Animation> Animation::Builder::make(const char* data, size_t data_len) {
471     TRACE_EVENT0("skottie", TRACE_FUNC);
472 
473     // Sanitize factory args.
474     class NullResourceProvider final : public ResourceProvider {
475         sk_sp<SkData> load(const char[], const char[]) const override { return nullptr; }
476     };
477     auto resolvedProvider = fResourceProvider
478             ? fResourceProvider : sk_make_sp<NullResourceProvider>();
479 
480     memset(&fStats, 0, sizeof(struct Stats));
481 
482     fStats.fJsonSize = data_len;
483     const auto t0 = std::chrono::steady_clock::now();
484 
485     const skjson::DOM dom(data, data_len);
486     if (!dom.root().is<skjson::ObjectValue>()) {
487         // TODO: more error info.
488         if (fLogger) {
489             fLogger->log(Logger::Level::kError, "Failed to parse JSON input.\n");
490         }
491         return nullptr;
492     }
493     const auto& json = dom.root().as<skjson::ObjectValue>();
494 
495     const auto t1 = std::chrono::steady_clock::now();
496     fStats.fJsonParseTimeMS = std::chrono::duration<float, std::milli>{t1-t0}.count();
497 
498     const auto version  = ParseDefault<SkString>(json["v"], SkString());
499     const auto size     = SkSize::Make(ParseDefault<float>(json["w"], 0.0f),
500                                        ParseDefault<float>(json["h"], 0.0f));
501     const auto fps      = ParseDefault<float>(json["fr"], -1.0f),
502                inPoint  = ParseDefault<float>(json["ip"], 0.0f),
503                outPoint = SkTMax(ParseDefault<float>(json["op"], SK_ScalarMax), inPoint),
504                duration = sk_ieee_float_divide(outPoint - inPoint, fps);
505 
506     if (size.isEmpty() || version.isEmpty() || fps <= 0 ||
507         !SkScalarIsFinite(inPoint) || !SkScalarIsFinite(outPoint) || !SkScalarIsFinite(duration)) {
508         if (fLogger) {
509             const auto msg = SkStringPrintf(
510                          "Invalid animation params (version: %s, size: [%f %f], frame rate: %f, "
511                          "in-point: %f, out-point: %f)\n",
512                          version.c_str(), size.width(), size.height(), fps, inPoint, outPoint);
513             fLogger->log(Logger::Level::kError, msg.c_str());
514         }
515         return nullptr;
516     }
517 
518     SkASSERT(resolvedProvider);
519     internal::AnimationBuilder builder(std::move(resolvedProvider), fFontMgr,
520                                        std::move(fPropertyObserver),
521                                        std::move(fLogger),
522                                        std::move(fMarkerObserver),
523                                        &fStats, size, duration, fps);
524     auto scene = builder.parse(json);
525 
526     const auto t2 = std::chrono::steady_clock::now();
527     fStats.fSceneParseTimeMS = std::chrono::duration<float, std::milli>{t2-t1}.count();
528     fStats.fTotalLoadTimeMS  = std::chrono::duration<float, std::milli>{t2-t0}.count();
529 
530     if (!scene && fLogger) {
531         fLogger->log(Logger::Level::kError, "Could not parse animation.\n");
532     }
533 
534     uint32_t flags = 0;
535     if (builder.hasNontrivialBlending()) {
536         flags |= Flags::kRequiresTopLevelIsolation;
537     }
538 
539     return sk_sp<Animation>(new Animation(std::move(scene),
540                                           std::move(version),
541                                           size,
542                                           inPoint,
543                                           outPoint,
544                                           duration,
545                                           flags));
546 }
547 
makeFromFile(const char path[])548 sk_sp<Animation> Animation::Builder::makeFromFile(const char path[]) {
549     const auto data = SkData::MakeFromFileName(path);
550 
551     return data ? this->make(static_cast<const char*>(data->data()), data->size())
552                 : nullptr;
553 }
554 
Animation(std::unique_ptr<sksg::Scene> scene,SkString version,const SkSize & size,SkScalar inPoint,SkScalar outPoint,SkScalar duration,uint32_t flags)555 Animation::Animation(std::unique_ptr<sksg::Scene> scene, SkString version, const SkSize& size,
556                      SkScalar inPoint, SkScalar outPoint, SkScalar duration, uint32_t flags)
557     : fScene(std::move(scene))
558     , fVersion(std::move(version))
559     , fSize(size)
560     , fInPoint(inPoint)
561     , fOutPoint(outPoint)
562     , fDuration(duration)
563     , fFlags(flags) {
564 
565     // In case the client calls render before the first tick.
566     this->seek(0);
567 }
568 
569 Animation::~Animation() = default;
570 
render(SkCanvas * canvas,const SkRect * dstR) const571 void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
572     this->render(canvas, dstR, 0);
573 }
574 
render(SkCanvas * canvas,const SkRect * dstR,RenderFlags renderFlags) const575 void Animation::render(SkCanvas* canvas, const SkRect* dstR, RenderFlags renderFlags) const {
576     TRACE_EVENT0("skottie", TRACE_FUNC);
577 
578     if (!fScene)
579         return;
580 
581     SkAutoCanvasRestore restore(canvas, true);
582 
583     const SkRect srcR = SkRect::MakeSize(this->size());
584     if (dstR) {
585         canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
586     }
587 
588     if ((fFlags & Flags::kRequiresTopLevelIsolation) &&
589         !(renderFlags & RenderFlag::kSkipTopLevelIsolation)) {
590         // The animation uses non-trivial blending, and needs
591         // to be rendered into a separate/transparent layer.
592         canvas->saveLayer(srcR, nullptr);
593     }
594 
595     canvas->clipRect(srcR);
596 
597     fScene->render(canvas);
598 }
599 
seek(SkScalar t,sksg::InvalidationController * ic)600 void Animation::seek(SkScalar t, sksg::InvalidationController* ic) {
601     TRACE_EVENT0("skottie", TRACE_FUNC);
602 
603     if (!fScene)
604         return;
605 
606     // Per AE/Lottie semantics out_point is exclusive.
607     const auto kLastValidFrame = std::nextafter(fOutPoint, fInPoint);
608 
609     fScene->animate(SkTPin(fInPoint + t * (fOutPoint - fInPoint), fInPoint, kLastValidFrame), ic);
610 }
611 
seekFrameTime(double t,sksg::InvalidationController * ic)612 void Animation::seekFrameTime(double t, sksg::InvalidationController* ic) {
613     if (double dur = this->duration()) {
614         this->seek((SkScalar)(t / dur), ic);
615     }
616 }
617 
Make(const char * data,size_t length)618 sk_sp<Animation> Animation::Make(const char* data, size_t length) {
619     return Builder().make(data, length);
620 }
621 
Make(SkStream * stream)622 sk_sp<Animation> Animation::Make(SkStream* stream) {
623     return Builder().make(stream);
624 }
625 
MakeFromFile(const char path[])626 sk_sp<Animation> Animation::MakeFromFile(const char path[]) {
627     return Builder().makeFromFile(path);
628 }
629 
630 } // namespace skottie
631