blob: ce2644ea5137a07958df46b5abc831942a0d1ffc [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
8#include "Skotty.h"
9
10#include "SkCanvas.h"
11#include "SkottyAnimator.h"
12#include "SkottyPriv.h"
13#include "SkottyProperties.h"
14#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 Malita6aaee592018-01-12 12:25:09 -050024#include "SkSGGradient.h"
Florin Malita094ccde2017-12-30 12:27:00 -050025#include "SkSGGroup.h"
Florin Malita49328072018-01-08 12:51:12 -050026#include "SkSGImage.h"
27#include "SkSGInvalidationController.h"
Florin Malita5f9102f2018-01-10 13:36:22 -050028#include "SkSGMaskEffect.h"
Florin Malitae6345d92018-01-03 23:37:54 -050029#include "SkSGMerge.h"
Florin Malitac0034172018-01-08 16:42:59 -050030#include "SkSGOpacityEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050031#include "SkSGPath.h"
Florin Malita2e1d7e22018-01-02 10:40:00 -050032#include "SkSGRect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050033#include "SkSGTransform.h"
Florin Malita51b8c892018-01-07 08:54:24 -050034#include "SkSGTrimEffect.h"
Florin Malita094ccde2017-12-30 12:27:00 -050035#include "SkStream.h"
36#include "SkTArray.h"
37#include "SkTHash.h"
38
39#include <cmath>
Florin Malita18eafd92018-01-04 21:11:55 -050040#include <unordered_map>
Florin Malitae6345d92018-01-03 23:37:54 -050041#include <vector>
42
Florin Malita094ccde2017-12-30 12:27:00 -050043#include "stdlib.h"
44
45namespace skotty {
46
47namespace {
48
49using AssetMap = SkTHashMap<SkString, const Json::Value*>;
50
51struct AttachContext {
Florin Malita49328072018-01-08 12:51:12 -050052 const ResourceProvider& fResources;
Florin Malita094ccde2017-12-30 12:27:00 -050053 const AssetMap& fAssets;
54 SkTArray<std::unique_ptr<AnimatorBase>>& fAnimators;
55};
56
57bool LogFail(const Json::Value& json, const char* msg) {
58 const auto dump = json.toStyledString();
59 LOG("!! %s: %s", msg, dump.c_str());
60 return false;
61}
62
63// This is the workhorse for binding properties: depending on whether the property is animated,
64// it will either apply immediately or instantiate and attach a keyframe animator.
Florin Malitaf9590922018-01-09 11:56:09 -050065template <typename ValT, typename NodeT>
66bool BindProperty(const Json::Value& jprop, AttachContext* ctx, const sk_sp<NodeT>& node,
67 typename Animator<ValT, NodeT>::ApplyFuncT&& apply) {
Florin Malita094ccde2017-12-30 12:27:00 -050068 if (!jprop.isObject())
69 return false;
70
Florin Malita95448a92018-01-08 10:15:12 -050071 const auto& jpropA = jprop["a"];
72 const auto& jpropK = jprop["k"];
73
74 // Older Json versions don't have an "a" animation marker.
75 // For those, we attempt to parse both ways.
76 if (jpropA.isNull() || !ParseBool(jpropA, "false")) {
Florin Malitaf9590922018-01-09 11:56:09 -050077 ValT val;
78 if (ValueTraits<ValT>::Parse(jpropK, &val)) {
Florin Malita95448a92018-01-08 10:15:12 -050079 // Static property.
Florin Malitaf9590922018-01-09 11:56:09 -050080 apply(node.get(), val);
Florin Malita95448a92018-01-08 10:15:12 -050081 return true;
Florin Malita094ccde2017-12-30 12:27:00 -050082 }
83
Florin Malita95448a92018-01-08 10:15:12 -050084 if (!jpropA.isNull()) {
85 return LogFail(jprop, "Could not parse (explicit) static property");
Florin Malita094ccde2017-12-30 12:27:00 -050086 }
Florin Malita094ccde2017-12-30 12:27:00 -050087 }
88
Florin Malita95448a92018-01-08 10:15:12 -050089 // Keyframe property.
Florin Malitaf9590922018-01-09 11:56:09 -050090 using AnimatorT = Animator<ValT, NodeT>;
91 auto animator = AnimatorT::Make(ParseFrames<ValT>(jpropK), node, std::move(apply));
Florin Malita95448a92018-01-08 10:15:12 -050092
93 if (!animator) {
94 return LogFail(jprop, "Could not parse keyframed property");
95 }
96
97 ctx->fAnimators.push_back(std::move(animator));
98
Florin Malita094ccde2017-12-30 12:27:00 -050099 return true;
100}
101
Florin Malita18eafd92018-01-04 21:11:55 -0500102sk_sp<sksg::Matrix> AttachMatrix(const Json::Value& t, AttachContext* ctx,
103 sk_sp<sksg::Matrix> parentMatrix) {
104 if (!t.isObject())
105 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500106
Florin Malita18eafd92018-01-04 21:11:55 -0500107 auto matrix = sksg::Matrix::Make(SkMatrix::I(), std::move(parentMatrix));
108 auto composite = sk_make_sp<CompositeTransform>(matrix);
Florin Malitaf9590922018-01-09 11:56:09 -0500109 auto anchor_attached = BindProperty<VectorValue>(t["a"], ctx, composite,
110 [](CompositeTransform* node, const VectorValue& a) {
111 node->setAnchorPoint(ValueTraits<VectorValue>::As<SkPoint>(a));
Florin Malita094ccde2017-12-30 12:27:00 -0500112 });
Florin Malitaf9590922018-01-09 11:56:09 -0500113 auto position_attached = BindProperty<VectorValue>(t["p"], ctx, composite,
114 [](CompositeTransform* node, const VectorValue& p) {
115 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
Florin Malita094ccde2017-12-30 12:27:00 -0500116 });
Florin Malitaf9590922018-01-09 11:56:09 -0500117 auto scale_attached = BindProperty<VectorValue>(t["s"], ctx, composite,
118 [](CompositeTransform* node, const VectorValue& s) {
119 node->setScale(ValueTraits<VectorValue>::As<SkVector>(s));
Florin Malita094ccde2017-12-30 12:27:00 -0500120 });
Florin Malitaf9590922018-01-09 11:56:09 -0500121 auto rotation_attached = BindProperty<ScalarValue>(t["r"], ctx, composite,
122 [](CompositeTransform* node, const ScalarValue& r) {
Florin Malita094ccde2017-12-30 12:27:00 -0500123 node->setRotation(r);
124 });
Florin Malitaf9590922018-01-09 11:56:09 -0500125 auto skew_attached = BindProperty<ScalarValue>(t["sk"], ctx, composite,
126 [](CompositeTransform* node, const ScalarValue& sk) {
Florin Malita094ccde2017-12-30 12:27:00 -0500127 node->setSkew(sk);
128 });
Florin Malitaf9590922018-01-09 11:56:09 -0500129 auto skewaxis_attached = BindProperty<ScalarValue>(t["sa"], ctx, composite,
130 [](CompositeTransform* node, const ScalarValue& sa) {
Florin Malita094ccde2017-12-30 12:27:00 -0500131 node->setSkewAxis(sa);
132 });
133
134 if (!anchor_attached &&
135 !position_attached &&
136 !scale_attached &&
137 !rotation_attached &&
138 !skew_attached &&
139 !skewaxis_attached) {
140 LogFail(t, "Could not parse transform");
Florin Malita18eafd92018-01-04 21:11:55 -0500141 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500142 }
143
Florin Malita18eafd92018-01-04 21:11:55 -0500144 return matrix;
Florin Malita094ccde2017-12-30 12:27:00 -0500145}
146
Florin Malitac0034172018-01-08 16:42:59 -0500147sk_sp<sksg::RenderNode> AttachOpacity(const Json::Value& jtransform, AttachContext* ctx,
148 sk_sp<sksg::RenderNode> childNode) {
149 if (!jtransform.isObject() || !childNode)
150 return childNode;
151
152 // This is more peeky than other attachers, because we want to avoid redundant opacity
153 // nodes for the extremely common case of static opaciy == 100.
154 const auto& opacity = jtransform["o"];
155 if (opacity.isObject() &&
156 !ParseBool(opacity["a"], true) &&
157 ParseScalar(opacity["k"], -1) == 100) {
158 // Ignoring static full opacity.
159 return childNode;
160 }
161
162 auto opacityNode = sksg::OpacityEffect::Make(childNode);
Florin Malitaf9590922018-01-09 11:56:09 -0500163 BindProperty<ScalarValue>(opacity, ctx, opacityNode,
164 [](sksg::OpacityEffect* node, const ScalarValue& o) {
Florin Malitac0034172018-01-08 16:42:59 -0500165 // BM opacity is [0..100]
166 node->setOpacity(o * 0.01f);
167 });
168
169 return opacityNode;
170}
171
Florin Malita094ccde2017-12-30 12:27:00 -0500172sk_sp<sksg::RenderNode> AttachShape(const Json::Value&, AttachContext* ctx);
173sk_sp<sksg::RenderNode> AttachComposition(const Json::Value&, AttachContext* ctx);
174
175sk_sp<sksg::RenderNode> AttachShapeGroup(const Json::Value& jgroup, AttachContext* ctx) {
176 SkASSERT(jgroup.isObject());
177
178 return AttachShape(jgroup["it"], ctx);
179}
180
181sk_sp<sksg::GeometryNode> AttachPathGeometry(const Json::Value& jpath, AttachContext* ctx) {
182 SkASSERT(jpath.isObject());
183
184 auto path_node = sksg::Path::Make();
Florin Malitaf9590922018-01-09 11:56:09 -0500185 auto path_attached = BindProperty<ShapeValue>(jpath["ks"], ctx, path_node,
186 [](sksg::Path* node, const ShapeValue& p) { node->setPath(p); });
Florin Malita094ccde2017-12-30 12:27:00 -0500187
188 if (path_attached)
189 LOG("** Attached path geometry - verbs: %d\n", path_node->getPath().countVerbs());
190
191 return path_attached ? path_node : nullptr;
192}
193
Florin Malita2e1d7e22018-01-02 10:40:00 -0500194sk_sp<sksg::GeometryNode> AttachRRectGeometry(const Json::Value& jrect, AttachContext* ctx) {
195 SkASSERT(jrect.isObject());
196
197 auto rect_node = sksg::RRect::Make();
198 auto composite = sk_make_sp<CompositeRRect>(rect_node);
199
Florin Malitaf9590922018-01-09 11:56:09 -0500200 auto p_attached = BindProperty<VectorValue>(jrect["p"], ctx, composite,
201 [](CompositeRRect* node, const VectorValue& p) {
202 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
203 });
204 auto s_attached = BindProperty<VectorValue>(jrect["s"], ctx, composite,
205 [](CompositeRRect* node, const VectorValue& s) {
206 node->setSize(ValueTraits<VectorValue>::As<SkSize>(s));
207 });
208 auto r_attached = BindProperty<ScalarValue>(jrect["r"], ctx, composite,
209 [](CompositeRRect* node, const ScalarValue& r) {
210 node->setRadius(SkSize::Make(r, r));
211 });
Florin Malita2e1d7e22018-01-02 10:40:00 -0500212
213 if (!p_attached && !s_attached && !r_attached) {
214 return nullptr;
215 }
216
Florin Malitafbc13f12018-01-04 10:26:35 -0500217 LOG("** Attached (r)rect geometry\n");
218
219 return rect_node;
220}
221
222sk_sp<sksg::GeometryNode> AttachEllipseGeometry(const Json::Value& jellipse, AttachContext* ctx) {
223 SkASSERT(jellipse.isObject());
224
225 auto rect_node = sksg::RRect::Make();
226 auto composite = sk_make_sp<CompositeRRect>(rect_node);
227
Florin Malitaf9590922018-01-09 11:56:09 -0500228 auto p_attached = BindProperty<VectorValue>(jellipse["p"], ctx, composite,
229 [](CompositeRRect* node, const VectorValue& p) {
230 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
231 });
232 auto s_attached = BindProperty<VectorValue>(jellipse["s"], ctx, composite,
233 [](CompositeRRect* node, const VectorValue& s) {
234 const auto sz = ValueTraits<VectorValue>::As<SkSize>(s);
235 node->setSize(sz);
236 node->setRadius(SkSize::Make(sz.width() / 2, sz.height() / 2));
237 });
Florin Malitafbc13f12018-01-04 10:26:35 -0500238
239 if (!p_attached && !s_attached) {
240 return nullptr;
241 }
242
243 LOG("** Attached ellipse geometry\n");
244
Florin Malita2e1d7e22018-01-02 10:40:00 -0500245 return rect_node;
246}
247
Florin Malita02a32b02018-01-04 11:27:09 -0500248sk_sp<sksg::GeometryNode> AttachPolystarGeometry(const Json::Value& jstar, AttachContext* ctx) {
249 SkASSERT(jstar.isObject());
250
251 static constexpr CompositePolyStar::Type gTypes[] = {
252 CompositePolyStar::Type::kStar, // "sy": 1
253 CompositePolyStar::Type::kPoly, // "sy": 2
254 };
255
256 const auto type = ParseInt(jstar["sy"], 0) - 1;
257 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gTypes))) {
258 LogFail(jstar, "Unknown polystar type");
259 return nullptr;
260 }
261
262 auto path_node = sksg::Path::Make();
263 auto composite = sk_make_sp<CompositePolyStar>(path_node, gTypes[type]);
264
Florin Malitaf9590922018-01-09 11:56:09 -0500265 BindProperty<VectorValue>(jstar["p"], ctx, composite,
266 [](CompositePolyStar* node, const VectorValue& p) {
267 node->setPosition(ValueTraits<VectorValue>::As<SkPoint>(p));
268 });
269 BindProperty<ScalarValue>(jstar["pt"], ctx, composite,
270 [](CompositePolyStar* node, const ScalarValue& pt) {
271 node->setPointCount(pt);
272 });
273 BindProperty<ScalarValue>(jstar["ir"], ctx, composite,
274 [](CompositePolyStar* node, const ScalarValue& ir) {
275 node->setInnerRadius(ir);
276 });
277 BindProperty<ScalarValue>(jstar["or"], ctx, composite,
278 [](CompositePolyStar* node, const ScalarValue& otr) {
Florin Malita9661b982018-01-06 14:25:49 -0500279 node->setOuterRadius(otr);
280 });
Florin Malitaf9590922018-01-09 11:56:09 -0500281 BindProperty<ScalarValue>(jstar["is"], ctx, composite,
282 [](CompositePolyStar* node, const ScalarValue& is) {
Florin Malita9661b982018-01-06 14:25:49 -0500283 node->setInnerRoundness(is);
284 });
Florin Malitaf9590922018-01-09 11:56:09 -0500285 BindProperty<ScalarValue>(jstar["os"], ctx, composite,
286 [](CompositePolyStar* node, const ScalarValue& os) {
Florin Malita9661b982018-01-06 14:25:49 -0500287 node->setOuterRoundness(os);
288 });
Florin Malitaf9590922018-01-09 11:56:09 -0500289 BindProperty<ScalarValue>(jstar["r"], ctx, composite,
290 [](CompositePolyStar* node, const ScalarValue& r) {
291 node->setRotation(r);
292 });
Florin Malita02a32b02018-01-04 11:27:09 -0500293
294 return path_node;
295}
296
Florin Malita6aaee592018-01-12 12:25:09 -0500297sk_sp<sksg::Color> AttachColor(const Json::Value& obj, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500298 SkASSERT(obj.isObject());
299
300 auto color_node = sksg::Color::Make(SK_ColorBLACK);
Florin Malita6aaee592018-01-12 12:25:09 -0500301 auto composite = sk_make_sp<CompositeColor>(color_node);
Florin Malitadcbb2db2018-01-09 13:11:56 -0500302 auto color_attached = BindProperty<VectorValue>(obj["c"], ctx, composite,
303 [](CompositeColor* node, const VectorValue& c) {
Florin Malitaf9590922018-01-09 11:56:09 -0500304 node->setColor(ValueTraits<VectorValue>::As<SkColor>(c));
305 });
Florin Malitadcbb2db2018-01-09 13:11:56 -0500306 auto opacity_attached = BindProperty<ScalarValue>(obj["o"], ctx, composite,
307 [](CompositeColor* node, const ScalarValue& o) {
308 node->setOpacity(o);
309 });
Florin Malita094ccde2017-12-30 12:27:00 -0500310
Florin Malitadcbb2db2018-01-09 13:11:56 -0500311 return (color_attached || opacity_attached) ? color_node : nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500312}
313
Florin Malita6aaee592018-01-12 12:25:09 -0500314sk_sp<sksg::Gradient> AttachGradient(const Json::Value& obj, AttachContext* ctx) {
315 SkASSERT(obj.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500316
Florin Malita6aaee592018-01-12 12:25:09 -0500317 const auto& stops = obj["g"];
318 if (!stops.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500319 return nullptr;
320
Florin Malita6aaee592018-01-12 12:25:09 -0500321 const auto stopCount = ParseInt(stops["p"], -1);
322 if (stopCount < 0)
323 return nullptr;
324
325 sk_sp<sksg::Gradient> gradient_node;
326 sk_sp<CompositeGradient> composite;
327
328 if (ParseInt(obj["t"], 1) == 1) {
329 auto linear_node = sksg::LinearGradient::Make();
330 composite = sk_make_sp<CompositeLinearGradient>(linear_node, stopCount);
331 gradient_node = std::move(linear_node);
332 } else {
333 auto radial_node = sksg::RadialGradient::Make();
334 composite = sk_make_sp<CompositeRadialGradient>(radial_node, stopCount);
335
336 // TODO: highlight, angle
337 gradient_node = std::move(radial_node);
338 }
339
340 BindProperty<VectorValue>(stops["k"], ctx, composite,
341 [](CompositeGradient* node, const VectorValue& stops) {
342 node->setColorStops(stops);
343 });
344 BindProperty<VectorValue>(obj["s"], ctx, composite,
345 [](CompositeGradient* node, const VectorValue& s) {
346 node->setStartPoint(ValueTraits<VectorValue>::As<SkPoint>(s));
347 });
348 BindProperty<VectorValue>(obj["e"], ctx, composite,
349 [](CompositeGradient* node, const VectorValue& e) {
350 node->setEndPoint(ValueTraits<VectorValue>::As<SkPoint>(e));
351 });
352
353 return gradient_node;
354}
355
356sk_sp<sksg::PaintNode> AttachPaint(const Json::Value& jfill, AttachContext* ctx,
357 sk_sp<sksg::PaintNode> paint_node) {
358 if (paint_node) {
359 paint_node->setAntiAlias(true);
360
361 // TODO: refactor opacity
362 }
363
364 return paint_node;
365}
366
367sk_sp<sksg::PaintNode> AttachStroke(const Json::Value& jstroke, AttachContext* ctx,
368 sk_sp<sksg::PaintNode> stroke_node) {
369 SkASSERT(jstroke.isObject());
370
371 if (!stroke_node)
372 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500373
374 stroke_node->setStyle(SkPaint::kStroke_Style);
375
Florin Malitaf9590922018-01-09 11:56:09 -0500376 auto width_attached = BindProperty<ScalarValue>(jstroke["w"], ctx, stroke_node,
Florin Malita6aaee592018-01-12 12:25:09 -0500377 [](sksg::PaintNode* node, const ScalarValue& w) {
Florin Malitaf9590922018-01-09 11:56:09 -0500378 node->setStrokeWidth(w);
379 });
Florin Malita094ccde2017-12-30 12:27:00 -0500380 if (!width_attached)
381 return nullptr;
382
383 stroke_node->setStrokeMiter(ParseScalar(jstroke["ml"], 4));
384
385 static constexpr SkPaint::Join gJoins[] = {
386 SkPaint::kMiter_Join,
387 SkPaint::kRound_Join,
388 SkPaint::kBevel_Join,
389 };
390 stroke_node->setStrokeJoin(gJoins[SkTPin<int>(ParseInt(jstroke["lj"], 1) - 1,
391 0, SK_ARRAY_COUNT(gJoins) - 1)]);
392
393 static constexpr SkPaint::Cap gCaps[] = {
394 SkPaint::kButt_Cap,
395 SkPaint::kRound_Cap,
396 SkPaint::kSquare_Cap,
397 };
398 stroke_node->setStrokeCap(gCaps[SkTPin<int>(ParseInt(jstroke["lc"], 1) - 1,
399 0, SK_ARRAY_COUNT(gCaps) - 1)]);
400
401 return stroke_node;
402}
403
Florin Malita6aaee592018-01-12 12:25:09 -0500404sk_sp<sksg::PaintNode> AttachColorFill(const Json::Value& jfill, AttachContext* ctx) {
405 SkASSERT(jfill.isObject());
406
407 return AttachPaint(jfill, ctx, AttachColor(jfill, ctx));
408}
409
410sk_sp<sksg::PaintNode> AttachGradientFill(const Json::Value& jfill, AttachContext* ctx) {
411 SkASSERT(jfill.isObject());
412
413 return AttachPaint(jfill, ctx, AttachGradient(jfill, ctx));
414}
415
416sk_sp<sksg::PaintNode> AttachColorStroke(const Json::Value& jstroke, AttachContext* ctx) {
417 SkASSERT(jstroke.isObject());
418
419 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachColor(jstroke, ctx)));
420}
421
422sk_sp<sksg::PaintNode> AttachGradientStroke(const Json::Value& jstroke, AttachContext* ctx) {
423 SkASSERT(jstroke.isObject());
424
425 return AttachStroke(jstroke, ctx, AttachPaint(jstroke, ctx, AttachGradient(jstroke, ctx)));
426}
427
Florin Malitae6345d92018-01-03 23:37:54 -0500428std::vector<sk_sp<sksg::GeometryNode>> AttachMergeGeometryEffect(
429 const Json::Value& jmerge, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
430 std::vector<sk_sp<sksg::GeometryNode>> merged;
431
432 static constexpr sksg::Merge::Mode gModes[] = {
433 sksg::Merge::Mode::kMerge, // "mm": 1
434 sksg::Merge::Mode::kUnion, // "mm": 2
435 sksg::Merge::Mode::kDifference, // "mm": 3
436 sksg::Merge::Mode::kIntersect, // "mm": 4
437 sksg::Merge::Mode::kXOR , // "mm": 5
438 };
439
Florin Malita51b8c892018-01-07 08:54:24 -0500440 const auto mode = gModes[SkTPin<int>(ParseInt(jmerge["mm"], 1) - 1,
441 0, SK_ARRAY_COUNT(gModes) - 1)];
Florin Malitae6345d92018-01-03 23:37:54 -0500442 merged.push_back(sksg::Merge::Make(std::move(geos), mode));
443
444 LOG("** Attached merge path effect, mode: %d\n", mode);
445
446 return merged;
447}
448
Florin Malita51b8c892018-01-07 08:54:24 -0500449std::vector<sk_sp<sksg::GeometryNode>> AttachTrimGeometryEffect(
450 const Json::Value& jtrim, AttachContext* ctx, std::vector<sk_sp<sksg::GeometryNode>>&& geos) {
451
452 enum class Mode {
453 kMerged, // "m": 1
454 kSeparate, // "m": 2
455 } gModes[] = { Mode::kMerged, Mode::kSeparate };
456
457 const auto mode = gModes[SkTPin<int>(ParseInt(jtrim["m"], 1) - 1,
458 0, SK_ARRAY_COUNT(gModes) - 1)];
459
460 std::vector<sk_sp<sksg::GeometryNode>> inputs;
461 if (mode == Mode::kMerged) {
462 inputs.push_back(sksg::Merge::Make(std::move(geos), sksg::Merge::Mode::kMerge));
463 } else {
464 inputs = std::move(geos);
465 }
466
467 std::vector<sk_sp<sksg::GeometryNode>> trimmed;
468 trimmed.reserve(inputs.size());
469 for (const auto& i : inputs) {
470 const auto trim = sksg::TrimEffect::Make(i);
471 trimmed.push_back(trim);
Florin Malitaf9590922018-01-09 11:56:09 -0500472 BindProperty<ScalarValue>(jtrim["s"], ctx, trim,
473 [](sksg::TrimEffect* node, const ScalarValue& s) {
Florin Malita51b8c892018-01-07 08:54:24 -0500474 node->setStart(s * 0.01f);
475 });
Florin Malitaf9590922018-01-09 11:56:09 -0500476 BindProperty<ScalarValue>(jtrim["e"], ctx, trim,
477 [](sksg::TrimEffect* node, const ScalarValue& e) {
Florin Malita51b8c892018-01-07 08:54:24 -0500478 node->setEnd(e * 0.01f);
479 });
480 // TODO: "offset" doesn't currently work the same as BM - figure out what's going on.
Florin Malitaf9590922018-01-09 11:56:09 -0500481 BindProperty<ScalarValue>(jtrim["o"], ctx, trim,
482 [](sksg::TrimEffect* node, const ScalarValue& o) {
Florin Malita51b8c892018-01-07 08:54:24 -0500483 node->setOffset(o * 0.01f);
484 });
485 }
486
487 return trimmed;
488}
489
Florin Malita094ccde2017-12-30 12:27:00 -0500490using GeometryAttacherT = sk_sp<sksg::GeometryNode> (*)(const Json::Value&, AttachContext*);
491static constexpr GeometryAttacherT gGeometryAttachers[] = {
492 AttachPathGeometry,
Florin Malita2e1d7e22018-01-02 10:40:00 -0500493 AttachRRectGeometry,
Florin Malitafbc13f12018-01-04 10:26:35 -0500494 AttachEllipseGeometry,
Florin Malita02a32b02018-01-04 11:27:09 -0500495 AttachPolystarGeometry,
Florin Malita094ccde2017-12-30 12:27:00 -0500496};
497
498using PaintAttacherT = sk_sp<sksg::PaintNode> (*)(const Json::Value&, AttachContext*);
499static constexpr PaintAttacherT gPaintAttachers[] = {
Florin Malita6aaee592018-01-12 12:25:09 -0500500 AttachColorFill,
501 AttachColorStroke,
502 AttachGradientFill,
503 AttachGradientStroke,
Florin Malita094ccde2017-12-30 12:27:00 -0500504};
505
506using GroupAttacherT = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*);
507static constexpr GroupAttacherT gGroupAttachers[] = {
508 AttachShapeGroup,
509};
510
Florin Malitae6345d92018-01-03 23:37:54 -0500511using GeometryEffectAttacherT =
512 std::vector<sk_sp<sksg::GeometryNode>> (*)(const Json::Value&,
513 AttachContext*,
514 std::vector<sk_sp<sksg::GeometryNode>>&&);
515static constexpr GeometryEffectAttacherT gGeometryEffectAttachers[] = {
516 AttachMergeGeometryEffect,
Florin Malita51b8c892018-01-07 08:54:24 -0500517 AttachTrimGeometryEffect,
Florin Malitae6345d92018-01-03 23:37:54 -0500518};
519
Florin Malita094ccde2017-12-30 12:27:00 -0500520enum class ShapeType {
521 kGeometry,
Florin Malitae6345d92018-01-03 23:37:54 -0500522 kGeometryEffect,
Florin Malita094ccde2017-12-30 12:27:00 -0500523 kPaint,
524 kGroup,
Florin Malitadacc02b2017-12-31 09:12:31 -0500525 kTransform,
Florin Malita094ccde2017-12-30 12:27:00 -0500526};
527
528struct ShapeInfo {
529 const char* fTypeString;
530 ShapeType fShapeType;
531 uint32_t fAttacherIndex; // index into respective attacher tables
532};
533
534const ShapeInfo* FindShapeInfo(const Json::Value& shape) {
535 static constexpr ShapeInfo gShapeInfo[] = {
Florin Malitafbc13f12018-01-04 10:26:35 -0500536 { "el", ShapeType::kGeometry , 2 }, // ellipse -> AttachEllipseGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500537 { "fl", ShapeType::kPaint , 0 }, // fill -> AttachColorFill
538 { "gf", ShapeType::kPaint , 2 }, // gfill -> AttachGradientFill
Florin Malitae6345d92018-01-03 23:37:54 -0500539 { "gr", ShapeType::kGroup , 0 }, // group -> AttachShapeGroup
Florin Malita6aaee592018-01-12 12:25:09 -0500540 { "gs", ShapeType::kPaint , 3 }, // gstroke -> AttachGradientStroke
Florin Malitae6345d92018-01-03 23:37:54 -0500541 { "mm", ShapeType::kGeometryEffect, 0 }, // merge -> AttachMergeGeometryEffect
Florin Malita02a32b02018-01-04 11:27:09 -0500542 { "rc", ShapeType::kGeometry , 1 }, // rrect -> AttachRRectGeometry
Florin Malitae6345d92018-01-03 23:37:54 -0500543 { "sh", ShapeType::kGeometry , 0 }, // shape -> AttachPathGeometry
Florin Malita02a32b02018-01-04 11:27:09 -0500544 { "sr", ShapeType::kGeometry , 3 }, // polystar -> AttachPolyStarGeometry
Florin Malita6aaee592018-01-12 12:25:09 -0500545 { "st", ShapeType::kPaint , 1 }, // stroke -> AttachColorStroke
Florin Malita51b8c892018-01-07 08:54:24 -0500546 { "tm", ShapeType::kGeometryEffect, 1 }, // trim -> AttachTrimGeometryEffect
Florin Malita18eafd92018-01-04 21:11:55 -0500547 { "tr", ShapeType::kTransform , 0 }, // transform -> In-place handler
Florin Malita094ccde2017-12-30 12:27:00 -0500548 };
549
550 if (!shape.isObject())
551 return nullptr;
552
553 const auto& type = shape["ty"];
554 if (!type.isString())
555 return nullptr;
556
557 const auto* info = bsearch(type.asCString(),
558 gShapeInfo,
559 SK_ARRAY_COUNT(gShapeInfo),
560 sizeof(ShapeInfo),
561 [](const void* key, const void* info) {
562 return strcmp(static_cast<const char*>(key),
563 static_cast<const ShapeInfo*>(info)->fTypeString);
564 });
565
566 return static_cast<const ShapeInfo*>(info);
567}
568
569sk_sp<sksg::RenderNode> AttachShape(const Json::Value& shapeArray, AttachContext* ctx) {
570 if (!shapeArray.isArray())
571 return nullptr;
572
Florin Malita2a8275b2018-01-02 12:52:43 -0500573 // (https://helpx.adobe.com/after-effects/using/overview-shape-layers-paths-vector.html#groups_and_render_order_for_shapes_and_shape_attributes)
574 //
575 // Render order for shapes within a shape layer
576 //
577 // The rules for rendering a shape layer are similar to the rules for rendering a composition
578 // that contains nested compositions:
579 //
580 // * Within a group, the shape at the bottom of the Timeline panel stacking order is rendered
581 // first.
582 //
583 // * All path operations within a group are performed before paint operations. This means,
584 // for example, that the stroke follows the distortions in the path made by the Wiggle Paths
585 // path operation. Path operations within a group are performed from top to bottom.
586 //
587 // * Paint operations within a group are performed from the bottom to the top in the Timeline
588 // panel stacking order. This means, for example, that a stroke is rendered on top of
589 // (in front of) a stroke that appears after it in the Timeline panel.
590 //
Florin Malitadacc02b2017-12-31 09:12:31 -0500591 sk_sp<sksg::Group> shape_group = sksg::Group::Make();
592 sk_sp<sksg::RenderNode> xformed_group = shape_group;
Florin Malita094ccde2017-12-30 12:27:00 -0500593
Florin Malitae6345d92018-01-03 23:37:54 -0500594 std::vector<sk_sp<sksg::GeometryNode>> geos;
595 std::vector<sk_sp<sksg::RenderNode>> draws;
Florin Malita094ccde2017-12-30 12:27:00 -0500596
597 for (const auto& s : shapeArray) {
598 const auto* info = FindShapeInfo(s);
599 if (!info) {
600 LogFail(s.isObject() ? s["ty"] : s, "Unknown shape");
601 continue;
602 }
603
604 switch (info->fShapeType) {
605 case ShapeType::kGeometry: {
606 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryAttachers));
607 if (auto geo = gGeometryAttachers[info->fAttacherIndex](s, ctx)) {
608 geos.push_back(std::move(geo));
609 }
610 } break;
Florin Malitae6345d92018-01-03 23:37:54 -0500611 case ShapeType::kGeometryEffect: {
612 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGeometryEffectAttachers));
613 geos = gGeometryEffectAttachers[info->fAttacherIndex](s, ctx, std::move(geos));
614 } break;
Florin Malita094ccde2017-12-30 12:27:00 -0500615 case ShapeType::kPaint: {
616 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gPaintAttachers));
617 if (auto paint = gPaintAttachers[info->fAttacherIndex](s, ctx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -0500618 for (const auto& geo : geos) {
619 draws.push_back(sksg::Draw::Make(geo, paint));
620 }
Florin Malita094ccde2017-12-30 12:27:00 -0500621 }
622 } break;
623 case ShapeType::kGroup: {
624 SkASSERT(info->fAttacherIndex < SK_ARRAY_COUNT(gGroupAttachers));
625 if (auto group = gGroupAttachers[info->fAttacherIndex](s, ctx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -0500626 draws.push_back(std::move(group));
Florin Malita094ccde2017-12-30 12:27:00 -0500627 }
628 } break;
Florin Malitadacc02b2017-12-31 09:12:31 -0500629 case ShapeType::kTransform: {
Florin Malita2a8275b2018-01-02 12:52:43 -0500630 // TODO: BM appears to transform the geometry, not the draw op itself.
Florin Malita18eafd92018-01-04 21:11:55 -0500631 if (auto matrix = AttachMatrix(s, ctx, nullptr)) {
632 xformed_group = sksg::Transform::Make(std::move(xformed_group),
633 std::move(matrix));
634 }
Florin Malitac0034172018-01-08 16:42:59 -0500635 xformed_group = AttachOpacity(s, ctx, std::move(xformed_group));
Florin Malitadacc02b2017-12-31 09:12:31 -0500636 } break;
Florin Malita094ccde2017-12-30 12:27:00 -0500637 }
638 }
639
Florin Malita2a8275b2018-01-02 12:52:43 -0500640 if (draws.empty()) {
641 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500642 }
643
Florin Malitae6345d92018-01-03 23:37:54 -0500644 for (auto draw = draws.rbegin(); draw != draws.rend(); ++draw) {
645 shape_group->addChild(std::move(*draw));
Florin Malita2a8275b2018-01-02 12:52:43 -0500646 }
647
Florin Malitae6345d92018-01-03 23:37:54 -0500648 LOG("** Attached shape: %zd draws.\n", draws.size());
Florin Malitadacc02b2017-12-31 09:12:31 -0500649 return xformed_group;
Florin Malita094ccde2017-12-30 12:27:00 -0500650}
651
652sk_sp<sksg::RenderNode> AttachCompLayer(const Json::Value& layer, AttachContext* ctx) {
653 SkASSERT(layer.isObject());
654
655 auto refId = ParseString(layer["refId"], "");
656 if (refId.isEmpty()) {
657 LOG("!! Comp layer missing refId\n");
658 return nullptr;
659 }
660
661 const auto* comp = ctx->fAssets.find(refId);
662 if (!comp) {
663 LOG("!! Pre-comp not found: '%s'\n", refId.c_str());
664 return nullptr;
665 }
666
667 // TODO: cycle detection
668 return AttachComposition(**comp, ctx);
669}
670
Florin Malita0e66fba2018-01-09 17:10:18 -0500671sk_sp<sksg::RenderNode> AttachSolidLayer(const Json::Value& jlayer, AttachContext*) {
672 SkASSERT(jlayer.isObject());
Florin Malita094ccde2017-12-30 12:27:00 -0500673
Florin Malita0e66fba2018-01-09 17:10:18 -0500674 const auto size = SkSize::Make(ParseScalar(jlayer["sw"], -1),
675 ParseScalar(jlayer["sh"], -1));
676 const auto hex = ParseString(jlayer["sc"], "");
677 uint32_t c;
678 if (size.isEmpty() ||
679 !hex.startsWith("#") ||
680 !SkParse::FindHex(hex.c_str() + 1, &c)) {
681 LogFail(jlayer, "Could not parse solid layer");
682 return nullptr;
683 }
684
685 const SkColor color = 0xff000000 | c;
686
687 return sksg::Draw::Make(sksg::Rect::Make(SkRect::MakeSize(size)),
688 sksg::Color::Make(color));
Florin Malita094ccde2017-12-30 12:27:00 -0500689}
690
Florin Malita49328072018-01-08 12:51:12 -0500691sk_sp<sksg::RenderNode> AttachImageAsset(const Json::Value& jimage, AttachContext* ctx) {
692 SkASSERT(jimage.isObject());
693
694 const auto name = ParseString(jimage["p"], ""),
695 path = ParseString(jimage["u"], "");
696 if (name.isEmpty())
697 return nullptr;
698
699 // TODO: plumb resource paths explicitly to ResourceProvider?
700 const auto resName = path.isEmpty() ? name : SkOSPath::Join(path.c_str(), name.c_str());
701 const auto resStream = ctx->fResources.openStream(resName.c_str());
702 if (!resStream || !resStream->hasLength()) {
703 LOG("!! Could not load image resource: %s\n", resName.c_str());
704 return nullptr;
705 }
706
707 // TODO: non-intrisic image sizing
708 return sksg::Image::Make(
709 SkImage::MakeFromEncoded(SkData::MakeFromStream(resStream.get(), resStream->getLength())));
710}
711
712sk_sp<sksg::RenderNode> AttachImageLayer(const Json::Value& layer, AttachContext* ctx) {
Florin Malita094ccde2017-12-30 12:27:00 -0500713 SkASSERT(layer.isObject());
714
Florin Malita49328072018-01-08 12:51:12 -0500715 auto refId = ParseString(layer["refId"], "");
716 if (refId.isEmpty()) {
717 LOG("!! Image layer missing refId\n");
718 return nullptr;
719 }
720
721 const auto* jimage = ctx->fAssets.find(refId);
722 if (!jimage) {
723 LOG("!! Image asset not found: '%s'\n", refId.c_str());
724 return nullptr;
725 }
726
727 return AttachImageAsset(**jimage, ctx);
Florin Malita094ccde2017-12-30 12:27:00 -0500728}
729
730sk_sp<sksg::RenderNode> AttachNullLayer(const Json::Value& layer, AttachContext*) {
731 SkASSERT(layer.isObject());
732
Florin Malita18eafd92018-01-04 21:11:55 -0500733 // Null layers are used solely to drive dependent transforms,
734 // but we use free-floating sksg::Matrices for that purpose.
Florin Malita094ccde2017-12-30 12:27:00 -0500735 return nullptr;
736}
737
738sk_sp<sksg::RenderNode> AttachShapeLayer(const Json::Value& layer, AttachContext* ctx) {
739 SkASSERT(layer.isObject());
740
741 LOG("** Attaching shape layer ind: %d\n", ParseInt(layer["ind"], 0));
742
743 return AttachShape(layer["shapes"], ctx);
744}
745
746sk_sp<sksg::RenderNode> AttachTextLayer(const Json::Value& layer, AttachContext*) {
747 SkASSERT(layer.isObject());
748
749 LOG("?? Text layer stub\n");
750 return nullptr;
751}
752
Florin Malita18eafd92018-01-04 21:11:55 -0500753struct AttachLayerContext {
754 AttachLayerContext(const Json::Value& jlayers, AttachContext* ctx)
755 : fLayerList(jlayers), fCtx(ctx) {}
756
757 const Json::Value& fLayerList;
758 AttachContext* fCtx;
759 std::unordered_map<const Json::Value*, sk_sp<sksg::Matrix>> fLayerMatrixCache;
760 std::unordered_map<int, const Json::Value*> fLayerIndexCache;
Florin Malita5f9102f2018-01-10 13:36:22 -0500761 sk_sp<sksg::RenderNode> fCurrentMatte;
Florin Malita18eafd92018-01-04 21:11:55 -0500762
763 const Json::Value* findLayer(int index) {
764 SkASSERT(fLayerList.isArray());
765
766 if (index < 0) {
767 return nullptr;
768 }
769
770 const auto cached = fLayerIndexCache.find(index);
771 if (cached != fLayerIndexCache.end()) {
772 return cached->second;
773 }
774
775 for (const auto& l : fLayerList) {
776 if (!l.isObject()) {
777 continue;
778 }
779
780 if (ParseInt(l["ind"], -1) == index) {
781 fLayerIndexCache.insert(std::make_pair(index, &l));
782 return &l;
783 }
784 }
785
786 return nullptr;
787 }
788
789 sk_sp<sksg::Matrix> AttachLayerMatrix(const Json::Value& jlayer) {
790 SkASSERT(jlayer.isObject());
791
792 const auto cached = fLayerMatrixCache.find(&jlayer);
793 if (cached != fLayerMatrixCache.end()) {
794 return cached->second;
795 }
796
797 const auto* parentLayer = this->findLayer(ParseInt(jlayer["parent"], -1));
798
799 // TODO: cycle detection?
800 auto parentMatrix = (parentLayer && parentLayer != &jlayer)
801 ? this->AttachLayerMatrix(*parentLayer) : nullptr;
802
803 auto layerMatrix = AttachMatrix(jlayer["ks"], fCtx, std::move(parentMatrix));
804 fLayerMatrixCache.insert(std::make_pair(&jlayer, layerMatrix));
805
806 return layerMatrix;
807 }
808};
809
810sk_sp<sksg::RenderNode> AttachLayer(const Json::Value& jlayer,
811 AttachLayerContext* layerCtx) {
812 if (!jlayer.isObject())
Florin Malita094ccde2017-12-30 12:27:00 -0500813 return nullptr;
814
815 using LayerAttacher = sk_sp<sksg::RenderNode> (*)(const Json::Value&, AttachContext*);
816 static constexpr LayerAttacher gLayerAttachers[] = {
817 AttachCompLayer, // 'ty': 0
818 AttachSolidLayer, // 'ty': 1
819 AttachImageLayer, // 'ty': 2
820 AttachNullLayer, // 'ty': 3
821 AttachShapeLayer, // 'ty': 4
822 AttachTextLayer, // 'ty': 5
823 };
824
Florin Malita18eafd92018-01-04 21:11:55 -0500825 int type = ParseInt(jlayer["ty"], -1);
Florin Malita094ccde2017-12-30 12:27:00 -0500826 if (type < 0 || type >= SkTo<int>(SK_ARRAY_COUNT(gLayerAttachers))) {
827 return nullptr;
828 }
829
Florin Malita71cba8f2018-01-09 08:07:14 -0500830 // Layer content.
831 auto layer = gLayerAttachers[type](jlayer, layerCtx->fCtx);
832 if (auto layerMatrix = layerCtx->AttachLayerMatrix(jlayer)) {
833 // Optional layer transform.
834 layer = sksg::Transform::Make(std::move(layer), std::move(layerMatrix));
835 }
836 // Optional layer opacity.
837 layer = AttachOpacity(jlayer["ks"], layerCtx->fCtx, std::move(layer));
Florin Malita18eafd92018-01-04 21:11:55 -0500838
Florin Malita71cba8f2018-01-09 08:07:14 -0500839 // TODO: we should also disable related/inactive animators.
840 class Activator final : public AnimatorBase {
841 public:
842 Activator(sk_sp<sksg::OpacityEffect> controlNode, float in, float out)
843 : fControlNode(std::move(controlNode))
844 , fIn(in)
845 , fOut(out) {}
846
Florin Malitaa6dd7522018-01-09 08:46:52 -0500847 void tick(float t) override {
Florin Malita71cba8f2018-01-09 08:07:14 -0500848 // Keep the layer fully transparent except for its [in..out] lifespan.
849 // (note: opacity == 0 disables rendering, while opacity == 1 is a noop)
850 fControlNode->setOpacity(t >= fIn && t <= fOut ? 1 : 0);
851 }
852
853 private:
854 const sk_sp<sksg::OpacityEffect> fControlNode;
855 const float fIn,
856 fOut;
857 };
858
859 auto layerControl = sksg::OpacityEffect::Make(std::move(layer));
860 const auto in = ParseScalar(jlayer["ip"], 0),
861 out = ParseScalar(jlayer["op"], in);
862
863 if (in >= out || ! layerControl)
864 return nullptr;
865
866 layerCtx->fCtx->fAnimators.push_back(skstd::make_unique<Activator>(layerControl, in, out));
867
Florin Malita5f9102f2018-01-10 13:36:22 -0500868 if (ParseBool(jlayer["td"], false)) {
869 // This layer is a matte. We apply it as a mask to the next layer.
870 layerCtx->fCurrentMatte = std::move(layerControl);
871 return nullptr;
872 }
873
874 if (layerCtx->fCurrentMatte) {
875 // There is a pending matte. Apply and reset.
876 return sksg::MaskEffect::Make(std::move(layerControl), std::move(layerCtx->fCurrentMatte));
877 }
878
Florin Malita71cba8f2018-01-09 08:07:14 -0500879 return layerControl;
Florin Malita094ccde2017-12-30 12:27:00 -0500880}
881
882sk_sp<sksg::RenderNode> AttachComposition(const Json::Value& comp, AttachContext* ctx) {
883 if (!comp.isObject())
884 return nullptr;
885
Florin Malita18eafd92018-01-04 21:11:55 -0500886 const auto& jlayers = comp["layers"];
887 if (!jlayers.isArray())
888 return nullptr;
Florin Malita094ccde2017-12-30 12:27:00 -0500889
Florin Malita18eafd92018-01-04 21:11:55 -0500890 SkSTArray<16, sk_sp<sksg::RenderNode>, true> layers;
891 AttachLayerContext layerCtx(jlayers, ctx);
892
893 for (const auto& l : jlayers) {
894 if (auto layer_fragment = AttachLayer(l, &layerCtx)) {
Florin Malita2a8275b2018-01-02 12:52:43 -0500895 layers.push_back(std::move(layer_fragment));
Florin Malita094ccde2017-12-30 12:27:00 -0500896 }
897 }
898
Florin Malita2a8275b2018-01-02 12:52:43 -0500899 if (layers.empty()) {
900 return nullptr;
901 }
902
903 // Layers are painted in bottom->top order.
904 auto comp_group = sksg::Group::Make();
905 for (int i = layers.count() - 1; i >= 0; --i) {
906 comp_group->addChild(std::move(layers[i]));
907 }
908
909 LOG("** Attached composition '%s': %d layers.\n",
910 ParseString(comp["id"], "").c_str(), layers.count());
911
Florin Malita094ccde2017-12-30 12:27:00 -0500912 return comp_group;
913}
914
915} // namespace
916
Florin Malita49328072018-01-08 12:51:12 -0500917std::unique_ptr<Animation> Animation::Make(SkStream* stream, const ResourceProvider& res) {
Florin Malita094ccde2017-12-30 12:27:00 -0500918 if (!stream->hasLength()) {
919 // TODO: handle explicit buffering?
920 LOG("!! cannot parse streaming content\n");
921 return nullptr;
922 }
923
924 Json::Value json;
925 {
926 auto data = SkData::MakeFromStream(stream, stream->getLength());
927 if (!data) {
928 LOG("!! could not read stream\n");
929 return nullptr;
930 }
931
932 Json::Reader reader;
933
934 auto dataStart = static_cast<const char*>(data->data());
935 if (!reader.parse(dataStart, dataStart + data->size(), json, false) || !json.isObject()) {
936 LOG("!! failed to parse json: %s\n", reader.getFormattedErrorMessages().c_str());
937 return nullptr;
938 }
939 }
940
941 const auto version = ParseString(json["v"], "");
942 const auto size = SkSize::Make(ParseScalar(json["w"], -1), ParseScalar(json["h"], -1));
943 const auto fps = ParseScalar(json["fr"], -1);
944
945 if (size.isEmpty() || version.isEmpty() || fps < 0) {
946 LOG("!! invalid animation params (version: %s, size: [%f %f], frame rate: %f)",
947 version.c_str(), size.width(), size.height(), fps);
948 return nullptr;
949 }
950
Florin Malita49328072018-01-08 12:51:12 -0500951 return std::unique_ptr<Animation>(new Animation(res, std::move(version), size, fps, json));
Florin Malita094ccde2017-12-30 12:27:00 -0500952}
953
Florin Malita49328072018-01-08 12:51:12 -0500954std::unique_ptr<Animation> Animation::MakeFromFile(const char path[], const ResourceProvider* res) {
955 class DirectoryResourceProvider final : public ResourceProvider {
956 public:
957 explicit DirectoryResourceProvider(SkString dir) : fDir(std::move(dir)) {}
958
959 std::unique_ptr<SkStream> openStream(const char resource[]) const override {
960 const auto resPath = SkOSPath::Join(fDir.c_str(), resource);
961 return SkStream::MakeFromFile(resPath.c_str());
962 }
963
964 private:
965 const SkString fDir;
966 };
967
968 const auto jsonStream = SkStream::MakeFromFile(path);
969 if (!jsonStream)
970 return nullptr;
971
972 std::unique_ptr<ResourceProvider> defaultProvider;
973 if (!res) {
974 defaultProvider = skstd::make_unique<DirectoryResourceProvider>(SkOSPath::Dirname(path));
975 }
976
977 return Make(jsonStream.get(), res ? *res : *defaultProvider);
978}
979
980Animation::Animation(const ResourceProvider& resources,
981 SkString version, const SkSize& size, SkScalar fps, const Json::Value& json)
Florin Malita094ccde2017-12-30 12:27:00 -0500982 : fVersion(std::move(version))
983 , fSize(size)
984 , fFrameRate(fps)
985 , fInPoint(ParseScalar(json["ip"], 0))
986 , fOutPoint(SkTMax(ParseScalar(json["op"], SK_ScalarMax), fInPoint)) {
987
988 AssetMap assets;
989 for (const auto& asset : json["assets"]) {
990 if (!asset.isObject()) {
991 continue;
992 }
993
994 assets.set(ParseString(asset["id"], ""), &asset);
995 }
996
Florin Malita49328072018-01-08 12:51:12 -0500997 AttachContext ctx = { resources, assets, fAnimators };
Florin Malita094ccde2017-12-30 12:27:00 -0500998 fDom = AttachComposition(json, &ctx);
999
Florin Malitadb385732018-01-09 12:19:32 -05001000 // In case the client calls render before the first tick.
1001 this->animationTick(0);
1002
Florin Malita094ccde2017-12-30 12:27:00 -05001003 LOG("** Attached %d animators\n", fAnimators.count());
1004}
1005
1006Animation::~Animation() = default;
1007
Mike Reed29859872018-01-08 08:25:27 -05001008void Animation::render(SkCanvas* canvas, const SkRect* dstR) const {
Florin Malita094ccde2017-12-30 12:27:00 -05001009 if (!fDom)
1010 return;
1011
1012 sksg::InvalidationController ic;
1013 fDom->revalidate(&ic, SkMatrix::I());
1014
1015 // TODO: proper inval
Mike Reed29859872018-01-08 08:25:27 -05001016 SkAutoCanvasRestore restore(canvas, true);
1017 const SkRect srcR = SkRect::MakeSize(this->size());
1018 if (dstR) {
1019 canvas->concat(SkMatrix::MakeRectToRect(srcR, *dstR, SkMatrix::kCenter_ScaleToFit));
1020 }
1021 canvas->clipRect(srcR);
Florin Malita094ccde2017-12-30 12:27:00 -05001022 fDom->render(canvas);
1023
1024 if (!fShowInval)
1025 return;
1026
1027 SkPaint fill, stroke;
1028 fill.setAntiAlias(true);
1029 fill.setColor(0x40ff0000);
1030 stroke.setAntiAlias(true);
1031 stroke.setColor(0xffff0000);
1032 stroke.setStyle(SkPaint::kStroke_Style);
1033
1034 for (const auto& r : ic) {
1035 canvas->drawRect(r, fill);
1036 canvas->drawRect(r, stroke);
1037 }
1038}
1039
1040void Animation::animationTick(SkMSec ms) {
1041 // 't' in the BM model really means 'frame #'
1042 auto t = static_cast<float>(ms) * fFrameRate / 1000;
1043
1044 t = fInPoint + std::fmod(t, fOutPoint - fInPoint);
1045
1046 // TODO: this can be optimized quite a bit with some sorting/state tracking.
1047 for (const auto& a : fAnimators) {
1048 a->tick(t);
1049 }
1050}
1051
1052} // namespace skotty