blob: e538d6fbfede84b9012a1077b5061671d33cb2bc [file] [log] [blame]
egdaniela22ea182014-06-11 06:51:51 -07001/*
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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "include/core/SkPathMeasure.h"
9#include "include/core/SkStrokeRec.h"
10#include "src/core/SkPointPriv.h"
11#include "src/utils/SkDashPathPriv.h"
egdaniela22ea182014-06-11 06:51:51 -070012
Ben Wagnerf08d1d02018-06-18 15:11:00 -040013#include <utility>
14
egdaniela22ea182014-06-11 06:51:51 -070015static inline int is_even(int x) {
caryclark3127c992015-12-09 12:02:30 -080016 return !(x & 1);
egdaniela22ea182014-06-11 06:51:51 -070017}
18
19static SkScalar find_first_interval(const SkScalar intervals[], SkScalar phase,
20 int32_t* index, int count) {
21 for (int i = 0; i < count; ++i) {
caryclarkd3cfd942016-03-17 05:33:28 -070022 SkScalar gap = intervals[i];
23 if (phase > gap || (phase == gap && gap)) {
24 phase -= gap;
egdaniela22ea182014-06-11 06:51:51 -070025 } else {
26 *index = i;
caryclarkd3cfd942016-03-17 05:33:28 -070027 return gap - phase;
egdaniela22ea182014-06-11 06:51:51 -070028 }
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
38void 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;
caryclarkeb75c7d2016-03-18 06:04:26 -070046 // 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) {
egdaniela22ea182014-06-11 06:51:51 -070052 phase = SkScalarMod(phase, len);
53 }
caryclarkeb75c7d2016-03-18 06:04:26 -070054 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);
egdaniela22ea182014-06-11 06:51:51 -070065 }
caryclarkeb75c7d2016-03-18 06:04:26 -070066 *adjustedPhase = phase;
egdaniela22ea182014-06-11 06:51:51 -070067 }
caryclarkeb75c7d2016-03-18 06:04:26 -070068 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);
egdaniela22ea182014-06-11 06:51:51 -070075}
76
77static 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()) {
Mike Reeda99b6ce2017-02-04 11:04:26 -050083 radius *= rec.getMiter();
egdaniela22ea182014-06-11 06:51:51 -070084 }
85 rect->outset(radius, radius);
86}
87
Greg Daniel9838b492017-12-21 14:55:00 +000088// 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.
93static 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
98static 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) {
Ben Wagnerf08d1d02018-06-18 15:11:00 -0400112 using std::swap;
113 swap(minXY, maxXY);
Greg Daniel9838b492017-12-21 14:55:00 +0000114 }
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) {
Ben Wagnerf08d1d02018-06-18 15:11:00 -0400142 using std::swap;
143 swap(minXY, maxXY);
Greg Daniel9838b492017-12-21 14:55:00 +0000144 }
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
Mike Kleine2556a42019-08-12 12:09:28 -0400154// Handles only lines and rects.
155// If cull_path() returns true, dstPath is the new smaller path,
Mike Klein0bbb3c12019-08-12 15:19:41 -0400156// otherwise dstPath may have been changed but you should ignore it.
egdaniela22ea182014-06-11 06:51:51 -0700157static bool cull_path(const SkPath& srcPath, const SkStrokeRec& rec,
Mike Klein0bbb3c12019-08-12 15:19:41 -0400158 const SkRect* cullRect, SkScalar intervalLength, SkPath* dstPath) {
159 if (!cullRect) {
160 SkPoint pts[2];
Greg Daniel9838b492017-12-21 14:55:00 +0000161 if (srcPath.isLine(pts) && pts[0] == pts[1]) {
162 adjust_zero_length_line(pts);
Mike Klein0bbb3c12019-08-12 15:19:41 -0400163 dstPath->moveTo(pts[0]);
164 dstPath->lineTo(pts[1]);
165 return true;
Greg Daniel9838b492017-12-21 14:55:00 +0000166 }
Mike Klein0bbb3c12019-08-12 15:19:41 -0400167 return false;
168 }
Mike Kleine2556a42019-08-12 12:09:28 -0400169
Mike Klein0bbb3c12019-08-12 15:19:41 -0400170 SkRect bounds;
171 bounds = *cullRect;
172 outset_for_stroke(&bounds, rec);
Mike Kleine2556a42019-08-12 12:09:28 -0400173
Mike Klein0bbb3c12019-08-12 15:19:41 -0400174 {
175 SkPoint pts[2];
176 if (srcPath.isLine(pts)) {
177 if (clip_line(pts, bounds, intervalLength, 0)) {
178 dstPath->moveTo(pts[0]);
179 dstPath->lineTo(pts[1]);
180 return true;
Greg Daniel9838b492017-12-21 14:55:00 +0000181 }
Greg Daniel9838b492017-12-21 14:55:00 +0000182 return false;
183 }
184 }
Mike Klein0bbb3c12019-08-12 15:19:41 -0400185
186 if (srcPath.isRect(nullptr)) {
187 // We'll break the rect into four lines, culling each separately.
188 SkPath::Iter iter(srcPath, false);
189
190 SkPoint pts[4]; // Rects are all moveTo and lineTo, so we'll only use pts[0] and pts[1].
191 SkAssertResult(SkPath::kMove_Verb == iter.next(pts));
192
193 SkScalar accum = 0; // Sum of unculled edge lengths to keep the phase correct.
194 while (iter.next(pts) == SkPath::kLine_Verb) {
195 // Notice this vector v and accum work with the original unclipped length.
196 SkVector v = pts[1] - pts[0];
197
198 // TODO: this whole bit of skip-moveTo() logic seems wrong to me.
199 // If the line is entirely outside clip rect, skip it.
200 bool inY = bounds.fTop <= pts[0].fY && pts[0].fY <= bounds.fBottom,
201 inX = bounds.fLeft <= pts[0].fX && pts[0].fX <= bounds.fRight ;
202 if (v.fX ? inY : inX) {
203 bool skipMoveTo = inX && inY;
204
205 if (clip_line(pts, bounds, intervalLength, SkScalarMod(accum, intervalLength))) {
206 if (accum == 0 || !skipMoveTo) {
207 dstPath->moveTo(pts[0]);
208 }
209 dstPath->lineTo(pts[1]);
210 }
211 }
212
213 // We either just traveled v.fX horizontally or v.fY vertically.
214 SkASSERT(v.fX == 0 || v.fY == 0);
215 accum += SkScalarAbs(v.fX + v.fY);
216 }
217 return !dstPath->isEmpty();
218 }
219
220 return false;
egdaniela22ea182014-06-11 06:51:51 -0700221}
222
223class SpecialLineRec {
224public:
225 bool init(const SkPath& src, SkPath* dst, SkStrokeRec* rec,
226 int intervalCount, SkScalar intervalLength) {
227 if (rec->isHairlineStyle() || !src.isLine(fPts)) {
228 return false;
229 }
230
231 // can relax this in the future, if we handle square and round caps
232 if (SkPaint::kButt_Cap != rec->getCap()) {
233 return false;
234 }
235
236 SkScalar pathLength = SkPoint::Distance(fPts[0], fPts[1]);
237
238 fTangent = fPts[1] - fPts[0];
239 if (fTangent.isZero()) {
240 return false;
241 }
242
243 fPathLength = pathLength;
244 fTangent.scale(SkScalarInvert(pathLength));
Cary Clarkdf429f32017-11-08 11:44:31 -0500245 SkPointPriv::RotateCCW(fTangent, &fNormal);
egdaniela22ea182014-06-11 06:51:51 -0700246 fNormal.scale(SkScalarHalf(rec->getWidth()));
247
248 // now estimate how many quads will be added to the path
249 // resulting segments = pathLen * intervalCount / intervalLen
250 // resulting points = 4 * segments
251
Mike Reeda99b6ce2017-02-04 11:04:26 -0500252 SkScalar ptCount = pathLength * intervalCount / (float)intervalLength;
lsalzmanf41ae2f2016-07-21 09:37:59 -0700253 ptCount = SkTMin(ptCount, SkDashPath::kMaxDashCount);
egdaniela22ea182014-06-11 06:51:51 -0700254 int n = SkScalarCeilToInt(ptCount) << 2;
255 dst->incReserve(n);
256
257 // we will take care of the stroking
258 rec->setFillStyle();
259 return true;
260 }
261
262 void addSegment(SkScalar d0, SkScalar d1, SkPath* path) const {
lsalzman0adbd3e2016-08-08 13:40:27 -0700263 SkASSERT(d0 <= fPathLength);
egdaniela22ea182014-06-11 06:51:51 -0700264 // clamp the segment to our length
265 if (d1 > fPathLength) {
266 d1 = fPathLength;
267 }
268
Mike Reeda99b6ce2017-02-04 11:04:26 -0500269 SkScalar x0 = fPts[0].fX + fTangent.fX * d0;
270 SkScalar x1 = fPts[0].fX + fTangent.fX * d1;
271 SkScalar y0 = fPts[0].fY + fTangent.fY * d0;
272 SkScalar y1 = fPts[0].fY + fTangent.fY * d1;
egdaniela22ea182014-06-11 06:51:51 -0700273
274 SkPoint pts[4];
275 pts[0].set(x0 + fNormal.fX, y0 + fNormal.fY); // moveTo
276 pts[1].set(x1 + fNormal.fX, y1 + fNormal.fY); // lineTo
277 pts[2].set(x1 - fNormal.fX, y1 - fNormal.fY); // lineTo
278 pts[3].set(x0 - fNormal.fX, y0 - fNormal.fY); // lineTo
279
280 path->addPoly(pts, SK_ARRAY_COUNT(pts), false);
281 }
282
283private:
284 SkPoint fPts[2];
285 SkVector fTangent;
286 SkVector fNormal;
287 SkScalar fPathLength;
288};
289
290
caryclarkeb75c7d2016-03-18 06:04:26 -0700291bool SkDashPath::InternalFilter(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
egdaniela22ea182014-06-11 06:51:51 -0700292 const SkRect* cullRect, const SkScalar aIntervals[],
293 int32_t count, SkScalar initialDashLength, int32_t initialDashIndex,
bsalomon398e3f42016-06-13 10:22:48 -0700294 SkScalar intervalLength,
295 StrokeRecApplication strokeRecApplication) {
Mike Reed4c651442018-08-23 12:47:59 -0400296 // we must always have an even number of intervals
297 SkASSERT(is_even(count));
egdaniela22ea182014-06-11 06:51:51 -0700298
caryclarkeb75c7d2016-03-18 06:04:26 -0700299 // we do nothing if the src wants to be filled
bsalomona0587862016-06-09 06:03:38 -0700300 SkStrokeRec::Style style = rec->getStyle();
301 if (SkStrokeRec::kFill_Style == style || SkStrokeRec::kStrokeAndFill_Style == style) {
egdaniela22ea182014-06-11 06:51:51 -0700302 return false;
303 }
304
305 const SkScalar* intervals = aIntervals;
306 SkScalar dashCount = 0;
307 int segCount = 0;
308
309 SkPath cullPathStorage;
310 const SkPath* srcPtr = &src;
311 if (cull_path(src, *rec, cullRect, intervalLength, &cullPathStorage)) {
Cary Clark4fb229d2017-12-22 08:10:09 -0500312 // if rect is closed, starts in a dash, and ends in a dash, add the initial join
313 // potentially a better fix is described here: bug.skia.org/7445
314 if (src.isRect(nullptr) && src.isLastContourClosed() && is_even(initialDashIndex)) {
315 SkScalar pathLength = SkPathMeasure(src, false, rec->getResScale()).getLength();
316 SkScalar endPhase = SkScalarMod(pathLength + initialDashLength, intervalLength);
317 int index = 0;
318 while (endPhase > intervals[index]) {
319 endPhase -= intervals[index++];
320 SkASSERT(index <= count);
Mike Reed4c651442018-08-23 12:47:59 -0400321 if (index == count) {
322 // We have run out of intervals. endPhase "should" never get to this point,
323 // but it could if the subtracts underflowed. Hence we will pin it as if it
324 // perfectly ran through the intervals.
325 // See crbug.com/875494 (and skbug.com/8274)
326 endPhase = 0;
327 break;
328 }
Cary Clark4fb229d2017-12-22 08:10:09 -0500329 }
330 // if dash ends inside "on", or ends at beginning of "off"
331 if (is_even(index) == (endPhase > 0)) {
332 SkPoint midPoint = src.getPoint(0);
333 // get vector at end of rect
334 int last = src.countPoints() - 1;
335 while (midPoint == src.getPoint(last)) {
336 --last;
337 SkASSERT(last >= 0);
338 }
339 // get vector at start of rect
340 int next = 1;
341 while (midPoint == src.getPoint(next)) {
342 ++next;
343 SkASSERT(next < last);
344 }
345 SkVector v = midPoint - src.getPoint(last);
346 const SkScalar kTinyOffset = SK_ScalarNearlyZero;
347 // scale vector to make start of tiny right angle
348 v *= kTinyOffset;
349 cullPathStorage.moveTo(midPoint - v);
350 cullPathStorage.lineTo(midPoint);
351 v = midPoint - src.getPoint(next);
352 // scale vector to make end of tiny right angle
353 v *= kTinyOffset;
354 cullPathStorage.lineTo(midPoint - v);
355 }
356 }
egdaniela22ea182014-06-11 06:51:51 -0700357 srcPtr = &cullPathStorage;
358 }
359
360 SpecialLineRec lineRec;
bsalomon398e3f42016-06-13 10:22:48 -0700361 bool specialLine = (StrokeRecApplication::kAllow == strokeRecApplication) &&
362 lineRec.init(*srcPtr, dst, rec, count >> 1, intervalLength);
egdaniela22ea182014-06-11 06:51:51 -0700363
caryclark1a7eb262016-01-21 07:07:02 -0800364 SkPathMeasure meas(*srcPtr, false, rec->getResScale());
egdaniela22ea182014-06-11 06:51:51 -0700365
366 do {
367 bool skipFirstSegment = meas.isClosed();
368 bool addedSegment = false;
369 SkScalar length = meas.getLength();
370 int index = initialDashIndex;
371
372 // Since the path length / dash length ratio may be arbitrarily large, we can exert
373 // significant memory pressure while attempting to build the filtered path. To avoid this,
374 // we simply give up dashing beyond a certain threshold.
375 //
376 // The original bug report (http://crbug.com/165432) is based on a path yielding more than
377 // 90 million dash segments and crashing the memory allocator. A limit of 1 million
378 // segments seems reasonable: at 2 verbs per segment * 9 bytes per verb, this caps the
379 // maximum dash memory overhead at roughly 17MB per path.
egdaniela22ea182014-06-11 06:51:51 -0700380 dashCount += length * (count >> 1) / intervalLength;
381 if (dashCount > kMaxDashCount) {
382 dst->reset();
383 return false;
384 }
385
386 // Using double precision to avoid looping indefinitely due to single precision rounding
387 // (for extreme path_length/dash_length ratios). See test_infinite_dash() unittest.
388 double distance = 0;
389 double dlen = initialDashLength;
390
391 while (distance < length) {
392 SkASSERT(dlen >= 0);
393 addedSegment = false;
caryclark5cb00a92015-08-26 09:04:55 -0700394 if (is_even(index) && !skipFirstSegment) {
egdaniela22ea182014-06-11 06:51:51 -0700395 addedSegment = true;
396 ++segCount;
397
398 if (specialLine) {
399 lineRec.addSegment(SkDoubleToScalar(distance),
400 SkDoubleToScalar(distance + dlen),
401 dst);
402 } else {
403 meas.getSegment(SkDoubleToScalar(distance),
404 SkDoubleToScalar(distance + dlen),
405 dst, true);
406 }
407 }
408 distance += dlen;
409
410 // clear this so we only respect it the first time around
411 skipFirstSegment = false;
412
413 // wrap around our intervals array if necessary
414 index += 1;
415 SkASSERT(index <= count);
416 if (index == count) {
417 index = 0;
418 }
419
420 // fetch our next dlen
421 dlen = intervals[index];
422 }
423
424 // extend if we ended on a segment and we need to join up with the (skipped) initial segment
425 if (meas.isClosed() && is_even(initialDashIndex) &&
caryclarkeb75c7d2016-03-18 06:04:26 -0700426 initialDashLength >= 0) {
egdaniela22ea182014-06-11 06:51:51 -0700427 meas.getSegment(0, initialDashLength, dst, !addedSegment);
428 ++segCount;
429 }
430 } while (meas.nextContour());
431
432 if (segCount > 1) {
433 dst->setConvexity(SkPath::kConcave_Convexity);
434 }
435
436 return true;
437}
438
439bool SkDashPath::FilterDashPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
440 const SkRect* cullRect, const SkPathEffect::DashInfo& info) {
caryclarkeb75c7d2016-03-18 06:04:26 -0700441 if (!ValidDashPath(info.fPhase, info.fIntervals, info.fCount)) {
442 return false;
443 }
egdaniela22ea182014-06-11 06:51:51 -0700444 SkScalar initialDashLength = 0;
445 int32_t initialDashIndex = 0;
446 SkScalar intervalLength = 0;
447 CalcDashParameters(info.fPhase, info.fIntervals, info.fCount,
448 &initialDashLength, &initialDashIndex, &intervalLength);
caryclarkeb75c7d2016-03-18 06:04:26 -0700449 return InternalFilter(dst, src, rec, cullRect, info.fIntervals, info.fCount, initialDashLength,
egdaniela22ea182014-06-11 06:51:51 -0700450 initialDashIndex, intervalLength);
451}
caryclarkeb75c7d2016-03-18 06:04:26 -0700452
453bool SkDashPath::ValidDashPath(SkScalar phase, const SkScalar intervals[], int32_t count) {
454 if (count < 2 || !SkIsAlign2(count)) {
455 return false;
456 }
457 SkScalar length = 0;
458 for (int i = 0; i < count; i++) {
459 if (intervals[i] < 0) {
460 return false;
461 }
462 length += intervals[i];
463 }
464 // watch out for values that might make us go out of bounds
465 return length > 0 && SkScalarIsFinite(phase) && SkScalarIsFinite(length);
466}