blob: c8144e446dc7073854b2faa7e49725b8837c1410 [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 Malita2518a0a2018-01-24 18:29:00 -050067template <typename T>
68bool BindProperty(const Json::Value& jprop, AttachContext* ctx,
69 typename Animator<T>::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 Malita2518a0a2018-01-24 18:29:00 -050079 T val;
80 if (ValueTraits<T>::Parse(jpropK, &val)) {
Florin Malita95448a92018-01-08 10:15:12 -050081 // Static property.
Florin Malita2518a0a2018-01-24 18:29:00 -050082 apply(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 Malita2518a0a2018-01-24 18:29:00 -050092 auto animator = Animator<T>::Make(jpropK, std::move(apply));
Florin Malita95448a92018-01-08 10:15:12 -050093
94 if (!animator) {
95 return LogFail(jprop, "Could not parse keyframed property");
96 }
97
98 ctx->fAnimators.push_back(std::move(animator));
99
Florin Malita094ccde2017-12-30 12:27:00 -0500100 return true;
101}
102
Florin Malita18eafd92018-01-04 21:11:55 -0500103sk_sp<sksg::Matrix> AttachMatrix(const Json::Value& t, AttachContext* ctx,
104 sk_sp<sksg::Matrix> parentMatrix) {
105 if (!t.isObject())
106 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500107
Florin Malita18eafd92018-01-04 21:11:55 -0500108 auto matrix = sksg::Matrix::Make(SkMatrix::I(), std::move(parentMatrix));
109 auto composite = sk_make_sp<CompositeTransform>(matrix);
Florin Malita2518a0a2018-01-24 18:29:00 -0500110 auto anchor_attached = BindProperty<VectorValue>(t["a"], ctx,
111 [composite](const VectorValue& a) {
112 composite->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
Florin Malita094ccde2017-12-30 12:27:00 -0500113 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500114 auto position_attached = BindProperty<VectorValue>(t["p"], ctx,
115 [composite](const VectorValue& p) {
116 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malita094ccde2017-12-30 12:27:00 -0500117 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500118 auto scale_attached = BindProperty<VectorValue>(t["s"], ctx,
119 [composite](const VectorValue& s) {
120 composite->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
Florin Malita094ccde2017-12-30 12:27:00 -0500121 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500122 auto rotation_attached = BindProperty<ScalarValue>(t["r"], ctx,
123 [composite](const ScalarValue& r) {
124 composite->setRotation(r);
Florin Malita094ccde2017-12-30 12:27:00 -0500125 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500126 auto skew_attached = BindProperty<ScalarValue>(t["sk"], ctx,
127 [composite](const ScalarValue& sk) {
128 composite->setSkew(sk);
Florin Malita094ccde2017-12-30 12:27:00 -0500129 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500130 auto skewaxis_attached = BindProperty<ScalarValue>(t["sa"], ctx,
131 [composite](const ScalarValue& sa) {
132 composite->setSkewAxis(sa);
Florin Malita094ccde2017-12-30 12:27:00 -0500133 });
134
135 if (!anchor_attached &&
136 !position_attached &&
137 !scale_attached &&
138 !rotation_attached &&
139 !skew_attached &&
140 !skewaxis_attached) {
141 LogFail(t, "Could not parse transform");
Florin Malita18eafd92018-01-04 21:11:55 -0500142 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500143 }
144
Florin Malita18eafd92018-01-04 21:11:55 -0500145 return matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500146}
147
Florin Malitac0034172018-01-08 16:42:59 -0500148sk_sp<sksg::RenderNode> AttachOpacity(const Json::Value& jtransform, AttachContext* ctx,
149 sk_sp<sksg::RenderNode> childNode) {
150 if (!jtransform.isObject() || !childNode)
151 return childNode;
152
153 // This is more peeky than other attachers, because we want to avoid redundant opacity
154 // nodes for the extremely common case of static opaciy == 100.
155 const auto& opacity = jtransform["o"];
156 if (opacity.isObject() &&
157 !ParseBool(opacity["a"], true) &&
158 ParseScalar(opacity["k"], -1) == 100) {
159 // Ignoring static full opacity.
160 return childNode;
161 }
162
163 auto opacityNode = sksg::OpacityEffect::Make(childNode);
Florin Malita2518a0a2018-01-24 18:29:00 -0500164 BindProperty<ScalarValue>(opacity, ctx,
165 [opacityNode](const ScalarValue& o) {
Florin Malitac0034172018-01-08 16:42:59 -0500166 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500167 opacityNode->setOpacity(o * 0.01f);
Florin Malitac0034172018-01-08 16:42:59 -0500168 });
169
170 return opacityNode;
171}
172
Florin Malita094ccde2017-12-30 12:27:00 -0500173sk_sp<sksg::RenderNode> AttachComposition(const Json::Value&, AttachContext* ctx);
174
Florin Malita25366fa2018-01-23 13:37:59 -0500175sk_sp<sksg::Path> AttachPath(const Json::Value& jpath, AttachContext* ctx) {
176 auto path_node = sksg::Path::Make();
Florin Malita2518a0a2018-01-24 18:29:00 -0500177 return BindProperty<ShapeValue>(jpath, ctx,
178 [path_node](const ShapeValue& p) { path_node->setPath(p); })
Florin Malita25366fa2018-01-23 13:37:59 -0500179 ? path_node
180 : nullptr;
181}
182
Florin Malita094ccde2017-12-30 12:27:00 -0500183sk_sp<sksg::GeometryNode> AttachPathGeometry(const Json::Value& jpath, AttachContext* ctx) {
184 SkASSERT(jpath.isObject());
185
Florin Malita25366fa2018-01-23 13:37:59 -0500186 return AttachPath(jpath["ks"], ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500187}
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 Malita2518a0a2018-01-24 18:29:00 -0500195 auto p_attached = BindProperty<VectorValue>(jrect["p"], ctx,
196 [composite](const VectorValue& p) {
197 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500198 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500199 auto s_attached = BindProperty<VectorValue>(jrect["s"], ctx,
200 [composite](const VectorValue& s) {
201 composite->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
Florin Malitaf9590922018-01-09 11:56:09 -0500202 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500203 auto r_attached = BindProperty<ScalarValue>(jrect["r"], ctx,
204 [composite](const ScalarValue& r) {
205 composite->setRadius(SkSize::Make(r, r));
Florin Malitaf9590922018-01-09 11:56:09 -0500206 });
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 Malita2518a0a2018-01-24 18:29:00 -0500223 auto p_attached = BindProperty<VectorValue>(jellipse["p"], ctx,
224 [composite](const VectorValue& p) {
225 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500226 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500227 auto s_attached = BindProperty<VectorValue>(jellipse["s"], ctx,
228 [composite](const VectorValue& s) {
Florin Malitaf9590922018-01-09 11:56:09 -0500229 const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
Florin Malita2518a0a2018-01-24 18:29:00 -0500230 composite->setSize(sz);
231 composite->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
Florin Malitaf9590922018-01-09 11:56:09 -0500232 });
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 Malita2518a0a2018-01-24 18:29:00 -0500260 BindProperty<VectorValue>(jstar["p"], ctx,
261 [composite](const VectorValue& p) {
262 composite->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malitaf9590922018-01-09 11:56:09 -0500263 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500264 BindProperty<ScalarValue>(jstar["pt"], ctx,
265 [composite](const ScalarValue& pt) {
266 composite->setPointCount(pt);
Florin Malitaf9590922018-01-09 11:56:09 -0500267 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500268 BindProperty<ScalarValue>(jstar["ir"], ctx,
269 [composite](const ScalarValue& ir) {
270 composite->setInnerRadius(ir);
Florin Malitaf9590922018-01-09 11:56:09 -0500271 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500272 BindProperty<ScalarValue>(jstar["or"], ctx,
273 [composite](const ScalarValue& otr) {
274 composite->setOuterRadius(otr);
Florin Malita9661b982018-01-06 14:25:49 -0500275 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500276 BindProperty<ScalarValue>(jstar["is"], ctx,
277 [composite](const ScalarValue& is) {
278 composite->setInnerRoundness(is);
Florin Malita9661b982018-01-06 14:25:49 -0500279 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500280 BindProperty<ScalarValue>(jstar["os"], ctx,
281 [composite](const ScalarValue& os) {
282 composite->setOuterRoundness(os);
Florin Malita9661b982018-01-06 14:25:49 -0500283 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500284 BindProperty<ScalarValue>(jstar["r"], ctx,
285 [composite](const ScalarValue& r) {
286 composite->setRotation(r);
Florin Malitaf9590922018-01-09 11:56:09 -0500287 });
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 Malita2518a0a2018-01-24 18:29:00 -0500296 auto color_attached = BindProperty<VectorValue>(obj["c"], ctx,
297 [color_node](const VectorValue& c) {
298 color_node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
Florin Malitaf9590922018-01-09 11:56:09 -0500299 });
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
Florin Malita2518a0a2018-01-24 18:29:00 -0500330 BindProperty<VectorValue>(stops["k"], ctx,
331 [composite](const VectorValue& stops) {
332 composite->setColorStops(stops);
Florin Malita6aaee592018-01-12 12:25:09 -0500333 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500334 BindProperty<VectorValue>(obj["s"], ctx,
335 [composite](const VectorValue& s) {
336 composite->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
Florin Malita6aaee592018-01-12 12:25:09 -0500337 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500338 BindProperty<VectorValue>(obj["e"], ctx,
339 [composite](const VectorValue& e) {
340 composite->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
Florin Malita6aaee592018-01-12 12:25:09 -0500341 });
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 Malita2518a0a2018-01-24 18:29:00 -0500351 BindProperty<ScalarValue>(jpaint["o"], ctx,
352 [paint_node](const ScalarValue& o) {
Florin Malita1586d852018-01-12 14:27:39 -0500353 // BM opacity is [0..100]
Florin Malita2518a0a2018-01-24 18:29:00 -0500354 paint_node->setOpacity(o * 0.01f);
Florin Malita1586d852018-01-12 14:27:39 -0500355 });
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 Malita2518a0a2018-01-24 18:29:00 -0500370 auto width_attached = BindProperty<ScalarValue>(jstroke["w"], ctx,
371 [stroke_node](const ScalarValue& w) {
372 stroke_node->setStrokeWidth(w);
Florin Malitaf9590922018-01-09 11:56:09 -0500373 });
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 Malita2518a0a2018-01-24 18:29:00 -0500466 BindProperty<ScalarValue>(jtrim["s"], ctx,
467 [trim](const ScalarValue& s) {
468 trim->setStart(s * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500469 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500470 BindProperty<ScalarValue>(jtrim["e"], ctx,
471 [trim](const ScalarValue& e) {
472 trim->setEnd(e * 0.01f);
Florin Malita51b8c892018-01-07 08:54:24 -0500473 });
Florin Malita2518a0a2018-01-24 18:29:00 -0500474 BindProperty<ScalarValue>(jtrim["o"], ctx,
475 [trim](const ScalarValue& o) {
476 trim->setOffset(o / 360);
Florin Malita51b8c892018-01-07 08:54:24 -0500477 });
478 }
479
480 return trimmed;
481}
482
Florin Malita094ccde2017-12-30 12:27:00 -0500483using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const Json::Value&, AttachContext*);
484static constexpr GeometryAttacherT gGeometryAttachers[] = {
485 AttachPathGeometry,
Florin Malita2e1d7e22018-01-02 10:40:00 -0500486 AttachRRectGeometry,
Florin Malitafbc13f12018-01-04 10:26:35 -0500487 AttachEllipseGeometry,
Florin Malita02a32b02018-01-04 11:27:09 -0500488 AttachPolystarGeometry,
Florin Malita094ccde2017-12-30 12:27:00 -0500489};
490
491using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const Json::Value&, AttachContext*);
492static constexpr PaintAttacherT gPaintAttachers[] = {
Florin Malita6aaee592018-01-12 12:25:09 -0500493 AttachColorFill,
494 AttachColorStroke,
495 AttachGradientFill,
496 AttachGradientStroke,
Florin Malita094ccde2017-12-30 12:27:00 -0500497};
498
Florin Malitae6345d92018-01-03 23:37:54 -0500499using GeometryEffectAttacherT =
500 std::vector<sk_sp<sksg::GeometryNode>> (*)(const Json::Value&,
501 AttachContext*,
502 std::vector<sk_sp<sksg::GeometryNode>>&&);
503static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
504 AttachMergeGeometryEffect,
Florin Malita51b8c892018-01-07 08:54:24 -0500505 AttachTrimGeometryEffect,
Florin Malitae6345d92018-01-03 23:37:54 -0500506};
507
Florin Malita094ccde2017-12-30 12:27:00 -0500508enum class ShapeType {
509 kGeometry,
Florin Malitae6345d92018-01-03 23:37:54 -0500510 kGeometryEffect,
Florin Malita094ccde2017-12-30 12:27:00 -0500511 kPaint,
512 kGroup,
Florin Malitadacc02b2017-12-31 09:12:31 -0500513 kTransform,
Florin Malita094ccde2017-12-30 12:27:00 -0500514};
515
516struct ShapeInfo {
517 const char* fTypeString;
518 ShapeType fShapeType;
519 uint32_t fAttacherIndex; // index into respective attacher tables
520};
521
522const ShapeInfo* FindShapeInfo(const Json::Value& shape) {
523 static constexpr ShapeInfo gShapeInfo[] = {
Florin Malitafbc13f12018-01-04 10:26:35 -0500524 { "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500525 { "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
526 { "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
Florin Malita16d0ad02018-01-19 15:07:29 -0500527 { "gr", ShapeType::kGroup , 0 }, // group -> Inline handler
Florin Malita6aaee592018-01-12 12:25:09 -0500528 { "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
Florin Malitae6345d92018-01-03 23:37:54 -0500529 { "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
Florin Malita02a32b02018-01-04 11:27:09 -0500530 { "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
Florin Malitae6345d92018-01-03 23:37:54 -0500531 { "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
Florin Malita02a32b02018-01-04 11:27:09 -0500532 { "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500533 { "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
Florin Malita51b8c892018-01-07 08:54:24 -0500534 { "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
Florin Malita16d0ad02018-01-19 15:07:29 -0500535 { "tr", ShapeType::kTransform , 0 }, // transform -> Inline handler
Florin Malita094ccde2017-12-30 12:27:00 -0500536 };
537
538 if (!shape.isObject())
539 return nullptr;
540
541 const auto& type = shape["ty"];
542 if (!type.isString())
543 return nullptr;
544
545 const auto* info = bsearch(type.asCString(),
546 gShapeInfo,
547 SK_ARRAY_COUNT(gShapeInfo),
548 sizeof(ShapeInfo),
549 [](const void* key, const void* info) {
550 return strcmp(static_cast<const char*>(key),
551 static_cast<const ShapeInfo*>(info)->fTypeString);
552 });
553
554 return static_cast<const ShapeInfo*>(info);
555}
556
Florin Malita16d0ad02018-01-19 15:07:29 -0500557struct GeometryEffectRec {
558 const Json::Value& fJson;
559 GeometryEffectAttacherT fAttach;
560};
561
Florin Malitaca4439f2018-01-23 10:31:59 -0500562struct AttachShapeContext {
563 AttachShapeContext(AttachContext* ctx,
564 std::vector<sk_sp<sksg::GeometryNode>>* geos,
565 std::vector<GeometryEffectRec>* effects,
566 size_t committedAnimators)
567 : fCtx(ctx)
568 , fGeometryStack(geos)
569 , fGeometryEffectStack(effects)
570 , fCommittedAnimators(committedAnimators) {}
571
572 AttachContext* fCtx;
573 std::vector<sk_sp<sksg::GeometryNode>>* fGeometryStack;
574 std::vector<GeometryEffectRec>* fGeometryEffectStack;
575 size_t fCommittedAnimators;
576};
577
578sk_sp<sksg::RenderNode> AttachShape(const Json::Value& jshape, AttachShapeContext* shapeCtx) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500579 if (!jshape.isArray())
Florin Malita094ccde2017-12-30 12:27:00 -0500580 return nullptr;
581
Florin Malitaca4439f2018-01-23 10:31:59 -0500582 SkDEBUGCODE(const auto initialGeometryEffects = shapeCtx->fGeometryEffectStack->size();)
Florin Malita094ccde2017-12-30 12:27:00 -0500583
Florin Malita16d0ad02018-01-19 15:07:29 -0500584 sk_sp<sksg::Group> shape_group = sksg::Group::Make();
585 sk_sp<sksg::RenderNode> shape_wrapper = shape_group;
586 sk_sp<sksg::Matrix> shape_matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500587
Florin Malita16d0ad02018-01-19 15:07:29 -0500588 struct ShapeRec {
589 const Json::Value& fJson;
590 const ShapeInfo& fInfo;
591 };
592
593 // First pass (bottom->top):
594 //
595 // * pick up the group transform and opacity
596 // * push local geometry effects onto the stack
597 // * store recs for next pass
598 //
599 std::vector<ShapeRec> recs;
600 for (Json::ArrayIndex i = 0; i < jshape.size(); ++i) {
601 const auto& s = jshape[jshape.size() - 1 - i];
Florin Malita094ccde2017-12-30 12:27:00 -0500602 const auto* info = FindShapeInfo(s);
603 if (!info) {
604 LogFail(s.isObject() ? s["ty"] : s, "Unknown shape");
605 continue;
606 }
607
Florin Malita16d0ad02018-01-19 15:07:29 -0500608 recs.push_back({ s, *info });
609
Florin Malita094ccde2017-12-30 12:27:00 -0500610 switch (info->fShapeType) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500611 case ShapeType::kTransform:
Florin Malitaca4439f2018-01-23 10:31:59 -0500612 if ((shape_matrix = AttachMatrix(s, shapeCtx->fCtx, nullptr))) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500613 shape_wrapper = sksg::Transform::Make(std::move(shape_wrapper), shape_matrix);
614 }
Florin Malitaca4439f2018-01-23 10:31:59 -0500615 shape_wrapper = AttachOpacity(s, shapeCtx->fCtx, std::move(shape_wrapper));
Florin Malita16d0ad02018-01-19 15:07:29 -0500616 break;
617 case ShapeType::kGeometryEffect:
618 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500619 shapeCtx->fGeometryEffectStack->push_back(
Florin Malita16d0ad02018-01-19 15:07:29 -0500620 { s, gGeometryEffectAttachers[info->fAttacherIndex] });
621 break;
622 default:
623 break;
624 }
625 }
626
627 // Second pass (top -> bottom, after 2x reverse):
628 //
629 // * track local geometry
630 // * emit local paints
631 //
632 std::vector<sk_sp<sksg::GeometryNode>> geos;
633 std::vector<sk_sp<sksg::RenderNode >> draws;
634 for (auto rec = recs.rbegin(); rec != recs.rend(); ++rec) {
635 switch (rec->fInfo.fShapeType) {
Florin Malita094ccde2017-12-30 12:27:00 -0500636 case ShapeType::kGeometry: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500637 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500638 if (auto geo = gGeometryAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
639 shapeCtx->fCtx)) {
Florin Malita094ccde2017-12-30 12:27:00 -0500640 geos.push_back(std::move(geo));
641 }
642 } break;
Florin Malitae6345d92018-01-03 23:37:54 -0500643 case ShapeType::kGeometryEffect: {
Florin Malita16d0ad02018-01-19 15:07:29 -0500644 // Apply the current effect and pop from the stack.
645 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
Florin Malitaee6de4b2018-01-21 11:13:17 -0500646 if (!geos.empty()) {
647 geos = gGeometryEffectAttachers[rec->fInfo.fAttacherIndex](rec->fJson,
Florin Malitaca4439f2018-01-23 10:31:59 -0500648 shapeCtx->fCtx,
Florin Malitaee6de4b2018-01-21 11:13:17 -0500649 std::move(geos));
650 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500651
Florin Malitaca4439f2018-01-23 10:31:59 -0500652 SkASSERT(shapeCtx->fGeometryEffectStack->back().fJson == rec->fJson);
653 SkASSERT(shapeCtx->fGeometryEffectStack->back().fAttach ==
Florin Malita16d0ad02018-01-19 15:07:29 -0500654 gGeometryEffectAttachers[rec->fInfo.fAttacherIndex]);
Florin Malitaca4439f2018-01-23 10:31:59 -0500655 shapeCtx->fGeometryEffectStack->pop_back();
Florin Malita094ccde2017-12-30 12:27:00 -0500656 } break;
657 case ShapeType::kGroup: {
Florin Malitaca4439f2018-01-23 10:31:59 -0500658 AttachShapeContext groupShapeCtx(shapeCtx->fCtx,
659 &geos,
660 shapeCtx->fGeometryEffectStack,
661 shapeCtx->fCommittedAnimators);
662 if (auto subgroup = AttachShape(rec->fJson["it"], &groupShapeCtx)) {
Florin Malita16d0ad02018-01-19 15:07:29 -0500663 draws.push_back(std::move(subgroup));
Florin Malitaca4439f2018-01-23 10:31:59 -0500664 SkASSERT(groupShapeCtx.fCommittedAnimators >= shapeCtx->fCommittedAnimators);
665 shapeCtx->fCommittedAnimators = groupShapeCtx.fCommittedAnimators;
Florin Malita094ccde2017-12-30 12:27:00 -0500666 }
667 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500668 case ShapeType::kPaint: {
669 SkASSERT(rec->fInfo.fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
Florin Malitaca4439f2018-01-23 10:31:59 -0500670 auto paint = gPaintAttachers[rec->fInfo.fAttacherIndex](rec->fJson, shapeCtx->fCtx);
Florin Malita16d0ad02018-01-19 15:07:29 -0500671 if (!paint || geos.empty())
672 break;
673
674 auto drawGeos = geos;
675
676 // Apply all pending effects from the stack.
Florin Malitaca4439f2018-01-23 10:31:59 -0500677 for (auto it = shapeCtx->fGeometryEffectStack->rbegin();
678 it != shapeCtx->fGeometryEffectStack->rend(); ++it) {
679 drawGeos = it->fAttach(it->fJson, shapeCtx->fCtx, std::move(drawGeos));
Florin Malita18eafd92018-01-04 21:11:55 -0500680 }
Florin Malita16d0ad02018-01-19 15:07:29 -0500681
682 // If we still have multiple geos, reduce using 'merge'.
683 auto geo = drawGeos.size() > 1
684 ? sksg::Merge::Make(std::move(drawGeos), sksg::Merge::Mode::kMerge)
685 : drawGeos[0];
686
687 SkASSERT(geo);
688 draws.push_back(sksg::Draw::Make(std::move(geo), std::move(paint)));
Florin Malitaca4439f2018-01-23 10:31:59 -0500689 shapeCtx->fCommittedAnimators = shapeCtx->fCtx->fAnimators.size();
Florin Malitadacc02b2017-12-31 09:12:31 -0500690 } break;
Florin Malita16d0ad02018-01-19 15:07:29 -0500691 default:
692 break;
Florin Malita094ccde2017-12-30 12:27:00 -0500693 }
694 }
695
Florin Malita16d0ad02018-01-19 15:07:29 -0500696 // By now we should have popped all local geometry effects.
Florin Malitaca4439f2018-01-23 10:31:59 -0500697 SkASSERT(shapeCtx->fGeometryEffectStack->size() == initialGeometryEffects);
Florin Malita16d0ad02018-01-19 15:07:29 -0500698
699 // Push transformed local geometries to parent list, for subsequent paints.
700 for (const auto& geo : geos) {
Florin Malitaca4439f2018-01-23 10:31:59 -0500701 shapeCtx->fGeometryStack->push_back(shape_matrix
Florin Malita16d0ad02018-01-19 15:07:29 -0500702 ? sksg::GeometryTransform::Make(std::move(geo), shape_matrix)
703 : std::move(geo));
Florin Malita094ccde2017-12-30 12:27:00 -0500704 }
705
Florin Malita16d0ad02018-01-19 15:07:29 -0500706 // Emit local draws reversed (bottom->top, per spec).
707 for (auto it = draws.rbegin(); it != draws.rend(); ++it) {
708 shape_group->addChild(std::move(*it));
Florin Malita2a8275b2018-01-02 12:52:43 -0500709 }
710
Florin Malita16d0ad02018-01-19 15:07:29 -0500711 return draws.empty() ? nullptr : shape_wrapper;
Florin Malita094ccde2017-12-30 12:27:00 -0500712}
713
714sk_sp<sksg::RenderNode> AttachCompLayer(const Json::Value& layer, AttachContext* ctx) {
715 SkASSERT(layer.isObject());
716
717 auto refId = ParseString(layer["refId"], "");
718 if (refId.isEmpty()) {
719 LOG("!! Comp layer missing refId\n");
720 return nullptr;
721 }
722
723 const auto* comp = ctx->fAssets.find(refId);
724 if (!comp) {
725 LOG("!! Pre-comp not found: '%s'\n", refId.c_str());
726 return nullptr;
727 }
728
729 // TODO: cycle detection
730 return AttachComposition(**comp, ctx);
731}
732
Florin Malita0e66fba2018-01-09 17:10:18 -0500733sk_sp<sksg::RenderNode> AttachSolidLayer(const Json::Value& jlayer, AttachContext*) {
734 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500735
Florin Malita0e66fba2018-01-09 17:10:18 -0500736 const auto size = SkSize::Make(ParseScalar(jlayer["sw"], -1),
737 ParseScalar(jlayer["sh"], -1));
738 const auto hex = ParseString(jlayer["sc"], "");
739 uint32_t c;
740 if (size.isEmpty() ||
741 !hex.startsWith("#") ||
742 !SkParse::FindHex(hex.c_str() + 1, &c)) {
743 LogFail(jlayer, "Could not parse solid layer");
744 return nullptr;
745 }
746
747 const SkColor color = 0xff000000 | c;
748
749 return sksg::Draw::Make(sksg::Rect::Make(SkRect::MakeSize(size)),
750 sksg::Color::Make(color));
Florin Malita094ccde2017-12-30 12:27:00 -0500751}
752
Florin Malita49328072018-01-08 12:51:12 -0500753sk_sp<sksg::RenderNode> AttachImageAsset(const Json::Value& jimage, AttachContext* ctx) {
754 SkASSERT(jimage.isObject());
755
756 const auto name = ParseString(jimage["p"], ""),
757 path = ParseString(jimage["u"], "");
758 if (name.isEmpty())
759 return nullptr;
760
761 // TODO: plumb resource paths explicitly to ResourceProvider?
762 const auto resName = path.isEmpty() ? name : SkOSPath::Join(path.c_str(), name.c_str());
763 const auto resStream = ctx->fResources.openStream(resName.c_str());
764 if (!resStream || !resStream->hasLength()) {
765 LOG("!! Could not load image resource: %s\n", resName.c_str());
766 return nullptr;
767 }
768
769 // TODO: non-intrisic image sizing
770 return sksg::Image::Make(
771 SkImage::MakeFromEncoded(SkData::MakeFromStream(resStream.get(), resStream->getLength())));
772}
773
774sk_sp<sksg::RenderNode> AttachImageLayer(const Json::Value& layer, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500775 SkASSERT(layer.isObject());
776
Florin Malita49328072018-01-08 12:51:12 -0500777 auto refId = ParseString(layer["refId"], "");
778 if (refId.isEmpty()) {
779 LOG("!! Image layer missing refId\n");
780 return nullptr;
781 }
782
783 const auto* jimage = ctx->fAssets.find(refId);
784 if (!jimage) {
785 LOG("!! Image asset not found: '%s'\n", refId.c_str());
786 return nullptr;
787 }
788
789 return AttachImageAsset(**jimage, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500790}
791
792sk_sp<sksg::RenderNode> AttachNullLayer(const Json::Value& layer, AttachContext*) {
793 SkASSERT(layer.isObject());
794
Florin Malita18eafd92018-01-04 21:11:55 -0500795 // Null layers are used solely to drive dependent transforms,
796 // but we use free-floating sksg::Matrices for that purpose.
Florin Malita094ccde2017-12-30 12:27:00 -0500797 return nullptr;
798}
799
800sk_sp<sksg::RenderNode> AttachShapeLayer(const Json::Value& layer, AttachContext* ctx) {
801 SkASSERT(layer.isObject());
802
803 LOG("** Attaching shape layer ind: %d\n", ParseInt(layer["ind"], 0));
804
Florin Malita16d0ad02018-01-19 15:07:29 -0500805 std::vector<sk_sp<sksg::GeometryNode>> geometryStack;
806 std::vector<GeometryEffectRec> geometryEffectStack;
Florin Malitaca4439f2018-01-23 10:31:59 -0500807 AttachShapeContext shapeCtx(ctx, &geometryStack, &geometryEffectStack, ctx->fAnimators.size());
808 auto shapeNode = AttachShape(layer["shapes"], &shapeCtx);
809
810 // Trim uncommitted animators: AttachShape consumes effects on the fly, and greedily attaches
811 // geometries => at the end, we can end up with unused geometries, which are nevertheless alive
812 // due to attached animators. To avoid this, we track committed animators and discard the
813 // orphans here.
814 SkASSERT(shapeCtx.fCommittedAnimators <= ctx->fAnimators.size());
815 ctx->fAnimators.resize(shapeCtx.fCommittedAnimators);
816
817 return shapeNode;
Florin Malita094ccde2017-12-30 12:27:00 -0500818}
819
820sk_sp<sksg::RenderNode> AttachTextLayer(const Json::Value& layer, AttachContext*) {
821 SkASSERT(layer.isObject());
822
823 LOG("?? Text layer stub\n");
824 return nullptr;
825}
826
Florin Malita18eafd92018-01-04 21:11:55 -0500827struct AttachLayerContext {
828 AttachLayerContext(const Json::Value& jlayers, AttachContext* ctx)
829 : fLayerList(jlayers), fCtx(ctx) {}
830
831 const Json::Value& fLayerList;
832 AttachContext* fCtx;
833 std::unordered_map<const Json::Value*, sk_sp<sksg::Matrix>> fLayerMatrixCache;
834 std::unordered_map<int, const Json::Value*> fLayerIndexCache;
Florin Malita5f9102f2018-01-10 13:36:22 -0500835 sk_sp<sksg::RenderNode> fCurrentMatte;
Florin Malita18eafd92018-01-04 21:11:55 -0500836
837 const Json::Value* findLayer(int index) {
838 SkASSERT(fLayerList.isArray());
839
840 if (index < 0) {
841 return nullptr;
842 }
843
844 const auto cached = fLayerIndexCache.find(index);
845 if (cached != fLayerIndexCache.end()) {
846 return cached->second;
847 }
848
849 for (const auto& l : fLayerList) {
850 if (!l.isObject()) {
851 continue;
852 }
853
854 if (ParseInt(l["ind"], -1) == index) {
855 fLayerIndexCache.insert(std::make_pair(index, &l));
856 return &l;
857 }
858 }
859
860 return nullptr;
861 }
862
863 sk_sp<sksg::Matrix> AttachLayerMatrix(const Json::Value& jlayer) {
864 SkASSERT(jlayer.isObject());
865
866 const auto cached = fLayerMatrixCache.find(&jlayer);
867 if (cached != fLayerMatrixCache.end()) {
868 return cached->second;
869 }
870
871 const auto* parentLayer = this->findLayer(ParseInt(jlayer["parent"], -1));
872
873 // TODO: cycle detection?
874 auto parentMatrix = (parentLayer && parentLayer != &jlayer)
875 ? this->AttachLayerMatrix(*parentLayer) : nullptr;
876
877 auto layerMatrix = AttachMatrix(jlayer["ks"], fCtx, std::move(parentMatrix));
878 fLayerMatrixCache.insert(std::make_pair(&jlayer, layerMatrix));
879
880 return layerMatrix;
881 }
882};
883
Florin Malita25366fa2018-01-23 13:37:59 -0500884SkBlendMode MaskBlendMode(char mode) {
885 switch (mode) {
886 case 'a': return SkBlendMode::kSrcOver; // Additive
887 case 's': return SkBlendMode::kExclusion; // Subtract
888 case 'i': return SkBlendMode::kDstIn; // Intersect
889 case 'l': return SkBlendMode::kLighten; // Lighten
890 case 'd': return SkBlendMode::kDarken; // Darken
891 case 'f': return SkBlendMode::kDifference; // Difference
892 default: break;
893 }
894
895 return SkBlendMode::kSrcOver;
896}
897
898sk_sp<sksg::RenderNode> AttachMask(const Json::Value& jmask,
899 AttachContext* ctx,
900 sk_sp<sksg::RenderNode> childNode) {
901 if (!jmask.isArray())
902 return childNode;
903
904 auto mask_group = sksg::Group::Make();
905
906 for (const auto& m : jmask) {
907 if (!m.isObject())
908 continue;
909
910 const auto inverted = ParseBool(m["inv"], false);
911 // TODO
912 if (inverted) {
913 LogFail(m, "Unsupported inverse mask");
914 continue;
915 }
916
917 auto mask_path = AttachPath(m["pt"], ctx);
918 if (!mask_path) {
919 LogFail(m, "Could not parse mask path");
920 continue;
921 }
922
923 auto mode = ParseString(m["mode"], "");
924 if (mode.size() != 1 || !strcmp(mode.c_str(), "n")) // "None" masks have no effect.
925 continue;
926
927 auto mask_paint = sksg::Color::Make(SK_ColorBLACK);
928 mask_paint->setBlendMode(MaskBlendMode(mode.c_str()[0]));
Florin Malita2518a0a2018-01-24 18:29:00 -0500929 BindProperty<ScalarValue>(m["o"], ctx,
930 [mask_paint](const ScalarValue& o) { mask_paint->setOpacity(o * 0.01f); });
Florin Malita25366fa2018-01-23 13:37:59 -0500931
932 mask_group->addChild(sksg::Draw::Make(std::move(mask_path), std::move(mask_paint)));
933 }
934
935 return mask_group->empty()
936 ? childNode
937 : sksg::MaskEffect::Make(std::move(childNode), std::move(mask_group));
938}
939
Florin Malita18eafd92018-01-04 21:11:55 -0500940sk_sp<sksg::RenderNode> AttachLayer(const Json::Value& jlayer,
941 AttachLayerContext* layerCtx) {
942 if (!jlayer.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500943 return nullptr;
944
945 using LayerAttacher = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*);
946 static constexpr LayerAttacher gLayerAttachers[] = {
947 AttachCompLayer, // 'ty': 0
948 AttachSolidLayer, // 'ty': 1
949 AttachImageLayer, // 'ty': 2
950 AttachNullLayer, // 'ty': 3
951 AttachShapeLayer, // 'ty': 4
952 AttachTextLayer, // 'ty': 5
953 };
954
Florin Malita18eafd92018-01-04 21:11:55 -0500955 int type = ParseInt(jlayer["ty"], -1);
Florin Malita094ccde2017-12-30 12:27:00 -0500956 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gLayerAttachers))) {
957 return nullptr;
958 }
959
Florin Malita71cba8f2018-01-09 08:07:14 -0500960 // Layer content.
961 auto layer = gLayerAttachers[type](jlayer, layerCtx->fCtx);
Florin Malita25366fa2018-01-23 13:37:59 -0500962 // Optional layer mask.
963 layer = AttachMask(jlayer["masksProperties"], layerCtx->fCtx, std::move(layer));
964 // Optional layer transform.
Florin Malita71cba8f2018-01-09 08:07:14 -0500965 if (auto layerMatrix = layerCtx->AttachLayerMatrix(jlayer)) {
Florin Malita71cba8f2018-01-09 08:07:14 -0500966 layer = sksg::Transform::Make(std::move(layer), std::move(layerMatrix));
967 }
968 // Optional layer opacity.
969 layer = AttachOpacity(jlayer["ks"], layerCtx->fCtx, std::move(layer));
Florin Malita18eafd92018-01-04 21:11:55 -0500970
Florin Malita71cba8f2018-01-09 08:07:14 -0500971 // TODO: we should also disable related/inactive animators.
Florin Malita35efaa82018-01-22 12:57:06 -0500972 class Activator final : public sksg::Animator {
Florin Malita71cba8f2018-01-09 08:07:14 -0500973 public:
974 Activator(sk_sp<sksg::OpacityEffect> controlNode, float in, float out)
975 : fControlNode(std::move(controlNode))
976 , fIn(in)
977 , fOut(out) {}
978
Florin Malita35efaa82018-01-22 12:57:06 -0500979 void onTick(float t) override {
Florin Malita71cba8f2018-01-09 08:07:14 -0500980 // Keep the layer fully transparent except for its [in..out] lifespan.
981 // (note: opacity == 0 disables rendering, while opacity == 1 is a noop)
982 fControlNode->setOpacity(t >= fIn && t <= fOut ? 1 : 0);
983 }
984
985 private:
986 const sk_sp<sksg::OpacityEffect> fControlNode;
987 const float fIn,
988 fOut;
989 };
990
991 auto layerControl = sksg::OpacityEffect::Make(std::move(layer));
992 const auto in = ParseScalar(jlayer["ip"], 0),
993 out = ParseScalar(jlayer["op"], in);
994
995 if (in >= out || ! layerControl)
996 return nullptr;
997
998 layerCtx->fCtx->fAnimators.push_back(skstd::make_unique<Activator>(layerControl, in, out));
999
Florin Malita5f9102f2018-01-10 13:36:22 -05001000 if (ParseBool(jlayer["td"], false)) {
1001 // This layer is a matte. We apply it as a mask to the next layer.
1002 layerCtx->fCurrentMatte = std::move(layerControl);
1003 return nullptr;
1004 }
1005
1006 if (layerCtx->fCurrentMatte) {
1007 // There is a pending matte. Apply and reset.
1008 return sksg::MaskEffect::Make(std::move(layerControl), std::move(layerCtx->fCurrentMatte));
1009 }
1010
Florin Malita71cba8f2018-01-09 08:07:14 -05001011 return layerControl;
Florin Malita094ccde2017-12-30 12:27:00 -05001012}
1013
1014sk_sp<sksg::RenderNode> AttachComposition(const Json::Value& comp, AttachContext* ctx) {
1015 if (!comp.isObject())
1016 return nullptr;
1017
Florin Malita18eafd92018-01-04 21:11:55 -05001018 const auto& jlayers = comp["layers"];
1019 if (!jlayers.isArray())
1020 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -05001021
Florin Malita18eafd92018-01-04 21:11:55 -05001022 SkSTArray<16, sk_sp<sksg::RenderNode>, true> layers;
1023 AttachLayerContext layerCtx(jlayers, ctx);
1024
1025 for (const auto& l : jlayers) {
1026 if (auto layer_fragment = AttachLayer(l, &layerCtx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -05001027 layers.push_back(std::move(layer_fragment));
Florin Malita094ccde2017-12-30 12:27:00 -05001028 }
1029 }
1030
Florin Malita2a8275b2018-01-02 12:52:43 -05001031 if (layers.empty()) {
1032 return nullptr;
1033 }
1034
1035 // Layers are painted in bottom->top order.
1036 auto comp_group = sksg::Group::Make();
1037 for (int i = layers.count() - 1; i >= 0; --i) {
1038 comp_group->addChild(std::move(layers[i]));
1039 }
1040
1041 LOG("** Attached composition '%s': %d layers.\n",
1042 ParseString(comp["id"], "").c_str(), layers.count());
1043
Florin Malita094ccde2017-12-30 12:27:00 -05001044 return comp_group;
1045}
1046
1047} // namespace
1048
Florin Malita49328072018-01-08 12:51:12 -05001049std::unique_ptr<Animation> Animation::Make(SkStream* stream, const ResourceProvider& res) {
Florin Malita094ccde2017-12-30 12:27:00 -05001050 if (!stream->hasLength()) {
1051 // TODO: handle explicit buffering?
1052 LOG("!! cannot parse streaming content\n");
1053 return nullptr;
1054 }
1055
1056 Json::Value json;
1057 {
1058 auto data = SkData::MakeFromStream(stream, stream->getLength());
1059 if (!data) {
1060 LOG("!! could not read stream\n");
1061 return nullptr;
1062 }
1063
1064 Json::Reader reader;
1065
1066 auto dataStart = static_cast<const char*>(data->data());
1067 if (!reader.parse(dataStart, dataStart + data->size(), json, false) || !json.isObject()) {
1068 LOG("!! failed to parse json: %s\n", reader.getFormattedErrorMessages().c_str());
1069 return nullptr;
1070 }
1071 }
1072
1073 const auto version = ParseString(json["v"], "");
1074 const auto size = SkSize::Make(ParseScalar(json["w"], -1), ParseScalar(json["h"], -1));
1075 const auto fps = ParseScalar(json["fr"], -1);
1076
1077 if (size.isEmpty() || version.isEmpty() || fps < 0) {
1078 LOG("!! invalid animation params (version: %s, size: [%f %f], frame rate: %f)",
1079 version.c_str(), size.width(), size.height(), fps);
1080 return nullptr;
1081 }
1082
Florin Malita49328072018-01-08 12:51:12 -05001083 return std::unique_ptr<Animation>(new Animation(res, std::move(version), size, fps, json));
Florin Malita094ccde2017-12-30 12:27:00 -05001084}
1085
Florin Malita49328072018-01-08 12:51:12 -05001086std::unique_ptr<Animation> Animation::MakeFromFile(const char path[], const ResourceProvider* res) {
1087 class DirectoryResourceProvider final : public ResourceProvider {
1088 public:
1089 explicit DirectoryResourceProvider(SkString dir) : fDir(std::move(dir)) {}
1090
1091 std::unique_ptr<SkStream> openStream(const char resource[]) const override {
1092 const auto resPath = SkOSPath::Join(fDir.c_str(), resource);
1093 return SkStream::MakeFromFile(resPath.c_str());
1094 }
1095
1096 private:
1097 const SkString fDir;
1098 };
1099
1100 const auto jsonStream = SkStream::MakeFromFile(path);
1101 if (!jsonStream)
1102 return nullptr;
1103
1104 std::unique_ptr<ResourceProvider> defaultProvider;
1105 if (!res) {
1106 defaultProvider = skstd::make_unique<DirectoryResourceProvider>(SkOSPath::Dirname(path));
1107 }
1108
1109 return Make(jsonStream.get(), res ? *res : *defaultProvider);
1110}
1111
1112Animation::Animation(const ResourceProvider& resources,
1113 SkString version, const SkSize& size, SkScalar fps, const Json::Value& json)
Florin Malita094ccde2017-12-30 12:27:00 -05001114 : fVersion(std::move(version))
1115 , fSize(size)
1116 , fFrameRate(fps)
1117 , fInPoint(ParseScalar(json["ip"], 0))
1118 , fOutPoint(SkTMax(ParseScalar(json["op"], SK_ScalarMax), fInPoint)) {
1119
1120 AssetMap assets;
1121 for (const auto& asset : json["assets"]) {
1122 if (!asset.isObject()) {
1123 continue;
1124 }
1125
1126 assets.set(ParseString(asset["id"], ""), &asset);
1127 }
1128
Florin Malita35efaa82018-01-22 12:57:06 -05001129 sksg::Scene::AnimatorList animators;
1130 AttachContext ctx = { resources, assets, animators };
1131 auto root = AttachComposition(json, &ctx);
1132
1133 LOG("** Attached %d animators\n", animators.size());
1134
1135 fScene = sksg::Scene::Make(std::move(root), std::move(animators));
Florin Malita094ccde2017-12-30 12:27:00 -05001136
Florin Malitadb385732018-01-09 12:19:32 -05001137 // In case the client calls render before the first tick.
1138 this->animationTick(0);
Florin Malita094ccde2017-12-30 12:27:00 -05001139}
1140
1141Animation::~Animation() = default;
1142
Florin Malita35efaa82018-01-22 12:57:06 -05001143void Animation::setShowInval(bool show) {
1144 if (fScene) {
1145 fScene->setShowInval(show);
1146 }
1147}
1148
Mike Reed29859872018-01-08 08:25:27 -05001149void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
Florin Malita35efaa82018-01-22 12:57:06 -05001150 if (!fScene)
Florin Malita094ccde2017-12-30 12:27:00 -05001151 return;
1152
Mike Reed29859872018-01-08 08:25:27 -05001153 SkAutoCanvasRestore restore(canvas, true);
1154 const SkRect srcR = SkRect::MakeSize(this->size());
1155 if (dstR) {
1156 canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
1157 }
1158 canvas->clipRect(srcR);
Florin Malita35efaa82018-01-22 12:57:06 -05001159 fScene->render(canvas);
Florin Malita094ccde2017-12-30 12:27:00 -05001160}
1161
1162void Animation::animationTick(SkMSec ms) {
Florin Malita35efaa82018-01-22 12:57:06 -05001163 if (!fScene)
1164 return;
1165
Florin Malita094ccde2017-12-30 12:27:00 -05001166 // 't' in the BM model really means 'frame #'
1167 auto t = static_cast<float>(ms) * fFrameRate / 1000;
1168
1169 t = fInPoint + std::fmod(t, fOutPoint - fInPoint);
1170
Florin Malita35efaa82018-01-22 12:57:06 -05001171 fScene->animate(t);
Florin Malita094ccde2017-12-30 12:27:00 -05001172}
1173
Florin Malita54f65c42018-01-16 17:04:30 -05001174} // namespace skottie