1 /*
2  * Copyright 2014 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 "SkDashPathPriv.h"
9 #include "SkPathMeasure.h"
10 #include "SkPointPriv.h"
11 #include "SkStrokeRec.h"
12 
13 #include <utility>
14 
is_even(int x)15 static inline int is_even(int x) {
16     return !(x & 1);
17 }
18 
find_first_interval(const SkScalar intervals[],SkScalar phase,int32_t * index,int count)19 static SkScalar find_first_interval(const SkScalar intervals[], SkScalar phase,
20                                     int32_t* index, int count) {
21     for (int i = 0; i < count; ++i) {
22         SkScalar gap = intervals[i];
23         if (phase > gap || (phase == gap && gap)) {
24             phase -= gap;
25         } else {
26             *index = i;
27             return gap - phase;
28         }
29     }
30     // If we get here, phase "appears" to be larger than our length. This
31     // shouldn't happen with perfect precision, but we can accumulate errors
32     // during the initial length computation (rounding can make our sum be too
33     // big or too small. In that event, we just have to eat the error here.
34     *index = 0;
35     return intervals[0];
36 }
37 
CalcDashParameters(SkScalar phase,const SkScalar intervals[],int32_t count,SkScalar * initialDashLength,int32_t * initialDashIndex,SkScalar * intervalLength,SkScalar * adjustedPhase)38 void SkDashPath::CalcDashParameters(SkScalar phase, const SkScalar intervals[], int32_t count,
39                                     SkScalar* initialDashLength, int32_t* initialDashIndex,
40                                     SkScalar* intervalLength, SkScalar* adjustedPhase) {
41     SkScalar len = 0;
42     for (int i = 0; i < count; i++) {
43         len += intervals[i];
44     }
45     *intervalLength = len;
46     // Adjust phase to be between 0 and len, "flipping" phase if negative.
47     // e.g., if len is 100, then phase of -20 (or -120) is equivalent to 80
48     if (adjustedPhase) {
49         if (phase < 0) {
50             phase = -phase;
51             if (phase > len) {
52                 phase = SkScalarMod(phase, len);
53             }
54             phase = len - phase;
55 
56             // Due to finite precision, it's possible that phase == len,
57             // even after the subtract (if len >>> phase), so fix that here.
58             // This fixes http://crbug.com/124652 .
59             SkASSERT(phase <= len);
60             if (phase == len) {
61                 phase = 0;
62             }
63         } else if (phase >= len) {
64             phase = SkScalarMod(phase, len);
65         }
66         *adjustedPhase = phase;
67     }
68     SkASSERT(phase >= 0 && phase < len);
69 
70     *initialDashLength = find_first_interval(intervals, phase,
71                                             initialDashIndex, count);
72 
73     SkASSERT(*initialDashLength >= 0);
74     SkASSERT(*initialDashIndex >= 0 && *initialDashIndex < count);
75 }
76 
outset_for_stroke(SkRect * rect,const SkStrokeRec & rec)77 static void outset_for_stroke(SkRect* rect, const SkStrokeRec& rec) {
78     SkScalar radius = SkScalarHalf(rec.getWidth());
79     if (0 == radius) {
80         radius = SK_Scalar1;    // hairlines
81     }
82     if (SkPaint::kMiter_Join == rec.getJoin()) {
83         radius *= rec.getMiter();
84     }
85     rect->outset(radius, radius);
86 }
87 
88 // If line is zero-length, bump out the end by a tiny amount
89 // to draw endcaps. The bump factor is sized so that
90 // SkPoint::Distance() computes a non-zero length.
91 // Offsets SK_ScalarNearlyZero or smaller create empty paths when Iter measures length.
92 // Large values are scaled by SK_ScalarNearlyZero so significant bits change.
adjust_zero_length_line(SkPoint pts[2])93 static void adjust_zero_length_line(SkPoint pts[2]) {
94     SkASSERT(pts[0] == pts[1]);
95     pts[1].fX += SkTMax(1.001f, pts[1].fX) * SK_ScalarNearlyZero;
96 }
97 
clip_line(SkPoint pts[2],const SkRect & bounds,SkScalar intervalLength,SkScalar priorPhase)98 static bool clip_line(SkPoint pts[2], const SkRect& bounds, SkScalar intervalLength,
99                       SkScalar priorPhase) {
100     SkVector dxy = pts[1] - pts[0];
101 
102     // only horizontal or vertical lines
103     if (dxy.fX && dxy.fY) {
104         return false;
105     }
106     int xyOffset = SkToBool(dxy.fY);  // 0 to adjust horizontal, 1 to adjust vertical
107 
108     SkScalar minXY = (&pts[0].fX)[xyOffset];
109     SkScalar maxXY = (&pts[1].fX)[xyOffset];
110     bool swapped = maxXY < minXY;
111     if (swapped) {
112         using std::swap;
113         swap(minXY, maxXY);
114     }
115 
116     SkASSERT(minXY <= maxXY);
117     SkScalar leftTop = (&bounds.fLeft)[xyOffset];
118     SkScalar rightBottom = (&bounds.fRight)[xyOffset];
119     if (maxXY < leftTop || minXY > rightBottom) {
120         return false;
121     }
122 
123     // Now we actually perform the chop, removing the excess to the left/top and
124     // right/bottom of the bounds (keeping our new line "in phase" with the dash,
125     // hence the (mod intervalLength).
126 
127     if (minXY < leftTop) {
128         minXY = leftTop - SkScalarMod(leftTop - minXY, intervalLength);
129         if (!swapped) {
130             minXY -= priorPhase;  // for rectangles, adjust by prior phase
131         }
132     }
133     if (maxXY > rightBottom) {
134         maxXY = rightBottom + SkScalarMod(maxXY - rightBottom, intervalLength);
135         if (swapped) {
136             maxXY += priorPhase;  // for rectangles, adjust by prior phase
137         }
138     }
139 
140     SkASSERT(maxXY >= minXY);
141     if (swapped) {
142         using std::swap;
143         swap(minXY, maxXY);
144     }
145     (&pts[0].fX)[xyOffset] = minXY;
146     (&pts[1].fX)[xyOffset] = maxXY;
147 
148     if (minXY == maxXY) {
149         adjust_zero_length_line(pts);
150     }
151     return true;
152 }
153 
contains_inclusive(const SkRect & rect,const SkPoint & pt)154 static bool contains_inclusive(const SkRect& rect, const SkPoint& pt) {
155     return rect.fLeft <= pt.fX && pt.fX <= rect.fRight &&
156             rect.fTop <= pt.fY && pt.fY <= rect.fBottom;
157 }
158 
159 // Returns true is b is between a and c, that is: a <= b <= c, or a >= b >= c.
160 // Can perform this test with one branch by observing that, relative to b,
161 // the condition is true only if one side is positive and one side is negative.
162 // If the numbers are very small, the optimization may return the wrong result
163 // because the multiply may generate a zero where the simple compare does not.
164 // For this reason the assert does not fire when all three numbers are near zero.
between(SkScalar a,SkScalar b,SkScalar c)165 static bool between(SkScalar a, SkScalar b, SkScalar c) {
166     SkASSERT(((a <= b && b <= c) || (a >= b && b >= c)) == ((a - b) * (c - b) <= 0)
167             || (SkScalarNearlyZero(a) && SkScalarNearlyZero(b) && SkScalarNearlyZero(c)));
168     return (a - b) * (c - b) <= 0;
169 }
170 
171 // Only handles lines for now. If returns true, dstPath is the new (smaller)
172 // path. If returns false, then dstPath parameter is ignored.
cull_path(const SkPath & srcPath,const SkStrokeRec & rec,const SkRect * cullRect,SkScalar intervalLength,SkPath * dstPath)173 static bool cull_path(const SkPath& srcPath, const SkStrokeRec& rec,
174                       const SkRect* cullRect, SkScalar intervalLength,
175                       SkPath* dstPath) {
176     SkPoint pts[4];
177     if (nullptr == cullRect) {
178         if (srcPath.isLine(pts) && pts[0] == pts[1]) {
179             adjust_zero_length_line(pts);
180         } else {
181             return false;
182         }
183     } else {
184         SkRect bounds;
185         bool isLine = srcPath.isLine(pts);
186         bool isRect = !isLine && srcPath.isRect(nullptr);
187         if (!isLine && !isRect) {
188             return false;
189         }
190         bounds = *cullRect;
191         outset_for_stroke(&bounds, rec);
192         if (isRect) {
193             // break rect into four lines, and call each one separately
194             SkPath::Iter iter(srcPath, false);
195             SkAssertResult(SkPath::kMove_Verb == iter.next(pts));
196             SkScalar priorLength = 0;
197             while (SkPath::kLine_Verb == iter.next(pts)) {
198                 SkVector v = pts[1] - pts[0];
199                 // if line is entirely outside clip rect, skip it
200                 if (v.fX ? between(bounds.fTop, pts[0].fY, bounds.fBottom) :
201                         between(bounds.fLeft, pts[0].fX, bounds.fRight)) {
202                     bool skipMoveTo = contains_inclusive(bounds, pts[0]);
203                     if (clip_line(pts, bounds, intervalLength,
204                                   SkScalarMod(priorLength, intervalLength))) {
205                         if (0 == priorLength || !skipMoveTo) {
206                             dstPath->moveTo(pts[0]);
207                         }
208                         dstPath->lineTo(pts[1]);
209                     }
210                 }
211                 // keep track of all prior lengths to set phase of next line
212                 priorLength += SkScalarAbs(v.fX ? v.fX : v.fY);
213             }
214             return !dstPath->isEmpty();
215         }
216         SkASSERT(isLine);
217         if (!clip_line(pts, bounds, intervalLength, 0)) {
218             return false;
219         }
220     }
221     dstPath->moveTo(pts[0]);
222     dstPath->lineTo(pts[1]);
223     return true;
224 }
225 
226 class SpecialLineRec {
227 public:
init(const SkPath & src,SkPath * dst,SkStrokeRec * rec,int intervalCount,SkScalar intervalLength)228     bool init(const SkPath& src, SkPath* dst, SkStrokeRec* rec,
229               int intervalCount, SkScalar intervalLength) {
230         if (rec->isHairlineStyle() || !src.isLine(fPts)) {
231             return false;
232         }
233 
234         // can relax this in the future, if we handle square and round caps
235         if (SkPaint::kButt_Cap != rec->getCap()) {
236             return false;
237         }
238 
239         SkScalar pathLength = SkPoint::Distance(fPts[0], fPts[1]);
240 
241         fTangent = fPts[1] - fPts[0];
242         if (fTangent.isZero()) {
243             return false;
244         }
245 
246         fPathLength = pathLength;
247         fTangent.scale(SkScalarInvert(pathLength));
248         SkPointPriv::RotateCCW(fTangent, &fNormal);
249         fNormal.scale(SkScalarHalf(rec->getWidth()));
250 
251         // now estimate how many quads will be added to the path
252         //     resulting segments = pathLen * intervalCount / intervalLen
253         //     resulting points = 4 * segments
254 
255         SkScalar ptCount = pathLength * intervalCount / (float)intervalLength;
256         ptCount = SkTMin(ptCount, SkDashPath::kMaxDashCount);
257         int n = SkScalarCeilToInt(ptCount) << 2;
258         dst->incReserve(n);
259 
260         // we will take care of the stroking
261         rec->setFillStyle();
262         return true;
263     }
264 
addSegment(SkScalar d0,SkScalar d1,SkPath * path) const265     void addSegment(SkScalar d0, SkScalar d1, SkPath* path) const {
266         SkASSERT(d0 <= fPathLength);
267         // clamp the segment to our length
268         if (d1 > fPathLength) {
269             d1 = fPathLength;
270         }
271 
272         SkScalar x0 = fPts[0].fX + fTangent.fX * d0;
273         SkScalar x1 = fPts[0].fX + fTangent.fX * d1;
274         SkScalar y0 = fPts[0].fY + fTangent.fY * d0;
275         SkScalar y1 = fPts[0].fY + fTangent.fY * d1;
276 
277         SkPoint pts[4];
278         pts[0].set(x0 + fNormal.fX, y0 + fNormal.fY);   // moveTo
279         pts[1].set(x1 + fNormal.fX, y1 + fNormal.fY);   // lineTo
280         pts[2].set(x1 - fNormal.fX, y1 - fNormal.fY);   // lineTo
281         pts[3].set(x0 - fNormal.fX, y0 - fNormal.fY);   // lineTo
282 
283         path->addPoly(pts, SK_ARRAY_COUNT(pts), false);
284     }
285 
286 private:
287     SkPoint fPts[2];
288     SkVector fTangent;
289     SkVector fNormal;
290     SkScalar fPathLength;
291 };
292 
293 
InternalFilter(SkPath * dst,const SkPath & src,SkStrokeRec * rec,const SkRect * cullRect,const SkScalar aIntervals[],int32_t count,SkScalar initialDashLength,int32_t initialDashIndex,SkScalar intervalLength,StrokeRecApplication strokeRecApplication)294 bool SkDashPath::InternalFilter(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
295                                 const SkRect* cullRect, const SkScalar aIntervals[],
296                                 int32_t count, SkScalar initialDashLength, int32_t initialDashIndex,
297                                 SkScalar intervalLength,
298                                 StrokeRecApplication strokeRecApplication) {
299     // we must always have an even number of intervals
300     SkASSERT(is_even(count));
301 
302     // we do nothing if the src wants to be filled
303     SkStrokeRec::Style style = rec->getStyle();
304     if (SkStrokeRec::kFill_Style == style || SkStrokeRec::kStrokeAndFill_Style == style) {
305         return false;
306     }
307 
308     const SkScalar* intervals = aIntervals;
309     SkScalar        dashCount = 0;
310     int             segCount = 0;
311 
312     SkPath cullPathStorage;
313     const SkPath* srcPtr = &src;
314     if (cull_path(src, *rec, cullRect, intervalLength, &cullPathStorage)) {
315         // if rect is closed, starts in a dash, and ends in a dash, add the initial join
316         // potentially a better fix is described here: bug.skia.org/7445
317         if (src.isRect(nullptr) && src.isLastContourClosed() && is_even(initialDashIndex)) {
318             SkScalar pathLength = SkPathMeasure(src, false, rec->getResScale()).getLength();
319             SkScalar endPhase = SkScalarMod(pathLength + initialDashLength, intervalLength);
320             int index = 0;
321             while (endPhase > intervals[index]) {
322                 endPhase -= intervals[index++];
323                 SkASSERT(index <= count);
324                 if (index == count) {
325                     // We have run out of intervals. endPhase "should" never get to this point,
326                     // but it could if the subtracts underflowed. Hence we will pin it as if it
327                     // perfectly ran through the intervals.
328                     // See crbug.com/875494 (and skbug.com/8274)
329                     endPhase = 0;
330                     break;
331                 }
332             }
333             // if dash ends inside "on", or ends at beginning of "off"
334             if (is_even(index) == (endPhase > 0)) {
335                 SkPoint midPoint = src.getPoint(0);
336                 // get vector at end of rect
337                 int last = src.countPoints() - 1;
338                 while (midPoint == src.getPoint(last)) {
339                     --last;
340                     SkASSERT(last >= 0);
341                 }
342                 // get vector at start of rect
343                 int next = 1;
344                 while (midPoint == src.getPoint(next)) {
345                     ++next;
346                     SkASSERT(next < last);
347                 }
348                 SkVector v = midPoint - src.getPoint(last);
349                 const SkScalar kTinyOffset = SK_ScalarNearlyZero;
350                 // scale vector to make start of tiny right angle
351                 v *= kTinyOffset;
352                 cullPathStorage.moveTo(midPoint - v);
353                 cullPathStorage.lineTo(midPoint);
354                 v = midPoint - src.getPoint(next);
355                 // scale vector to make end of tiny right angle
356                 v *= kTinyOffset;
357                 cullPathStorage.lineTo(midPoint - v);
358             }
359         }
360         srcPtr = &cullPathStorage;
361     }
362 
363     SpecialLineRec lineRec;
364     bool specialLine = (StrokeRecApplication::kAllow == strokeRecApplication) &&
365                        lineRec.init(*srcPtr, dst, rec, count >> 1, intervalLength);
366 
367     SkPathMeasure   meas(*srcPtr, false, rec->getResScale());
368 
369     do {
370         bool        skipFirstSegment = meas.isClosed();
371         bool        addedSegment = false;
372         SkScalar    length = meas.getLength();
373         int         index = initialDashIndex;
374 
375         // Since the path length / dash length ratio may be arbitrarily large, we can exert
376         // significant memory pressure while attempting to build the filtered path. To avoid this,
377         // we simply give up dashing beyond a certain threshold.
378         //
379         // The original bug report (http://crbug.com/165432) is based on a path yielding more than
380         // 90 million dash segments and crashing the memory allocator. A limit of 1 million
381         // segments seems reasonable: at 2 verbs per segment * 9 bytes per verb, this caps the
382         // maximum dash memory overhead at roughly 17MB per path.
383         dashCount += length * (count >> 1) / intervalLength;
384         if (dashCount > kMaxDashCount) {
385             dst->reset();
386             return false;
387         }
388 
389         // Using double precision to avoid looping indefinitely due to single precision rounding
390         // (for extreme path_length/dash_length ratios). See test_infinite_dash() unittest.
391         double  distance = 0;
392         double  dlen = initialDashLength;
393 
394         while (distance < length) {
395             SkASSERT(dlen >= 0);
396             addedSegment = false;
397             if (is_even(index) && !skipFirstSegment) {
398                 addedSegment = true;
399                 ++segCount;
400 
401                 if (specialLine) {
402                     lineRec.addSegment(SkDoubleToScalar(distance),
403                                        SkDoubleToScalar(distance + dlen),
404                                        dst);
405                 } else {
406                     meas.getSegment(SkDoubleToScalar(distance),
407                                     SkDoubleToScalar(distance + dlen),
408                                     dst, true);
409                 }
410             }
411             distance += dlen;
412 
413             // clear this so we only respect it the first time around
414             skipFirstSegment = false;
415 
416             // wrap around our intervals array if necessary
417             index += 1;
418             SkASSERT(index <= count);
419             if (index == count) {
420                 index = 0;
421             }
422 
423             // fetch our next dlen
424             dlen = intervals[index];
425         }
426 
427         // extend if we ended on a segment and we need to join up with the (skipped) initial segment
428         if (meas.isClosed() && is_even(initialDashIndex) &&
429             initialDashLength >= 0) {
430             meas.getSegment(0, initialDashLength, dst, !addedSegment);
431             ++segCount;
432         }
433     } while (meas.nextContour());
434 
435     if (segCount > 1) {
436         dst->setConvexity(SkPath::kConcave_Convexity);
437     }
438 
439     return true;
440 }
441 
FilterDashPath(SkPath * dst,const SkPath & src,SkStrokeRec * rec,const SkRect * cullRect,const SkPathEffect::DashInfo & info)442 bool SkDashPath::FilterDashPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
443                                 const SkRect* cullRect, const SkPathEffect::DashInfo& info) {
444     if (!ValidDashPath(info.fPhase, info.fIntervals, info.fCount)) {
445         return false;
446     }
447     SkScalar initialDashLength = 0;
448     int32_t initialDashIndex = 0;
449     SkScalar intervalLength = 0;
450     CalcDashParameters(info.fPhase, info.fIntervals, info.fCount,
451                        &initialDashLength, &initialDashIndex, &intervalLength);
452     return InternalFilter(dst, src, rec, cullRect, info.fIntervals, info.fCount, initialDashLength,
453                           initialDashIndex, intervalLength);
454 }
455 
ValidDashPath(SkScalar phase,const SkScalar intervals[],int32_t count)456 bool SkDashPath::ValidDashPath(SkScalar phase, const SkScalar intervals[], int32_t count) {
457     if (count < 2 || !SkIsAlign2(count)) {
458         return false;
459     }
460     SkScalar length = 0;
461     for (int i = 0; i < count; i++) {
462         if (intervals[i] < 0) {
463             return false;
464         }
465         length += intervals[i];
466     }
467     // watch out for values that might make us go out of bounds
468     return length > 0 && SkScalarIsFinite(phase) && SkScalarIsFinite(length);
469 }
470