blob: a67b8c569964a9baaf18ccb42471e7dd59ee1cd6 [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,
156// otherwise dstPath is ignored.
egdaniela22ea182014-06-11 06:51:51 -0700157static bool cull_path(const SkPath& srcPath, const SkStrokeRec& rec,
158 const SkRect* cullRect, SkScalar intervalLength,
159 SkPath* dstPath) {
Greg Daniel9838b492017-12-21 14:55:00 +0000160 SkPoint pts[4];
161 if (nullptr == cullRect) {
162 if (srcPath.isLine(pts) && pts[0] == pts[1]) {
163 adjust_zero_length_line(pts);
164 } else {
165 return false;
166 }
167 } else {
168 SkRect bounds;
169 bool isLine = srcPath.isLine(pts);
170 bool isRect = !isLine && srcPath.isRect(nullptr);
171 if (!isLine && !isRect) {
172 return false;
173 }
174 bounds = *cullRect;
175 outset_for_stroke(&bounds, rec);
176 if (isRect) {
177 // break rect into four lines, and call each one separately
178 SkPath::Iter iter(srcPath, false);
179 SkAssertResult(SkPath::kMove_Verb == iter.next(pts));
180 SkScalar priorLength = 0;
181 while (SkPath::kLine_Verb == iter.next(pts)) {
182 SkVector v = pts[1] - pts[0];
Mike Kleine2556a42019-08-12 12:09:28 -0400183
Greg Daniel9838b492017-12-21 14:55:00 +0000184 // if line is entirely outside clip rect, skip it
Mike Kleine2556a42019-08-12 12:09:28 -0400185 bool inY = bounds.fTop <= pts[0].fY && pts[0].fY <= bounds.fBottom,
186 inX = bounds.fLeft <= pts[0].fX && pts[0].fX <= bounds.fRight ;
187 if (v.fX ? inY : inX) {
188 bool skipMoveTo = inX && inY;
189
Greg Daniel9838b492017-12-21 14:55:00 +0000190 if (clip_line(pts, bounds, intervalLength,
191 SkScalarMod(priorLength, intervalLength))) {
192 if (0 == priorLength || !skipMoveTo) {
193 dstPath->moveTo(pts[0]);
194 }
195 dstPath->lineTo(pts[1]);
196 }
197 }
198 // keep track of all prior lengths to set phase of next line
199 priorLength += SkScalarAbs(v.fX ? v.fX : v.fY);
200 }
201 return !dstPath->isEmpty();
202 }
203 SkASSERT(isLine);
204 if (!clip_line(pts, bounds, intervalLength, 0)) {
205 return false;
206 }
207 }
egdaniela22ea182014-06-11 06:51:51 -0700208 dstPath->moveTo(pts[0]);
209 dstPath->lineTo(pts[1]);
210 return true;
211}
212
213class SpecialLineRec {
214public:
215 bool init(const SkPath& src, SkPath* dst, SkStrokeRec* rec,
216 int intervalCount, SkScalar intervalLength) {
217 if (rec->isHairlineStyle() || !src.isLine(fPts)) {
218 return false;
219 }
220
221 // can relax this in the future, if we handle square and round caps
222 if (SkPaint::kButt_Cap != rec->getCap()) {
223 return false;
224 }
225
226 SkScalar pathLength = SkPoint::Distance(fPts[0], fPts[1]);
227
228 fTangent = fPts[1] - fPts[0];
229 if (fTangent.isZero()) {
230 return false;
231 }
232
233 fPathLength = pathLength;
234 fTangent.scale(SkScalarInvert(pathLength));
Cary Clarkdf429f32017-11-08 11:44:31 -0500235 SkPointPriv::RotateCCW(fTangent, &fNormal);
egdaniela22ea182014-06-11 06:51:51 -0700236 fNormal.scale(SkScalarHalf(rec->getWidth()));
237
238 // now estimate how many quads will be added to the path
239 // resulting segments = pathLen * intervalCount / intervalLen
240 // resulting points = 4 * segments
241
Mike Reeda99b6ce2017-02-04 11:04:26 -0500242 SkScalar ptCount = pathLength * intervalCount / (float)intervalLength;
lsalzmanf41ae2f2016-07-21 09:37:59 -0700243 ptCount = SkTMin(ptCount, SkDashPath::kMaxDashCount);
egdaniela22ea182014-06-11 06:51:51 -0700244 int n = SkScalarCeilToInt(ptCount) << 2;
245 dst->incReserve(n);
246
247 // we will take care of the stroking
248 rec->setFillStyle();
249 return true;
250 }
251
252 void addSegment(SkScalar d0, SkScalar d1, SkPath* path) const {
lsalzman0adbd3e2016-08-08 13:40:27 -0700253 SkASSERT(d0 <= fPathLength);
egdaniela22ea182014-06-11 06:51:51 -0700254 // clamp the segment to our length
255 if (d1 > fPathLength) {
256 d1 = fPathLength;
257 }
258
Mike Reeda99b6ce2017-02-04 11:04:26 -0500259 SkScalar x0 = fPts[0].fX + fTangent.fX * d0;
260 SkScalar x1 = fPts[0].fX + fTangent.fX * d1;
261 SkScalar y0 = fPts[0].fY + fTangent.fY * d0;
262 SkScalar y1 = fPts[0].fY + fTangent.fY * d1;
egdaniela22ea182014-06-11 06:51:51 -0700263
264 SkPoint pts[4];
265 pts[0].set(x0 + fNormal.fX, y0 + fNormal.fY); // moveTo
266 pts[1].set(x1 + fNormal.fX, y1 + fNormal.fY); // lineTo
267 pts[2].set(x1 - fNormal.fX, y1 - fNormal.fY); // lineTo
268 pts[3].set(x0 - fNormal.fX, y0 - fNormal.fY); // lineTo
269
270 path->addPoly(pts, SK_ARRAY_COUNT(pts), false);
271 }
272
273private:
274 SkPoint fPts[2];
275 SkVector fTangent;
276 SkVector fNormal;
277 SkScalar fPathLength;
278};
279
280
caryclarkeb75c7d2016-03-18 06:04:26 -0700281bool SkDashPath::InternalFilter(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
egdaniela22ea182014-06-11 06:51:51 -0700282 const SkRect* cullRect, const SkScalar aIntervals[],
283 int32_t count, SkScalar initialDashLength, int32_t initialDashIndex,
bsalomon398e3f42016-06-13 10:22:48 -0700284 SkScalar intervalLength,
285 StrokeRecApplication strokeRecApplication) {
Mike Reed4c651442018-08-23 12:47:59 -0400286 // we must always have an even number of intervals
287 SkASSERT(is_even(count));
egdaniela22ea182014-06-11 06:51:51 -0700288
caryclarkeb75c7d2016-03-18 06:04:26 -0700289 // we do nothing if the src wants to be filled
bsalomona0587862016-06-09 06:03:38 -0700290 SkStrokeRec::Style style = rec->getStyle();
291 if (SkStrokeRec::kFill_Style == style || SkStrokeRec::kStrokeAndFill_Style == style) {
egdaniela22ea182014-06-11 06:51:51 -0700292 return false;
293 }
294
295 const SkScalar* intervals = aIntervals;
296 SkScalar dashCount = 0;
297 int segCount = 0;
298
299 SkPath cullPathStorage;
300 const SkPath* srcPtr = &src;
301 if (cull_path(src, *rec, cullRect, intervalLength, &cullPathStorage)) {
Cary Clark4fb229d2017-12-22 08:10:09 -0500302 // if rect is closed, starts in a dash, and ends in a dash, add the initial join
303 // potentially a better fix is described here: bug.skia.org/7445
304 if (src.isRect(nullptr) && src.isLastContourClosed() && is_even(initialDashIndex)) {
305 SkScalar pathLength = SkPathMeasure(src, false, rec->getResScale()).getLength();
306 SkScalar endPhase = SkScalarMod(pathLength + initialDashLength, intervalLength);
307 int index = 0;
308 while (endPhase > intervals[index]) {
309 endPhase -= intervals[index++];
310 SkASSERT(index <= count);
Mike Reed4c651442018-08-23 12:47:59 -0400311 if (index == count) {
312 // We have run out of intervals. endPhase "should" never get to this point,
313 // but it could if the subtracts underflowed. Hence we will pin it as if it
314 // perfectly ran through the intervals.
315 // See crbug.com/875494 (and skbug.com/8274)
316 endPhase = 0;
317 break;
318 }
Cary Clark4fb229d2017-12-22 08:10:09 -0500319 }
320 // if dash ends inside "on", or ends at beginning of "off"
321 if (is_even(index) == (endPhase > 0)) {
322 SkPoint midPoint = src.getPoint(0);
323 // get vector at end of rect
324 int last = src.countPoints() - 1;
325 while (midPoint == src.getPoint(last)) {
326 --last;
327 SkASSERT(last >= 0);
328 }
329 // get vector at start of rect
330 int next = 1;
331 while (midPoint == src.getPoint(next)) {
332 ++next;
333 SkASSERT(next < last);
334 }
335 SkVector v = midPoint - src.getPoint(last);
336 const SkScalar kTinyOffset = SK_ScalarNearlyZero;
337 // scale vector to make start of tiny right angle
338 v *= kTinyOffset;
339 cullPathStorage.moveTo(midPoint - v);
340 cullPathStorage.lineTo(midPoint);
341 v = midPoint - src.getPoint(next);
342 // scale vector to make end of tiny right angle
343 v *= kTinyOffset;
344 cullPathStorage.lineTo(midPoint - v);
345 }
346 }
egdaniela22ea182014-06-11 06:51:51 -0700347 srcPtr = &cullPathStorage;
348 }
349
350 SpecialLineRec lineRec;
bsalomon398e3f42016-06-13 10:22:48 -0700351 bool specialLine = (StrokeRecApplication::kAllow == strokeRecApplication) &&
352 lineRec.init(*srcPtr, dst, rec, count >> 1, intervalLength);
egdaniela22ea182014-06-11 06:51:51 -0700353
caryclark1a7eb262016-01-21 07:07:02 -0800354 SkPathMeasure meas(*srcPtr, false, rec->getResScale());
egdaniela22ea182014-06-11 06:51:51 -0700355
356 do {
357 bool skipFirstSegment = meas.isClosed();
358 bool addedSegment = false;
359 SkScalar length = meas.getLength();
360 int index = initialDashIndex;
361
362 // Since the path length / dash length ratio may be arbitrarily large, we can exert
363 // significant memory pressure while attempting to build the filtered path. To avoid this,
364 // we simply give up dashing beyond a certain threshold.
365 //
366 // The original bug report (http://crbug.com/165432) is based on a path yielding more than
367 // 90 million dash segments and crashing the memory allocator. A limit of 1 million
368 // segments seems reasonable: at 2 verbs per segment * 9 bytes per verb, this caps the
369 // maximum dash memory overhead at roughly 17MB per path.
egdaniela22ea182014-06-11 06:51:51 -0700370 dashCount += length * (count >> 1) / intervalLength;
371 if (dashCount > kMaxDashCount) {
372 dst->reset();
373 return false;
374 }
375
376 // Using double precision to avoid looping indefinitely due to single precision rounding
377 // (for extreme path_length/dash_length ratios). See test_infinite_dash() unittest.
378 double distance = 0;
379 double dlen = initialDashLength;
380
381 while (distance < length) {
382 SkASSERT(dlen >= 0);
383 addedSegment = false;
caryclark5cb00a92015-08-26 09:04:55 -0700384 if (is_even(index) && !skipFirstSegment) {
egdaniela22ea182014-06-11 06:51:51 -0700385 addedSegment = true;
386 ++segCount;
387
388 if (specialLine) {
389 lineRec.addSegment(SkDoubleToScalar(distance),
390 SkDoubleToScalar(distance + dlen),
391 dst);
392 } else {
393 meas.getSegment(SkDoubleToScalar(distance),
394 SkDoubleToScalar(distance + dlen),
395 dst, true);
396 }
397 }
398 distance += dlen;
399
400 // clear this so we only respect it the first time around
401 skipFirstSegment = false;
402
403 // wrap around our intervals array if necessary
404 index += 1;
405 SkASSERT(index <= count);
406 if (index == count) {
407 index = 0;
408 }
409
410 // fetch our next dlen
411 dlen = intervals[index];
412 }
413
414 // extend if we ended on a segment and we need to join up with the (skipped) initial segment
415 if (meas.isClosed() && is_even(initialDashIndex) &&
caryclarkeb75c7d2016-03-18 06:04:26 -0700416 initialDashLength >= 0) {
egdaniela22ea182014-06-11 06:51:51 -0700417 meas.getSegment(0, initialDashLength, dst, !addedSegment);
418 ++segCount;
419 }
420 } while (meas.nextContour());
421
422 if (segCount > 1) {
423 dst->setConvexity(SkPath::kConcave_Convexity);
424 }
425
426 return true;
427}
428
429bool SkDashPath::FilterDashPath(SkPath* dst, const SkPath& src, SkStrokeRec* rec,
430 const SkRect* cullRect, const SkPathEffect::DashInfo& info) {
caryclarkeb75c7d2016-03-18 06:04:26 -0700431 if (!ValidDashPath(info.fPhase, info.fIntervals, info.fCount)) {
432 return false;
433 }
egdaniela22ea182014-06-11 06:51:51 -0700434 SkScalar initialDashLength = 0;
435 int32_t initialDashIndex = 0;
436 SkScalar intervalLength = 0;
437 CalcDashParameters(info.fPhase, info.fIntervals, info.fCount,
438 &initialDashLength, &initialDashIndex, &intervalLength);
caryclarkeb75c7d2016-03-18 06:04:26 -0700439 return InternalFilter(dst, src, rec, cullRect, info.fIntervals, info.fCount, initialDashLength,
egdaniela22ea182014-06-11 06:51:51 -0700440 initialDashIndex, intervalLength);
441}
caryclarkeb75c7d2016-03-18 06:04:26 -0700442
443bool SkDashPath::ValidDashPath(SkScalar phase, const SkScalar intervals[], int32_t count) {
444 if (count < 2 || !SkIsAlign2(count)) {
445 return false;
446 }
447 SkScalar length = 0;
448 for (int i = 0; i < count; i++) {
449 if (intervals[i] < 0) {
450 return false;
451 }
452 length += intervals[i];
453 }
454 // watch out for values that might make us go out of bounds
455 return length > 0 && SkScalarIsFinite(phase) && SkScalarIsFinite(length);
456}