lottie/performance: clip out path early during rle generation.
[platform/core/uifw/lottie-player.git] / src / lottie / lottieitem.cpp
1 #include "lottieitem.h"
2 #include <cmath>
3 #include <algorithm>
4 #include "vbitmap.h"
5 #include "vdasher.h"
6 #include "vpainter.h"
7 #include "vraster.h"
8
9 /* Lottie Layer Rules
10  * 1. time stretch is pre calculated and applied to all the properties of the
11  * lottilayer model and all its children
12  * 2. The frame property could be reversed using,time-reverse layer property in
13  * AE. which means (start frame > endFrame) 3.
14  */
15
16 LOTCompItem::LOTCompItem(LOTModel *model)
17     : mRootModel(model), mUpdateViewBox(false), mCurFrameNo(-1)
18 {
19     mCompData = model->mRoot.get();
20     mRootLayer = createLayerItem(mCompData->mRootLayer.get());
21     mRootLayer->updateStaticProperty();
22     mViewSize = mCompData->size();
23 }
24
25 std::unique_ptr<LOTLayerItem>
26 LOTCompItem::createLayerItem(LOTLayerData *layerData)
27 {
28     switch (layerData->mLayerType) {
29     case LayerType::Precomp: {
30         return std::make_unique<LOTCompLayerItem>(layerData);
31         break;
32     }
33     case LayerType::Solid: {
34         return std::make_unique<LOTSolidLayerItem>(layerData);
35         break;
36     }
37     case LayerType::Shape: {
38         return std::make_unique<LOTShapeLayerItem>(layerData);
39         break;
40     }
41     case LayerType::Null: {
42         return std::make_unique<LOTNullLayerItem>(layerData);
43         break;
44     }
45     default:
46         return nullptr;
47         break;
48     }
49 }
50
51 void LOTCompItem::resize(const VSize &size)
52 {
53     if (mViewSize == size) return;
54     mViewSize = size;
55     mUpdateViewBox = true;
56 }
57
58 VSize LOTCompItem::size() const
59 {
60     return mViewSize;
61 }
62
63 bool LOTCompItem::update(int frameNo)
64 {
65     // check if cached frame is same as requested frame.
66     if (!mUpdateViewBox && (mCurFrameNo == frameNo)) return false;
67
68     /*
69      * if viewbox dosen't scale exactly to the viewport
70      * we scale the viewbox keeping AspectRatioPreserved and then align the
71      * viewbox to the viewport using AlignCenter rule.
72      */
73     VSize viewPort = mViewSize;
74     VSize viewBox = mCompData->size();
75
76     float sx = float(viewPort.width()) / viewBox.width();
77     float sy = float(viewPort.height()) / viewBox.height();
78     float scale = fmin(sx, sy);
79     float tx = (viewPort.width() - viewBox.width() * scale) * 0.5;
80     float ty = (viewPort.height() - viewBox.height() * scale) * 0.5;
81
82     VMatrix m;
83     m.translate(tx, ty).scale(scale, scale);
84     mRootLayer->update(frameNo, m, 1.0);
85
86     mCurFrameNo = frameNo;
87     mUpdateViewBox = false;
88     return true;
89 }
90
91 void LOTCompItem::buildRenderList()
92 {
93     mDrawableList.clear();
94     mRootLayer->renderList(mDrawableList);
95
96     mRenderList.clear();
97     for (auto &i : mDrawableList) {
98         LOTDrawable *lotDrawable = static_cast<LOTDrawable *>(i);
99         lotDrawable->sync();
100         mRenderList.push_back(lotDrawable->mCNode.get());
101     }
102 }
103
104 const std::vector<LOTNode *> &LOTCompItem::renderList() const
105 {
106     return mRenderList;
107 }
108
109 bool LOTCompItem::render(const lottie::Surface &surface)
110 {
111     VBitmap bitmap((uchar *)surface.buffer(), surface.width(), surface.height(),
112                    surface.bytesPerLine(), VBitmap::Format::ARGB32_Premultiplied,
113                    nullptr, nullptr);
114
115     /* schedule all preprocess task for this frame at once.
116      */
117     mDrawableList.clear();
118     mRootLayer->renderList(mDrawableList);
119     VRect clip(0, 0, surface.width(), surface.height());
120     for (auto &e : mDrawableList) {
121         e->preprocess(clip);
122     }
123
124     VPainter painter(&bitmap);
125     mRootLayer->render(&painter, {}, {}, nullptr);
126
127     return true;
128 }
129
130 void LOTMaskItem::update(int frameNo, const VMatrix &parentMatrix,
131                          float parentAlpha, const DirtyFlag &/*flag*/)
132 {
133     if (mData->mShape.isStatic()) {
134         if (mLocalPath.empty()) {
135             mData->mShape.value(frameNo).toPath(mLocalPath);
136         }
137     } else {
138         mData->mShape.value(frameNo).toPath(mLocalPath);
139     }
140     float opacity = mData->opacity(frameNo);
141     opacity = opacity * parentAlpha;
142     mCombinedAlpha = opacity;
143
144     VPath path = mLocalPath;
145     path.transform(parentMatrix);
146
147     mRleTask = VRaster::generateFillInfo(std::move(path), std::move(mRle));
148     mRle = VRle();
149 }
150
151 VRle LOTMaskItem::rle()
152 {
153     if (mRleTask.valid()) {
154         mRle = mRleTask.get();
155         if (!vCompare(mCombinedAlpha, 1.0f))
156             mRle *= (mCombinedAlpha * 255);
157         if (mData->mInv) mRle.invert();
158     }
159     return mRle;
160 }
161
162 void LOTLayerItem::render(VPainter *painter, const VRle &inheritMask, const VRle &inheritMatte, LOTLayerItem *matteSource)
163 {
164     VRle matteRle;
165     if (matteSource) {
166         mDrawableList.clear();
167         matteSource->renderList(mDrawableList);
168         for (auto &i : mDrawableList) {
169             matteRle = matteRle + i->rle();
170         }
171
172         if (!inheritMatte.empty())
173             matteRle = matteRle & inheritMatte;
174     } else {
175         matteRle = inheritMatte;
176     }
177     mDrawableList.clear();
178     renderList(mDrawableList);
179
180     VRle mask;
181     if (hasMask()) {
182         mask = maskRle(painter->clipBoundingRect());
183         if (!inheritMask.empty())
184             mask = mask & inheritMask;
185         // if resulting mask is empty then return.
186         if (mask.empty())
187             return;
188     } else {
189         mask = inheritMask;
190     }
191
192     for (auto &i : mDrawableList) {
193         painter->setBrush(i->mBrush);
194         VRle rle = i->rle();
195         if (!mask.empty()) rle = rle & mask;
196
197         if (rle.empty()) continue;
198
199         if (!matteRle.empty()) {
200             if (mLayerData->mMatteType == MatteType::AlphaInv) {
201                 rle = rle - matteRle;
202             } else {
203                 rle = rle & matteRle;
204             }
205         }
206         painter->drawRle(VPoint(), rle);
207     }
208 }
209
210 VRle LOTLayerItem::maskRle(const VRect &clipRect)
211 {
212     VRle rle;
213     for (auto &i : mMasks) {
214         switch (i->maskMode()) {
215         case LOTMaskData::Mode::Add: {
216             rle = rle + i->rle();
217             break;
218         }
219         case LOTMaskData::Mode::Substarct: {
220             if (rle.empty() && !clipRect.empty())
221                 rle = VRle::toRle(clipRect);
222             rle = rle - i->rle();
223             break;
224         }
225         case LOTMaskData::Mode::Intersect: {
226             rle = rle & i->rle();
227             break;
228         }
229         case LOTMaskData::Mode::Difference: {
230             rle = rle ^ i->rle();
231             break;
232         }
233         default:
234             break;
235         }
236     }
237     return rle;
238 }
239
240 LOTLayerItem::LOTLayerItem(LOTLayerData *layerData): mLayerData(layerData)
241 {
242     if (mLayerData->mHasMask) {
243         for (auto &i : mLayerData->mMasks) {
244             mMasks.push_back(std::make_unique<LOTMaskItem>(i.get()));
245         }
246     }
247 }
248
249 void LOTLayerItem::updateStaticProperty()
250 {
251     if (mParentLayer) mParentLayer->updateStaticProperty();
252
253     mStatic = mLayerData->isStatic();
254     mStatic = mParentLayer ? (mStatic & mParentLayer->isStatic()) : mStatic;
255     mStatic = mPrecompLayer ? (mStatic & mPrecompLayer->isStatic()) : mStatic;
256 }
257
258 void LOTLayerItem::update(int frameNumber, const VMatrix &parentMatrix,
259                           float parentAlpha)
260 {
261     mFrameNo = frameNumber;
262     // 1. check if the layer is part of the current frame
263     if (!visible()) return;
264
265     // 2. calculate the parent matrix and alpha
266     VMatrix m = matrix(frameNo());
267     m *= parentMatrix;
268     float alpha = parentAlpha * opacity(frameNo());
269
270     // 6. update the mask
271     if (hasMask()) {
272         for (auto &i : mMasks) i->update(frameNo(), m, alpha, mDirtyFlag);
273     }
274
275     // 3. update the dirty flag based on the change
276     if (!mCombinedMatrix.fuzzyCompare(m)) {
277         mDirtyFlag |= DirtyFlagBit::Matrix;
278     }
279     if (!vCompare(mCombinedAlpha, alpha)) {
280         mDirtyFlag |= DirtyFlagBit::Alpha;
281     }
282     mCombinedMatrix = m;
283     mCombinedAlpha = alpha;
284
285     // 4. if no parent property change and layer is static then nothing to do.
286     if ((flag() & DirtyFlagBit::None) && isStatic()) return;
287
288     // 5. update the content of the layer
289     updateContent();
290
291     // 6. reset the dirty flag
292     mDirtyFlag = DirtyFlagBit::None;
293 }
294
295 float LOTLayerItem::opacity(int frameNo) const
296 {
297     return mLayerData->mTransform->opacity(frameNo);
298 }
299
300 VMatrix LOTLayerItem::matrix(int frameNo) const
301 {
302     if (mParentLayer)
303         return mLayerData->mTransform->matrix(frameNo, mLayerData->autoOrient()) *
304                mParentLayer->matrix(frameNo);
305     else
306         return mLayerData->mTransform->matrix(frameNo, mLayerData->autoOrient());
307 }
308
309 bool LOTLayerItem::visible() const
310 {
311     if (frameNo() >= mLayerData->inFrame() &&
312         frameNo() < mLayerData->outFrame())
313         return true;
314     else
315         return false;
316 }
317
318 LOTCompLayerItem::LOTCompLayerItem(LOTLayerData *layerModel)
319     : LOTLayerItem(layerModel)
320 {
321     // 1. create layer item
322     for (auto &i : mLayerData->mChildren) {
323         LOTLayerData *layerModel = static_cast<LOTLayerData *>(i.get());
324         auto layerItem = LOTCompItem::createLayerItem(layerModel);
325         if (layerItem) mLayers.push_back(std::move(layerItem));
326     }
327
328     // 2. update parent layer
329     for (const auto &layer : mLayers) {
330         int id = layer->parentId();
331         if (id >= 0) {
332             auto search = std::find_if(mLayers.begin(), mLayers.end(),
333                             [id](const auto& val){ return val->id() == id;});
334             if (search != mLayers.end()) layer->setParentLayer((*search).get());
335         }
336         // update the precomp layer if its not the root layer.
337         if (!layerModel->root()) layer->setPrecompLayer(this);
338     }
339
340     // 3. keep the layer in back-to-front order.
341     // as lottie model keeps the data in front-toback-order.
342     std::reverse(mLayers.begin(), mLayers.end());
343 }
344
345 void LOTCompLayerItem::updateStaticProperty()
346 {
347     LOTLayerItem::updateStaticProperty();
348
349     for (const auto &layer : mLayers) {
350         layer->updateStaticProperty();
351     }
352 }
353
354 void LOTCompLayerItem::render(VPainter *painter, const VRle &inheritMask, const VRle &inheritMatte, LOTLayerItem *matteSource)
355 {
356     VRle matteRle;
357     if (matteSource) {
358         mDrawableList.clear();
359         matteSource->renderList(mDrawableList);
360         for (auto &i : mDrawableList) {
361             matteRle = matteRle + i->rle();
362         }
363
364         if (!inheritMatte.empty())
365             matteRle = matteRle & inheritMatte;
366     } else {
367         matteRle = inheritMatte;
368     }
369
370     VRle mask;
371     if (hasMask()) {
372         mask = maskRle(painter->clipBoundingRect());
373         if (!inheritMask.empty())
374             mask = mask & inheritMask;
375         // if resulting mask is empty then return.
376         if (mask.empty())
377             return;
378     } else {
379         mask = inheritMask;
380     }
381
382     LOTLayerItem *matteLayer = nullptr;
383     for (const auto &layer : mLayers) {
384         if (!matteLayer && layer->hasMatte()) {
385             matteLayer = layer.get();
386             continue;
387         }
388
389         if (matteLayer) {
390             if (matteLayer->visible() && layer->visible())
391                 matteLayer->render(painter, mask, matteRle, layer.get());
392             matteLayer = nullptr;
393         } else {
394             if (layer->visible())
395                 layer->render(painter, mask, matteRle, nullptr);
396         }
397     }
398 }
399
400 void LOTCompLayerItem::updateContent()
401 {
402     for (const auto &layer : mLayers) {
403         layer->update( mLayerData->timeRemap(frameNo()) - mLayerData->startFrame(),
404                        combinedMatrix(), combinedAlpha());
405     }
406 }
407
408 void LOTCompLayerItem::renderList(std::vector<VDrawable *> &list)
409 {
410     if (!visible()) return;
411
412     for (const auto &layer : mLayers) {
413         layer->renderList(list);
414     }
415 }
416
417 LOTSolidLayerItem::LOTSolidLayerItem(LOTLayerData *layerData)
418     : LOTLayerItem(layerData)
419 {
420 }
421
422 void LOTSolidLayerItem::updateContent()
423 {
424     if (!mRenderNode) {
425         mRenderNode = std::make_unique<LOTDrawable>();
426         mRenderNode->mType = VDrawable::Type::Fill;
427         mRenderNode->mFlag |= VDrawable::DirtyState::All;
428     }
429
430     if (flag() & DirtyFlagBit::Matrix) {
431         VPath path;
432         path.addRect(
433             VRectF(0, 0, mLayerData->solidWidth(), mLayerData->solidHeight()));
434         path.transform(combinedMatrix());
435         mRenderNode->mFlag |= VDrawable::DirtyState::Path;
436         mRenderNode->mPath = path;
437     }
438     if (flag() & DirtyFlagBit::Alpha) {
439         LottieColor color = mLayerData->solidColor();
440         VBrush      brush(color.toColor(combinedAlpha()));
441         mRenderNode->setBrush(brush);
442         mRenderNode->mFlag |= VDrawable::DirtyState::Brush;
443     }
444 }
445
446 void LOTSolidLayerItem::renderList(std::vector<VDrawable *> &list)
447 {
448     if (!visible()) return;
449
450     list.push_back(mRenderNode.get());
451 }
452
453 LOTNullLayerItem::LOTNullLayerItem(LOTLayerData *layerData)
454     : LOTLayerItem(layerData)
455 {
456 }
457 void LOTNullLayerItem::updateContent() {}
458
459 LOTShapeLayerItem::LOTShapeLayerItem(LOTLayerData *layerData)
460     : LOTLayerItem(layerData)
461 {
462     mRoot = std::make_unique<LOTContentGroupItem>(nullptr);
463     mRoot->addChildren(layerData);
464
465     std::vector<LOTPathDataItem *> list;
466     mRoot->processPaintItems(list);
467
468     if (layerData->hasPathOperator()) {
469         list.clear();
470         mRoot->processTrimItems(list);
471     }
472 }
473
474 std::unique_ptr<LOTContentItem>
475 LOTShapeLayerItem::createContentItem(LOTData *contentData)
476 {
477     switch (contentData->type()) {
478     case LOTData::Type::ShapeGroup: {
479         return std::make_unique<LOTContentGroupItem>(
480             static_cast<LOTShapeGroupData *>(contentData));
481         break;
482     }
483     case LOTData::Type::Rect: {
484         return std::make_unique<LOTRectItem>(static_cast<LOTRectData *>(contentData));
485         break;
486     }
487     case LOTData::Type::Ellipse: {
488         return std::make_unique<LOTEllipseItem>(static_cast<LOTEllipseData *>(contentData));
489         break;
490     }
491     case LOTData::Type::Shape: {
492         return std::make_unique<LOTShapeItem>(static_cast<LOTShapeData *>(contentData));
493         break;
494     }
495     case LOTData::Type::Polystar: {
496         return std::make_unique<LOTPolystarItem>(static_cast<LOTPolystarData *>(contentData));
497         break;
498     }
499     case LOTData::Type::Fill: {
500         return std::make_unique<LOTFillItem>(static_cast<LOTFillData *>(contentData));
501         break;
502     }
503     case LOTData::Type::GFill: {
504         return std::make_unique<LOTGFillItem>(static_cast<LOTGFillData *>(contentData));
505         break;
506     }
507     case LOTData::Type::Stroke: {
508         return std::make_unique<LOTStrokeItem>(static_cast<LOTStrokeData *>(contentData));
509         break;
510     }
511     case LOTData::Type::GStroke: {
512         return std::make_unique<LOTGStrokeItem>(static_cast<LOTGStrokeData *>(contentData));
513         break;
514     }
515     case LOTData::Type::Repeater: {
516         return std::make_unique<LOTRepeaterItem>(static_cast<LOTRepeaterData *>(contentData));
517         break;
518     }
519     case LOTData::Type::Trim: {
520         return std::make_unique<LOTTrimItem>(static_cast<LOTTrimData *>(contentData));
521         break;
522     }
523     default:
524         return nullptr;
525         break;
526     }
527 }
528
529 void LOTShapeLayerItem::updateContent()
530 {
531     mRoot->update(frameNo(), combinedMatrix(), combinedAlpha(), flag());
532
533     if (mLayerData->hasPathOperator()) {
534         mRoot->applyTrim();
535     }
536 }
537
538 void LOTShapeLayerItem::renderList(std::vector<VDrawable *> &list)
539 {
540     if (!visible()) return;
541     mRoot->renderList(list);
542 }
543
544 LOTContentGroupItem::LOTContentGroupItem(LOTShapeGroupData *data) : mData(data)
545 {
546     addChildren(mData);
547 }
548
549 void LOTContentGroupItem::addChildren(LOTGroupData *data)
550 {
551     if (!data) return;
552
553     for (auto &i : data->mChildren) {
554         auto content = LOTShapeLayerItem::createContentItem(i.get());
555         if (content) {
556             content->setParent(this);
557             mContents.push_back(std::move(content));
558         }
559     }
560
561     // keep the content in back-to-front order.
562     std::reverse(mContents.begin(), mContents.end());
563 }
564
565 void LOTContentGroupItem::update(int frameNo, const VMatrix &parentMatrix,
566                                  float parentAlpha, const DirtyFlag &flag)
567 {
568     VMatrix   m = parentMatrix;
569     float     alpha = parentAlpha;
570     DirtyFlag newFlag = flag;
571
572     if (mData) {
573         // update the matrix and the flag
574         if ((flag & DirtyFlagBit::Matrix) ||
575             !mData->mTransform->staticMatrix()) {
576             newFlag |= DirtyFlagBit::Matrix;
577         }
578         m = mData->mTransform->matrix(frameNo);
579         m *= parentMatrix;
580         alpha *= mData->mTransform->opacity(frameNo);
581
582         if (!vCompare(alpha, parentAlpha)) {
583             newFlag |= DirtyFlagBit::Alpha;
584         }
585     }
586
587     mMatrix = m;
588
589     for (const auto &content : mContents) {
590         content->update(frameNo, m, alpha, newFlag);
591     }
592 }
593
594 void LOTContentGroupItem::applyTrim()
595 {
596     for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
597         auto content = (*i).get();
598         if (auto trim = dynamic_cast<LOTTrimItem *>(content)) {
599             trim->update();
600         } else if (auto group = dynamic_cast<LOTContentGroupItem *>(content)) {
601             group->applyTrim();
602         }
603     }
604 }
605
606 void LOTContentGroupItem::renderList(std::vector<VDrawable *> &list)
607 {
608     for (const auto &content : mContents) {
609         content->renderList(list);
610     }
611 }
612
613 void LOTContentGroupItem::processPaintItems(
614     std::vector<LOTPathDataItem *> &list)
615 {
616     int curOpCount = list.size();
617     for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
618         auto content = (*i).get();
619         if (auto pathNode = dynamic_cast<LOTPathDataItem *>(content)) {
620             // add it to the list
621             list.push_back(pathNode);
622         } else if (auto paintNode = dynamic_cast<LOTPaintDataItem *>(content)) {
623             // the node is a paint data node update the path list of the paint item.
624             paintNode->addPathItems(list, curOpCount);
625         } else if (auto groupNode =
626                        dynamic_cast<LOTContentGroupItem *>(content)) {
627             // update the groups node with current list
628             groupNode->processPaintItems(list);
629         }
630     }
631 }
632
633 void LOTContentGroupItem::processTrimItems(
634     std::vector<LOTPathDataItem *> &list)
635 {
636     int curOpCount = list.size();
637     for (auto i = mContents.rbegin(); i != mContents.rend(); ++i) {
638         auto content = (*i).get();
639         if (auto pathNode = dynamic_cast<LOTPathDataItem *>(content)) {
640             // add it to the list
641             list.push_back(pathNode);
642         } else if (auto trimNode = dynamic_cast<LOTTrimItem *>(content)) {
643             // the node is a paint data node update the path list of the paint item.
644             trimNode->addPathItems(list, curOpCount);
645         } else if (auto groupNode =
646                        dynamic_cast<LOTContentGroupItem *>(content)) {
647             // update the groups node with current list
648             groupNode->processTrimItems(list);
649         }
650     }
651 }
652
653 void LOTPathDataItem::update(int frameNo, const VMatrix &,
654                              float, const DirtyFlag &flag)
655 {
656     mPathChanged = false;
657
658     // 1. update the local path if needed
659     if (hasChanged(frameNo)) {
660         updatePath(mLocalPath, frameNo);
661         mPathChanged = true;
662         mNeedUpdate = true;
663     }
664
665     mTemp = mLocalPath;
666
667     // 3. compute the final path with parentMatrix
668     if ((flag & DirtyFlagBit::Matrix) || mPathChanged) {
669         mPathChanged = true;
670     }
671 }
672
673 const VPath & LOTPathDataItem::finalPath()
674 {
675     if (mPathChanged || mNeedUpdate) {
676         mFinalPath.clone(mTemp);
677         mFinalPath.transform(static_cast<LOTContentGroupItem *>(parent())->matrix());
678         mNeedUpdate = false;
679     }
680     return mFinalPath;
681 }
682 LOTRectItem::LOTRectItem(LOTRectData *data)
683     : LOTPathDataItem(data->isStatic()), mData(data)
684 {
685 }
686
687 void LOTRectItem::updatePath(VPath& path, int frameNo)
688 {
689     VPointF pos = mData->mPos.value(frameNo);
690     VPointF size = mData->mSize.value(frameNo);
691     float   roundness = mData->mRound.value(frameNo);
692     VRectF  r(pos.x() - size.x() / 2, pos.y() - size.y() / 2, size.x(),
693              size.y());
694
695     path.reset();
696     path.addRoundRect(r, roundness, mData->direction());
697     updateCache(frameNo, pos, size, roundness);
698 }
699
700 LOTEllipseItem::LOTEllipseItem(LOTEllipseData *data)
701     : LOTPathDataItem(data->isStatic()), mData(data)
702 {
703 }
704
705 void LOTEllipseItem::updatePath(VPath& path, int frameNo)
706 {
707     VPointF pos = mData->mPos.value(frameNo);
708     VPointF size = mData->mSize.value(frameNo);
709     VRectF  r(pos.x() - size.x() / 2, pos.y() - size.y() / 2, size.x(),
710              size.y());
711
712     path.reset();
713     path.addOval(r, mData->direction());
714     updateCache(frameNo, pos, size);
715 }
716
717 LOTShapeItem::LOTShapeItem(LOTShapeData *data)
718     : LOTPathDataItem(data->isStatic()), mData(data)
719 {
720 }
721
722 void LOTShapeItem::updatePath(VPath& path, int frameNo)
723 {
724     mData->mShape.value(frameNo).toPath(path);
725 }
726
727 LOTPolystarItem::LOTPolystarItem(LOTPolystarData *data)
728     : LOTPathDataItem(data->isStatic()), mData(data)
729 {
730 }
731
732 void LOTPolystarItem::updatePath(VPath& path, int frameNo)
733 {
734     VPointF pos = mData->mPos.value(frameNo);
735     float   points = mData->mPointCount.value(frameNo);
736     float   innerRadius = mData->mInnerRadius.value(frameNo);
737     float   outerRadius = mData->mOuterRadius.value(frameNo);
738     float   innerRoundness = mData->mInnerRoundness.value(frameNo);
739     float   outerRoundness = mData->mOuterRoundness.value(frameNo);
740     float   rotation = mData->mRotation.value(frameNo);
741
742     path.reset();
743     VMatrix m;
744
745     if (mData->mType == LOTPolystarData::PolyType::Star) {
746         path.addPolystar(points, innerRadius, outerRadius, innerRoundness,
747                          outerRoundness, 0.0, 0.0, 0.0, mData->direction());
748     } else {
749         path.addPolygon(points, outerRadius, outerRoundness, 0.0, 0.0, 0.0,
750                         mData->direction());
751     }
752
753     m.translate(pos.x(), pos.y()).rotate(rotation);
754     m.rotate(rotation);
755     path.transform(m);
756     updateCache(frameNo, pos, points, innerRadius, outerRadius,
757                 innerRoundness, outerRoundness, rotation);
758 }
759
760 /*
761  * PaintData Node handling
762  *
763  */
764 LOTPaintDataItem::LOTPaintDataItem(bool staticContent):mDrawable(std::make_unique<LOTDrawable>()),
765                                                        mStaticContent(staticContent){}
766
767 void LOTPaintDataItem::update(int frameNo, const VMatrix &parentMatrix,
768                               float parentAlpha, const DirtyFlag &flag)
769 {
770     mRenderNodeUpdate = true;
771     mParentAlpha = parentAlpha;
772     mFlag = flag;
773     mFrameNo = frameNo;
774
775     updateContent(frameNo);
776 }
777
778 void LOTPaintDataItem::updateRenderNode()
779 {
780     bool dirty = false;
781     for (auto &i : mPathItems) {
782         if (i->dirty()) {
783             dirty = true;
784             break;
785         }
786     }
787
788     if (dirty) {
789         mPath.reset();
790
791         for (auto &i : mPathItems) {
792             mPath.addPath(i->finalPath());
793         }
794         mDrawable->setPath(mPath);
795     } else {
796         if (mDrawable->mFlag & VDrawable::DirtyState::Path)
797             mDrawable->mPath = mPath;
798     }
799 }
800
801 void LOTPaintDataItem::renderList(std::vector<VDrawable *> &list)
802 {
803     if (mRenderNodeUpdate) {
804         updateRenderNode();
805         LOTPaintDataItem::updateRenderNode();
806         mRenderNodeUpdate = false;
807     }
808     list.push_back(mDrawable.get());
809 }
810
811
812 void LOTPaintDataItem::addPathItems(std::vector<LOTPathDataItem *> &list, int startOffset)
813 {
814     std::copy(list.begin() + startOffset, list.end(), back_inserter(mPathItems));
815 }
816
817
818 LOTFillItem::LOTFillItem(LOTFillData *data)
819     : LOTPaintDataItem(data->isStatic()), mData(data)
820 {
821 }
822
823 void LOTFillItem::updateContent(int frameNo)
824 {
825     LottieColor c = mData->mColor.value(frameNo);
826     float       opacity = mData->opacity(frameNo);
827     mColor = c.toColor(opacity);
828     mFillRule = mData->fillRule();
829 }
830
831 void LOTFillItem::updateRenderNode()
832 {
833     VColor color = mColor;
834
835     color.setAlpha(color.a * parentAlpha());
836     VBrush brush(color);
837     mDrawable->setBrush(brush);
838     mDrawable->setFillRule(mFillRule);
839 }
840
841 LOTGFillItem::LOTGFillItem(LOTGFillData *data)
842     : LOTPaintDataItem(data->isStatic()), mData(data)
843 {
844 }
845
846 void LOTGFillItem::updateContent(int frameNo)
847 {
848     mData->update(mGradient, frameNo);
849     mGradient->mMatrix = static_cast<LOTContentGroupItem *>(parent())->matrix();
850     mFillRule = mData->fillRule();
851 }
852
853 void LOTGFillItem::updateRenderNode()
854 {
855     mGradient->setAlpha(parentAlpha());
856     mDrawable->setBrush(VBrush(mGradient.get()));
857     mDrawable->setFillRule(mFillRule);
858 }
859
860 LOTStrokeItem::LOTStrokeItem(LOTStrokeData *data)
861     : LOTPaintDataItem(data->isStatic()), mData(data)
862 {
863     mDashArraySize = 0;
864 }
865
866 void LOTStrokeItem::updateContent(int frameNo)
867 {
868     LottieColor c = mData->mColor.value(frameNo);
869     float       opacity = mData->opacity(frameNo);
870     mColor = c.toColor(opacity);
871     mCap = mData->capStyle();
872     mJoin = mData->joinStyle();
873     mMiterLimit = mData->meterLimit();
874     mWidth = mData->width(frameNo);
875     if (mData->hasDashInfo()) {
876         mDashArraySize = mData->getDashInfo(frameNo, mDashArray);
877     }
878 }
879
880 static float getScale(const VMatrix &matrix)
881 {
882     constexpr float SQRT_2 = 1.41421;
883     VPointF         p1(0, 0);
884     VPointF         p2(SQRT_2, SQRT_2);
885     p1 = matrix.map(p1);
886     p2 = matrix.map(p2);
887     VPointF final = p2 - p1;
888
889     return std::sqrt(final.x() * final.x() + final.y() * final.y()) / 2.0;
890 }
891
892 void LOTStrokeItem::updateRenderNode()
893 {
894     VColor color = mColor;
895
896     color.setAlpha(color.a * parentAlpha());
897     VBrush brush(color);
898     mDrawable->setBrush(brush);
899     float scale = getScale(static_cast<LOTContentGroupItem *>(parent())->matrix());
900     mDrawable->setStrokeInfo(mCap, mJoin, mMiterLimit,
901                             mWidth * scale);
902     if (mDashArraySize) {
903         for (int i = 0 ; i < mDashArraySize ; i++)
904             mDashArray[i] *= scale;
905         mDrawable->setDashInfo(mDashArray, mDashArraySize);
906     }
907 }
908
909 LOTGStrokeItem::LOTGStrokeItem(LOTGStrokeData *data)
910     : LOTPaintDataItem(data->isStatic()), mData(data)
911 {
912     mDashArraySize = 0;
913 }
914
915 void LOTGStrokeItem::updateContent(int frameNo)
916 {
917     mData->update(mGradient, frameNo);
918     mGradient->mMatrix = static_cast<LOTContentGroupItem *>(parent())->matrix();
919     mCap = mData->capStyle();
920     mJoin = mData->joinStyle();
921     mMiterLimit = mData->meterLimit();
922     mWidth = mData->width(frameNo);
923     if (mData->hasDashInfo()) {
924         mDashArraySize = mData->getDashInfo(frameNo, mDashArray);
925     }
926 }
927
928 void LOTGStrokeItem::updateRenderNode()
929 {
930     float scale = getScale(mGradient->mMatrix);
931     mGradient->setAlpha(parentAlpha());
932     mDrawable->setBrush(VBrush(mGradient.get()));
933     mDrawable->setStrokeInfo(mCap, mJoin, mMiterLimit,
934                             mWidth * scale);
935     if (mDashArraySize) {
936         for (int i = 0 ; i < mDashArraySize ; i++)
937             mDashArray[i] *= scale;
938         mDrawable->setDashInfo(mDashArray, mDashArraySize);
939     }
940 }
941
942 LOTTrimItem::LOTTrimItem(LOTTrimData *data) : mData(data) {}
943
944 void LOTTrimItem::update(int frameNo, const VMatrix &/*parentMatrix*/,
945                          float /*parentAlpha*/, const DirtyFlag &/*flag*/)
946 {
947     mDirty = false;
948
949     if (mCache.mFrameNo == frameNo) return;
950
951     float   start = mData->start(frameNo);
952     float   end = mData->end(frameNo);
953     float   offset = mData->offset(frameNo);
954
955     if (!(vCompare(mCache.mStart, start) && vCompare(mCache.mEnd, end) &&
956           vCompare(mCache.mOffset, offset))) {
957         mDirty = true;
958         mCache.mStart = start;
959         mCache.mEnd = end;
960         mCache.mOffset = offset;
961     }
962     mCache.mFrameNo = frameNo;
963 }
964
965 void LOTTrimItem::update()
966 {
967     // when both path and trim are not dirty
968     if (!(mDirty || pathDirty())) return;
969
970     if (vCompare(std::fabs(mCache.mStart - mCache.mEnd) , 1)) return;
971
972     if (vCompare(mCache.mStart, mCache.mEnd)) {
973         for (auto &i : mPathItems) {
974             i->updatePath(VPath());
975         }
976         return;
977     }
978
979
980     if (mData->type() == LOTTrimData::TrimType::Simultaneously) {
981         for (auto &i : mPathItems) {
982             VPathMesure pm;
983             pm.setStart(mCache.mStart);
984             pm.setEnd(mCache.mEnd);
985             pm.setOffset(mCache.mOffset);
986             i->updatePath(pm.trim(i->localPath()));
987         }
988     } else { // LOTTrimData::TrimType::Individually
989         float totalLength = 0.0;
990         for (auto &i : mPathItems) {
991             totalLength += i->localPath().length();
992         }
993         float offset = totalLength * mCache.mOffset;
994         float start = totalLength * mCache.mStart;
995         float end  = totalLength * mCache.mEnd;
996         start += offset;
997         end +=offset;
998         // normalize start, end value to 0 - totalLength
999         if (fabs(start) > totalLength) start = fmod(start, totalLength);
1000         if (fabs(end) > totalLength) end = fmod(end, totalLength);
1001
1002         if (start >= 0 && end >= 0) {
1003             if (start > end) std::swap(start, end);
1004         } else if ( start < 0 && end < 0) {
1005             start += totalLength;
1006             end += totalLength;
1007             if (start > end) std::swap(start, end);
1008         } else {
1009             // one is +ve and one is -ve so the
1010             // segment will be wrapped from end segment to start segment.
1011             // we need to split it in two segment.
1012             //@TODO
1013             return;
1014         }
1015
1016         if (start < end ) {
1017             float curLen = 0.0;
1018             for (auto &i : mPathItems) {
1019                 if (curLen > end) {
1020                     // update with empty path.
1021                     i->updatePath(VPath());
1022                     continue;
1023                 }
1024                 float len = i->localPath().length();
1025
1026                 if (curLen < start  && curLen + len < start) {
1027                     curLen += len;
1028                     // update with empty path.
1029                     i->updatePath(VPath());
1030                     continue;
1031                 } else if (start <= curLen && end >= curLen + len) {
1032                     // inside segment
1033                     curLen += len;
1034                     continue;
1035                 } else {
1036                     float local_start = start > curLen ? start - curLen : 0;
1037                     local_start /= len;
1038                     float local_end = curLen + len < end ? len : end - curLen;
1039                     local_end /= len;
1040                     VPathMesure pm;
1041                     pm.setStart(local_start);
1042                     pm.setEnd(local_end);
1043                     VPath p = pm.trim(i->localPath());
1044                     i->updatePath(p);
1045                     curLen += len;
1046                 }
1047             }
1048         }
1049     }
1050
1051 }
1052
1053
1054 void LOTTrimItem::addPathItems(std::vector<LOTPathDataItem *> &list, int startOffset)
1055 {
1056     std::copy(list.begin() + startOffset, list.end(), back_inserter(mPathItems));
1057 }
1058
1059
1060 LOTRepeaterItem::LOTRepeaterItem(LOTRepeaterData *data) : mData(data) {}
1061
1062 void LOTRepeaterItem::update(int /*frameNo*/, const VMatrix &/*parentMatrix*/,
1063                              float /*parentAlpha*/, const DirtyFlag &/*flag*/)
1064 {
1065 }
1066
1067 void LOTRepeaterItem::renderList(std::vector<VDrawable *> &/*list*/) {}
1068
1069 static void updateGStops(LOTNode *n, const VGradient *grad)
1070 {
1071     if (grad->mStops.size() != n->mGradient.stopCount) {
1072         if (n->mGradient.stopCount)
1073             free(n->mGradient.stopPtr);
1074         n->mGradient.stopCount = grad->mStops.size();
1075         n->mGradient.stopPtr = (LOTGradientStop *) malloc(n->mGradient.stopCount * sizeof(LOTGradientStop));
1076     }
1077
1078     LOTGradientStop *ptr = n->mGradient.stopPtr;
1079     for (const auto &i : grad->mStops) {
1080         ptr->pos = i.first;
1081         ptr->a = i.second.alpha() * grad->alpha();
1082         ptr->r = i.second.red();
1083         ptr->g = i.second.green();
1084         ptr->b = i.second.blue();
1085         ptr++;
1086     }
1087
1088 }
1089
1090 void LOTDrawable::sync()
1091 {
1092     if (!mCNode) {
1093         mCNode = std::make_unique<LOTNode>();
1094         mCNode->mGradient.stopPtr = nullptr;
1095         mCNode->mGradient.stopCount = 0;
1096     }
1097
1098     mCNode->mFlag = ChangeFlagNone;
1099     if (mFlag & DirtyState::None) return;
1100
1101     if (mFlag & DirtyState::Path) {
1102         const std::vector<VPath::Element> &elm = mPath.elements();
1103         const std::vector<VPointF> &       pts = mPath.points();
1104         const float *ptPtr = reinterpret_cast<const float *>(pts.data());
1105         const char * elmPtr = reinterpret_cast<const char *>(elm.data());
1106         mCNode->mPath.elmPtr = elmPtr;
1107         mCNode->mPath.elmCount = elm.size();
1108         mCNode->mPath.ptPtr = ptPtr;
1109         mCNode->mPath.ptCount = 2 * pts.size();
1110         mCNode->mFlag |= ChangeFlagPath;
1111     }
1112
1113     if (mStroke.enable) {
1114         mCNode->mStroke.width = mStroke.width;
1115         mCNode->mStroke.meterLimit = mStroke.meterLimit;
1116         mCNode->mStroke.enable = 1;
1117
1118         switch (mFillRule) {
1119         case FillRule::EvenOdd:
1120             mCNode->mFillRule = LOTFillRule::FillEvenOdd;
1121             break;
1122         default:
1123             mCNode->mFillRule = LOTFillRule::FillWinding;
1124             break;
1125         }
1126
1127         switch (mStroke.cap) {
1128         case CapStyle::Flat:
1129             mCNode->mStroke.cap = LOTCapStyle::CapFlat;
1130             break;
1131         case CapStyle::Square:
1132             mCNode->mStroke.cap = LOTCapStyle::CapSquare;
1133             break;
1134         case CapStyle::Round:
1135             mCNode->mStroke.cap = LOTCapStyle::CapRound;
1136             break;
1137         default:
1138             mCNode->mStroke.cap = LOTCapStyle::CapFlat;
1139             break;
1140         }
1141
1142         switch (mStroke.join) {
1143         case JoinStyle::Miter:
1144             mCNode->mStroke.join = LOTJoinStyle::JoinMiter;
1145             break;
1146         case JoinStyle::Bevel:
1147             mCNode->mStroke.join = LOTJoinStyle::JoinBevel;
1148             break;
1149         case JoinStyle::Round:
1150             mCNode->mStroke.join = LOTJoinStyle::JoinRound;
1151             break;
1152         default:
1153             mCNode->mStroke.join = LOTJoinStyle::JoinMiter;
1154             break;
1155         }
1156
1157         mCNode->mStroke.dashArray = mStroke.mDash.data();
1158         mCNode->mStroke.dashArraySize = mStroke.mDash.size();
1159
1160     } else {
1161         mCNode->mStroke.enable = 0;
1162     }
1163
1164     switch (mBrush.type()) {
1165     case VBrush::Type::Solid:
1166         mCNode->mBrushType = LOTBrushType::BrushSolid;
1167         mCNode->mColor.r = mBrush.mColor.r;
1168         mCNode->mColor.g = mBrush.mColor.g;
1169         mCNode->mColor.b = mBrush.mColor.b;
1170         mCNode->mColor.a = mBrush.mColor.a;
1171         break;
1172     case VBrush::Type::LinearGradient: {
1173         mCNode->mBrushType = LOTBrushType::BrushGradient;
1174         mCNode->mGradient.type = LOTGradientType::GradientLinear;
1175         VPointF s = mBrush.mGradient->mMatrix.map({mBrush.mGradient->linear.x1,
1176                                                    mBrush.mGradient->linear.y1});
1177         VPointF e = mBrush.mGradient->mMatrix.map({mBrush.mGradient->linear.x2,
1178                                                    mBrush.mGradient->linear.y2});
1179         mCNode->mGradient.start.x = s.x();
1180         mCNode->mGradient.start.y = s.y();
1181         mCNode->mGradient.end.x = e.x();
1182         mCNode->mGradient.end.y = e.y();
1183         updateGStops(mCNode.get(), mBrush.mGradient);
1184         break;
1185     }
1186     case VBrush::Type::RadialGradient: {
1187         mCNode->mBrushType = LOTBrushType::BrushGradient;
1188         mCNode->mGradient.type = LOTGradientType::GradientRadial;
1189         VPointF c = mBrush.mGradient->mMatrix.map({mBrush.mGradient->radial.cx,
1190                                                    mBrush.mGradient->radial.cy});
1191         VPointF f = mBrush.mGradient->mMatrix.map({mBrush.mGradient->radial.fx,
1192                                                    mBrush.mGradient->radial.fy});
1193         mCNode->mGradient.center.x = c.x();
1194         mCNode->mGradient.center.y = c.y();
1195         mCNode->mGradient.focal.x = f.x();
1196         mCNode->mGradient.focal.y = f.y();
1197
1198         float scale = getScale(mBrush.mGradient->mMatrix);
1199         mCNode->mGradient.cradius = mBrush.mGradient->radial.cradius * scale;
1200         mCNode->mGradient.fradius = mBrush.mGradient->radial.fradius * scale;
1201         updateGStops(mCNode.get(), mBrush.mGradient);
1202         break;
1203     }
1204     default:
1205         break;
1206     }
1207 }