blob: becf3bf470096393c01f4490e3d825cdd516d778 [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 Malita54f65c42018-01-16 17:04:30 -050011#include "SkottieAnimator.h"
12#include "SkottiePriv.h"
13#include "SkottieProperties.h"
Florin Malita094ccde2017-12-30 12:27:00 -050014#include "SkData.h"
Florin Malita49328072018-01-08 12:51:12 -050015#include "SkImage.h"
Florin Malita094ccde2017-12-30 12:27:00 -050016#include "SkMakeUnique.h"
Florin Malita49328072018-01-08 12:51:12 -050017#include "SkOSPath.h"
Florin Malita094ccde2017-12-30 12:27:00 -050018#include "SkPaint.h"
Florin Malita0e66fba2018-01-09 17:10:18 -050019#include "SkParse.h"
Florin Malita094ccde2017-12-30 12:27:00 -050020#include "SkPath.h"
21#include "SkPoint.h"
22#include "SkSGColor.h"
23#include "SkSGDraw.h"
Florin Malita16d0ad02018-01-19 15:07:29 -050024#include "SkSGGeometryTransform.h"
Florin Malita6aaee592018-01-12 12:25:09 -050025#include "SkSGGradient.h"
Florin Malita094ccde2017-12-30 12:27:00 -050026#include "SkSGGroup.h"
Florin Malita49328072018-01-08 12:51:12 -050027#include "SkSGImage.h"
28#include "SkSGInvalidationController.h"
Florin Malita5f9102f2018-01-10 13:36:22 -050029#include "SkSGMaskEffect.h"
Florin Malitae6345d92018-01-03 23:37:54 -050030#include "SkSGMerge.h"
Florin Malitac0034172018-01-08 16:42:59 -050031#include "SkSGOpacityEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050032#include "SkSGPath.h"
Florin Malita2e1d7e22018-01-02 10:40:00 -050033#include "SkSGRect.h"
Florin Malita35efaa82018-01-22 12:57:06 -050034#include "SkSGScene.h"
Florin Malita094ccde2017-12-30 12:27:00 -050035#include "SkSGTransform.h"
Florin Malita51b8c892018-01-07 08:54:24 -050036#include "SkSGTrimEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050037#include "SkStream.h"
38#include "SkTArray.h"
39#include "SkTHash.h"
40
41#include <cmath>
Florin Malita18eafd92018-01-04 21:11:55 -050042#include <unordered_map>
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
49namespace {
50
51using AssetMap = SkTHashMap<SkString, const Json::Value*>;
52
53struct AttachContext {
Florin Malita35efaa82018-01-22 12:57:06 -050054 const ResourceProvider& fResources;
55 const AssetMap& fAssets;
56 sksg::Scene::AnimatorList& fAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -050057};
58
59bool LogFail(const Json::Value& json, const char* msg) {
60 const auto dump = json.toStyledString();
61 LOG("!! %s: %s", msg, dump.c_str());
62 return false;
63}
64
65// This is the workhorse for binding properties: depending on whether the property is animated,
66// it will either apply immediately or instantiate and attach a keyframe animator.
Florin Malitaf9590922018-01-09 11:56:09 -050067template <typename ValT, typename NodeT>
68bool BindProperty(const Json::Value& jprop, AttachContext* ctx, const sk_sp<NodeT>& node,
69 typename Animator<ValT, NodeT>::ApplyFuncT&& apply) {
Florin Malita094ccde2017-12-30 12:27:00 -050070 if (!jprop.isObject())
71 return false;
72
Florin Malita95448a92018-01-08 10:15:12 -050073 const auto& jpropA = jprop["a"];
74 const auto& jpropK = jprop["k"];
75
76 // Older Json versions don't have an "a" animation marker.
77 // For those, we attempt to parse both ways.
78 if (jpropA.isNull() || !ParseBool(jpropA, "false")) {
Florin Malitaf9590922018-01-09 11:56:09 -050079 ValT val;
80 if (ValueTraits<ValT>::Parse(jpropK, &val)) {
Florin Malita95448a92018-01-08 10:15:12 -050081 // Static property.
Florin Malitaf9590922018-01-09 11:56:09 -050082 apply(node.get(), val);
Florin Malita95448a92018-01-08 10:15:12 -050083 return true;
Florin Malita094ccde2017-12-30 12:27:00 -050084 }
85
Florin Malita95448a92018-01-08 10:15:12 -050086 if (!jpropA.isNull()) {
87 return LogFail(jprop, "Could not parse (explicit) static property");
Florin Malita094ccde2017-12-30 12:27:00 -050088 }
Florin Malita094ccde2017-12-30 12:27:00 -050089 }
90
Florin Malita95448a92018-01-08 10:15:12 -050091 // Keyframe property.
Florin Malitaf9590922018-01-09 11:56:09 -050092 using AnimatorT = Animator<ValT, NodeT>;
93 auto animator = AnimatorT::Make(ParseFrames<ValT>(jpropK), node, std::move(apply));
Florin Malita95448a92018-01-08 10:15:12 -050094
95 if (!animator) {
96 return LogFail(jprop, "Could not parse keyframed property");
97 }
98
99 ctx->fAnimators.push_back(std::move(animator));
100
Florin Malita094ccde2017-12-30 12:27:00 -0500101 return true;
102}
103
Florin Malita18eafd92018-01-04 21:11:55 -0500104sk_sp<sksg::Matrix> AttachMatrix(const Json::Value& t, AttachContext* ctx,
105 sk_sp<sksg::Matrix> parentMatrix) {
106 if (!t.isObject())
107 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500108
Florin Malita18eafd92018-01-04 21:11:55 -0500109 auto matrix = sksg::Matrix::Make(SkMatrix::I(), std::move(parentMatrix));
110 auto composite = sk_make_sp<CompositeTransform>(matrix);
Florin Malitaf9590922018-01-09 11:56:09 -0500111 auto anchor_attached = BindProperty<VectorValue>(t["a"], ctx, composite,
112 [](CompositeTransform* node, const VectorValue& a) {
113 node->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
Florin Malita094ccde2017-12-30 12:27:00 -0500114 });
Florin Malitaf9590922018-01-09 11:56:09 -0500115 auto position_attached = BindProperty<VectorValue>(t["p"], ctx, composite,
116 [](CompositeTransform* node, const VectorValue& p) {
117 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malita094ccde2017-12-30 12:27:00 -0500118 });
Florin Malitaf9590922018-01-09 11:56:09 -0500119 auto scale_attached = BindProperty<VectorValue>(t["s"], ctx, composite,
120 [](CompositeTransform* node, const VectorValue& s) {
121 node->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
Florin Malita094ccde2017-12-30 12:27:00 -0500122 });
Florin Malitaf9590922018-01-09 11:56:09 -0500123 auto rotation_attached = BindProperty<ScalarValue>(t["r"], ctx, composite,
124 [](CompositeTransform* node, const ScalarValue& r) {
Florin Malita094ccde2017-12-30 12:27:00 -0500125 node->setRotation(r);
126 });
Florin Malitaf9590922018-01-09 11:56:09 -0500127 auto skew_attached = BindProperty<ScalarValue>(t["sk"], ctx, composite,
128 [](CompositeTransform* node, const ScalarValue& sk) {
Florin Malita094ccde2017-12-30 12:27:00 -0500129 node->setSkew(sk);
130 });
Florin Malitaf9590922018-01-09 11:56:09 -0500131 auto skewaxis_attached = BindProperty<ScalarValue>(t["sa"], ctx, composite,
132 [](CompositeTransform* node, const ScalarValue& sa) {
Florin Malita094ccde2017-12-30 12:27:00 -0500133 node->setSkewAxis(sa);
134 });
135
136 if (!anchor_attached &&
137 !position_attached &&
138 !scale_attached &&
139 !rotation_attached &&
140 !skew_attached &&
141 !skewaxis_attached) {
142 LogFail(t, "Could not parse transform");
Florin Malita18eafd92018-01-04 21:11:55 -0500143 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500144 }
145
Florin Malita18eafd92018-01-04 21:11:55 -0500146 return matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500147}
148
Florin Malitac0034172018-01-08 16:42:59 -0500149sk_sp<sksg::RenderNode> AttachOpacity(const Json::Value& jtransform, AttachContext* ctx,
150 sk_sp<sksg::RenderNode> childNode) {
151 if (!jtransform.isObject() || !childNode)
152 return childNode;
153
154 // This is more peeky than other attachers, because we want to avoid redundant opacity
155 // nodes for the extremely common case of static opaciy == 100.
156 const auto& opacity = jtransform["o"];
157 if (opacity.isObject() &&
158 !ParseBool(opacity["a"], true) &&
159 ParseScalar(opacity["k"], -1) == 100) {
160 // Ignoring static full opacity.
161 return childNode;
162 }
163
164 auto opacityNode = sksg::OpacityEffect::Make(childNode);
Florin Malitaf9590922018-01-09 11:56:09 -0500165 BindProperty<ScalarValue>(opacity, ctx, opacityNode,
166 [](sksg::OpacityEffect* node, const ScalarValue& o) {
Florin Malitac0034172018-01-08 16:42:59 -0500167 // BM opacity is [0..100]
168 node->setOpacity(o * 0.01f);
169 });
170
171 return opacityNode;
172}
173
Florin Malita094ccde2017-12-30 12:27:00 -0500174sk_sp<sksg::RenderNode> AttachComposition(const Json::Value&, AttachContext* ctx);
175
Florin Malita094ccde2017-12-30 12:27:00 -0500176sk_sp<sksg::GeometryNode> AttachPathGeometry(const Json::Value& jpath, AttachContext* ctx) {
177 SkASSERT(jpath.isObject());
178
179 auto path_node = sksg::Path::Make();
Florin Malitaf9590922018-01-09 11:56:09 -0500180 auto path_attached = BindProperty<ShapeValue>(jpath["ks"], ctx, path_node,
181 [](sksg::Path* node, const ShapeValue& p) { node->setPath(p); });
Florin Malita094ccde2017-12-30 12:27:00 -0500182
183 if (path_attached)
184 LOG("** Attached path geometry - verbs: %d\n", path_node->getPath().countVerbs());
185
186 return path_attached ? path_node : nullptr;
187}
188
Florin Malita2e1d7e22018-01-02 10:40:00 -0500189sk_sp<sksg::GeometryNode> AttachRRectGeometry(const Json::Value& jrect, AttachContext* ctx) {
190 SkASSERT(jrect.isObject());
191
192 auto rect_node = sksg::RRect::Make();
193 auto composite = sk_make_sp<CompositeRRect>(rect_node);
194
Florin Malitaf9590922018-01-09 11:56:09 -0500195 auto p_attached = BindProperty<VectorValue>(jrect["p"], ctx, composite,
196 [](CompositeRRect* node, const VectorValue& p) {
197 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
198 });
199 auto s_attached = BindProperty<VectorValue>(jrect["s"], ctx, composite,
200 [](CompositeRRect* node, const VectorValue& s) {
201 node->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
202 });
203 auto r_attached = BindProperty<ScalarValue>(jrect["r"], ctx, composite,
204 [](CompositeRRect* node, const ScalarValue& r) {
205 node->setRadius(SkSize::Make(r, r));
206 });
Florin Malita2e1d7e22018-01-02 10:40:00 -0500207
208 if (!p_attached && !s_attached && !r_attached) {
209 return nullptr;
210 }
211
Florin Malitafbc13f12018-01-04 10:26:35 -0500212 LOG("** Attached (r)rect geometry\n");
213
214 return rect_node;
215}
216
217sk_sp<sksg::GeometryNode> AttachEllipseGeometry(const Json::Value& jellipse, AttachContext* ctx) {
218 SkASSERT(jellipse.isObject());
219
220 auto rect_node = sksg::RRect::Make();
221 auto composite = sk_make_sp<CompositeRRect>(rect_node);
222
Florin Malitaf9590922018-01-09 11:56:09 -0500223 auto p_attached = BindProperty<VectorValue>(jellipse["p"], ctx, composite,
224 [](CompositeRRect* node, const VectorValue& p) {
225 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
226 });
227 auto s_attached = BindProperty<VectorValue>(jellipse["s"], ctx, composite,
228 [](CompositeRRect* node, const VectorValue& s) {
229 const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
230 node->setSize(sz);
231 node->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
232 });
Florin Malitafbc13f12018-01-04 10:26:35 -0500233
234 if (!p_attached && !s_attached) {
235 return nullptr;
236 }
237
238 LOG("** Attached ellipse geometry\n");
239
Florin Malita2e1d7e22018-01-02 10:40:00 -0500240 return rect_node;
241}
242
Florin Malita02a32b02018-01-04 11:27:09 -0500243sk_sp<sksg::GeometryNode> AttachPolystarGeometry(const Json::Value& jstar, AttachContext* ctx) {
244 SkASSERT(jstar.isObject());
245
246 static constexpr CompositePolyStar::Type gTypes[] = {
247 CompositePolyStar::Type::kStar, // "sy": 1
248 CompositePolyStar::Type::kPoly, // "sy": 2
249 };
250
251 const auto type = ParseInt(jstar["sy"], 0) - 1;
252 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gTypes))) {
253 LogFail(jstar, "Unknown polystar type");
254 return nullptr;
255 }
256
257 auto path_node = sksg::Path::Make();
258 auto composite = sk_make_sp<CompositePolyStar>(path_node, gTypes[type]);
259
Florin Malitaf9590922018-01-09 11:56:09 -0500260 BindProperty<VectorValue>(jstar["p"], ctx, composite,
261 [](CompositePolyStar* node, const VectorValue& p) {
262 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
263 });
264 BindProperty<ScalarValue>(jstar["pt"], ctx, composite,
265 [](CompositePolyStar* node, const ScalarValue& pt) {
266 node->setPointCount(pt);
267 });
268 BindProperty<ScalarValue>(jstar["ir"], ctx, composite,
269 [](CompositePolyStar* node, const ScalarValue& ir) {
270 node->setInnerRadius(ir);
271 });
272 BindProperty<ScalarValue>(jstar["or"], ctx, composite,
273 [](CompositePolyStar* node, const ScalarValue& otr) {
Florin Malita9661b982018-01-06 14:25:49 -0500274 node->setOuterRadius(otr);
275 });
Florin Malitaf9590922018-01-09 11:56:09 -0500276 BindProperty<ScalarValue>(jstar["is"], ctx, composite,
277 [](CompositePolyStar* node, const ScalarValue& is) {
Florin Malita9661b982018-01-06 14:25:49 -0500278 node->setInnerRoundness(is);
279 });
Florin Malitaf9590922018-01-09 11:56:09 -0500280 BindProperty<ScalarValue>(jstar["os"], ctx, composite,
281 [](CompositePolyStar* node, const ScalarValue& os) {
Florin Malita9661b982018-01-06 14:25:49 -0500282 node->setOuterRoundness(os);
283 });
Florin Malitaf9590922018-01-09 11:56:09 -0500284 BindProperty<ScalarValue>(jstar["r"], ctx, composite,
285 [](CompositePolyStar* node, const ScalarValue& r) {
286 node->setRotation(r);
287 });
Florin Malita02a32b02018-01-04 11:27:09 -0500288
289 return path_node;
290}
291
Florin Malita6aaee592018-01-12 12:25:09 -0500292sk_sp<sksg::Color> AttachColor(const Json::Value& obj, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500293 SkASSERT(obj.isObject());
294
295 auto color_node = sksg::Color::Make(SK_ColorBLACK);
Florin Malita1586d852018-01-12 14:27:39 -0500296 auto color_attached = BindProperty<VectorValue>(obj["c"], ctx, color_node,
297 [](sksg::Color* node, const VectorValue& c) {
Florin Malitaf9590922018-01-09 11:56:09 -0500298 node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
299 });
Florin Malita094ccde2017-12-30 12:27:00 -0500300
Florin Malita1586d852018-01-12 14:27:39 -0500301 return color_attached ? color_node : nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500302}
303
Florin Malita6aaee592018-01-12 12:25:09 -0500304sk_sp<sksg::Gradient> AttachGradient(const Json::Value& obj, AttachContext* ctx) {
305 SkASSERT(obj.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500306
Florin Malita6aaee592018-01-12 12:25:09 -0500307 const auto& stops = obj["g"];
308 if (!stops.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500309 return nullptr;
310
Florin Malita6aaee592018-01-12 12:25:09 -0500311 const auto stopCount = ParseInt(stops["p"], -1);
312 if (stopCount < 0)
313 return nullptr;
314
315 sk_sp<sksg::Gradient> gradient_node;
316 sk_sp<CompositeGradient> composite;
317
318 if (ParseInt(obj["t"], 1) == 1) {
319 auto linear_node = sksg::LinearGradient::Make();
320 composite = sk_make_sp<CompositeLinearGradient>(linear_node, stopCount);
321 gradient_node = std::move(linear_node);
322 } else {
323 auto radial_node = sksg::RadialGradient::Make();
324 composite = sk_make_sp<CompositeRadialGradient>(radial_node, stopCount);
325
326 // TODO: highlight, angle
327 gradient_node = std::move(radial_node);
328 }
329
330 BindProperty<VectorValue>(stops["k"], ctx, composite,
331 [](CompositeGradient* node, const VectorValue& stops) {
332 node->setColorStops(stops);
333 });
334 BindProperty<VectorValue>(obj["s"], ctx, composite,
335 [](CompositeGradient* node, const VectorValue& s) {
336 node->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
337 });
338 BindProperty<VectorValue>(obj["e"], ctx, composite,
339 [](CompositeGradient* node, const VectorValue& e) {
340 node->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
341 });
342
343 return gradient_node;
344}
345
Florin Malita1586d852018-01-12 14:27:39 -0500346sk_sp<sksg::PaintNode> AttachPaint(const Json::Value& jpaint, AttachContext* ctx,
Florin Malita6aaee592018-01-12 12:25:09 -0500347 sk_sp<sksg::PaintNode> paint_node) {
348 if (paint_node) {
349 paint_node->setAntiAlias(true);
350
Florin Malita1586d852018-01-12 14:27:39 -0500351 BindProperty<ScalarValue>(jpaint["o"], ctx, paint_node,
352 [](sksg::PaintNode* node, const ScalarValue& o) {
353 // BM opacity is [0..100]
354 node->setOpacity(o * 0.01f);
355 });
Florin Malita6aaee592018-01-12 12:25:09 -0500356 }
357
358 return paint_node;
359}
360
361sk_sp<sksg::PaintNode> AttachStroke(const Json::Value& jstroke, AttachContext* ctx,
362 sk_sp<sksg::PaintNode> stroke_node) {
363 SkASSERT(jstroke.isObject());
364
365 if (!stroke_node)
366 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500367
368 stroke_node->setStyle(SkPaint::kStroke_Style);
369
Florin Malitaf9590922018-01-09 11:56:09 -0500370 auto width_attached = BindProperty<ScalarValue>(jstroke["w"], ctx, stroke_node,
Florin Malita6aaee592018-01-12 12:25:09 -0500371 [](sksg::PaintNode* node, const ScalarValue& w) {
Florin Malitaf9590922018-01-09 11:56:09 -0500372 node->setStrokeWidth(w);
373 });
Florin Malita094ccde2017-12-30 12:27:00 -0500374 if (!width_attached)
375 return nullptr;
376
377 stroke_node->setStrokeMiter(ParseScalar(jstroke["ml"], 4));
378
379 static constexpr SkPaint::Join gJoins[] = {
380 SkPaint::kMiter_Join,
381 SkPaint::kRound_Join,
382 SkPaint::kBevel_Join,
383 };
384 stroke_node->setStrokeJoin(gJoins[SkTPin<int>(ParseInt(jstroke["lj"], 1) - 1,
385 0, SK_ARRAY_COUNT(gJoins) - 1)]);
386
387 static constexpr SkPaint::Cap gCaps[] = {
388 SkPaint::kButt_Cap,
389 SkPaint::kRound_Cap,
390 SkPaint::kSquare_Cap,
391 };
392 stroke_node->setStrokeCap(gCaps[SkTPin<int>(ParseInt(jstroke["lc"], 1) - 1,
393 0, SK_ARRAY_COUNT(gCaps) - 1)]);
394
395 return stroke_node;
396}
397
Florin Malita6aaee592018-01-12 12:25:09 -0500398sk_sp<sksg::PaintNode> AttachColorFill(const Json::Value& jfill, AttachContext* ctx) {
399 SkASSERT(jfill.isObject());
400
401 return AttachPaint(jfill, ctx, AttachColor(jfill, ctx));
402}
403
404sk_sp<sksg::PaintNode> AttachGradientFill(const Json::Value& jfill, AttachContext* ctx) {
405 SkASSERT(jfill.isObject());
406
407 return AttachPaint(jfill, ctx, AttachGradient(jfill, ctx));
408}
409
410sk_sp<sksg::PaintNode> AttachColorStroke(const Json::Value& jstroke, AttachContext* ctx) {
411 SkASSERT(jstroke.isObject());
412
413 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachColor(jstroke, ctx)));
414}
415
416sk_sp<sksg::PaintNode> AttachGradientStroke(const Json::Value& jstroke, AttachContext* ctx) {
417 SkASSERT(jstroke.isObject());
418
419 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachGradient(jstroke, ctx)));
420}
421
Florin Malitae6345d92018-01-03 23:37:54 -0500422std::vector<sk_sp<sksg::GeometryNode>> AttachMergeGeometryEffect(
423 const Json::Value& jmerge, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
424 std::vector<sk_sp<sksg::GeometryNode>> merged;
425
426 static constexpr sksg::Merge::Mode gModes[] = {
427 sksg::Merge::Mode::kMerge, // "mm": 1
428 sksg::Merge::Mode::kUnion, // "mm": 2
429 sksg::Merge::Mode::kDifference, // "mm": 3
430 sksg::Merge::Mode::kIntersect, // "mm": 4
431 sksg::Merge::Mode::kXOR , // "mm": 5
432 };
433
Florin Malita51b8c892018-01-07 08:54:24 -0500434 const auto mode = gModes[SkTPin<int>(ParseInt(jmerge["mm"], 1) - 1,
435 0, SK_ARRAY_COUNT(gModes) - 1)];
Florin Malitae6345d92018-01-03 23:37:54 -0500436 merged.push_back(sksg::Merge::Make(std::move(geos), mode));
437
438 LOG("** Attached merge path effect, mode: %d\n", mode);
439
440 return merged;
441}
442
Florin Malita51b8c892018-01-07 08:54:24 -0500443std::vector<sk_sp<sksg::GeometryNode>> AttachTrimGeometryEffect(
444 const Json::Value& jtrim, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
445
446 enum class Mode {
447 kMerged, // "m": 1
448 kSeparate, // "m": 2
449 } gModes[] = { Mode::kMerged, Mode::kSeparate };
450
451 const auto mode = gModes[SkTPin<int>(ParseInt(jtrim["m"], 1) - 1,
452 0, SK_ARRAY_COUNT(gModes) - 1)];
453
454 std::vector<sk_sp<sksg::GeometryNode>> inputs;
455 if (mode == Mode::kMerged) {
456 inputs.push_back(sksg::Merge::Make(std::move(geos), sksg::Merge::Mode::kMerge));
457 } else {
458 inputs = std::move(geos);
459 }
460
461 std::vector<sk_sp<sksg::GeometryNode>> trimmed;
462 trimmed.reserve(inputs.size());
463 for (const auto& i : inputs) {
464 const auto trim = sksg::TrimEffect::Make(i);
465 trimmed.push_back(trim);
Florin Malitaf9590922018-01-09 11:56:09 -0500466 BindProperty<ScalarValue>(jtrim["s"], ctx, trim,
467 [](sksg::TrimEffect* node, const ScalarValue& s) {
Florin Malita51b8c892018-01-07 08:54:24 -0500468 node->setStart(s * 0.01f);
469 });
Florin Malitaf9590922018-01-09 11:56:09 -0500470 BindProperty<ScalarValue>(jtrim["e"], ctx, trim,
471 [](sksg::TrimEffect* node, const ScalarValue& e) {
Florin Malita51b8c892018-01-07 08:54:24 -0500472 node->setEnd(e * 0.01f);
473 });
474 // TODO: "offset" doesn't currently work the same as BM - figure out what's going on.
Florin Malitaf9590922018-01-09 11:56:09 -0500475 BindProperty<ScalarValue>(jtrim["o"], ctx, trim,
476 [](sksg::TrimEffect* node, const ScalarValue& o) {
Florin Malita51b8c892018-01-07 08:54:24 -0500477 node->setOffset(o * 0.01f);
478 });
479 }
480
481 return trimmed;
482}
483
Florin Malita094ccde2017-12-30 12:27:00 -0500484using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const Json::Value&, AttachContext*);
485static constexpr GeometryAttacherT gGeometryAttachers[] = {
486 AttachPathGeometry,
Florin Malita2e1d7e22018-01-02 10:40:00 -0500487 AttachRRectGeometry,
Florin Malitafbc13f12018-01-04 10:26:35 -0500488 AttachEllipseGeometry,
Florin Malita02a32b02018-01-04 11:27:09 -0500489 AttachPolystarGeometry,
Florin Malita094ccde2017-12-30 12:27:00 -0500490};
491
492using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const Json::Value&, AttachContext*);
493static constexpr PaintAttacherT gPaintAttachers[] = {
Florin Malita6aaee592018-01-12 12:25:09 -0500494 AttachColorFill,
495 AttachColorStroke,
496 AttachGradientFill,
497 AttachGradientStroke,
Florin Malita094ccde2017-12-30 12:27:00 -0500498};
499
Florin Malitae6345d92018-01-03 23:37:54 -0500500using GeometryEffectAttacherT =
501 std::vector<sk_sp<sksg::GeometryNode>> (*)(const Json::Value&,
502 AttachContext*,
503 std::vector<sk_sp<sksg::GeometryNode>>&&);
504static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
505 AttachMergeGeometryEffect,
Florin Malita51b8c892018-01-07 08:54:24 -0500506 AttachTrimGeometryEffect,
Florin Malitae6345d92018-01-03 23:37:54 -0500507};
508
Florin Malita094ccde2017-12-30 12:27:00 -0500509enum class ShapeType {
510 kGeometry,
Florin Malitae6345d92018-01-03 23:37:54 -0500511 kGeometryEffect,
Florin Malita094ccde2017-12-30 12:27:00 -0500512 kPaint,
513 kGroup,
Florin Malitadacc02b2017-12-31 09:12:31 -0500514 kTransform,
Florin Malita094ccde2017-12-30 12:27:00 -0500515};
516
517struct ShapeInfo {
518 const char* fTypeString;
519 ShapeType fShapeType;
520 uint32_t fAttacherIndex; // index into respective attacher tables
521};
522
523const ShapeInfo* FindShapeInfo(const Json::Value& shape) {
524 static constexpr ShapeInfo gShapeInfo[] = {
Florin Malitafbc13f12018-01-04 10:26:35 -0500525 { "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500526 { "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
527 { "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
Florin Malita16d0ad02018-01-19 15:07:29 -0500528 { "gr", ShapeType::kGroup , 0 }, // group -> Inline handler
Florin Malita6aaee592018-01-12 12:25:09 -0500529 { "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
Florin Malitae6345d92018-01-03 23:37:54 -0500530 { "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
Florin Malita02a32b02018-01-04 11:27:09 -0500531 { "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
Florin Malitae6345d92018-01-03 23:37:54 -0500532 { "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
Florin Malita02a32b02018-01-04 11:27:09 -0500533 { "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500534 { "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
Florin Malita51b8c892018-01-07 08:54:24 -0500535 { "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
Florin Malita16d0ad02018-01-19 15:07:29 -0500536 { "tr", ShapeType::kTransform , 0 }, // transform -> Inline handler
Florin Malita094ccde2017-12-30 12:27:00 -0500537 };
538
539 if (!shape.isObject())
540 return nullptr;
541
542 const auto& type = shape["ty"];
543 if (!type.isString())
544 return nullptr;
545
546 const auto* info = bsearch(type.asCString(),
547 gShapeInfo,
548 SK_ARRAY_COUNT(gShapeInfo),
549 sizeof(ShapeInfo),
550 [](const void* key, const void* info) {
551 return strcmp(static_cast<const char*>(key),
552 static_cast<const ShapeInfo*>(info)->fTypeString);
553 });
554
555 return static_cast<const ShapeInfo*>(info);
556}
557
Florin Malita16d0ad02018-01-19 15:07:29 -0500558struct GeometryEffectRec {
559 const Json::Value& fJson;
560 GeometryEffectAttacherT fAttach;
561};
562
563sk_sp<sksg::RenderNode> AttachShape(const Json::Value& jshape, AttachContext* ctx,
564 std::vector<sk_sp<sksg::GeometryNode>>* geometryStack,
565 std::vector<GeometryEffectRec>* geometryEffectStack) {
566 if (!jshape.isArray())
Florin Malita094ccde2017-12-30 12:27:00 -0500567 return nullptr;
568
Florin Malita16d0ad02018-01-19 15:07:29 -0500569 SkDEBUGCODE(const auto initialGeometryEffects = geometryEffectStack->size();)
Florin Malita094ccde2017-12-30 12:27:00 -0500570
Florin Malita16d0ad02018-01-19 15:07:29 -0500571 sk_sp<sksg::Group> shape_group = sksg::Group::Make();
572 sk_sp<sksg::RenderNode> shape_wrapper = shape_group;
573 sk_sp<sksg::Matrix> shape_matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500574
Florin Malita16d0ad02018-01-19 15:07:29 -0500575 struct ShapeRec {
576 const Json::Value& fJson;
577 const ShapeInfo& fInfo;
578 };
579
580 // First pass (bottom->top):
581 //
582 // * pick up the group transform and opacity
583 // * push local geometry effects onto the stack
584 // * store recs for next pass
585 //
586 std::vector<ShapeRec> recs;
587 for (Json::ArrayIndex i = 0; i < jshape.size(); ++i) {
588 const auto& s = jshape[jshape.size() - 1 - i];
Florin Malita094ccde2017-12-30 12:27:00 -0500589 const auto* info = FindShapeInfo(s);
590 if (!info) {
591 LogFail(s.isObject() ? s["ty"] : s, "Unknown shape");
592 continue;
593 }
594
Florin Malita16d0ad02018-01-19 15:07:29 -0500595 recs.push_back({ s, *info });
596
Florin Malita094ccde2017-12-30 12:27:00 -0500597 switch (info->fShapeType) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500598 case ShapeType::kTransform:
599 if ((shape_matrix = AttachMatrix(s, ctx, nullptr))) {
600 shape_wrapper = sksg::Transform::Make(std::move(shape_wrapper), shape_matrix);
601 }
602 shape_wrapper = AttachOpacity(s, ctx, std::move(shape_wrapper));
603 break;
604 case ShapeType::kGeometryEffect:
605 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
606 geometryEffectStack->push_back(
607 { s, gGeometryEffectAttachers[info->fAttacherIndex] });
608 break;
609 default:
610 break;
611 }
612 }
613
614 // Second pass (top -> bottom, after 2x reverse):
615 //
616 // * track local geometry
617 // * emit local paints
618 //
619 std::vector<sk_sp<sksg::GeometryNode>> geos;
620 std::vector<sk_sp<sksg::RenderNode >> draws;
621 for (auto rec = recs.rbegin(); rec != recs.rend(); ++rec) {
622 switch (rec->fInfo.fShapeType) {
Florin Malita094ccde2017-12-30 12:27:00 -0500623 case ShapeType::kGeometry: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500624 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
625 if (auto geo = gGeometryAttachers[rec->fInfo.fAttacherIndex](rec->fJson, ctx)) {
Florin Malita094ccde2017-12-30 12:27:00 -0500626 geos.push_back(std::move(geo));
627 }
628 } break;
Florin Malitae6345d92018-01-03 23:37:54 -0500629 case ShapeType::kGeometryEffect: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500630 // Apply the current effect and pop from the stack.
631 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaee6de4b2018-01-21 11:13:17 -0500632 if (!geos.empty()) {
633 geos = gGeometryEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
634 ctx,
635 std::move(geos));
636 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500637
638 SkASSERT(geometryEffectStack->back().fJson == rec->fJson);
639 SkASSERT(geometryEffectStack->back().fAttach ==
640 gGeometryEffectAttachers[rec->fInfo.fAttacherIndex]);
641 geometryEffectStack->pop_back();
Florin Malita094ccde2017-12-30 12:27:00 -0500642 } break;
643 case ShapeType::kGroup: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500644 if (auto subgroup = AttachShape(rec->fJson["it"], ctx, &geos, geometryEffectStack)) {
645 draws.push_back(std::move(subgroup));
Florin Malita094ccde2017-12-30 12:27:00 -0500646 }
647 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500648 case ShapeType::kPaint: {
649 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
650 auto paint = gPaintAttachers[rec->fInfo.fAttacherIndex](rec->fJson, ctx);
651 if (!paint || geos.empty())
652 break;
653
654 auto drawGeos = geos;
655
656 // Apply all pending effects from the stack.
657 for (auto it = geometryEffectStack->rbegin(); it != geometryEffectStack->rend(); ++it) {
658 drawGeos = it->fAttach(it->fJson, ctx, std::move(drawGeos));
Florin Malita18eafd92018-01-04 21:11:55 -0500659 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500660
661 // If we still have multiple geos, reduce using 'merge'.
662 auto geo = drawGeos.size() > 1
663 ? sksg::Merge::Make(std::move(drawGeos), sksg::Merge::Mode::kMerge)
664 : drawGeos[0];
665
666 SkASSERT(geo);
667 draws.push_back(sksg::Draw::Make(std::move(geo), std::move(paint)));
Florin Malitadacc02b2017-12-31 09:12:31 -0500668 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500669 default:
670 break;
Florin Malita094ccde2017-12-30 12:27:00 -0500671 }
672 }
673
Florin Malita16d0ad02018-01-19 15:07:29 -0500674 // By now we should have popped all local geometry effects.
675 SkASSERT(geometryEffectStack->size() == initialGeometryEffects);
676
677 // Push transformed local geometries to parent list, for subsequent paints.
678 for (const auto& geo : geos) {
679 geometryStack->push_back(shape_matrix
680 ? sksg::GeometryTransform::Make(std::move(geo), shape_matrix)
681 : std::move(geo));
Florin Malita094ccde2017-12-30 12:27:00 -0500682 }
683
Florin Malita16d0ad02018-01-19 15:07:29 -0500684 // Emit local draws reversed (bottom->top, per spec).
685 for (auto it = draws.rbegin(); it != draws.rend(); ++it) {
686 shape_group->addChild(std::move(*it));
Florin Malita2a8275b2018-01-02 12:52:43 -0500687 }
688
Florin Malita16d0ad02018-01-19 15:07:29 -0500689 return draws.empty() ? nullptr : shape_wrapper;
Florin Malita094ccde2017-12-30 12:27:00 -0500690}
691
692sk_sp<sksg::RenderNode> AttachCompLayer(const Json::Value& layer, AttachContext* ctx) {
693 SkASSERT(layer.isObject());
694
695 auto refId = ParseString(layer["refId"], "");
696 if (refId.isEmpty()) {
697 LOG("!! Comp layer missing refId\n");
698 return nullptr;
699 }
700
701 const auto* comp = ctx->fAssets.find(refId);
702 if (!comp) {
703 LOG("!! Pre-comp not found: '%s'\n", refId.c_str());
704 return nullptr;
705 }
706
707 // TODO: cycle detection
708 return AttachComposition(**comp, ctx);
709}
710
Florin Malita0e66fba2018-01-09 17:10:18 -0500711sk_sp<sksg::RenderNode> AttachSolidLayer(const Json::Value& jlayer, AttachContext*) {
712 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500713
Florin Malita0e66fba2018-01-09 17:10:18 -0500714 const auto size = SkSize::Make(ParseScalar(jlayer["sw"], -1),
715 ParseScalar(jlayer["sh"], -1));
716 const auto hex = ParseString(jlayer["sc"], "");
717 uint32_t c;
718 if (size.isEmpty() ||
719 !hex.startsWith("#") ||
720 !SkParse::FindHex(hex.c_str() + 1, &c)) {
721 LogFail(jlayer, "Could not parse solid layer");
722 return nullptr;
723 }
724
725 const SkColor color = 0xff000000 | c;
726
727 return sksg::Draw::Make(sksg::Rect::Make(SkRect::MakeSize(size)),
728 sksg::Color::Make(color));
Florin Malita094ccde2017-12-30 12:27:00 -0500729}
730
Florin Malita49328072018-01-08 12:51:12 -0500731sk_sp<sksg::RenderNode> AttachImageAsset(const Json::Value& jimage, AttachContext* ctx) {
732 SkASSERT(jimage.isObject());
733
734 const auto name = ParseString(jimage["p"], ""),
735 path = ParseString(jimage["u"], "");
736 if (name.isEmpty())
737 return nullptr;
738
739 // TODO: plumb resource paths explicitly to ResourceProvider?
740 const auto resName = path.isEmpty() ? name : SkOSPath::Join(path.c_str(), name.c_str());
741 const auto resStream = ctx->fResources.openStream(resName.c_str());
742 if (!resStream || !resStream->hasLength()) {
743 LOG("!! Could not load image resource: %s\n", resName.c_str());
744 return nullptr;
745 }
746
747 // TODO: non-intrisic image sizing
748 return sksg::Image::Make(
749 SkImage::MakeFromEncoded(SkData::MakeFromStream(resStream.get(), resStream->getLength())));
750}
751
752sk_sp<sksg::RenderNode> AttachImageLayer(const Json::Value& layer, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500753 SkASSERT(layer.isObject());
754
Florin Malita49328072018-01-08 12:51:12 -0500755 auto refId = ParseString(layer["refId"], "");
756 if (refId.isEmpty()) {
757 LOG("!! Image layer missing refId\n");
758 return nullptr;
759 }
760
761 const auto* jimage = ctx->fAssets.find(refId);
762 if (!jimage) {
763 LOG("!! Image asset not found: '%s'\n", refId.c_str());
764 return nullptr;
765 }
766
767 return AttachImageAsset(**jimage, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500768}
769
770sk_sp<sksg::RenderNode> AttachNullLayer(const Json::Value& layer, AttachContext*) {
771 SkASSERT(layer.isObject());
772
Florin Malita18eafd92018-01-04 21:11:55 -0500773 // Null layers are used solely to drive dependent transforms,
774 // but we use free-floating sksg::Matrices for that purpose.
Florin Malita094ccde2017-12-30 12:27:00 -0500775 return nullptr;
776}
777
778sk_sp<sksg::RenderNode> AttachShapeLayer(const Json::Value& layer, AttachContext* ctx) {
779 SkASSERT(layer.isObject());
780
781 LOG("** Attaching shape layer ind: %d\n", ParseInt(layer["ind"], 0));
782
Florin Malita16d0ad02018-01-19 15:07:29 -0500783 std::vector<sk_sp<sksg::GeometryNode>> geometryStack;
784 std::vector<GeometryEffectRec> geometryEffectStack;
785 return AttachShape(layer["shapes"], ctx, &geometryStack, &geometryEffectStack);
Florin Malita094ccde2017-12-30 12:27:00 -0500786}
787
788sk_sp<sksg::RenderNode> AttachTextLayer(const Json::Value& layer, AttachContext*) {
789 SkASSERT(layer.isObject());
790
791 LOG("?? Text layer stub\n");
792 return nullptr;
793}
794
Florin Malita18eafd92018-01-04 21:11:55 -0500795struct AttachLayerContext {
796 AttachLayerContext(const Json::Value& jlayers, AttachContext* ctx)
797 : fLayerList(jlayers), fCtx(ctx) {}
798
799 const Json::Value& fLayerList;
800 AttachContext* fCtx;
801 std::unordered_map<const Json::Value*, sk_sp<sksg::Matrix>> fLayerMatrixCache;
802 std::unordered_map<int, const Json::Value*> fLayerIndexCache;
Florin Malita5f9102f2018-01-10 13:36:22 -0500803 sk_sp<sksg::RenderNode> fCurrentMatte;
Florin Malita18eafd92018-01-04 21:11:55 -0500804
805 const Json::Value* findLayer(int index) {
806 SkASSERT(fLayerList.isArray());
807
808 if (index < 0) {
809 return nullptr;
810 }
811
812 const auto cached = fLayerIndexCache.find(index);
813 if (cached != fLayerIndexCache.end()) {
814 return cached->second;
815 }
816
817 for (const auto& l : fLayerList) {
818 if (!l.isObject()) {
819 continue;
820 }
821
822 if (ParseInt(l["ind"], -1) == index) {
823 fLayerIndexCache.insert(std::make_pair(index, &l));
824 return &l;
825 }
826 }
827
828 return nullptr;
829 }
830
831 sk_sp<sksg::Matrix> AttachLayerMatrix(const Json::Value& jlayer) {
832 SkASSERT(jlayer.isObject());
833
834 const auto cached = fLayerMatrixCache.find(&jlayer);
835 if (cached != fLayerMatrixCache.end()) {
836 return cached->second;
837 }
838
839 const auto* parentLayer = this->findLayer(ParseInt(jlayer["parent"], -1));
840
841 // TODO: cycle detection?
842 auto parentMatrix = (parentLayer && parentLayer != &jlayer)
843 ? this->AttachLayerMatrix(*parentLayer) : nullptr;
844
845 auto layerMatrix = AttachMatrix(jlayer["ks"], fCtx, std::move(parentMatrix));
846 fLayerMatrixCache.insert(std::make_pair(&jlayer, layerMatrix));
847
848 return layerMatrix;
849 }
850};
851
852sk_sp<sksg::RenderNode> AttachLayer(const Json::Value& jlayer,
853 AttachLayerContext* layerCtx) {
854 if (!jlayer.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500855 return nullptr;
856
857 using LayerAttacher = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*);
858 static constexpr LayerAttacher gLayerAttachers[] = {
859 AttachCompLayer, // 'ty': 0
860 AttachSolidLayer, // 'ty': 1
861 AttachImageLayer, // 'ty': 2
862 AttachNullLayer, // 'ty': 3
863 AttachShapeLayer, // 'ty': 4
864 AttachTextLayer, // 'ty': 5
865 };
866
Florin Malita18eafd92018-01-04 21:11:55 -0500867 int type = ParseInt(jlayer["ty"], -1);
Florin Malita094ccde2017-12-30 12:27:00 -0500868 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gLayerAttachers))) {
869 return nullptr;
870 }
871
Florin Malita71cba8f2018-01-09 08:07:14 -0500872 // Layer content.
873 auto layer = gLayerAttachers[type](jlayer, layerCtx->fCtx);
874 if (auto layerMatrix = layerCtx->AttachLayerMatrix(jlayer)) {
875 // Optional layer transform.
876 layer = sksg::Transform::Make(std::move(layer), std::move(layerMatrix));
877 }
878 // Optional layer opacity.
879 layer = AttachOpacity(jlayer["ks"], layerCtx->fCtx, std::move(layer));
Florin Malita18eafd92018-01-04 21:11:55 -0500880
Florin Malita71cba8f2018-01-09 08:07:14 -0500881 // TODO: we should also disable related/inactive animators.
Florin Malita35efaa82018-01-22 12:57:06 -0500882 class Activator final : public sksg::Animator {
Florin Malita71cba8f2018-01-09 08:07:14 -0500883 public:
884 Activator(sk_sp<sksg::OpacityEffect> controlNode, float in, float out)
885 : fControlNode(std::move(controlNode))
886 , fIn(in)
887 , fOut(out) {}
888
Florin Malita35efaa82018-01-22 12:57:06 -0500889 void onTick(float t) override {
Florin Malita71cba8f2018-01-09 08:07:14 -0500890 // Keep the layer fully transparent except for its [in..out] lifespan.
891 // (note: opacity == 0 disables rendering, while opacity == 1 is a noop)
892 fControlNode->setOpacity(t >= fIn && t <= fOut ? 1 : 0);
893 }
894
895 private:
896 const sk_sp<sksg::OpacityEffect> fControlNode;
897 const float fIn,
898 fOut;
899 };
900
901 auto layerControl = sksg::OpacityEffect::Make(std::move(layer));
902 const auto in = ParseScalar(jlayer["ip"], 0),
903 out = ParseScalar(jlayer["op"], in);
904
905 if (in >= out || ! layerControl)
906 return nullptr;
907
908 layerCtx->fCtx->fAnimators.push_back(skstd::make_unique<Activator>(layerControl, in, out));
909
Florin Malita5f9102f2018-01-10 13:36:22 -0500910 if (ParseBool(jlayer["td"], false)) {
911 // This layer is a matte. We apply it as a mask to the next layer.
912 layerCtx->fCurrentMatte = std::move(layerControl);
913 return nullptr;
914 }
915
916 if (layerCtx->fCurrentMatte) {
917 // There is a pending matte. Apply and reset.
918 return sksg::MaskEffect::Make(std::move(layerControl), std::move(layerCtx->fCurrentMatte));
919 }
920
Florin Malita71cba8f2018-01-09 08:07:14 -0500921 return layerControl;
Florin Malita094ccde2017-12-30 12:27:00 -0500922}
923
924sk_sp<sksg::RenderNode> AttachComposition(const Json::Value& comp, AttachContext* ctx) {
925 if (!comp.isObject())
926 return nullptr;
927
Florin Malita18eafd92018-01-04 21:11:55 -0500928 const auto& jlayers = comp["layers"];
929 if (!jlayers.isArray())
930 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500931
Florin Malita18eafd92018-01-04 21:11:55 -0500932 SkSTArray<16, sk_sp<sksg::RenderNode>, true> layers;
933 AttachLayerContext layerCtx(jlayers, ctx);
934
935 for (const auto& l : jlayers) {
936 if (auto layer_fragment = AttachLayer(l, &layerCtx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -0500937 layers.push_back(std::move(layer_fragment));
Florin Malita094ccde2017-12-30 12:27:00 -0500938 }
939 }
940
Florin Malita2a8275b2018-01-02 12:52:43 -0500941 if (layers.empty()) {
942 return nullptr;
943 }
944
945 // Layers are painted in bottom->top order.
946 auto comp_group = sksg::Group::Make();
947 for (int i = layers.count() - 1; i >= 0; --i) {
948 comp_group->addChild(std::move(layers[i]));
949 }
950
951 LOG("** Attached composition '%s': %d layers.\n",
952 ParseString(comp["id"], "").c_str(), layers.count());
953
Florin Malita094ccde2017-12-30 12:27:00 -0500954 return comp_group;
955}
956
957} // namespace
958
Florin Malita49328072018-01-08 12:51:12 -0500959std::unique_ptr<Animation> Animation::Make(SkStream* stream, const ResourceProvider& res) {
Florin Malita094ccde2017-12-30 12:27:00 -0500960 if (!stream->hasLength()) {
961 // TODO: handle explicit buffering?
962 LOG("!! cannot parse streaming content\n");
963 return nullptr;
964 }
965
966 Json::Value json;
967 {
968 auto data = SkData::MakeFromStream(stream, stream->getLength());
969 if (!data) {
970 LOG("!! could not read stream\n");
971 return nullptr;
972 }
973
974 Json::Reader reader;
975
976 auto dataStart = static_cast<const char*>(data->data());
977 if (!reader.parse(dataStart, dataStart + data->size(), json, false) || !json.isObject()) {
978 LOG("!! failed to parse json: %s\n", reader.getFormattedErrorMessages().c_str());
979 return nullptr;
980 }
981 }
982
983 const auto version = ParseString(json["v"], "");
984 const auto size = SkSize::Make(ParseScalar(json["w"], -1), ParseScalar(json["h"], -1));
985 const auto fps = ParseScalar(json["fr"], -1);
986
987 if (size.isEmpty() || version.isEmpty() || fps < 0) {
988 LOG("!! invalid animation params (version: %s, size: [%f %f], frame rate: %f)",
989 version.c_str(), size.width(), size.height(), fps);
990 return nullptr;
991 }
992
Florin Malita49328072018-01-08 12:51:12 -0500993 return std::unique_ptr<Animation>(new Animation(res, std::move(version), size, fps, json));
Florin Malita094ccde2017-12-30 12:27:00 -0500994}
995
Florin Malita49328072018-01-08 12:51:12 -0500996std::unique_ptr<Animation> Animation::MakeFromFile(const char path[], const ResourceProvider* res) {
997 class DirectoryResourceProvider final : public ResourceProvider {
998 public:
999 explicit DirectoryResourceProvider(SkString dir) : fDir(std::move(dir)) {}
1000
1001 std::unique_ptr<SkStream> openStream(const char resource[]) const override {
1002 const auto resPath = SkOSPath::Join(fDir.c_str(), resource);
1003 return SkStream::MakeFromFile(resPath.c_str());
1004 }
1005
1006 private:
1007 const SkString fDir;
1008 };
1009
1010 const auto jsonStream = SkStream::MakeFromFile(path);
1011 if (!jsonStream)
1012 return nullptr;
1013
1014 std::unique_ptr<ResourceProvider> defaultProvider;
1015 if (!res) {
1016 defaultProvider = skstd::make_unique<DirectoryResourceProvider>(SkOSPath::Dirname(path));
1017 }
1018
1019 return Make(jsonStream.get(), res ? *res : *defaultProvider);
1020}
1021
1022Animation::Animation(const ResourceProvider& resources,
1023 SkString version, const SkSize& size, SkScalar fps, const Json::Value& json)
Florin Malita094ccde2017-12-30 12:27:00 -05001024 : fVersion(std::move(version))
1025 , fSize(size)
1026 , fFrameRate(fps)
1027 , fInPoint(ParseScalar(json["ip"], 0))
1028 , fOutPoint(SkTMax(ParseScalar(json["op"], SK_ScalarMax), fInPoint)) {
1029
1030 AssetMap assets;
1031 for (const auto& asset : json["assets"]) {
1032 if (!asset.isObject()) {
1033 continue;
1034 }
1035
1036 assets.set(ParseString(asset["id"], ""), &asset);
1037 }
1038
Florin Malita35efaa82018-01-22 12:57:06 -05001039 sksg::Scene::AnimatorList animators;
1040 AttachContext ctx = { resources, assets, animators };
1041 auto root = AttachComposition(json, &ctx);
1042
1043 LOG("** Attached %d animators\n", animators.size());
1044
1045 fScene = sksg::Scene::Make(std::move(root), std::move(animators));
Florin Malita094ccde2017-12-30 12:27:00 -05001046
Florin Malitadb385732018-01-09 12:19:32 -05001047 // In case the client calls render before the first tick.
1048 this->animationTick(0);
Florin Malita094ccde2017-12-30 12:27:00 -05001049}
1050
1051Animation::~Animation() = default;
1052
Florin Malita35efaa82018-01-22 12:57:06 -05001053void Animation::setShowInval(bool show) {
1054 if (fScene) {
1055 fScene->setShowInval(show);
1056 }
1057}
1058
Mike Reed29859872018-01-08 08:25:27 -05001059void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
Florin Malita35efaa82018-01-22 12:57:06 -05001060 if (!fScene)
Florin Malita094ccde2017-12-30 12:27:00 -05001061 return;
1062
Mike Reed29859872018-01-08 08:25:27 -05001063 SkAutoCanvasRestore restore(canvas, true);
1064 const SkRect srcR = SkRect::MakeSize(this->size());
1065 if (dstR) {
1066 canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
1067 }
1068 canvas->clipRect(srcR);
Florin Malita35efaa82018-01-22 12:57:06 -05001069 fScene->render(canvas);
Florin Malita094ccde2017-12-30 12:27:00 -05001070}
1071
1072void Animation::animationTick(SkMSec ms) {
Florin Malita35efaa82018-01-22 12:57:06 -05001073 if (!fScene)
1074 return;
1075
Florin Malita094ccde2017-12-30 12:27:00 -05001076 // 't' in the BM model really means 'frame #'
1077 auto t = static_cast<float>(ms) * fFrameRate / 1000;
1078
1079 t = fInPoint + std::fmod(t, fOutPoint - fInPoint);
1080
Florin Malita35efaa82018-01-22 12:57:06 -05001081 fScene->animate(t);
Florin Malita094ccde2017-12-30 12:27:00 -05001082}
1083
Florin Malita54f65c42018-01-16 17:04:30 -05001084} // namespace skottie