Debian Codegraph @

tools/viewer/SkottieSlide.cpp

raw
1 /*
2 * Copyright 2017 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "tools/viewer/SkottieSlide.h"
9
10 #if defined(SK_ENABLE_SKOTTIE)
11
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkFont.h"
14 #include "include/core/SkFontMgr.h"
15 #include "include/private/base/SkNoncopyable.h"
16 #include "include/private/base/SkTPin.h"
17 #include "modules/audioplayer/SkAudioPlayer.h"
18 #include "modules/skottie/include/Skottie.h"
19 #include "modules/skottie/include/SkottieProperty.h"
20 #include "modules/skottie/include/SlotManager.h"
21 #include "modules/skottie/include/TextShaper.h"
22 #include "modules/skottie/utils/SkottieUtils.h"
23 #include "modules/skottie/utils/TextEditor.h"
24 #include "modules/skresources/include/SkResources.h"
25 #include "modules/skshaper/utils/FactoryHelpers.h"
26 #include "src/base/SkTime.h"
27 #include "src/core/SkOSFile.h"
28 #include "src/utils/SkOSPath.h"
29 #include "tools/Resources.h"
30 #include "tools/fonts/FontToolUtils.h"
31 #include "tools/timer/TimeUtils.h"
32
33 #include <cmath>
34 #include <vector>
35
36 #include "imgui.h"
37
38 namespace {
39
40 class Track final : public skresources::ExternalTrackAsset {
41 public:
42 explicit Track(std::unique_ptr<SkAudioPlayer> player) : fPlayer(std::move(player)) {}
43
44 private:
45 void seek(float t) override {
46 if (fPlayer->isStopped() && t >=0) {
47 fPlayer->play();
48 }
49
50 if (fPlayer->isPlaying()) {
51 if (t < 0) {
52 fPlayer->stop();
53 } else {
54 static constexpr float kTolerance = 0.075f;
55 const auto player_pos = fPlayer->time();
56
57 if (std::abs(player_pos - t) > kTolerance) {
58 fPlayer->setTime(t);
59 }
60 }
61 }
62 }
63
64 const std::unique_ptr<SkAudioPlayer> fPlayer;
65 };
66
67 class AudioProviderProxy final : public skresources::ResourceProviderProxyBase {
68 public:
69 explicit AudioProviderProxy(sk_sp<skresources::ResourceProvider> rp)
70 : skresources::ResourceProviderProxyBase(std::move(rp)) {}
71
72 private:
73 sk_sp<skresources::ExternalTrackAsset> loadAudioAsset(const char path[],
74 const char name[],
75 const char[] /*id*/) override {
76 if (auto data = this->load(path, name)) {
77 if (auto player = SkAudioPlayer::Make(std::move(data))) {
78 return sk_make_sp<Track>(std::move(player));
79 }
80 }
81
82 return nullptr;
83 }
84 };
85
86 class Decorator : public SkNoncopyable {
87 public:
88 virtual ~Decorator() = default;
89
90 // We pass in the Matrix and have the Decorator handle using it independently
91 // This is so decorators can keep position on screen after moving.
92 virtual void render(SkCanvas*, double, const SkMatrix) = 0;
93 };
94
95 class SimpleMarker final : public Decorator {
96 public:
97 ~SimpleMarker() override = default;
98
99 static std::unique_ptr<Decorator> Make() { return std::make_unique<SimpleMarker>(); }
100
101 void render(SkCanvas* canvas, double t, const SkMatrix transform) override {
102 canvas->concat(transform);
103 SkPaint p;
104 p.setAntiAlias(true);
105
106 p.setColor(SK_ColorGREEN);
107 canvas->drawCircle(0, 0, 5, p);
108
109 p.setColor(SK_ColorRED);
110 p.setStrokeWidth(1.5f);
111 canvas->drawLine(-10, 0, 10, 0, p);
112 canvas->drawLine(0, -10, 0, 10, p);
113 }
114 };
115
116 class TestingResourceProvider : public skresources::ResourceProvider {
117 public:
118 TestingResourceProvider() {}
119
120 sk_sp<SkData> load(const char resource_path[], const char resource_name[]) const override {
121 auto it = fResources.find(resource_name);
122 if (it != fResources.end()) {
123 return it->second;
124 } else {
125 return GetResourceAsData(SkOSPath::Join(resource_path, resource_name).c_str());
126 }
127 }
128
129 sk_sp<skresources::ImageAsset> loadImageAsset(const char resource_path[],
130 const char resource_name[],
131 const char /*resource_id*/[]) const override {
132 auto data = this->load(resource_path, resource_name);
133 // Viewer should have already registered the codecs necessary for MultiFrameImageAsset
134 return skresources::MultiFrameImageAsset::Make(data);
135 }
136
137 void addPath(const char resource_name[], const SkPath& path) {
138 fResources[resource_name] = path.serialize();
139 }
140
141 private:
142 std::unordered_map<std::string, sk_sp<SkData>> fResources;
143 };
144
145 static const struct DecoratorRec {
146 const char* fName;
147 std::unique_ptr<Decorator>(*fFactory)();
148 } kDecorators[] = {
149 { "Simple marker", SimpleMarker::Make },
150 };
151
152 class TextTracker final : public skottie::PropertyObserver {
153 public:
154 explicit TextTracker(sk_sp<PropertyObserver> delegate) : fDelegate(std::move(delegate)) {}
155
156 std::vector<std::unique_ptr<skottie::TextPropertyHandle>>& props() {
157 return fTextProps;
158 }
159
160 private:
161 void onTextProperty(const char node_name[],
162 const LazyHandle<skottie::TextPropertyHandle>& lh) override {
163 fTextProps.push_back(lh());
164
165 if (fDelegate) {
166 fDelegate->onTextProperty(node_name, lh);
167 }
168 }
169
170 const sk_sp<PropertyObserver> fDelegate;
171 std::vector<std::unique_ptr<skottie::TextPropertyHandle>> fTextProps;
172 };
173
174 sk_sp<SkShapers::Factory> make_shapers_factory() {
175 #if defined(SK_SHAPER_UNICODE_AVAILABLE)
176 return sk_make_sp<SkShapers::HarfbuzzFactory>(
177 skottie::MakeStrictLinebreakUnicode(
178 SkShapers::BestAvailableUnicode()));
179 #else
180 return nullptr;
181 #endif
182 }
183
184 } // namespace
185
186 class SkottieSlide::TransformTracker : public skottie::PropertyObserver {
187 public:
188 void renderUI() {
189 if (ImGui::Begin("Transform Tracker", nullptr)) {
190 if (ImGui::BeginCombo("Transform", fTransformSelect
191 ? std::get<0>(*fTransformSelect).c_str()
192 : nullptr)) {
193 if (ImGui::Selectable("(none)", true)) {
194 fTransformSelect = nullptr;
195 }
196 for (const auto& entry : fTransforms) {
197 const auto* transform_name = std::get<0>(entry).c_str();
198 if (ImGui::Selectable(transform_name, false)) {
199 if (!fTransformSelect ||
200 transform_name != std::get<0>(*fTransformSelect).c_str()) {
201 fTransformSelect = &entry;
202 // Reset the decorator on transform change.
203 fDecorator = fDecoratorSelect->fFactory();
204 }
205 }
206 }
207 ImGui::EndCombo();
208 }
209
210 if (ImGui::BeginCombo("Decoration", fDecoratorSelect->fName)) {
211 for (const auto& dec : kDecorators) {
212 if (ImGui::Selectable(dec.fName, false)) {
213 if (dec.fName != fDecoratorSelect->fName) {
214 fDecoratorSelect = &dec;
215 fDecorator = fDecoratorSelect->fFactory();
216 }
217 }
218 }
219 ImGui::EndCombo();
220 }
221 }
222 ImGui::End();
223 }
224
225 void renderTracker(SkCanvas* canvas, double time, const SkSize& win_size, const SkSize& anim_size) const {
226 if (!fTransformSelect) {
227 return;
228 }
229
230 const auto tprop = std::get<1>(*fTransformSelect)->get();
231
232 const auto m = SkMatrix::Translate(tprop.fPosition.fX, tprop.fPosition.fY)
233 * SkMatrix::RotateDeg(tprop.fRotation)
234 * SkMatrix::Scale (tprop.fScale.fX*0.01f, tprop.fScale.fY*0.01f)
235 * SkMatrix::Translate(tprop.fAnchorPoint.fX, tprop.fAnchorPoint.fY);
236
237 const auto viewer_matrix = SkMatrix::RectToRectOrIdentity(SkRect::MakeSize(anim_size),
238 SkRect::MakeSize(win_size),
239 SkMatrix::kCenter_ScaleToFit);
240
241 SkAutoCanvasRestore acr(canvas, true);
242 canvas->concat(viewer_matrix);
243
244 SkASSERT(fDecorator);
245 fDecorator->render(canvas, time, m);
246 }
247
248 private:
249 void onTransformProperty(const char name[],
250 const LazyHandle<skottie::TransformPropertyHandle>& lh) override {
251
252 fTransforms.push_back(std::make_tuple(SkString(name), lh()));
253 }
254
255 using TransformT = std::tuple<SkString, std::unique_ptr<skottie::TransformPropertyHandle>>;
256
257 std::vector<TransformT> fTransforms;
258 std::unique_ptr<Decorator> fDecorator;
259 const TransformT* fTransformSelect = nullptr;
260 const DecoratorRec* fDecoratorSelect = &kDecorators[0];
261 };
262
263 // Holds a pointer to a slot manager and the list of slots for the UI widget to track
264 class SkottieSlide::SlotManagerInterface {
265 public:
266 SlotManagerInterface(sk_sp<skottie::SlotManager> slotManager, sk_sp<skresources::ResourceProvider> rp)
267 : fSlotManager(std::move(slotManager))
268 , fResourceProvider(std::move(rp))
269 {}
270
271
272 void renderUI() {
273 if (ImGui::Begin("Slot Manager", nullptr)) {
274 ImGui::Text("Color Slots");
275 for (size_t i = 0; i < fColorSlots.size(); i++) {
276 auto& cSlot = fColorSlots.at(i);
277 ImGui::PushID(i);
278 ImGui::Text("%s", cSlot.first.c_str());
279 if (ImGui::ColorEdit4("Color", cSlot.second.data())) {
280 this->pushSlots();
281 }
282 ImGui::PopID();
283 }
284 ImGui::Text("Scalar Slots");
285 for (size_t i = 0; i < fScalarSlots.size(); i++) {
286 auto& oSlot = fScalarSlots.at(i);
287 ImGui::PushID(i);
288 ImGui::Text("%s", oSlot.first.c_str());
289 if (ImGui::InputFloat("Scalar", &(oSlot.second))) {
290 this->pushSlots();
291 }
292 ImGui::PopID();
293 }
294 ImGui::Text("Vec2 Slots");
295 for (size_t i = 0; i < fVec2Slots.size(); i++) {
296 auto& vSlot = fVec2Slots.at(i);
297 ImGui::PushID(i);
298 ImGui::Text("%s", vSlot.first.c_str());
299 if (ImGui::InputFloat2("x, y", &(vSlot.second.x))) {
300 this->pushSlots();
301 }
302 ImGui::PopID();
303 }
304 ImGui::Text("Text Slots");
305 for (size_t i = 0; i < fTextStringSlots.size(); i++) {
306 auto& tSlot = fTextStringSlots.at(i);
307 ImGui::PushID(i);
308 ImGui::Text("%s", tSlot.first.c_str());
309 if (ImGui::InputText("Text", tSlot.second.source.data(),
310 tSlot.second.source.size())) {
311 this->pushSlots();
312 }
313 if (ImGui::BeginCombo("Font", tSlot.second.font.data())) {
314 for (const auto& typeface : fTypefaceList) {
315 if (ImGui::Selectable(typeface, false)) {
316 tSlot.second.font = typeface;
317 this->pushSlots();
318 }
319 }
320 ImGui::EndCombo();
321 }
322 ImGui::PopID();
323 }
324
325 ImGui::Text("Image Slots");
326 for (size_t i = 0; i < fImageSlots.size(); i++) {
327 auto& iSlot = fImageSlots.at(i);
328 ImGui::PushID(i);
329 ImGui::Text("%s", iSlot.first.c_str());
330 if (ImGui::BeginCombo("Resource", iSlot.second.data())) {
331 for (const auto& res : fResList) {
332 if (ImGui::Selectable(res.c_str(), false)) {
333 iSlot.second = res.c_str();
334 this->pushSlots();
335 }
336 }
337 ImGui::EndCombo();
338 }
339 ImGui::PopID();
340 }
341 }
342 ImGui::End();
343 }
344
345 void pushSlots() {
346 for(const auto& s : fColorSlots) {
347 fSlotManager->setColorSlot(s.first, SkColor4f{s.second[0], s.second[1],
348 s.second[2], s.second[3]}.toSkColor());
349 }
350 for(const auto& s : fScalarSlots) {
351 fSlotManager->setScalarSlot(s.first, s.second);
352 }
353 for(const auto& s : fVec2Slots) {
354 fSlotManager->setVec2Slot(s.first, {s.second.x, s.second.y});
355 }
356 for(const auto& s : fTextStringSlots) {
357 auto t = fSlotManager->getTextSlot(s.first);
358 t->fText = SkString(s.second.source.data());
359 t->fTypeface = ToolUtils::TestFontMgr()->matchFamilyStyle(s.second.font.c_str(),
360 SkFontStyle());
361 fSlotManager->setTextSlot(s.first, *t);
362 }
363 for(const auto& s : fImageSlots) {
364 auto image = fResourceProvider->loadImageAsset("images/", s.second.c_str(), nullptr);
365 fSlotManager->setImageSlot(s.first, image);
366 }
367 }
368
369 void initializeSlotManagerUI() {
370 prepareImageAssetList(GetResourcePath("skottie/images").c_str());
371 // only initialize if slots are unpopulated
372 if (fColorSlots.empty() && fScalarSlots.empty() && fTextStringSlots.empty()) {
373 auto slotInfos = fSlotManager->getSlotInfo();
374 for (const auto &sid : slotInfos.fColorSlotIDs) {
375 addColorSlot(sid);
376 }
377 for (const auto &sid : slotInfos.fScalarSlotIDs) {
378 addScalarSlot(sid);
379 }
380 for (const auto &sid : slotInfos.fVec2SlotIDs) {
381 addVec2Slot(sid);
382 }
383 for (const auto &sid : slotInfos.fImageSlotIDs) {
384 addImageSlot(sid);
385 }
386 for (const auto &sid : slotInfos.fTextSlotIDs) {
387 addTextSlot(sid);
388 }
389 }
390 }
391
392 private:
393 static constexpr int kBufferLen = 256;
394
395 sk_sp<skottie::SlotManager> fSlotManager;
396 const sk_sp<skresources::ResourceProvider> fResourceProvider;
397 std::vector<SkString> fResList;
398 static constexpr std::array<const char*, 4> fTypefaceList = {"Arial",
399 "Courier New",
400 "Roboto-Regular",
401 "Georgia"};
402
403 using GuiTextBuffer = std::array<char, kBufferLen>;
404
405 void addColorSlot(SkString slotID) {
406 auto c = fSlotManager->getColorSlot(slotID);
407 SkColor4f color4f = SkColor4f::FromColor(*c);
408 fColorSlots.push_back(std::make_pair(slotID, color4f.array()));
409 }
410
411 void addScalarSlot(SkString slotID) {
412 fScalarSlots.push_back(std::make_pair(slotID, *fSlotManager->getScalarSlot(slotID)));
413 }
414
415 void addVec2Slot(SkString slotID) {
416 fVec2Slots.push_back(std::make_pair(slotID, *fSlotManager->getVec2Slot(slotID)));
417 }
418
419 void addTextSlot(SkString slotID) {
420 std::array<char, kBufferLen> textSource = {'\0'};
421 SkString s = fSlotManager->getTextSlot(slotID)->fText;
422 std::copy(s.data(), s.data() + s.size(), textSource.data());
423 TextSlotData data = {textSource, fTypefaceList[0]};
424 fTextStringSlots.push_back(std::make_pair(slotID, data));
425 }
426
427 void addImageSlot(SkString slotID) {
428 fImageSlots.push_back(std::make_pair(slotID, fResList[0].data()));
429 }
430
431 void prepareImageAssetList(const char* dirname) {
432 fResList.clear();
433 SkOSFile::Iter iter(dirname, ".png");
434 for (SkString file; iter.next(&file); ) {
435 fResList.push_back(file);
436 }
437 }
438
439 struct TextSlotData {
440 GuiTextBuffer source;
441 std::string font;
442 };
443
444 std::vector<std::pair<SkString, std::array<float, 4>>> fColorSlots;
445 std::vector<std::pair<SkString, float>> fScalarSlots;
446 std::vector<std::pair<SkString, SkV2>> fVec2Slots;
447 std::vector<std::pair<SkString, TextSlotData>> fTextStringSlots;
448 std::vector<std::pair<SkString, std::string>> fImageSlots;
449
450 };
451
452 static void draw_stats_box(SkCanvas* canvas, const skottie::Animation::Builder::Stats& stats) {
453 static constexpr SkRect kR = { 10, 10, 280, 120 };
454 static constexpr SkScalar kTextSize = 20;
455
456 SkPaint paint;
457 paint.setAntiAlias(true);
458 paint.setColor(0xffeeeeee);
459
460 SkFont font(ToolUtils::DefaultTypeface(), kTextSize);
461
462 canvas->drawRect(kR, paint);
463
464 paint.setColor(SK_ColorBLACK);
465
466 const auto json_size = SkStringPrintf("Json size: %zu bytes",
467 stats.fJsonSize);
468 canvas->drawString(json_size, kR.x() + 10, kR.y() + kTextSize * 1, font, paint);
469 const auto animator_count = SkStringPrintf("Animator count: %zu",
470 stats.fAnimatorCount);
471 canvas->drawString(animator_count, kR.x() + 10, kR.y() + kTextSize * 2, font, paint);
472 const auto json_parse_time = SkStringPrintf("Json parse time: %.3f ms",
473 stats.fJsonParseTimeMS);
474 canvas->drawString(json_parse_time, kR.x() + 10, kR.y() + kTextSize * 3, font, paint);
475 const auto scene_parse_time = SkStringPrintf("Scene build time: %.3f ms",
476 stats.fSceneParseTimeMS);
477 canvas->drawString(scene_parse_time, kR.x() + 10, kR.y() + kTextSize * 4, font, paint);
478 const auto total_load_time = SkStringPrintf("Total load time: %.3f ms",
479 stats.fTotalLoadTimeMS);
480 canvas->drawString(total_load_time, kR.x() + 10, kR.y() + kTextSize * 5, font, paint);
481
482 paint.setStyle(SkPaint::kStroke_Style);
483 canvas->drawRect(kR, paint);
484 }
485
486 SkottieSlide::SkottieSlide(const SkString& name, const SkString& path)
487 : fPath(path) {
488 fName = name;
489 }
490
491 void SkottieSlide::init() {
492 class Logger final : public skottie::Logger {
493 public:
494 struct LogEntry {
495 SkString fMessage,
496 fJSON;
497 };
498
499 void log(skottie::Logger::Level lvl, const char message[], const char json[]) override {
500 auto& log = lvl == skottie::Logger::Level::kError ? fErrors : fWarnings;
501 log.push_back({ SkString(message), json ? SkString(json) : SkString() });
502 }
503
504 void report() const {
505 SkDebugf("Animation loaded with %zu error%s, %zu warning%s.\n",
506 fErrors.size(), fErrors.size() == 1 ? "" : "s",
507 fWarnings.size(), fWarnings.size() == 1 ? "" : "s");
508
509 const auto& show = [](const LogEntry& log, const char prefix[]) {
510 SkDebugf("%s%s", prefix, log.fMessage.c_str());
511 if (!log.fJSON.isEmpty())
512 SkDebugf(" : %s", log.fJSON.c_str());
513 SkDebugf("\n");
514 };
515
516 for (const auto& err : fErrors) show(err, " !! ");
517 for (const auto& wrn : fWarnings) show(wrn, " ?? ");
518 }
519
520 private:
521 std::vector<LogEntry> fErrors,
522 fWarnings;
523 };
524
525 auto logger = sk_make_sp<Logger>();
526
527 uint32_t flags = 0;
528 if (fPreferGlyphPaths) {
529 flags |= skottie::Animation::Builder::kPreferEmbeddedFonts;
530 }
531 skottie::Animation::Builder builder(flags);
532
533 // Viewer should have already registered the codecs necessary for DataURIResourceProviderProxy
534 auto predecode = skresources::ImageDecodeStrategy::kPreDecode;
535 auto resource_provider =
536 sk_make_sp<AudioProviderProxy>(skresources::DataURIResourceProviderProxy::Make(
537 skresources::FileResourceProvider::Make(SkOSPath::Dirname(fPath.c_str()),
538 predecode),
539 predecode,
540 ToolUtils::TestFontMgr()));
541
542 static constexpr char kInterceptPrefix[] = "__";
543 auto precomp_interceptor =
544 sk_make_sp<skottie_utils::ExternalAnimationPrecompInterceptor>(resource_provider,
545 kInterceptPrefix);
546
547 fTransformTracker = sk_make_sp<TransformTracker>();
548 auto text_tracker = sk_make_sp<TextTracker>(fTransformTracker);
549
550 builder.setLogger(logger)
551 .setFontManager(ToolUtils::TestFontMgr())
552 .setPrecompInterceptor(std::move(precomp_interceptor))
553 .setResourceProvider(resource_provider)
554 .setPropertyObserver(text_tracker)
555 .setTextShapingFactory(make_shapers_factory());
556
557 fAnimation = builder.makeFromFile(fPath.c_str());
558 fAnimationStats = builder.getStats();
559 fTimeBase = 0; // force a time reset
560
561 if (fAnimation) {
562 if (!fSlotManagerInterface) {
563 fSlotManagerInterface =
564 std::make_unique<SlotManagerInterface>(builder.getSlotManager(), resource_provider);
565 }
566
567 auto li = builder.getLayerInfo();
568
569 for (const auto& layer : li) {
570 SkDebugf(
571 "Layer: Name: \"%s\" | Size: %.2fx%.2f | In/Out: [%.2f, %.2f]\n",
572 layer.fName.c_str(),
573 layer.fSize.width(),
574 layer.fSize.height(),
575 layer.fInPoint,
576 layer.fOutPoint
577 );
578 }
579
580 fSlotManagerInterface->initializeSlotManagerUI();
581
582 fAnimation->seek(0);
583 fFrameTimes.resize(SkScalarCeilToInt(fAnimation->duration() * fAnimation->fps()));
584 SkDebugf("Loaded Bodymovin animation v: %s, size: [%f %f]\n",
585 fAnimation->version().c_str(),
586 fAnimation->size().width(),
587 fAnimation->size().height());
588 logger->report();
589
590 if (auto text_props = std::move(text_tracker->props()); !text_props.empty()) {
591 // Attach the editor to the first text layer, and track the rest as dependents.
592 auto editor_target = std::move(text_props[0]);
593 text_props.erase(text_props.cbegin());
594 fTextEditor = sk_make_sp<skottie_utils::TextEditor>(std::move(editor_target),
595 std::move(text_props));
596 fTextEditor->setCursorWeight(1.2f);
597 }
598 } else {
599 SkDebugf("failed to load Bodymovin animation: %s\n", fPath.c_str());
600 }
601 }
602
603 void SkottieSlide::load(SkScalar w, SkScalar h) {
604 fWinSize = SkSize::Make(w, h);
605 this->init();
606 }
607
608 void SkottieSlide::unload() {
609 fAnimation.reset();
610 }
611
612 void SkottieSlide::resize(SkScalar w, SkScalar h) {
613 fWinSize = { w, h };
614 }
615
616 void SkottieSlide::draw(SkCanvas* canvas) {
617 if (fAnimation) {
618 SkAutoCanvasRestore acr(canvas, true);
619 const auto dstR = SkRect::MakeSize(fWinSize);
620
621 {
622 const auto t0 = SkTime::GetNSecs();
623 fAnimation->render(canvas, &dstR);
624
625 // TODO: this does not capture GPU flush time!
626 const auto frame_index = static_cast<size_t>(fCurrentFrame);
627 fFrameTimes[frame_index] = static_cast<float>((SkTime::GetNSecs() - t0) * 1e-6);
628 }
629
630 double fr = 60;
631 if (fFrameRate != 0) {
632 fr = fFrameRate;
633 }
634 fTransformTracker->renderTracker(canvas, fCurrentFrame/fr, fWinSize, fAnimation->size());
635
636 if (fShowAnimationStats) {
637 draw_stats_box(canvas, fAnimationStats);
638 }
639 if (fShowAnimationInval) {
640 const auto t = SkMatrix::RectToRectOrIdentity(SkRect::MakeSize(fAnimation->size()), dstR,
641 SkMatrix::kCenter_ScaleToFit);
642 SkPaint fill, stroke;
643 fill.setAntiAlias(true);
644 fill.setColor(0x40ff0000);
645 stroke.setAntiAlias(true);
646 stroke.setColor(0xffff0000);
647 stroke.setStyle(SkPaint::kStroke_Style);
648
649 for (const auto& r : fInvalController) {
650 SkRect bounds;
651 t.mapRect(&bounds, r);
652 canvas->drawRect(bounds, fill);
653 canvas->drawRect(bounds, stroke);
654 }
655 }
656 if (fShowUI) {
657 this->renderUI();
658 }
659 if (fShowSlotManager) {
660 // not able to track layers with a PropertyObserver while using SM's PropertyObserver
661 fShowTrackerUI = false;
662 fSlotManagerInterface->renderUI();
663 }
664 if (fShowTrackerUI) {
665 fTransformTracker->renderUI();
666 }
667 }
668 }
669
670 bool SkottieSlide::animate(double nanos) {
671 if (!fTimeBase) {
672 // Reset the animation time.
673 fTimeBase = nanos;
674 }
675
676 if (fAnimation) {
677 fInvalController.reset();
678
679 const auto frame_count = fAnimation->duration() * fAnimation->fps();
680
681 if (!fDraggingProgress) {
682 // Clock-driven progress: update current frame.
683 const double t_sec = (nanos - fTimeBase) * 1e-9;
684 fCurrentFrame = std::fmod(t_sec * fAnimation->fps(), frame_count);
685 } else {
686 // Slider-driven progress: update the time origin.
687 fTimeBase = nanos - fCurrentFrame / fAnimation->fps() * 1e9;
688 }
689
690 // Sanitize and rate-lock the current frame.
691 fCurrentFrame = SkTPin<float>(fCurrentFrame, 0.0f, frame_count - 1);
692 if (fFrameRate > 0) {
693 const auto fps_scale = fFrameRate / fAnimation->fps();
694 fCurrentFrame = std::trunc(fCurrentFrame * fps_scale) / fps_scale;
695 }
696
697 fAnimation->seekFrame(fCurrentFrame, fShowAnimationInval ? &fInvalController
698 : nullptr);
699 }
700 return true;
701 }
702
703 bool SkottieSlide::onChar(SkUnichar c) {
704 if (fTextEditor && fTextEditor->onCharInput(c)) {
705 return true;
706 }
707
708 switch (c) {
709 case 'I':
710 fShowAnimationStats = !fShowAnimationStats;
711 return true;
712 case 'G':
713 fPreferGlyphPaths = !fPreferGlyphPaths;
714 this->load(fWinSize.width(), fWinSize.height());
715 return true;
716 case 'T':
717 fShowTrackerUI = !fShowTrackerUI;
718 return true;
719 case 'M':
720 fShowSlotManager = !fShowSlotManager;
721 return true;
722 case 'E':
723 if (fTextEditor) {
724 fTextEditor->toggleEnabled();
725 }
726 return true;
727 }
728
729 return Slide::onChar(c);
730 }
731
732 bool SkottieSlide::onMouse(SkScalar x, SkScalar y, skui::InputState state, skui::ModifierKey mod) {
733 if (fTextEditor && fTextEditor->onMouseInput(x, y, state, mod)) {
734 return true;
735 }
736
737 switch (state) {
738 case skui::InputState::kUp:
739 fShowAnimationInval = !fShowAnimationInval;
740 fShowAnimationStats = !fShowAnimationStats;
741 break;
742 default:
743 break;
744 }
745
746 fShowUI = this->UIArea().contains(x, y);
747
748 return false;
749 }
750
751 SkRect SkottieSlide::UIArea() const {
752 static constexpr float kUIHeight = 120.0f;
753
754 return SkRect::MakeXYWH(0, fWinSize.height() - kUIHeight, fWinSize.width(), kUIHeight);
755 }
756
757 void SkottieSlide::renderUI() {
758 static constexpr auto kUI_opacity = 0.35f,
759 kUI_hist_height = 50.0f,
760 kUI_fps_width = 100.0f;
761
762 auto add_frame_rate_option = [this](const char* label, double rate) {
763 const auto is_selected = (fFrameRate == rate);
764 if (ImGui::Selectable(label, is_selected)) {
765 fFrameRate = rate;
766 fFrameRateLabel = label;
767 }
768 if (is_selected) {
769 ImGui::SetItemDefaultFocus();
770 }
771 };
772
773 ImGui::SetNextWindowBgAlpha(kUI_opacity);
774 if (ImGui::Begin("Skottie Controls", nullptr, ImGuiWindowFlags_NoDecoration |
775 ImGuiWindowFlags_NoResize |
776 ImGuiWindowFlags_NoMove |
777 ImGuiWindowFlags_NoSavedSettings |
778 ImGuiWindowFlags_NoFocusOnAppearing |
779 ImGuiWindowFlags_NoNav)) {
780 const auto ui_area = this->UIArea();
781 ImGui::SetWindowPos(ImVec2(ui_area.x(), ui_area.y()));
782 ImGui::SetWindowSize(ImVec2(ui_area.width(), ui_area.height()));
783
784 ImGui::PushItemWidth(-1);
785 ImGui::PlotHistogram("", fFrameTimes.data(), fFrameTimes.size(),
786 0, nullptr, FLT_MAX, FLT_MAX, ImVec2(0, kUI_hist_height));
787 ImGui::SliderFloat("", &fCurrentFrame, 0, fAnimation->duration() * fAnimation->fps() - 1);
788 fDraggingProgress = ImGui::IsItemActive();
789 ImGui::PopItemWidth();
790
791 ImGui::PushItemWidth(kUI_fps_width);
792 if (ImGui::BeginCombo("FPS", fFrameRateLabel)) {
793 add_frame_rate_option("", 0.0);
794 add_frame_rate_option("Native", fAnimation->fps());
795 add_frame_rate_option( "1", 1.0);
796 add_frame_rate_option("15", 15.0);
797 add_frame_rate_option("24", 24.0);
798 add_frame_rate_option("30", 30.0);
799 add_frame_rate_option("60", 60.0);
800 ImGui::EndCombo();
801 }
802 ImGui::PopItemWidth();
803 }
804 ImGui::End();
805 }
806
807 #endif // SK_ENABLE_SKOTTIE