82d812e8dbc758ae12ac714f2facdf0b2cc602e4
[platform/core/graphics/tizenvg.git] / src / lib / sw_engine / tvgSwShape.cpp
1 /*
2  * Copyright (c) 2020 - 2023 the ThorVG project. All rights reserved.
3
4  * Permission is hereby granted, free of charge, to any person obtaining a copy
5  * of this software and associated documentation files (the "Software"), to deal
6  * in the Software without restriction, including without limitation the rights
7  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8  * copies of the Software, and to permit persons to whom the Software is
9  * furnished to do so, subject to the following conditions:
10
11  * The above copyright notice and this permission notice shall be included in all
12  * copies or substantial portions of the Software.
13
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20  * SOFTWARE.
21  */
22
23 #include "tvgSwCommon.h"
24 #include "tvgBezier.h"
25 #include <float.h>
26 #include <math.h>
27
28 /************************************************************************/
29 /* Internal Class Implementation                                        */
30 /************************************************************************/
31
32 struct Line
33 {
34     Point pt1;
35     Point pt2;
36 };
37
38
39 static float _lineLength(const Point& pt1, const Point& pt2)
40 {
41     /* approximate sqrt(x*x + y*y) using alpha max plus beta min algorithm.
42        With alpha = 1, beta = 3/8, giving results with the largest error less
43        than 7% compared to the exact value. */
44     Point diff = {pt2.x - pt1.x, pt2.y - pt1.y};
45     if (diff.x < 0) diff.x = -diff.x;
46     if (diff.y < 0) diff.y = -diff.y;
47     return (diff.x > diff.y) ? (diff.x + diff.y * 0.375f) : (diff.y + diff.x * 0.375f);
48 }
49
50
51 static void _lineSplitAt(const Line& cur, float at, Line& left, Line& right)
52 {
53     auto len = _lineLength(cur.pt1, cur.pt2);
54     auto dx = ((cur.pt2.x - cur.pt1.x) / len) * at;
55     auto dy = ((cur.pt2.y - cur.pt1.y) / len) * at;
56     left.pt1 = cur.pt1;
57     left.pt2.x = left.pt1.x + dx;
58     left.pt2.y = left.pt1.y + dy;
59     right.pt1 = left.pt2;
60     right.pt2 = cur.pt2;
61 }
62
63
64 static bool _growOutlineContour(SwOutline& outline, uint32_t n)
65 {
66     if (outline.reservedCntrsCnt >= outline.cntrsCnt + n) return false;
67     outline.reservedCntrsCnt = outline.cntrsCnt + n;
68     outline.cntrs = static_cast<uint32_t*>(realloc(outline.cntrs, outline.reservedCntrsCnt * sizeof(uint32_t)));
69     return true;
70 }
71
72
73 static void _reserveOutlineClose(SwOutline& outline)
74 {
75     //Dash outlines are always opened.
76     //Only normal outlines use this information, it sholud be same to their contour counts.
77     if (outline.closed) free(outline.closed);
78     outline.closed = static_cast<bool*>(calloc(outline.reservedCntrsCnt, sizeof(bool)));
79 }
80
81
82 static void _resetOutlineClose(SwOutline& outline)
83 {
84     memset(outline.closed, 0x0, outline.reservedCntrsCnt * sizeof(bool));
85 }
86
87
88 static void _growOutlinePoint(SwOutline& outline, uint32_t n)
89 {
90     if (outline.reservedPtsCnt >= outline.ptsCnt + n) return;
91     outline.reservedPtsCnt = outline.ptsCnt + n;
92     outline.pts = static_cast<SwPoint*>(realloc(outline.pts, outline.reservedPtsCnt * sizeof(SwPoint)));
93     outline.types = static_cast<uint8_t*>(realloc(outline.types, outline.reservedPtsCnt * sizeof(uint8_t)));
94 }
95
96
97 static void _outlineEnd(SwOutline& outline)
98 {
99     if (outline.ptsCnt == 0) return;
100
101     _growOutlineContour(outline, 1);
102     outline.cntrs[outline.cntrsCnt] = outline.ptsCnt - 1;
103     ++outline.cntrsCnt;
104 }
105
106
107 static void _outlineMoveTo(SwOutline& outline, const Point* to, const Matrix* transform)
108 {
109     _growOutlinePoint(outline, 1);
110
111     outline.pts[outline.ptsCnt] = mathTransform(to, transform);
112     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_POINT;
113
114     if (outline.ptsCnt > 0) {
115         _growOutlineContour(outline, 1);
116         outline.cntrs[outline.cntrsCnt] = outline.ptsCnt - 1;
117         ++outline.cntrsCnt;
118     }
119
120     ++outline.ptsCnt;
121 }
122
123
124 static void _outlineLineTo(SwOutline& outline, const Point* to, const Matrix* transform)
125 {
126     _growOutlinePoint(outline, 1);
127
128     outline.pts[outline.ptsCnt] = mathTransform(to, transform);
129     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_POINT;
130     ++outline.ptsCnt;
131 }
132
133
134 static void _outlineCubicTo(SwOutline& outline, const Point* ctrl1, const Point* ctrl2, const Point* to, const Matrix* transform)
135 {
136     _growOutlinePoint(outline, 3);
137
138     outline.pts[outline.ptsCnt] = mathTransform(ctrl1, transform);
139     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_CUBIC;
140     ++outline.ptsCnt;
141
142     outline.pts[outline.ptsCnt] = mathTransform(ctrl2, transform);
143     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_CUBIC;
144     ++outline.ptsCnt;
145
146     outline.pts[outline.ptsCnt] = mathTransform(to, transform);
147     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_POINT;
148     ++outline.ptsCnt;
149 }
150
151
152 static void _outlineClose(SwOutline& outline)
153 {
154     uint32_t i = 0;
155
156     if (outline.cntrsCnt > 0) {
157         i = outline.cntrs[outline.cntrsCnt - 1] + 1;
158     } else {
159         i = 0;   //First Path
160     }
161
162     //Make sure there is at least one point in the current path
163     if (outline.ptsCnt == i) return;
164
165     //Close the path
166     _growOutlinePoint(outline, 1);
167
168     outline.pts[outline.ptsCnt] = outline.pts[i];
169     outline.types[outline.ptsCnt] = SW_CURVE_TYPE_POINT;
170     ++outline.ptsCnt;
171     outline.closed[outline.cntrsCnt] = true;
172 }
173
174
175 static void _dashLineTo(SwDashStroke& dash, const Point* to, const Matrix* transform)
176 {
177     _growOutlinePoint(*dash.outline, dash.outline->ptsCnt >> 1);
178     _growOutlineContour(*dash.outline, dash.outline->cntrsCnt >> 1);
179
180     Line cur = {dash.ptCur, *to};
181     auto len = _lineLength(cur.pt1, cur.pt2);
182
183     if (len < dash.curLen) {
184         dash.curLen -= len;
185         if (!dash.curOpGap) {
186             _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
187             _outlineLineTo(*dash.outline, to, transform);
188         }
189     } else {
190         while (len > dash.curLen) {
191             len -= dash.curLen;
192             Line left, right;
193             _lineSplitAt(cur, dash.curLen, left, right);;
194             dash.curIdx = (dash.curIdx + 1) % dash.cnt;
195             if (!dash.curOpGap) {
196                 _outlineMoveTo(*dash.outline, &left.pt1, transform);
197                 _outlineLineTo(*dash.outline, &left.pt2, transform);
198             }
199             dash.curLen = dash.pattern[dash.curIdx];
200             dash.curOpGap = !dash.curOpGap;
201             cur = right;
202             dash.ptCur = cur.pt1;
203         }
204         //leftovers
205         dash.curLen -= len;
206         if (!dash.curOpGap) {
207             _outlineMoveTo(*dash.outline, &cur.pt1, transform);
208             _outlineLineTo(*dash.outline, &cur.pt2, transform);
209         }
210         if (dash.curLen < 1 && TO_SWCOORD(len) > 1) {
211             //move to next dash
212             dash.curIdx = (dash.curIdx + 1) % dash.cnt;
213             dash.curLen = dash.pattern[dash.curIdx];
214             dash.curOpGap = !dash.curOpGap;
215         }
216     }
217     dash.ptCur = *to;
218 }
219
220
221 static void _dashCubicTo(SwDashStroke& dash, const Point* ctrl1, const Point* ctrl2, const Point* to, const Matrix* transform)
222 {
223     _growOutlinePoint(*dash.outline, dash.outline->ptsCnt >> 1);
224     _growOutlineContour(*dash.outline, dash.outline->cntrsCnt >> 1);
225
226     Bezier cur = {dash.ptCur, *ctrl1, *ctrl2, *to};
227     auto len = bezLength(cur);
228
229     if (len < dash.curLen) {
230         dash.curLen -= len;
231         if (!dash.curOpGap) {
232             _outlineMoveTo(*dash.outline, &dash.ptCur, transform);
233             _outlineCubicTo(*dash.outline, ctrl1, ctrl2, to, transform);
234         }
235     } else {
236         while (len > dash.curLen) {
237             Bezier left, right;
238             len -= dash.curLen;
239             bezSplitAt(cur, dash.curLen, left, right);
240             if (!dash.curOpGap) {
241                 // leftovers from a previous command don't require moveTo
242                 if (dash.pattern[dash.curIdx] - dash.curLen < FLT_EPSILON) {
243                     _outlineMoveTo(*dash.outline, &left.start, transform);
244                 }
245                 _outlineCubicTo(*dash.outline, &left.ctrl1, &left.ctrl2, &left.end, transform);
246             }
247             dash.curIdx = (dash.curIdx + 1) % dash.cnt;
248             dash.curLen = dash.pattern[dash.curIdx];
249             dash.curOpGap = !dash.curOpGap;
250             cur = right;
251             dash.ptCur = right.start;
252         }
253         //leftovers
254         dash.curLen -= len;
255         if (!dash.curOpGap) {
256             _outlineMoveTo(*dash.outline, &cur.start, transform);
257             _outlineCubicTo(*dash.outline, &cur.ctrl1, &cur.ctrl2, &cur.end, transform);
258         }
259         if (dash.curLen < 1 && TO_SWCOORD(len) > 1) {
260             //move to next dash
261             dash.curIdx = (dash.curIdx + 1) % dash.cnt;
262             dash.curLen = dash.pattern[dash.curIdx];
263             dash.curOpGap = !dash.curOpGap;
264         }
265     }
266     dash.ptCur = *to;
267 }
268
269
270 static SwOutline* _genDashOutline(const Shape* sdata, const Matrix* transform)
271 {
272     const PathCommand* cmds = nullptr;
273     auto cmdCnt = sdata->pathCommands(&cmds);
274
275     const Point* pts = nullptr;
276     auto ptsCnt = sdata->pathCoords(&pts);
277
278     //No actual shape data
279     if (cmdCnt == 0 || ptsCnt == 0) return nullptr;
280
281     SwDashStroke dash;
282     dash.curIdx = 0;
283     dash.curLen = 0;
284     dash.ptStart = {0, 0};
285     dash.ptCur = {0, 0};
286     dash.curOpGap = false;
287
288     const float* pattern;
289     dash.cnt = sdata->strokeDash(&pattern);
290     if (dash.cnt == 0) return nullptr;
291
292     //OPTMIZE ME: Use mempool???
293     dash.pattern = const_cast<float*>(pattern);
294     dash.outline = static_cast<SwOutline*>(calloc(1, sizeof(SwOutline)));
295
296     //smart reservation
297     auto outlinePtsCnt = 0;
298     auto outlineCntrsCnt = 0;
299
300     for (uint32_t i = 0; i < cmdCnt; ++i) {
301         switch (*(cmds + i)) {
302             case PathCommand::Close: {
303                 ++outlinePtsCnt;
304                 break;
305             }
306             case PathCommand::MoveTo: {
307                 ++outlineCntrsCnt;
308                 ++outlinePtsCnt;
309                 break;
310             }
311             case PathCommand::LineTo: {
312                 ++outlinePtsCnt;
313                 break;
314             }
315             case PathCommand::CubicTo: {
316                 outlinePtsCnt += 3;
317                 break;
318             }
319         }
320     }
321
322     ++outlinePtsCnt;    //for close
323     ++outlineCntrsCnt;  //for end
324
325     //No idea exact count.... Reserve Approximitely 20x...
326     _growOutlinePoint(*dash.outline, outlinePtsCnt * 20);
327     _growOutlineContour(*dash.outline, outlineCntrsCnt * 20);
328
329     while (cmdCnt-- > 0) {
330         switch (*cmds) {
331             case PathCommand::Close: {
332                 _dashLineTo(dash, &dash.ptStart, transform);
333                 break;
334             }
335             case PathCommand::MoveTo: {
336                 //reset the dash
337                 dash.curIdx = 0;
338                 dash.curLen = *dash.pattern;
339                 dash.curOpGap = false;
340                 dash.ptStart = dash.ptCur = *pts;
341                 ++pts;
342                 break;
343             }
344             case PathCommand::LineTo: {
345                 _dashLineTo(dash, pts, transform);
346                 ++pts;
347                 break;
348             }
349             case PathCommand::CubicTo: {
350                 _dashCubicTo(dash, pts, pts + 1, pts + 2, transform);
351                 pts += 3;
352                 break;
353             }
354         }
355         ++cmds;
356     }
357
358     _outlineEnd(*dash.outline);
359
360     return dash.outline;
361 }
362
363
364 static bool _axisAlignedRect(const SwOutline* outline)
365 {
366     //Fast Track: axis-aligned rectangle?
367     if (outline->ptsCnt != 5) return false;
368
369     auto pt1 = outline->pts + 0;
370     auto pt2 = outline->pts + 1;
371     auto pt3 = outline->pts + 2;
372     auto pt4 = outline->pts + 3;
373
374     auto a = SwPoint{pt1->x, pt3->y};
375     auto b = SwPoint{pt3->x, pt1->y};
376
377     if ((*pt2 == a && *pt4 == b) || (*pt2 == b && *pt4 == a)) return true;
378
379     return false;
380 }
381
382
383
384 static bool _genOutline(SwShape* shape, const Shape* sdata, const Matrix* transform, SwMpool* mpool, unsigned tid, bool hasComposite)
385 {
386     const PathCommand* cmds = nullptr;
387     auto cmdCnt = sdata->pathCommands(&cmds);
388
389     const Point* pts = nullptr;
390     auto ptsCnt = sdata->pathCoords(&pts);
391
392     //No actual shape data
393     if (cmdCnt == 0 || ptsCnt == 0) return false;
394
395     //smart reservation
396     auto outlinePtsCnt = 0;
397     auto outlineCntrsCnt = 0;
398     auto closeCnt = 0;
399
400     for (uint32_t i = 0; i < cmdCnt; ++i) {
401         switch (*(cmds + i)) {
402             case PathCommand::Close: {
403                 ++outlinePtsCnt;
404                 ++closeCnt;
405                 break;
406             }
407             case PathCommand::MoveTo: {
408                 ++outlineCntrsCnt;
409                 ++outlinePtsCnt;
410                 break;
411             }
412             case PathCommand::LineTo: {
413                 ++outlinePtsCnt;
414                 break;
415             }
416             case PathCommand::CubicTo: {
417                 outlinePtsCnt += 3;
418                 break;
419             }
420         }
421     }
422
423     if (static_cast<uint32_t>(outlinePtsCnt - closeCnt) > ptsCnt) {
424         TVGERR("SW_ENGINE", "Wrong a pair of the commands & points - required(%d), current(%d)", outlinePtsCnt - closeCnt, ptsCnt);
425         return false;
426     }
427
428     ++outlinePtsCnt;    //for close
429     ++outlineCntrsCnt;  //for end
430
431     shape->outline = mpoolReqOutline(mpool, tid);
432     auto outline = shape->outline;
433
434     _growOutlinePoint(*outline, outlinePtsCnt);
435
436      if (_growOutlineContour(*outline, outlineCntrsCnt)) {
437         _reserveOutlineClose(*outline);
438     } else {
439         _resetOutlineClose(*outline);
440     }
441
442     //Generate Outlines
443     while (cmdCnt-- > 0) {
444         switch (*cmds) {
445             case PathCommand::Close: {
446                 _outlineClose(*outline);
447                 break;
448             }
449             case PathCommand::MoveTo: {
450                 _outlineMoveTo(*outline, pts, transform);
451                 ++pts;
452                 break;
453             }
454             case PathCommand::LineTo: {
455                 _outlineLineTo(*outline, pts, transform);
456                 ++pts;
457                 break;
458             }
459             case PathCommand::CubicTo: {
460                 _outlineCubicTo(*outline, pts, pts + 1, pts + 2, transform);
461                 pts += 3;
462                 break;
463             }
464         }
465         ++cmds;
466     }
467
468     _outlineEnd(*outline);
469
470     outline->fillRule = sdata->fillRule();
471     shape->outline = outline;
472
473     shape->fastTrack = (!hasComposite && _axisAlignedRect(shape->outline));
474     return true;
475 }
476
477
478 /************************************************************************/
479 /* External Class Implementation                                        */
480 /************************************************************************/
481
482 bool shapePrepare(SwShape* shape, const Shape* sdata, const Matrix* transform,  const SwBBox& clipRegion, SwBBox& renderRegion, SwMpool* mpool, unsigned tid, bool hasComposite)
483 {
484     if (!_genOutline(shape, sdata, transform, mpool, tid, hasComposite)) return false;
485     if (!mathUpdateOutlineBBox(shape->outline, clipRegion, renderRegion, shape->fastTrack)) return false;
486
487     //Keep it for Rasterization Region
488     shape->bbox = renderRegion;
489
490     //Check valid region
491     if (renderRegion.max.x - renderRegion.min.x < 1 && renderRegion.max.y - renderRegion.min.y < 1) return false;
492
493     //Check boundary
494     if (renderRegion.min.x >= clipRegion.max.x || renderRegion.min.y >= clipRegion.max.y ||
495         renderRegion.max.x <= clipRegion.min.x || renderRegion.max.y <= clipRegion.min.y) return false;
496
497     return true;
498 }
499
500
501 bool shapePrepared(const SwShape* shape)
502 {
503     return shape->rle ? true : false;
504 }
505
506
507 bool shapeGenRle(SwShape* shape, TVG_UNUSED const Shape* sdata, bool antiAlias)
508 {
509     //FIXME: Should we draw it?
510     //Case: Stroke Line
511     //if (shape.outline->opened) return true;
512
513     //Case A: Fast Track Rectangle Drawing
514     if (shape->fastTrack) return true;
515
516     //Case B: Normal Shape RLE Drawing
517     if ((shape->rle = rleRender(shape->rle, shape->outline, shape->bbox, antiAlias))) return true;
518
519     return false;
520 }
521
522
523 void shapeDelOutline(SwShape* shape, SwMpool* mpool, uint32_t tid)
524 {
525     mpoolRetOutline(mpool, tid);
526     shape->outline = nullptr;
527 }
528
529
530 void shapeReset(SwShape* shape)
531 {
532     rleReset(shape->rle);
533     rleReset(shape->strokeRle);
534     shape->fastTrack = false;
535     shape->bbox.reset();
536 }
537
538
539 void shapeFree(SwShape* shape)
540 {
541     rleFree(shape->rle);
542     shapeDelFill(shape);
543
544     if (shape->stroke) {
545         rleFree(shape->strokeRle);
546         strokeFree(shape->stroke);
547     }
548 }
549
550
551 void shapeDelStroke(SwShape* shape)
552 {
553     if (!shape->stroke) return;
554     rleFree(shape->strokeRle);
555     shape->strokeRle = nullptr;
556     strokeFree(shape->stroke);
557     shape->stroke = nullptr;
558 }
559
560
561 void shapeResetStroke(SwShape* shape, const Shape* sdata, const Matrix* transform)
562 {
563     if (!shape->stroke) shape->stroke = static_cast<SwStroke*>(calloc(1, sizeof(SwStroke)));
564     auto stroke = shape->stroke;
565     if (!stroke) return;
566
567     strokeReset(stroke, sdata, transform);
568     rleReset(shape->strokeRle);
569 }
570
571
572 bool shapeGenStrokeRle(SwShape* shape, const Shape* sdata, const Matrix* transform, const SwBBox& clipRegion, SwBBox& renderRegion, SwMpool* mpool, unsigned tid)
573 {
574     SwOutline* shapeOutline = nullptr;
575     SwOutline* strokeOutline = nullptr;
576     bool freeOutline = false;
577     bool ret = true;
578
579     //Dash Style Stroke
580     if (sdata->strokeDash(nullptr) > 0) {
581         shapeOutline = _genDashOutline(sdata, transform);
582         if (!shapeOutline) return false;
583         freeOutline = true;
584     //Normal Style stroke
585     } else {
586         if (!shape->outline) {
587             if (!_genOutline(shape, sdata, transform, mpool, tid, false)) return false;
588         }
589         shapeOutline = shape->outline;
590     }
591
592     if (!strokeParseOutline(shape->stroke, *shapeOutline)) {
593         ret = false;
594         goto fail;
595     }
596
597     strokeOutline = strokeExportOutline(shape->stroke, mpool, tid);
598
599     if (!mathUpdateOutlineBBox(strokeOutline, clipRegion, renderRegion, false)) {
600         ret = false;
601         goto fail;
602     }
603
604     shape->strokeRle = rleRender(shape->strokeRle, strokeOutline, renderRegion, true);
605
606 fail:
607     if (freeOutline) {
608         if (shapeOutline->cntrs) free(shapeOutline->cntrs);
609         if (shapeOutline->pts) free(shapeOutline->pts);
610         if (shapeOutline->types) free(shapeOutline->types);
611         if (shapeOutline->closed) free(shapeOutline->closed);
612         free(shapeOutline);
613     }
614     mpoolRetStrokeOutline(mpool, tid);
615
616     return ret;
617 }
618
619
620 bool shapeGenFillColors(SwShape* shape, const Fill* fill, const Matrix* transform, SwSurface* surface, uint32_t opacity, bool ctable)
621 {
622     return fillGenColorTable(shape->fill, fill, transform, surface, opacity, ctable);
623 }
624
625
626 bool shapeGenStrokeFillColors(SwShape* shape, const Fill* fill, const Matrix* transform, SwSurface* surface, uint32_t opacity, bool ctable)
627 {
628     return fillGenColorTable(shape->stroke->fill, fill, transform, surface, opacity, ctable);
629 }
630
631
632 void shapeResetFill(SwShape* shape)
633 {
634     if (!shape->fill) {
635         shape->fill = static_cast<SwFill*>(calloc(1, sizeof(SwFill)));
636         if (!shape->fill) return;
637     }
638     fillReset(shape->fill);
639 }
640
641
642 void shapeResetStrokeFill(SwShape* shape)
643 {
644     if (!shape->stroke->fill) {
645         shape->stroke->fill = static_cast<SwFill*>(calloc(1, sizeof(SwFill)));
646         if (!shape->stroke->fill) return;
647     }
648     fillReset(shape->stroke->fill);
649 }
650
651
652 void shapeDelFill(SwShape* shape)
653 {
654     if (!shape->fill) return;
655     fillFree(shape->fill);
656     shape->fill = nullptr;
657 }
658
659
660 void shapeDelStrokeFill(SwShape* shape)
661 {
662     if (!shape->stroke->fill) return;
663     fillFree(shape->stroke->fill);
664     shape->stroke->fill = nullptr;
665 }