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