blob: 5b0e83699779b7a3c05aa2e0bce862102f5066ca [file] [log] [blame]
Florin Malita094ccde2017-12-30 12:27:00 -05001/*
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
Florin Malita54f65c42018-01-16 17:04:30 -05008#include "Skottie.h"
Florin Malita094ccde2017-12-30 12:27:00 -05009
10#include "SkCanvas.h"
Florin Malitafc807c82018-01-25 22:35:09 -050011#include "SkJSONCPP.h"
Florin Malita54f65c42018-01-16 17:04:30 -050012#include "SkottieAnimator.h"
Florin Malitacf8ed522018-01-25 15:27:33 -050013#include "SkottieParser.h"
Florin Malita54f65c42018-01-16 17:04:30 -050014#include "SkottieProperties.h"
Florin Malita094ccde2017-12-30 12:27:00 -050015#include "SkData.h"
Florin Malita49328072018-01-08 12:51:12 -050016#include "SkImage.h"
Florin Malita094ccde2017-12-30 12:27:00 -050017#include "SkMakeUnique.h"
Florin Malita49328072018-01-08 12:51:12 -050018#include "SkOSPath.h"
Florin Malita094ccde2017-12-30 12:27:00 -050019#include "SkPaint.h"
Florin Malita0e66fba2018-01-09 17:10:18 -050020#include "SkParse.h"
Florin Malita094ccde2017-12-30 12:27:00 -050021#include "SkPoint.h"
Florin Malita38ea40e2018-01-29 16:31:14 -050022#include "SkSGClipEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050023#include "SkSGColor.h"
24#include "SkSGDraw.h"
Florin Malita16d0ad02018-01-19 15:07:29 -050025#include "SkSGGeometryTransform.h"
Florin Malita6aaee592018-01-12 12:25:09 -050026#include "SkSGGradient.h"
Florin Malita094ccde2017-12-30 12:27:00 -050027#include "SkSGGroup.h"
Florin Malita49328072018-01-08 12:51:12 -050028#include "SkSGImage.h"
29#include "SkSGInvalidationController.h"
Florin Malita5f9102f2018-01-10 13:36:22 -050030#include "SkSGMaskEffect.h"
Florin Malitae6345d92018-01-03 23:37:54 -050031#include "SkSGMerge.h"
Florin Malitac0034172018-01-08 16:42:59 -050032#include "SkSGOpacityEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050033#include "SkSGPath.h"
Florin Malita2e1d7e22018-01-02 10:40:00 -050034#include "SkSGRect.h"
Florin Malita35efaa82018-01-22 12:57:06 -050035#include "SkSGScene.h"
Florin Malita094ccde2017-12-30 12:27:00 -050036#include "SkSGTransform.h"
Florin Malita51b8c892018-01-07 08:54:24 -050037#include "SkSGTrimEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050038#include "SkStream.h"
39#include "SkTArray.h"
40#include "SkTHash.h"
41
42#include <cmath>
Florin Malitae6345d92018-01-03 23:37:54 -050043#include <vector>
44
Florin Malita094ccde2017-12-30 12:27:00 -050045#include "stdlib.h"
46
Florin Malita54f65c42018-01-16 17:04:30 -050047namespace skottie {
Florin Malita094ccde2017-12-30 12:27:00 -050048
Florin Malitacf8ed522018-01-25 15:27:33 -050049#define LOG SkDebugf
50
Florin Malita094ccde2017-12-30 12:27:00 -050051namespace {
52
Florin Malitadd22cf962018-01-29 15:42:01 +000053using AssetMap = SkTHashMap<SkString, const Json::Value*>;
Florin Malita094ccde2017-12-30 12:27:00 -050054
55struct AttachContext {
Florin Malitacca86f32018-01-29 10:49:49 -050056 const ResourceProvider& fResources;
57 const AssetMap& fAssets;
Florin Malita1022f742018-02-23 11:10:22 -050058 const float fFrameRate;
Florin Malitacca86f32018-01-29 10:49:49 -050059 sksg::AnimatorList& fAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -050060};
61
62bool LogFail(const Json::Value& json, const char* msg) {
63 const auto dump = json.toStyledString();
64 LOG("!! %s: %s", msg, dump.c_str());
65 return false;
66}
67
Florin Malita18eafd92018-01-04 21:11:55 -050068sk_sp<sksg::Matrix> AttachMatrix(const Json::Value& t, AttachContext* ctx,
69 sk_sp<sksg::Matrix> parentMatrix) {
70 if (!t.isObject())
71 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -050072
Florin Malita18eafd92018-01-04 21:11:55 -050073 auto matrix = sksg::Matrix::Make(SkMatrix::I(), std::move(parentMatrix));
74 auto composite = sk_make_sp<CompositeTransform>(matrix);
Florin Malitafc807c82018-01-25 22:35:09 -050075 auto anchor_attached = BindProperty<VectorValue>(t["a"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050076 [composite](const VectorValue& a) {
77 composite->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
Florin Malita094ccde2017-12-30 12:27:00 -050078 });
Florin Malitafc807c82018-01-25 22:35:09 -050079 auto position_attached = BindProperty<VectorValue>(t["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050080 [composite](const VectorValue& p) {
81 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malita094ccde2017-12-30 12:27:00 -050082 });
Florin Malitafc807c82018-01-25 22:35:09 -050083 auto scale_attached = BindProperty<VectorValue>(t["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050084 [composite](const VectorValue& s) {
85 composite->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
Florin Malita094ccde2017-12-30 12:27:00 -050086 });
Florin Malita1eb98db2018-01-26 15:03:38 -050087
88 auto* jrotation = &t["r"];
89 if (jrotation->isNull()) {
90 // 3d rotations have separate rx,ry,rz components. While we don't fully support them,
91 // we can still make use of rz.
92 jrotation = &t["rz"];
93 }
94 auto rotation_attached = BindProperty<ScalarValue>(*jrotation, &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050095 [composite](const ScalarValue& r) {
96 composite->setRotation(r);
Florin Malita094ccde2017-12-30 12:27:00 -050097 });
Florin Malitafc807c82018-01-25 22:35:09 -050098 auto skew_attached = BindProperty<ScalarValue>(t["sk"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -050099 [composite](const ScalarValue& sk) {
100 composite->setSkew(sk);
Florin Malita094ccde2017-12-30 12:27:00 -0500101 });
Florin Malitafc807c82018-01-25 22:35:09 -0500102 auto skewaxis_attached = BindProperty<ScalarValue>(t["sa"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500103 [composite](const ScalarValue& sa) {
104 composite->setSkewAxis(sa);
Florin Malita094ccde2017-12-30 12:27:00 -0500105 });
106
107 if (!anchor_attached &&
108 !position_attached &&
109 !scale_attached &&
110 !rotation_attached &&
111 !skew_attached &&
112 !skewaxis_attached) {
113 LogFail(t, "Could not parse transform");
Florin Malita18eafd92018-01-04 21:11:55 -0500114 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500115 }
116
Florin Malita18eafd92018-01-04 21:11:55 -0500117 return matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500118}
119
Florin Malitac0034172018-01-08 16:42:59 -0500120sk_sp<sksg::RenderNode> AttachOpacity(const Json::Value& jtransform, AttachContext* ctx,
121 sk_sp<sksg::RenderNode> childNode) {
122 if (!jtransform.isObject() || !childNode)
123 return childNode;
124
125 // This is more peeky than other attachers, because we want to avoid redundant opacity
126 // nodes for the extremely common case of static opaciy == 100.
127 const auto& opacity = jtransform["o"];
128 if (opacity.isObject() &&
Florin Malitacf8ed522018-01-25 15:27:33 -0500129 !ParseDefault(opacity["a"], true) &&
130 ParseDefault(opacity["k"], -1) == 100) {
Florin Malitac0034172018-01-08 16:42:59 -0500131 // Ignoring static full opacity.
132 return childNode;
133 }
134
135 auto opacityNode = sksg::OpacityEffect::Make(childNode);
Florin Malitafc807c82018-01-25 22:35:09 -0500136 BindProperty<ScalarValue>(opacity, &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500137 [opacityNode](const ScalarValue& o) {
Florin Malitac0034172018-01-08 16:42:59 -0500138 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500139 opacityNode->setOpacity(o * 0.01f);
Florin Malitac0034172018-01-08 16:42:59 -0500140 });
141
142 return opacityNode;
143}
144
Florin Malita094ccde2017-12-30 12:27:00 -0500145sk_sp<sksg::RenderNode> AttachComposition(const Json::Value&, AttachContext* ctx);
146
Florin Malita25366fa2018-01-23 13:37:59 -0500147sk_sp<sksg::Path> AttachPath(const Json::Value& jpath, AttachContext* ctx) {
148 auto path_node = sksg::Path::Make();
Florin Malitafc807c82018-01-25 22:35:09 -0500149 return BindProperty<ShapeValue>(jpath, &ctx->fAnimators,
150 [path_node](const ShapeValue& p) { path_node->setPath(p); })
Florin Malita25366fa2018-01-23 13:37:59 -0500151 ? path_node
152 : nullptr;
153}
154
Florin Malita094ccde2017-12-30 12:27:00 -0500155sk_sp<sksg::GeometryNode> AttachPathGeometry(const Json::Value& jpath, AttachContext* ctx) {
156 SkASSERT(jpath.isObject());
157
Florin Malita25366fa2018-01-23 13:37:59 -0500158 return AttachPath(jpath["ks"], ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500159}
160
Florin Malita2e1d7e22018-01-02 10:40:00 -0500161sk_sp<sksg::GeometryNode> AttachRRectGeometry(const Json::Value& jrect, AttachContext* ctx) {
162 SkASSERT(jrect.isObject());
163
164 auto rect_node = sksg::RRect::Make();
165 auto composite = sk_make_sp<CompositeRRect>(rect_node);
166
Florin Malitafc807c82018-01-25 22:35:09 -0500167 auto p_attached = BindProperty<VectorValue>(jrect["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500168 [composite](const VectorValue& p) {
169 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500170 });
Florin Malitafc807c82018-01-25 22:35:09 -0500171 auto s_attached = BindProperty<VectorValue>(jrect["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500172 [composite](const VectorValue& s) {
173 composite->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
Florin Malitaf9590922018-01-09 11:56:09 -0500174 });
Florin Malitafc807c82018-01-25 22:35:09 -0500175 auto r_attached = BindProperty<ScalarValue>(jrect["r"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500176 [composite](const ScalarValue& r) {
177 composite->setRadius(SkSize::Make(r, r));
Florin Malitaf9590922018-01-09 11:56:09 -0500178 });
Florin Malita2e1d7e22018-01-02 10:40:00 -0500179
180 if (!p_attached && !s_attached && !r_attached) {
181 return nullptr;
182 }
183
Florin Malitafbc13f12018-01-04 10:26:35 -0500184 return rect_node;
185}
186
187sk_sp<sksg::GeometryNode> AttachEllipseGeometry(const Json::Value& jellipse, AttachContext* ctx) {
188 SkASSERT(jellipse.isObject());
189
190 auto rect_node = sksg::RRect::Make();
191 auto composite = sk_make_sp<CompositeRRect>(rect_node);
192
Florin Malitafc807c82018-01-25 22:35:09 -0500193 auto p_attached = BindProperty<VectorValue>(jellipse["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500194 [composite](const VectorValue& p) {
195 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500196 });
Florin Malitafc807c82018-01-25 22:35:09 -0500197 auto s_attached = BindProperty<VectorValue>(jellipse["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500198 [composite](const VectorValue& s) {
Florin Malitaf9590922018-01-09 11:56:09 -0500199 const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
Florin Malita2518a0a2018-01-24 18:29:00 -0500200 composite->setSize(sz);
201 composite->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
Florin Malitaf9590922018-01-09 11:56:09 -0500202 });
Florin Malitafbc13f12018-01-04 10:26:35 -0500203
204 if (!p_attached && !s_attached) {
205 return nullptr;
206 }
207
Florin Malita2e1d7e22018-01-02 10:40:00 -0500208 return rect_node;
209}
210
Florin Malita02a32b02018-01-04 11:27:09 -0500211sk_sp<sksg::GeometryNode> AttachPolystarGeometry(const Json::Value& jstar, AttachContext* ctx) {
212 SkASSERT(jstar.isObject());
213
214 static constexpr CompositePolyStar::Type gTypes[] = {
215 CompositePolyStar::Type::kStar, // "sy": 1
216 CompositePolyStar::Type::kPoly, // "sy": 2
217 };
218
Florin Malitacf8ed522018-01-25 15:27:33 -0500219 const auto type = ParseDefault(jstar["sy"], 0) - 1;
Florin Malita02a32b02018-01-04 11:27:09 -0500220 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gTypes))) {
221 LogFail(jstar, "Unknown polystar type");
222 return nullptr;
223 }
224
225 auto path_node = sksg::Path::Make();
226 auto composite = sk_make_sp<CompositePolyStar>(path_node, gTypes[type]);
227
Florin Malitafc807c82018-01-25 22:35:09 -0500228 BindProperty<VectorValue>(jstar["p"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500229 [composite](const VectorValue& p) {
230 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500231 });
Florin Malitafc807c82018-01-25 22:35:09 -0500232 BindProperty<ScalarValue>(jstar["pt"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500233 [composite](const ScalarValue& pt) {
234 composite->setPointCount(pt);
Florin Malitaf9590922018-01-09 11:56:09 -0500235 });
Florin Malitafc807c82018-01-25 22:35:09 -0500236 BindProperty<ScalarValue>(jstar["ir"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500237 [composite](const ScalarValue& ir) {
238 composite->setInnerRadius(ir);
Florin Malitaf9590922018-01-09 11:56:09 -0500239 });
Florin Malitafc807c82018-01-25 22:35:09 -0500240 BindProperty<ScalarValue>(jstar["or"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500241 [composite](const ScalarValue& otr) {
242 composite->setOuterRadius(otr);
Florin Malita9661b982018-01-06 14:25:49 -0500243 });
Florin Malitafc807c82018-01-25 22:35:09 -0500244 BindProperty<ScalarValue>(jstar["is"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500245 [composite](const ScalarValue& is) {
246 composite->setInnerRoundness(is);
Florin Malita9661b982018-01-06 14:25:49 -0500247 });
Florin Malitafc807c82018-01-25 22:35:09 -0500248 BindProperty<ScalarValue>(jstar["os"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500249 [composite](const ScalarValue& os) {
250 composite->setOuterRoundness(os);
Florin Malita9661b982018-01-06 14:25:49 -0500251 });
Florin Malitafc807c82018-01-25 22:35:09 -0500252 BindProperty<ScalarValue>(jstar["r"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500253 [composite](const ScalarValue& r) {
254 composite->setRotation(r);
Florin Malitaf9590922018-01-09 11:56:09 -0500255 });
Florin Malita02a32b02018-01-04 11:27:09 -0500256
257 return path_node;
258}
259
Florin Malita6aaee592018-01-12 12:25:09 -0500260sk_sp<sksg::Color> AttachColor(const Json::Value& obj, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500261 SkASSERT(obj.isObject());
262
263 auto color_node = sksg::Color::Make(SK_ColorBLACK);
Florin Malitafc807c82018-01-25 22:35:09 -0500264 auto color_attached = BindProperty<VectorValue>(obj["c"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500265 [color_node](const VectorValue& c) {
266 color_node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
Florin Malitaf9590922018-01-09 11:56:09 -0500267 });
Florin Malita094ccde2017-12-30 12:27:00 -0500268
Florin Malita1586d852018-01-12 14:27:39 -0500269 return color_attached ? color_node : nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500270}
271
Florin Malita6aaee592018-01-12 12:25:09 -0500272sk_sp<sksg::Gradient> AttachGradient(const Json::Value& obj, AttachContext* ctx) {
273 SkASSERT(obj.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500274
Florin Malita6aaee592018-01-12 12:25:09 -0500275 const auto& stops = obj["g"];
276 if (!stops.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500277 return nullptr;
278
Florin Malitacf8ed522018-01-25 15:27:33 -0500279 const auto stopCount = ParseDefault(stops["p"], -1);
Florin Malita6aaee592018-01-12 12:25:09 -0500280 if (stopCount < 0)
281 return nullptr;
282
283 sk_sp<sksg::Gradient> gradient_node;
284 sk_sp<CompositeGradient> composite;
285
Florin Malitacf8ed522018-01-25 15:27:33 -0500286 if (ParseDefault(obj["t"], 1) == 1) {
Florin Malita6aaee592018-01-12 12:25:09 -0500287 auto linear_node = sksg::LinearGradient::Make();
288 composite = sk_make_sp<CompositeLinearGradient>(linear_node, stopCount);
289 gradient_node = std::move(linear_node);
290 } else {
291 auto radial_node = sksg::RadialGradient::Make();
292 composite = sk_make_sp<CompositeRadialGradient>(radial_node, stopCount);
293
294 // TODO: highlight, angle
295 gradient_node = std::move(radial_node);
296 }
297
Florin Malitafc807c82018-01-25 22:35:09 -0500298 BindProperty<VectorValue>(stops["k"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500299 [composite](const VectorValue& stops) {
300 composite->setColorStops(stops);
Florin Malita6aaee592018-01-12 12:25:09 -0500301 });
Florin Malitafc807c82018-01-25 22:35:09 -0500302 BindProperty<VectorValue>(obj["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500303 [composite](const VectorValue& s) {
304 composite->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
Florin Malita6aaee592018-01-12 12:25:09 -0500305 });
Florin Malitafc807c82018-01-25 22:35:09 -0500306 BindProperty<VectorValue>(obj["e"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500307 [composite](const VectorValue& e) {
308 composite->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
Florin Malita6aaee592018-01-12 12:25:09 -0500309 });
310
311 return gradient_node;
312}
313
Florin Malita1586d852018-01-12 14:27:39 -0500314sk_sp<sksg::PaintNode> AttachPaint(const Json::Value& jpaint, AttachContext* ctx,
Florin Malita6aaee592018-01-12 12:25:09 -0500315 sk_sp<sksg::PaintNode> paint_node) {
316 if (paint_node) {
317 paint_node->setAntiAlias(true);
318
Florin Malitafc807c82018-01-25 22:35:09 -0500319 BindProperty<ScalarValue>(jpaint["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500320 [paint_node](const ScalarValue& o) {
Florin Malita1586d852018-01-12 14:27:39 -0500321 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500322 paint_node->setOpacity(o * 0.01f);
Florin Malita1586d852018-01-12 14:27:39 -0500323 });
Florin Malita6aaee592018-01-12 12:25:09 -0500324 }
325
326 return paint_node;
327}
328
329sk_sp<sksg::PaintNode> AttachStroke(const Json::Value& jstroke, AttachContext* ctx,
330 sk_sp<sksg::PaintNode> stroke_node) {
331 SkASSERT(jstroke.isObject());
332
333 if (!stroke_node)
334 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500335
336 stroke_node->setStyle(SkPaint::kStroke_Style);
337
Florin Malitafc807c82018-01-25 22:35:09 -0500338 auto width_attached = BindProperty<ScalarValue>(jstroke["w"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500339 [stroke_node](const ScalarValue& w) {
340 stroke_node->setStrokeWidth(w);
Florin Malitaf9590922018-01-09 11:56:09 -0500341 });
Florin Malita094ccde2017-12-30 12:27:00 -0500342 if (!width_attached)
343 return nullptr;
344
Florin Malitacf8ed522018-01-25 15:27:33 -0500345 stroke_node->setStrokeMiter(ParseDefault(jstroke["ml"], 4.0f));
Florin Malita094ccde2017-12-30 12:27:00 -0500346
347 static constexpr SkPaint::Join gJoins[] = {
348 SkPaint::kMiter_Join,
349 SkPaint::kRound_Join,
350 SkPaint::kBevel_Join,
351 };
Florin Malitacf8ed522018-01-25 15:27:33 -0500352 stroke_node->setStrokeJoin(gJoins[SkTPin<int>(ParseDefault(jstroke["lj"], 1) - 1,
Florin Malita094ccde2017-12-30 12:27:00 -0500353 0, SK_ARRAY_COUNT(gJoins) - 1)]);
354
355 static constexpr SkPaint::Cap gCaps[] = {
356 SkPaint::kButt_Cap,
357 SkPaint::kRound_Cap,
358 SkPaint::kSquare_Cap,
359 };
Florin Malitacf8ed522018-01-25 15:27:33 -0500360 stroke_node->setStrokeCap(gCaps[SkTPin<int>(ParseDefault(jstroke["lc"], 1) - 1,
Florin Malita094ccde2017-12-30 12:27:00 -0500361 0, SK_ARRAY_COUNT(gCaps) - 1)]);
362
363 return stroke_node;
364}
365
Florin Malita6aaee592018-01-12 12:25:09 -0500366sk_sp<sksg::PaintNode> AttachColorFill(const Json::Value& jfill, AttachContext* ctx) {
367 SkASSERT(jfill.isObject());
368
369 return AttachPaint(jfill, ctx, AttachColor(jfill, ctx));
370}
371
372sk_sp<sksg::PaintNode> AttachGradientFill(const Json::Value& jfill, AttachContext* ctx) {
373 SkASSERT(jfill.isObject());
374
375 return AttachPaint(jfill, ctx, AttachGradient(jfill, ctx));
376}
377
378sk_sp<sksg::PaintNode> AttachColorStroke(const Json::Value& jstroke, AttachContext* ctx) {
379 SkASSERT(jstroke.isObject());
380
381 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachColor(jstroke, ctx)));
382}
383
384sk_sp<sksg::PaintNode> AttachGradientStroke(const Json::Value& jstroke, AttachContext* ctx) {
385 SkASSERT(jstroke.isObject());
386
387 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachGradient(jstroke, ctx)));
388}
389
Florin Malitae6345d92018-01-03 23:37:54 -0500390std::vector<sk_sp<sksg::GeometryNode>> AttachMergeGeometryEffect(
391 const Json::Value& jmerge, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
392 std::vector<sk_sp<sksg::GeometryNode>> merged;
393
394 static constexpr sksg::Merge::Mode gModes[] = {
395 sksg::Merge::Mode::kMerge, // "mm": 1
396 sksg::Merge::Mode::kUnion, // "mm": 2
397 sksg::Merge::Mode::kDifference, // "mm": 3
398 sksg::Merge::Mode::kIntersect, // "mm": 4
399 sksg::Merge::Mode::kXOR , // "mm": 5
400 };
401
Florin Malitacf8ed522018-01-25 15:27:33 -0500402 const auto mode = gModes[SkTPin<int>(ParseDefault(jmerge["mm"], 1) - 1,
Florin Malita51b8c892018-01-07 08:54:24 -0500403 0, SK_ARRAY_COUNT(gModes) - 1)];
Florin Malitae6345d92018-01-03 23:37:54 -0500404 merged.push_back(sksg::Merge::Make(std::move(geos), mode));
405
Florin Malitae6345d92018-01-03 23:37:54 -0500406 return merged;
407}
408
Florin Malita51b8c892018-01-07 08:54:24 -0500409std::vector<sk_sp<sksg::GeometryNode>> AttachTrimGeometryEffect(
410 const Json::Value& jtrim, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
411
412 enum class Mode {
413 kMerged, // "m": 1
414 kSeparate, // "m": 2
415 } gModes[] = { Mode::kMerged, Mode::kSeparate };
416
Florin Malitacf8ed522018-01-25 15:27:33 -0500417 const auto mode = gModes[SkTPin<int>(ParseDefault(jtrim["m"], 1) - 1,
Florin Malita51b8c892018-01-07 08:54:24 -0500418 0, SK_ARRAY_COUNT(gModes) - 1)];
419
420 std::vector<sk_sp<sksg::GeometryNode>> inputs;
421 if (mode == Mode::kMerged) {
422 inputs.push_back(sksg::Merge::Make(std::move(geos), sksg::Merge::Mode::kMerge));
423 } else {
424 inputs = std::move(geos);
425 }
426
427 std::vector<sk_sp<sksg::GeometryNode>> trimmed;
428 trimmed.reserve(inputs.size());
429 for (const auto& i : inputs) {
430 const auto trim = sksg::TrimEffect::Make(i);
431 trimmed.push_back(trim);
Florin Malitafc807c82018-01-25 22:35:09 -0500432 BindProperty<ScalarValue>(jtrim["s"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500433 [trim](const ScalarValue& s) {
434 trim->setStart(s * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500435 });
Florin Malitafc807c82018-01-25 22:35:09 -0500436 BindProperty<ScalarValue>(jtrim["e"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500437 [trim](const ScalarValue& e) {
438 trim->setEnd(e * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500439 });
Florin Malitafc807c82018-01-25 22:35:09 -0500440 BindProperty<ScalarValue>(jtrim["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500441 [trim](const ScalarValue& o) {
442 trim->setOffset(o / 360);
Florin Malita51b8c892018-01-07 08:54:24 -0500443 });
444 }
445
446 return trimmed;
447}
448
Florin Malita094ccde2017-12-30 12:27:00 -0500449using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const Json::Value&, AttachContext*);
450static constexpr GeometryAttacherT gGeometryAttachers[] = {
451 AttachPathGeometry,
Florin Malita2e1d7e22018-01-02 10:40:00 -0500452 AttachRRectGeometry,
Florin Malitafbc13f12018-01-04 10:26:35 -0500453 AttachEllipseGeometry,
Florin Malita02a32b02018-01-04 11:27:09 -0500454 AttachPolystarGeometry,
Florin Malita094ccde2017-12-30 12:27:00 -0500455};
456
457using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const Json::Value&, AttachContext*);
458static constexpr PaintAttacherT gPaintAttachers[] = {
Florin Malita6aaee592018-01-12 12:25:09 -0500459 AttachColorFill,
460 AttachColorStroke,
461 AttachGradientFill,
462 AttachGradientStroke,
Florin Malita094ccde2017-12-30 12:27:00 -0500463};
464
Florin Malitae6345d92018-01-03 23:37:54 -0500465using GeometryEffectAttacherT =
466 std::vector<sk_sp<sksg::GeometryNode>> (*)(const Json::Value&,
467 AttachContext*,
468 std::vector<sk_sp<sksg::GeometryNode>>&&);
469static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
470 AttachMergeGeometryEffect,
Florin Malita51b8c892018-01-07 08:54:24 -0500471 AttachTrimGeometryEffect,
Florin Malitae6345d92018-01-03 23:37:54 -0500472};
473
Florin Malita094ccde2017-12-30 12:27:00 -0500474enum class ShapeType {
475 kGeometry,
Florin Malitae6345d92018-01-03 23:37:54 -0500476 kGeometryEffect,
Florin Malita094ccde2017-12-30 12:27:00 -0500477 kPaint,
478 kGroup,
Florin Malitadacc02b2017-12-31 09:12:31 -0500479 kTransform,
Florin Malita094ccde2017-12-30 12:27:00 -0500480};
481
482struct ShapeInfo {
483 const char* fTypeString;
484 ShapeType fShapeType;
485 uint32_t fAttacherIndex; // index into respective attacher tables
486};
487
488const ShapeInfo* FindShapeInfo(const Json::Value& shape) {
489 static constexpr ShapeInfo gShapeInfo[] = {
Florin Malitafbc13f12018-01-04 10:26:35 -0500490 { "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500491 { "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
492 { "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
Florin Malita16d0ad02018-01-19 15:07:29 -0500493 { "gr", ShapeType::kGroup , 0 }, // group -> Inline handler
Florin Malita6aaee592018-01-12 12:25:09 -0500494 { "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
Florin Malitae6345d92018-01-03 23:37:54 -0500495 { "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
Florin Malita02a32b02018-01-04 11:27:09 -0500496 { "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
Florin Malitae6345d92018-01-03 23:37:54 -0500497 { "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
Florin Malita02a32b02018-01-04 11:27:09 -0500498 { "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500499 { "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
Florin Malita51b8c892018-01-07 08:54:24 -0500500 { "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
Florin Malita16d0ad02018-01-19 15:07:29 -0500501 { "tr", ShapeType::kTransform , 0 }, // transform -> Inline handler
Florin Malita094ccde2017-12-30 12:27:00 -0500502 };
503
504 if (!shape.isObject())
505 return nullptr;
506
507 const auto& type = shape["ty"];
508 if (!type.isString())
509 return nullptr;
510
511 const auto* info = bsearch(type.asCString(),
512 gShapeInfo,
513 SK_ARRAY_COUNT(gShapeInfo),
514 sizeof(ShapeInfo),
515 [](const void* key, const void* info) {
516 return strcmp(static_cast<const char*>(key),
517 static_cast<const ShapeInfo*>(info)->fTypeString);
518 });
519
520 return static_cast<const ShapeInfo*>(info);
521}
522
Florin Malita16d0ad02018-01-19 15:07:29 -0500523struct GeometryEffectRec {
524 const Json::Value& fJson;
525 GeometryEffectAttacherT fAttach;
526};
527
Florin Malitaca4439f2018-01-23 10:31:59 -0500528struct AttachShapeContext {
529 AttachShapeContext(AttachContext* ctx,
530 std::vector<sk_sp<sksg::GeometryNode>>* geos,
531 std::vector<GeometryEffectRec>* effects,
532 size_t committedAnimators)
533 : fCtx(ctx)
534 , fGeometryStack(geos)
535 , fGeometryEffectStack(effects)
536 , fCommittedAnimators(committedAnimators) {}
537
538 AttachContext* fCtx;
539 std::vector<sk_sp<sksg::GeometryNode>>* fGeometryStack;
540 std::vector<GeometryEffectRec>* fGeometryEffectStack;
541 size_t fCommittedAnimators;
542};
543
544sk_sp<sksg::RenderNode> AttachShape(const Json::Value& jshape, AttachShapeContext* shapeCtx) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500545 if (!jshape.isArray())
Florin Malita094ccde2017-12-30 12:27:00 -0500546 return nullptr;
547
Florin Malitaca4439f2018-01-23 10:31:59 -0500548 SkDEBUGCODE(const auto initialGeometryEffects = shapeCtx->fGeometryEffectStack->size();)
Florin Malita094ccde2017-12-30 12:27:00 -0500549
Florin Malita16d0ad02018-01-19 15:07:29 -0500550 sk_sp<sksg::Group> shape_group = sksg::Group::Make();
551 sk_sp<sksg::RenderNode> shape_wrapper = shape_group;
552 sk_sp<sksg::Matrix> shape_matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500553
Florin Malita16d0ad02018-01-19 15:07:29 -0500554 struct ShapeRec {
555 const Json::Value& fJson;
556 const ShapeInfo& fInfo;
557 };
558
559 // First pass (bottom->top):
560 //
561 // * pick up the group transform and opacity
562 // * push local geometry effects onto the stack
563 // * store recs for next pass
564 //
565 std::vector<ShapeRec> recs;
566 for (Json::ArrayIndex i = 0; i < jshape.size(); ++i) {
567 const auto& s = jshape[jshape.size() - 1 - i];
Florin Malita094ccde2017-12-30 12:27:00 -0500568 const auto* info = FindShapeInfo(s);
569 if (!info) {
570 LogFail(s.isObject() ? s["ty"] : s, "Unknown shape");
571 continue;
572 }
573
Florin Malita16d0ad02018-01-19 15:07:29 -0500574 recs.push_back({ s, *info });
575
Florin Malita094ccde2017-12-30 12:27:00 -0500576 switch (info->fShapeType) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500577 case ShapeType::kTransform:
Florin Malitaca4439f2018-01-23 10:31:59 -0500578 if ((shape_matrix = AttachMatrix(s, shapeCtx->fCtx, nullptr))) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500579 shape_wrapper = sksg::Transform::Make(std::move(shape_wrapper), shape_matrix);
580 }
Florin Malitaca4439f2018-01-23 10:31:59 -0500581 shape_wrapper = AttachOpacity(s, shapeCtx->fCtx, std::move(shape_wrapper));
Florin Malita16d0ad02018-01-19 15:07:29 -0500582 break;
583 case ShapeType::kGeometryEffect:
584 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500585 shapeCtx->fGeometryEffectStack->push_back(
Florin Malita16d0ad02018-01-19 15:07:29 -0500586 { s, gGeometryEffectAttachers[info->fAttacherIndex] });
587 break;
588 default:
589 break;
590 }
591 }
592
593 // Second pass (top -> bottom, after 2x reverse):
594 //
595 // * track local geometry
596 // * emit local paints
597 //
598 std::vector<sk_sp<sksg::GeometryNode>> geos;
599 std::vector<sk_sp<sksg::RenderNode >> draws;
600 for (auto rec = recs.rbegin(); rec != recs.rend(); ++rec) {
601 switch (rec->fInfo.fShapeType) {
Florin Malita094ccde2017-12-30 12:27:00 -0500602 case ShapeType::kGeometry: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500603 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500604 if (auto geo = gGeometryAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
605 shapeCtx->fCtx)) {
Florin Malita094ccde2017-12-30 12:27:00 -0500606 geos.push_back(std::move(geo));
607 }
608 } break;
Florin Malitae6345d92018-01-03 23:37:54 -0500609 case ShapeType::kGeometryEffect: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500610 // Apply the current effect and pop from the stack.
611 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaee6de4b2018-01-21 11:13:17 -0500612 if (!geos.empty()) {
613 geos = gGeometryEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
Florin Malitaca4439f2018-01-23 10:31:59 -0500614 shapeCtx->fCtx,
Florin Malitaee6de4b2018-01-21 11:13:17 -0500615 std::move(geos));
616 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500617
Florin Malitaca4439f2018-01-23 10:31:59 -0500618 SkASSERT(shapeCtx->fGeometryEffectStack->back().fJson == rec->fJson);
619 SkASSERT(shapeCtx->fGeometryEffectStack->back().fAttach ==
Florin Malita16d0ad02018-01-19 15:07:29 -0500620 gGeometryEffectAttachers[rec->fInfo.fAttacherIndex]);
Florin Malitaca4439f2018-01-23 10:31:59 -0500621 shapeCtx->fGeometryEffectStack->pop_back();
Florin Malita094ccde2017-12-30 12:27:00 -0500622 } break;
623 case ShapeType::kGroup: {
Florin Malitaca4439f2018-01-23 10:31:59 -0500624 AttachShapeContext groupShapeCtx(shapeCtx->fCtx,
625 &geos,
626 shapeCtx->fGeometryEffectStack,
627 shapeCtx->fCommittedAnimators);
628 if (auto subgroup = AttachShape(rec->fJson["it"], &groupShapeCtx)) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500629 draws.push_back(std::move(subgroup));
Florin Malitaca4439f2018-01-23 10:31:59 -0500630 SkASSERT(groupShapeCtx.fCommittedAnimators >= shapeCtx->fCommittedAnimators);
631 shapeCtx->fCommittedAnimators = groupShapeCtx.fCommittedAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -0500632 }
633 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500634 case ShapeType::kPaint: {
635 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500636 auto paint = gPaintAttachers[rec->fInfo.fAttacherIndex](rec->fJson, shapeCtx->fCtx);
Florin Malita16d0ad02018-01-19 15:07:29 -0500637 if (!paint || geos.empty())
638 break;
639
640 auto drawGeos = geos;
641
642 // Apply all pending effects from the stack.
Florin Malitaca4439f2018-01-23 10:31:59 -0500643 for (auto it = shapeCtx->fGeometryEffectStack->rbegin();
644 it != shapeCtx->fGeometryEffectStack->rend(); ++it) {
645 drawGeos = it->fAttach(it->fJson, shapeCtx->fCtx, std::move(drawGeos));
Florin Malita18eafd92018-01-04 21:11:55 -0500646 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500647
648 // If we still have multiple geos, reduce using 'merge'.
649 auto geo = drawGeos.size() > 1
650 ? sksg::Merge::Make(std::move(drawGeos), sksg::Merge::Mode::kMerge)
651 : drawGeos[0];
652
653 SkASSERT(geo);
654 draws.push_back(sksg::Draw::Make(std::move(geo), std::move(paint)));
Florin Malitaca4439f2018-01-23 10:31:59 -0500655 shapeCtx->fCommittedAnimators = shapeCtx->fCtx->fAnimators.size();
Florin Malitadacc02b2017-12-31 09:12:31 -0500656 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500657 default:
658 break;
Florin Malita094ccde2017-12-30 12:27:00 -0500659 }
660 }
661
Florin Malita16d0ad02018-01-19 15:07:29 -0500662 // By now we should have popped all local geometry effects.
Florin Malitaca4439f2018-01-23 10:31:59 -0500663 SkASSERT(shapeCtx->fGeometryEffectStack->size() == initialGeometryEffects);
Florin Malita16d0ad02018-01-19 15:07:29 -0500664
665 // Push transformed local geometries to parent list, for subsequent paints.
666 for (const auto& geo : geos) {
Florin Malitaca4439f2018-01-23 10:31:59 -0500667 shapeCtx->fGeometryStack->push_back(shape_matrix
Florin Malita16d0ad02018-01-19 15:07:29 -0500668 ? sksg::GeometryTransform::Make(std::move(geo), shape_matrix)
669 : std::move(geo));
Florin Malita094ccde2017-12-30 12:27:00 -0500670 }
671
Florin Malita16d0ad02018-01-19 15:07:29 -0500672 // Emit local draws reversed (bottom->top, per spec).
673 for (auto it = draws.rbegin(); it != draws.rend(); ++it) {
674 shape_group->addChild(std::move(*it));
Florin Malita2a8275b2018-01-02 12:52:43 -0500675 }
676
Florin Malita16d0ad02018-01-19 15:07:29 -0500677 return draws.empty() ? nullptr : shape_wrapper;
Florin Malita094ccde2017-12-30 12:27:00 -0500678}
679
Florin Malita1022f742018-02-23 11:10:22 -0500680sk_sp<sksg::RenderNode> AttachNestedAnimation(const char* path, AttachContext* ctx) {
681 class SkottieSGAdapter final : public sksg::RenderNode {
682 public:
683 explicit SkottieSGAdapter(sk_sp<Animation> animation)
684 : fAnimation(std::move(animation)) {
685 SkASSERT(fAnimation);
686 }
687
688 protected:
689 SkRect onRevalidate(sksg::InvalidationController*, const SkMatrix&) override {
690 return SkRect::MakeSize(fAnimation->size());
691 }
692
693 void onRender(SkCanvas* canvas) const override {
694 fAnimation->render(canvas);
695 }
696
697 private:
698 const sk_sp<Animation> fAnimation;
699 };
700
701 class SkottieAnimatorAdapter final : public sksg::Animator {
702 public:
703 SkottieAnimatorAdapter(sk_sp<Animation> animation, float frameRate)
704 : fAnimation(std::move(animation))
705 , fFrameRate(frameRate) {
706 SkASSERT(fAnimation);
707 SkASSERT(fFrameRate > 0);
708 }
709
710 protected:
711 void onTick(float t) {
712 // map back from frame # to ms.
713 const auto t_ms = t * 1000 / fFrameRate;
714 fAnimation->animationTick(t_ms);
715 }
716
717 private:
718 const sk_sp<Animation> fAnimation;
719 const float fFrameRate;
720 };
721
722 const auto resStream = ctx->fResources.openStream(path);
723 if (!resStream || !resStream->hasLength()) {
724 LOG("!! Could not open: %s\n", path);
725 return nullptr;
726 }
727
728 auto animation = Animation::Make(resStream.get(), ctx->fResources);
729 if (!animation) {
730 LOG("!! Could not load nested animation: %s\n", path);
731 return nullptr;
732 }
733
734 ctx->fAnimators.push_back(skstd::make_unique<SkottieAnimatorAdapter>(animation,
735 ctx->fFrameRate));
736
737 return sk_make_sp<SkottieSGAdapter>(std::move(animation));
738}
739
Florin Malitaeb87d672018-01-29 15:28:24 -0500740sk_sp<sksg::RenderNode> AttachCompLayer(const Json::Value& jlayer, AttachContext* ctx,
741 float* time_bias, float* time_scale) {
742 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500743
Florin Malitacf8ed522018-01-25 15:27:33 -0500744 SkString refId;
Florin Malitaeb87d672018-01-29 15:28:24 -0500745 if (!Parse(jlayer["refId"], &refId) || refId.isEmpty()) {
Florin Malitadd22cf962018-01-29 15:42:01 +0000746 LOG("!! Comp layer missing refId\n");
Florin Malita094ccde2017-12-30 12:27:00 -0500747 return nullptr;
748 }
749
Florin Malitaeb87d672018-01-29 15:28:24 -0500750 const auto start_time = ParseDefault(jlayer["st"], 0.0f),
751 stretch_time = ParseDefault(jlayer["sr"], 1.0f);
752
753 *time_bias = -start_time;
754 *time_scale = 1 / stretch_time;
755 if (SkScalarIsNaN(*time_scale)) {
756 *time_scale = 1;
757 }
758
Florin Malita1022f742018-02-23 11:10:22 -0500759 if (refId.startsWith("$")) {
760 return AttachNestedAnimation(refId.c_str() + 1, ctx);
761 }
762
763 const auto* comp = ctx->fAssets.find(refId);
764 if (!comp) {
765 LOG("!! Pre-comp not found: '%s'\n", refId.c_str());
766 return nullptr;
767 }
768
Florin Malitadd22cf962018-01-29 15:42:01 +0000769 // TODO: cycle detection
770 return AttachComposition(**comp, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500771}
772
Florin Malitaeb87d672018-01-29 15:28:24 -0500773sk_sp<sksg::RenderNode> AttachSolidLayer(const Json::Value& jlayer, AttachContext*,
774 float*, float*) {
Florin Malita0e66fba2018-01-09 17:10:18 -0500775 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500776
Florin Malitacf8ed522018-01-25 15:27:33 -0500777 const auto size = SkSize::Make(ParseDefault(jlayer["sw"], 0.0f),
778 ParseDefault(jlayer["sh"], 0.0f));
779 const auto hex = ParseDefault(jlayer["sc"], SkString());
Florin Malita0e66fba2018-01-09 17:10:18 -0500780 uint32_t c;
781 if (size.isEmpty() ||
782 !hex.startsWith("#") ||
783 !SkParse::FindHex(hex.c_str() + 1, &c)) {
784 LogFail(jlayer, "Could not parse solid layer");
785 return nullptr;
786 }
787
788 const SkColor color = 0xff000000 | c;
789
790 return sksg::Draw::Make(sksg::Rect::Make(SkRect::MakeSize(size)),
791 sksg::Color::Make(color));
Florin Malita094ccde2017-12-30 12:27:00 -0500792}
793
Florin Malita49328072018-01-08 12:51:12 -0500794sk_sp<sksg::RenderNode> AttachImageAsset(const Json::Value& jimage, AttachContext* ctx) {
795 SkASSERT(jimage.isObject());
796
Florin Malitacf8ed522018-01-25 15:27:33 -0500797 const auto name = ParseDefault(jimage["p"], SkString()),
798 path = ParseDefault(jimage["u"], SkString());
Florin Malita49328072018-01-08 12:51:12 -0500799 if (name.isEmpty())
800 return nullptr;
801
802 // TODO: plumb resource paths explicitly to ResourceProvider?
803 const auto resName = path.isEmpty() ? name : SkOSPath::Join(path.c_str(), name.c_str());
804 const auto resStream = ctx->fResources.openStream(resName.c_str());
805 if (!resStream || !resStream->hasLength()) {
806 LOG("!! Could not load image resource: %s\n", resName.c_str());
807 return nullptr;
808 }
809
810 // TODO: non-intrisic image sizing
811 return sksg::Image::Make(
812 SkImage::MakeFromEncoded(SkData::MakeFromStream(resStream.get(), resStream->getLength())));
813}
814
Florin Malitaeb87d672018-01-29 15:28:24 -0500815sk_sp<sksg::RenderNode> AttachImageLayer(const Json::Value& layer, AttachContext* ctx,
816 float*, float*) {
Florin Malitadd22cf962018-01-29 15:42:01 +0000817 SkASSERT(layer.isObject());
818
819 SkString refId;
820 if (!Parse(layer["refId"], &refId) || refId.isEmpty()) {
821 LOG("!! Image layer missing refId\n");
822 return nullptr;
823 }
824
825 const auto* jimage = ctx->fAssets.find(refId);
826 if (!jimage) {
827 LOG("!! Image asset not found: '%s'\n", refId.c_str());
828 return nullptr;
829 }
830
831 return AttachImageAsset(**jimage, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500832}
833
Florin Malitaeb87d672018-01-29 15:28:24 -0500834sk_sp<sksg::RenderNode> AttachNullLayer(const Json::Value& layer, AttachContext*, float*, float*) {
Florin Malita094ccde2017-12-30 12:27:00 -0500835 SkASSERT(layer.isObject());
836
Florin Malita18eafd92018-01-04 21:11:55 -0500837 // Null layers are used solely to drive dependent transforms,
838 // but we use free-floating sksg::Matrices for that purpose.
Florin Malita094ccde2017-12-30 12:27:00 -0500839 return nullptr;
840}
841
Florin Malitaeb87d672018-01-29 15:28:24 -0500842sk_sp<sksg::RenderNode> AttachShapeLayer(const Json::Value& layer, AttachContext* ctx,
843 float*, float*) {
Florin Malita094ccde2017-12-30 12:27:00 -0500844 SkASSERT(layer.isObject());
845
Florin Malita16d0ad02018-01-19 15:07:29 -0500846 std::vector<sk_sp<sksg::GeometryNode>> geometryStack;
847 std::vector<GeometryEffectRec> geometryEffectStack;
Florin Malitaca4439f2018-01-23 10:31:59 -0500848 AttachShapeContext shapeCtx(ctx, &geometryStack, &geometryEffectStack, ctx->fAnimators.size());
849 auto shapeNode = AttachShape(layer["shapes"], &shapeCtx);
850
851 // Trim uncommitted animators: AttachShape consumes effects on the fly, and greedily attaches
852 // geometries => at the end, we can end up with unused geometries, which are nevertheless alive
853 // due to attached animators. To avoid this, we track committed animators and discard the
854 // orphans here.
855 SkASSERT(shapeCtx.fCommittedAnimators <= ctx->fAnimators.size());
856 ctx->fAnimators.resize(shapeCtx.fCommittedAnimators);
857
858 return shapeNode;
Florin Malita094ccde2017-12-30 12:27:00 -0500859}
860
Florin Malitaeb87d672018-01-29 15:28:24 -0500861sk_sp<sksg::RenderNode> AttachTextLayer(const Json::Value& layer, AttachContext*, float*, float*) {
Florin Malita094ccde2017-12-30 12:27:00 -0500862 SkASSERT(layer.isObject());
863
864 LOG("?? Text layer stub\n");
865 return nullptr;
866}
867
Florin Malita18eafd92018-01-04 21:11:55 -0500868struct AttachLayerContext {
869 AttachLayerContext(const Json::Value& jlayers, AttachContext* ctx)
870 : fLayerList(jlayers), fCtx(ctx) {}
871
Florin Malita4a490682018-01-28 14:27:51 -0500872 const Json::Value& fLayerList;
873 AttachContext* fCtx;
874 SkTHashMap<int, sk_sp<sksg::Matrix>> fLayerMatrixMap;
875 sk_sp<sksg::RenderNode> fCurrentMatte;
Florin Malita18eafd92018-01-04 21:11:55 -0500876
Florin Malita4a490682018-01-28 14:27:51 -0500877 sk_sp<sksg::Matrix> AttachParentLayerMatrix(const Json::Value& jlayer) {
878 SkASSERT(jlayer.isObject());
Florin Malita18eafd92018-01-04 21:11:55 -0500879 SkASSERT(fLayerList.isArray());
880
Florin Malita4a490682018-01-28 14:27:51 -0500881 const auto parent_index = ParseDefault(jlayer["parent"], -1);
882 if (parent_index < 0)
Florin Malita18eafd92018-01-04 21:11:55 -0500883 return nullptr;
Florin Malita18eafd92018-01-04 21:11:55 -0500884
Florin Malita4a490682018-01-28 14:27:51 -0500885 if (auto* m = fLayerMatrixMap.find(parent_index))
886 return *m;
Florin Malita18eafd92018-01-04 21:11:55 -0500887
888 for (const auto& l : fLayerList) {
889 if (!l.isObject()) {
890 continue;
891 }
892
Florin Malita4a490682018-01-28 14:27:51 -0500893 if (ParseDefault(l["ind"], -1) == parent_index) {
894 return this->AttachLayerMatrix(l);
Florin Malita18eafd92018-01-04 21:11:55 -0500895 }
896 }
897
898 return nullptr;
899 }
900
901 sk_sp<sksg::Matrix> AttachLayerMatrix(const Json::Value& jlayer) {
902 SkASSERT(jlayer.isObject());
903
Florin Malita4a490682018-01-28 14:27:51 -0500904 const auto layer_index = ParseDefault(jlayer["ind"], -1);
905 if (layer_index < 0)
906 return nullptr;
Florin Malita18eafd92018-01-04 21:11:55 -0500907
Florin Malita4a490682018-01-28 14:27:51 -0500908 if (auto* m = fLayerMatrixMap.find(layer_index))
909 return *m;
Florin Malita18eafd92018-01-04 21:11:55 -0500910
Florin Malita4a490682018-01-28 14:27:51 -0500911 // Add a stub entry to break recursion cycles.
912 fLayerMatrixMap.set(layer_index, nullptr);
Florin Malita18eafd92018-01-04 21:11:55 -0500913
Florin Malita4a490682018-01-28 14:27:51 -0500914 auto parent_matrix = this->AttachParentLayerMatrix(jlayer);
Florin Malita18eafd92018-01-04 21:11:55 -0500915
Florin Malita4a490682018-01-28 14:27:51 -0500916 return *fLayerMatrixMap.set(layer_index,
917 AttachMatrix(jlayer["ks"],
918 fCtx,
919 this->AttachParentLayerMatrix(jlayer)));
Florin Malita18eafd92018-01-04 21:11:55 -0500920 }
921};
922
Florin Malita25366fa2018-01-23 13:37:59 -0500923SkBlendMode MaskBlendMode(char mode) {
924 switch (mode) {
925 case 'a': return SkBlendMode::kSrcOver; // Additive
926 case 's': return SkBlendMode::kExclusion; // Subtract
927 case 'i': return SkBlendMode::kDstIn; // Intersect
928 case 'l': return SkBlendMode::kLighten; // Lighten
929 case 'd': return SkBlendMode::kDarken; // Darken
930 case 'f': return SkBlendMode::kDifference; // Difference
931 default: break;
932 }
933
934 return SkBlendMode::kSrcOver;
935}
936
937sk_sp<sksg::RenderNode> AttachMask(const Json::Value& jmask,
938 AttachContext* ctx,
939 sk_sp<sksg::RenderNode> childNode) {
940 if (!jmask.isArray())
941 return childNode;
942
943 auto mask_group = sksg::Group::Make();
944
945 for (const auto& m : jmask) {
946 if (!m.isObject())
947 continue;
948
Florin Malitacf8ed522018-01-25 15:27:33 -0500949 const auto inverted = ParseDefault(m["inv"], false);
Florin Malita25366fa2018-01-23 13:37:59 -0500950 // TODO
951 if (inverted) {
952 LogFail(m, "Unsupported inverse mask");
953 continue;
954 }
955
956 auto mask_path = AttachPath(m["pt"], ctx);
957 if (!mask_path) {
958 LogFail(m, "Could not parse mask path");
959 continue;
960 }
961
Florin Malitacf8ed522018-01-25 15:27:33 -0500962 SkString mode;
963 if (!Parse(m["mode"], &mode) ||
964 mode.size() != 1 ||
965 !strcmp(mode.c_str(), "n")) { // "None" masks have no effect.
Florin Malita25366fa2018-01-23 13:37:59 -0500966 continue;
Florin Malitacf8ed522018-01-25 15:27:33 -0500967 }
Florin Malita25366fa2018-01-23 13:37:59 -0500968
969 auto mask_paint = sksg::Color::Make(SK_ColorBLACK);
Florin Malitaaa71c892018-01-30 09:27:01 -0500970 mask_paint->setAntiAlias(true);
Florin Malita25366fa2018-01-23 13:37:59 -0500971 mask_paint->setBlendMode(MaskBlendMode(mode.c_str()[0]));
Florin Malitafc807c82018-01-25 22:35:09 -0500972 BindProperty<ScalarValue>(m["o"], &ctx->fAnimators,
Florin Malita2518a0a2018-01-24 18:29:00 -0500973 [mask_paint](const ScalarValue& o) { mask_paint->setOpacity(o * 0.01f); });
Florin Malita25366fa2018-01-23 13:37:59 -0500974
975 mask_group->addChild(sksg::Draw::Make(std::move(mask_path), std::move(mask_paint)));
976 }
977
978 return mask_group->empty()
979 ? childNode
980 : sksg::MaskEffect::Make(std::move(childNode), std::move(mask_group));
981}
982
Florin Malita18eafd92018-01-04 21:11:55 -0500983sk_sp<sksg::RenderNode> AttachLayer(const Json::Value& jlayer,
984 AttachLayerContext* layerCtx) {
985 if (!jlayer.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500986 return nullptr;
987
Florin Malitaeb87d672018-01-29 15:28:24 -0500988 using LayerAttacher = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*,
989 float* time_bias, float* time_scale);
Florin Malita094ccde2017-12-30 12:27:00 -0500990 static constexpr LayerAttacher gLayerAttachers[] = {
991 AttachCompLayer, // 'ty': 0
992 AttachSolidLayer, // 'ty': 1
993 AttachImageLayer, // 'ty': 2
994 AttachNullLayer, // 'ty': 3
995 AttachShapeLayer, // 'ty': 4
996 AttachTextLayer, // 'ty': 5
997 };
998
Florin Malitacf8ed522018-01-25 15:27:33 -0500999 int type = ParseDefault(jlayer["ty"], -1);
Florin Malita094ccde2017-12-30 12:27:00 -05001000 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gLayerAttachers))) {
1001 return nullptr;
1002 }
1003
Florin Malitacca86f32018-01-29 10:49:49 -05001004 sksg::AnimatorList layer_animators;
Florin Malita1022f742018-02-23 11:10:22 -05001005 AttachContext local_ctx = { layerCtx->fCtx->fResources,
1006 layerCtx->fCtx->fAssets,
1007 layerCtx->fCtx->fFrameRate,
1008 layer_animators};
Florin Malitacca86f32018-01-29 10:49:49 -05001009
Florin Malitaeb87d672018-01-29 15:28:24 -05001010 // Layer attachers may adjust these.
1011 float time_bias = 0,
1012 time_scale = 1;
1013
Florin Malita71cba8f2018-01-09 08:07:14 -05001014 // Layer content.
Florin Malitaeb87d672018-01-29 15:28:24 -05001015 auto layer = gLayerAttachers[type](jlayer, &local_ctx, &time_bias, &time_scale);
Florin Malita38ea40e2018-01-29 16:31:14 -05001016
1017 // Clip layers with explicit dimensions.
1018 float w, h;
1019 if (Parse(jlayer["w"], &w) && Parse(jlayer["h"], &h)) {
1020 layer = sksg::ClipEffect::Make(std::move(layer),
1021 sksg::Rect::Make(SkRect::MakeWH(w, h)),
1022 true);
1023 }
1024
Florin Malita25366fa2018-01-23 13:37:59 -05001025 // Optional layer mask.
Florin Malitacca86f32018-01-29 10:49:49 -05001026 layer = AttachMask(jlayer["masksProperties"], &local_ctx, std::move(layer));
Florin Malita38ea40e2018-01-29 16:31:14 -05001027
Florin Malita25366fa2018-01-23 13:37:59 -05001028 // Optional layer transform.
Florin Malita71cba8f2018-01-09 08:07:14 -05001029 if (auto layerMatrix = layerCtx->AttachLayerMatrix(jlayer)) {
Florin Malita71cba8f2018-01-09 08:07:14 -05001030 layer = sksg::Transform::Make(std::move(layer), std::move(layerMatrix));
1031 }
Florin Malita38ea40e2018-01-29 16:31:14 -05001032
Florin Malita71cba8f2018-01-09 08:07:14 -05001033 // Optional layer opacity.
Florin Malitacca86f32018-01-29 10:49:49 -05001034 layer = AttachOpacity(jlayer["ks"], &local_ctx, std::move(layer));
Florin Malita18eafd92018-01-04 21:11:55 -05001035
Florin Malitaeb87d672018-01-29 15:28:24 -05001036 class LayerController final : public sksg::GroupAnimator {
Florin Malita71cba8f2018-01-09 08:07:14 -05001037 public:
Florin Malitaeb87d672018-01-29 15:28:24 -05001038 LayerController(sksg::AnimatorList&& layer_animators,
1039 sk_sp<sksg::OpacityEffect> controlNode,
1040 float in, float out,
1041 float time_bias, float time_scale)
Florin Malitacca86f32018-01-29 10:49:49 -05001042 : INHERITED(std::move(layer_animators))
1043 , fControlNode(std::move(controlNode))
Florin Malita71cba8f2018-01-09 08:07:14 -05001044 , fIn(in)
Florin Malitaeb87d672018-01-29 15:28:24 -05001045 , fOut(out)
1046 , fTimeBias(time_bias)
1047 , fTimeScale(time_scale) {}
Florin Malita71cba8f2018-01-09 08:07:14 -05001048
Florin Malita35efaa82018-01-22 12:57:06 -05001049 void onTick(float t) override {
Florin Malitacca86f32018-01-29 10:49:49 -05001050 const auto active = (t >= fIn && t <= fOut);
1051
Florin Malita71cba8f2018-01-09 08:07:14 -05001052 // Keep the layer fully transparent except for its [in..out] lifespan.
1053 // (note: opacity == 0 disables rendering, while opacity == 1 is a noop)
Florin Malitacca86f32018-01-29 10:49:49 -05001054 fControlNode->setOpacity(active ? 1 : 0);
1055
1056 // Dispatch ticks only while active.
1057 if (active)
Florin Malitaeb87d672018-01-29 15:28:24 -05001058 this->INHERITED::onTick((t + fTimeBias) * fTimeScale);
Florin Malita71cba8f2018-01-09 08:07:14 -05001059 }
1060
1061 private:
1062 const sk_sp<sksg::OpacityEffect> fControlNode;
1063 const float fIn,
Florin Malitaeb87d672018-01-29 15:28:24 -05001064 fOut,
1065 fTimeBias,
1066 fTimeScale;
Florin Malitacca86f32018-01-29 10:49:49 -05001067
1068 using INHERITED = sksg::GroupAnimator;
Florin Malita71cba8f2018-01-09 08:07:14 -05001069 };
1070
Florin Malitaeb87d672018-01-29 15:28:24 -05001071 auto controller_node = sksg::OpacityEffect::Make(std::move(layer));
1072 const auto in = ParseDefault(jlayer["ip"], 0.0f),
1073 out = ParseDefault(jlayer["op"], in);
Florin Malita71cba8f2018-01-09 08:07:14 -05001074
Florin Malitaeb87d672018-01-29 15:28:24 -05001075 if (!jlayer["tm"].isNull()) {
1076 LogFail(jlayer["tm"], "Unsupported time remapping");
1077 }
1078
1079 if (in >= out || !controller_node)
Florin Malita71cba8f2018-01-09 08:07:14 -05001080 return nullptr;
1081
Florin Malitacca86f32018-01-29 10:49:49 -05001082 layerCtx->fCtx->fAnimators.push_back(
Florin Malitaeb87d672018-01-29 15:28:24 -05001083 skstd::make_unique<LayerController>(std::move(layer_animators),
1084 controller_node,
1085 in,
1086 out,
1087 time_bias,
1088 time_scale));
Florin Malita71cba8f2018-01-09 08:07:14 -05001089
Florin Malitacf8ed522018-01-25 15:27:33 -05001090 if (ParseDefault(jlayer["td"], false)) {
Florin Malita5f9102f2018-01-10 13:36:22 -05001091 // This layer is a matte. We apply it as a mask to the next layer.
Florin Malitaeb87d672018-01-29 15:28:24 -05001092 layerCtx->fCurrentMatte = std::move(controller_node);
Florin Malita5f9102f2018-01-10 13:36:22 -05001093 return nullptr;
1094 }
1095
1096 if (layerCtx->fCurrentMatte) {
1097 // There is a pending matte. Apply and reset.
Florin Malitaeb87d672018-01-29 15:28:24 -05001098 return sksg::MaskEffect::Make(std::move(controller_node),
1099 std::move(layerCtx->fCurrentMatte));
Florin Malita5f9102f2018-01-10 13:36:22 -05001100 }
1101
Florin Malitaeb87d672018-01-29 15:28:24 -05001102 return controller_node;
Florin Malita094ccde2017-12-30 12:27:00 -05001103}
1104
1105sk_sp<sksg::RenderNode> AttachComposition(const Json::Value& comp, AttachContext* ctx) {
1106 if (!comp.isObject())
1107 return nullptr;
1108
Florin Malita18eafd92018-01-04 21:11:55 -05001109 const auto& jlayers = comp["layers"];
1110 if (!jlayers.isArray())
1111 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -05001112
Florin Malita18eafd92018-01-04 21:11:55 -05001113 SkSTArray<16, sk_sp<sksg::RenderNode>, true> layers;
1114 AttachLayerContext layerCtx(jlayers, ctx);
1115
1116 for (const auto& l : jlayers) {
1117 if (auto layer_fragment = AttachLayer(l, &layerCtx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -05001118 layers.push_back(std::move(layer_fragment));
Florin Malita094ccde2017-12-30 12:27:00 -05001119 }
1120 }
1121
Florin Malita2a8275b2018-01-02 12:52:43 -05001122 if (layers.empty()) {
1123 return nullptr;
1124 }
1125
1126 // Layers are painted in bottom->top order.
1127 auto comp_group = sksg::Group::Make();
1128 for (int i = layers.count() - 1; i >= 0; --i) {
1129 comp_group->addChild(std::move(layers[i]));
1130 }
1131
1132 LOG("** Attached composition '%s': %d layers.\n",
Florin Malitacf8ed522018-01-25 15:27:33 -05001133 ParseDefault(comp["id"], SkString()).c_str(), layers.count());
Florin Malita2a8275b2018-01-02 12:52:43 -05001134
Florin Malita094ccde2017-12-30 12:27:00 -05001135 return comp_group;
1136}
1137
1138} // namespace
1139
Florin Malita1022f742018-02-23 11:10:22 -05001140sk_sp<Animation> Animation::Make(SkStream* stream, const ResourceProvider& res) {
Florin Malita094ccde2017-12-30 12:27:00 -05001141 if (!stream->hasLength()) {
1142 // TODO: handle explicit buffering?
1143 LOG("!! cannot parse streaming content\n");
1144 return nullptr;
1145 }
1146
1147 Json::Value json;
1148 {
1149 auto data = SkData::MakeFromStream(stream, stream->getLength());
1150 if (!data) {
1151 LOG("!! could not read stream\n");
1152 return nullptr;
1153 }
1154
1155 Json::Reader reader;
1156
1157 auto dataStart = static_cast<const char*>(data->data());
1158 if (!reader.parse(dataStart, dataStart + data->size(), json, false) || !json.isObject()) {
1159 LOG("!! failed to parse json: %s\n", reader.getFormattedErrorMessages().c_str());
1160 return nullptr;
1161 }
1162 }
1163
Florin Malitacf8ed522018-01-25 15:27:33 -05001164 const auto version = ParseDefault(json["v"], SkString());
1165 const auto size = SkSize::Make(ParseDefault(json["w"], 0.0f),
1166 ParseDefault(json["h"], 0.0f));
1167 const auto fps = ParseDefault(json["fr"], -1.0f);
Florin Malita094ccde2017-12-30 12:27:00 -05001168
Florin Malita1022f742018-02-23 11:10:22 -05001169 if (size.isEmpty() || version.isEmpty() || fps <= 0) {
Florin Malita094ccde2017-12-30 12:27:00 -05001170 LOG("!! invalid animation params (version: %s, size: [%f %f], frame rate: %f)",
1171 version.c_str(), size.width(), size.height(), fps);
1172 return nullptr;
1173 }
1174
Florin Malita1022f742018-02-23 11:10:22 -05001175 return sk_sp<Animation>(new Animation(res, std::move(version), size, fps, json));
Florin Malita094ccde2017-12-30 12:27:00 -05001176}
1177
Florin Malita1022f742018-02-23 11:10:22 -05001178sk_sp<Animation> Animation::MakeFromFile(const char path[], const ResourceProvider* res) {
Florin Malita49328072018-01-08 12:51:12 -05001179 class DirectoryResourceProvider final : public ResourceProvider {
1180 public:
1181 explicit DirectoryResourceProvider(SkString dir) : fDir(std::move(dir)) {}
1182
1183 std::unique_ptr<SkStream> openStream(const char resource[]) const override {
1184 const auto resPath = SkOSPath::Join(fDir.c_str(), resource);
1185 return SkStream::MakeFromFile(resPath.c_str());
1186 }
1187
1188 private:
1189 const SkString fDir;
1190 };
1191
1192 const auto jsonStream = SkStream::MakeFromFile(path);
1193 if (!jsonStream)
1194 return nullptr;
1195
1196 std::unique_ptr<ResourceProvider> defaultProvider;
1197 if (!res) {
1198 defaultProvider = skstd::make_unique<DirectoryResourceProvider>(SkOSPath::Dirname(path));
1199 }
1200
1201 return Make(jsonStream.get(), res ? *res : *defaultProvider);
1202}
1203
1204Animation::Animation(const ResourceProvider& resources,
1205 SkString version, const SkSize& size, SkScalar fps, const Json::Value& json)
Florin Malita094ccde2017-12-30 12:27:00 -05001206 : fVersion(std::move(version))
1207 , fSize(size)
1208 , fFrameRate(fps)
Florin Malitacf8ed522018-01-25 15:27:33 -05001209 , fInPoint(ParseDefault(json["ip"], 0.0f))
1210 , fOutPoint(SkTMax(ParseDefault(json["op"], SK_ScalarMax), fInPoint)) {
Florin Malita094ccde2017-12-30 12:27:00 -05001211
1212 AssetMap assets;
1213 for (const auto& asset : json["assets"]) {
1214 if (!asset.isObject()) {
1215 continue;
1216 }
1217
Florin Malitadd22cf962018-01-29 15:42:01 +00001218 assets.set(ParseDefault(asset["id"], SkString()), &asset);
Florin Malita094ccde2017-12-30 12:27:00 -05001219 }
1220
Florin Malitacca86f32018-01-29 10:49:49 -05001221 sksg::AnimatorList animators;
Florin Malita1022f742018-02-23 11:10:22 -05001222 AttachContext ctx = { resources, assets, fFrameRate, animators };
Florin Malita35efaa82018-01-22 12:57:06 -05001223 auto root = AttachComposition(json, &ctx);
1224
1225 LOG("** Attached %d animators\n", animators.size());
1226
1227 fScene = sksg::Scene::Make(std::move(root), std::move(animators));
Florin Malita094ccde2017-12-30 12:27:00 -05001228
Florin Malitadb385732018-01-09 12:19:32 -05001229 // In case the client calls render before the first tick.
1230 this->animationTick(0);
Florin Malita094ccde2017-12-30 12:27:00 -05001231}
1232
1233Animation::~Animation() = default;
1234
Florin Malita35efaa82018-01-22 12:57:06 -05001235void Animation::setShowInval(bool show) {
1236 if (fScene) {
1237 fScene->setShowInval(show);
1238 }
1239}
1240
Mike Reed29859872018-01-08 08:25:27 -05001241void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
Florin Malita35efaa82018-01-22 12:57:06 -05001242 if (!fScene)
Florin Malita094ccde2017-12-30 12:27:00 -05001243 return;
1244
Mike Reed29859872018-01-08 08:25:27 -05001245 SkAutoCanvasRestore restore(canvas, true);
1246 const SkRect srcR = SkRect::MakeSize(this->size());
1247 if (dstR) {
1248 canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
1249 }
1250 canvas->clipRect(srcR);
Florin Malita35efaa82018-01-22 12:57:06 -05001251 fScene->render(canvas);
Florin Malita094ccde2017-12-30 12:27:00 -05001252}
1253
1254void Animation::animationTick(SkMSec ms) {
Florin Malita35efaa82018-01-22 12:57:06 -05001255 if (!fScene)
1256 return;
1257
Florin Malita094ccde2017-12-30 12:27:00 -05001258 // 't' in the BM model really means 'frame #'
1259 auto t = static_cast<float>(ms) * fFrameRate / 1000;
1260
1261 t = fInPoint + std::fmod(t, fOutPoint - fInPoint);
1262
Florin Malita35efaa82018-01-22 12:57:06 -05001263 fScene->animate(t);
Florin Malita094ccde2017-12-30 12:27:00 -05001264}
1265
Florin Malita54f65c42018-01-16 17:04:30 -05001266} // namespace skottie