Debian Codegraph @

tools/viewer/VariableWidthStrokerSlide.cpp

raw
1 /*
2 * Copyright 2020 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 "imgui.h"
9 #include "include/core/SkBitmap.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkPath.h"
12 #include "include/core/SkPathBuilder.h"
13 #include "include/core/SkPathMeasure.h"
14 #include "include/core/SkPathUtils.h"
15 #include "include/utils/SkParsePath.h"
16 #include "src/core/SkGeometry.h"
17 #include "tools/viewer/ClickHandlerSlide.h"
18
19 #include <stack>
20 #include <vector>
21
22 namespace {
23
24 //////////////////////////////////////////////////////////////////////////////
25
26 constexpr inline SkPoint rotate90(const SkPoint& p) { return {p.fY, -p.fX}; }
27 inline SkPoint rotate180(const SkPoint& p) { return p * -1; }
28 inline bool isClockwise(const SkPoint& a, const SkPoint& b) { return a.cross(b) > 0; }
29
30 static SkPoint checkSetLength(SkPoint p, float len, const char* file, int line) {
31 if (!p.setLength(len)) {
32 SkDebugf("%s:%d: Failed to set point length\n", file, line);
33 }
34 return p;
35 }
36
37 /** Version of setLength that prints debug msg on failure to help catch edge cases */
38 #define setLength(p, len) checkSetLength(p, len, __FILE__, __LINE__)
39
40 constexpr uint64_t choose(uint64_t n, uint64_t k) {
41 SkASSERT(n >= k);
42 uint64_t result = 1;
43 for (uint64_t i = 1; i <= k; i++) {
44 result *= (n + 1 - i);
45 result /= i;
46 }
47 return result;
48 }
49
50 //////////////////////////////////////////////////////////////////////////////
51
52 /**
53 * A scalar (float-valued weights) Bezier curve of arbitrary degree.
54 */
55 class ScalarBezCurve {
56 public:
57 inline static constexpr int kDegreeInvalid = -1;
58
59 /** Creates an empty curve with invalid degree. */
60 ScalarBezCurve() : fDegree(kDegreeInvalid) {}
61
62 /** Creates a curve of the specified degree with weights initialized to 0. */
63 explicit ScalarBezCurve(int degree) : fDegree(degree) {
64 SkASSERT(degree >= 0);
65 fWeights.resize(degree + 1, {0});
66 }
67
68 /** Creates a curve of specified degree with the given weights. */
69 ScalarBezCurve(int degree, const std::vector<float>& weights) : ScalarBezCurve(degree) {
70 SkASSERT(degree >= 0);
71 SkASSERT(weights.size() == (size_t)degree + 1);
72 fWeights.insert(fWeights.begin(), weights.begin(), weights.end());
73 }
74
75 /** Returns the extreme-valued weight */
76 float extremumWeight() const {
77 float f = 0;
78 int sign = 1;
79 for (float w : fWeights) {
80 if (std::abs(w) > f) {
81 f = std::abs(w);
82 sign = w >= 0 ? 1 : -1;
83 }
84 }
85 return sign * f;
86 }
87
88 /** Evaluates the curve at t */
89 float eval(float t) const { return Eval(*this, t); }
90
91 /** Evaluates the curve at t */
92 static float Eval(const ScalarBezCurve& curve, float t) {
93 // Set up starting point of recursion (k=0)
94 ScalarBezCurve result = curve;
95
96 for (int k = 1; k <= curve.fDegree; k++) {
97 // k is level of recursion, k-1 has previous level's values.
98 for (int i = curve.fDegree; i >= k; i--) {
99 result.fWeights[i] = result.fWeights[i - 1] * (1 - t) + result.fWeights[i] * t;
100 }
101 }
102
103 return result.fWeights[curve.fDegree];
104 }
105
106 /** Splits this curve at t into two halves (of the same degree) */
107 void split(float t, ScalarBezCurve* left, ScalarBezCurve* right) const {
108 Split(*this, t, left, right);
109 }
110
111 /** Splits this curve into the subinterval [tmin,tmax]. */
112 void split(float tmin, float tmax, ScalarBezCurve* result) const {
113 // TODO: I believe there's a more efficient algorithm for this
114 const float tRel = tmin / tmax;
115 ScalarBezCurve ll, rl, rr;
116 this->split(tmax, &rl, &rr);
117 rl.split(tRel, &ll, result);
118 }
119
120 /** Splits the curve at t into two halves (of the same degree) */
121 static void Split(const ScalarBezCurve& curve,
122 float t,
123 ScalarBezCurve* left,
124 ScalarBezCurve* right) {
125 // Set up starting point of recursion (k=0)
126 const int degree = curve.fDegree;
127 ScalarBezCurve result = curve;
128 *left = ScalarBezCurve(degree);
129 *right = ScalarBezCurve(degree);
130 left->fWeights[0] = curve.fWeights[0];
131 right->fWeights[degree] = curve.fWeights[degree];
132
133 for (int k = 1; k <= degree; k++) {
134 // k is level of recursion, k-1 has previous level's values.
135 for (int i = degree; i >= k; i--) {
136 result.fWeights[i] = result.fWeights[i - 1] * (1 - t) + result.fWeights[i] * t;
137 }
138
139 left->fWeights[k] = result.fWeights[k];
140 right->fWeights[degree - k] = result.fWeights[degree];
141 }
142 }
143
144 /**
145 * Increases the degree of the curve to the given degree. Has no effect if the
146 * degree is already equal to the given degree.
147 *
148 * This process is always exact (NB the reverse, degree reduction, is not exact).
149 */
150 void elevateDegree(int newDegree) {
151 if (newDegree == fDegree) {
152 return;
153 }
154
155 fWeights = ElevateDegree(*this, newDegree).fWeights;
156 fDegree = newDegree;
157 }
158
159 /**
160 * Increases the degree of the curve to the given degree. Has no effect if the
161 * degree is already equal to the given degree.
162 *
163 * This process is always exact (NB the reverse, degree reduction, is not exact).
164 */
165 static ScalarBezCurve ElevateDegree(const ScalarBezCurve& curve, int newDegree) {
166 SkASSERT(newDegree >= curve.degree());
167 if (newDegree == curve.degree()) {
168 return curve;
169 }
170
171 // From Farouki, Rajan, "Algorithms for polynomials in Bernstein form" 1988.
172 ScalarBezCurve elevated(newDegree);
173 const int r = newDegree - curve.fDegree;
174 const int n = curve.fDegree;
175
176 for (int i = 0; i <= n + r; i++) {
177 elevated.fWeights[i] = 0;
178 for (int j = std::max(0, i - r); j <= std::min(n, i); j++) {
179 const float f =
180 (choose(n, j) * choose(r, i - j)) / static_cast<float>(choose(n + r, i));
181 elevated.fWeights[i] += curve.fWeights[j] * f;
182 }
183 }
184
185 return elevated;
186 }
187
188 /**
189 * Returns the zero-set of this curve, which is a list of t values where the curve crosses 0.
190 */
191 std::vector<float> zeroSet() const { return ZeroSet(*this); }
192
193 /**
194 * Returns the zero-set of the curve, which is a list of t values where the curve crosses 0.
195 */
196 static std::vector<float> ZeroSet(const ScalarBezCurve& curve) {
197 constexpr float kTol = 0.001f;
198 std::vector<float> result;
199 ZeroSetRec(curve, 0, 1, kTol, &result);
200 return result;
201 }
202
203 /** Multiplies the curve's weights by a constant value */
204 static ScalarBezCurve Mul(const ScalarBezCurve& curve, float f) {
205 ScalarBezCurve result = curve;
206 for (int k = 0; k <= curve.fDegree; k++) {
207 result.fWeights[k] *= f;
208 }
209 return result;
210 }
211
212 /**
213 * Multiplies the two curves and returns the result.
214 *
215 * Degree of resulting curve is the sum of the degrees of the input curves.
216 */
217 static ScalarBezCurve Mul(const ScalarBezCurve& a, const ScalarBezCurve& b) {
218 // From G. Elber, "Free form surface analysis using a hybrid of symbolic and numeric
219 // computation". PhD thesis, 1992. p.11.
220 const int n = a.degree(), m = b.degree();
221 const int newDegree = n + m;
222 ScalarBezCurve result(newDegree);
223
224 for (int k = 0; k <= newDegree; k++) {
225 result.fWeights[k] = 0;
226 for (int i = std::max(0, k - n); i <= std::min(k, m); i++) {
227 const float f =
228 (choose(m, i) * choose(n, k - i)) / static_cast<float>(choose(m + n, k));
229 result.fWeights[k] += a.fWeights[i] * b.fWeights[k - i] * f;
230 }
231 }
232
233 return result;
234 }
235
236 /** Returns a^2 + b^2. This is a specialized method because the loops are easily fused. */
237 static ScalarBezCurve AddSquares(const ScalarBezCurve& a, const ScalarBezCurve& b) {
238 const int n = a.degree(), m = b.degree();
239 const int newDegree = n + m;
240 ScalarBezCurve result(newDegree);
241
242 for (int k = 0; k <= newDegree; k++) {
243 float aSq = 0, bSq = 0;
244 for (int i = std::max(0, k - n); i <= std::min(k, m); i++) {
245 const float f =
246 (choose(m, i) * choose(n, k - i)) / static_cast<float>(choose(m + n, k));
247 aSq += a.fWeights[i] * a.fWeights[k - i] * f;
248 bSq += b.fWeights[i] * b.fWeights[k - i] * f;
249 }
250 result.fWeights[k] = aSq + bSq;
251 }
252
253 return result;
254 }
255
256 /** Returns a - b. */
257 static ScalarBezCurve Sub(const ScalarBezCurve& a, const ScalarBezCurve& b) {
258 ScalarBezCurve result = a;
259 result.sub(b);
260 return result;
261 }
262
263 /** Subtracts the other curve from this curve */
264 void sub(const ScalarBezCurve& other) {
265 SkASSERT(other.fDegree == fDegree);
266 for (int k = 0; k <= fDegree; k++) {
267 fWeights[k] -= other.fWeights[k];
268 }
269 }
270
271 /** Subtracts a constant from this curve */
272 void sub(float f) {
273 for (int k = 0; k <= fDegree; k++) {
274 fWeights[k] -= f;
275 }
276 }
277
278 /** Returns the curve degree */
279 int degree() const { return fDegree; }
280
281 /** Returns the curve weights */
282 const std::vector<float>& weights() const { return fWeights; }
283
284 float operator[](size_t i) const { return fWeights[i]; }
285 float& operator[](size_t i) { return fWeights[i]; }
286
287 private:
288 /** Recursive helper for ZeroSet */
289 static void ZeroSetRec(const ScalarBezCurve& curve,
290 float tmin,
291 float tmax,
292 float tol,
293 std::vector<float>* result) {
294 float lenP = 0;
295 bool allPos = curve.fWeights[0] >= 0, allNeg = curve.fWeights[0] < 0;
296 for (int i = 1; i <= curve.fDegree; i++) {
297 lenP += std::abs(curve.fWeights[i] - curve.fWeights[i - 1]);
298 allPos &= curve.fWeights[i] >= 0;
299 allNeg &= curve.fWeights[i] < 0;
300 }
301 if (lenP <= tol) {
302 result->push_back((tmin + tmax) * 0.5);
303 return;
304 } else if (allPos || allNeg) {
305 // No zero crossings possible if the coefficients don't change sign (convex hull
306 // property)
307 return;
308 } else if (SkScalarNearlyZero(tmax - tmin)) {
309 return;
310 } else {
311 ScalarBezCurve left(curve.fDegree), right(curve.fDegree);
312 Split(curve, 0.5f, &left, &right);
313
314 const float tmid = (tmin + tmax) * 0.5;
315 ZeroSetRec(left, tmin, tmid, tol, result);
316 ZeroSetRec(right, tmid, tmax, tol, result);
317 }
318 }
319
320 int fDegree;
321 std::vector<float> fWeights;
322 };
323
324 //////////////////////////////////////////////////////////////////////////////
325
326 /** Helper class that measures per-verb path lengths. */
327 class PathVerbMeasure {
328 public:
329 explicit PathVerbMeasure(const SkPath& path) : fPath(path), fIter(path, false) { nextVerb(); }
330
331 SkScalar totalLength() const;
332
333 SkScalar currentVerbLength() { return fMeas.getLength(); }
334
335 void nextVerb();
336
337 private:
338 const SkPath& fPath;
339 SkPoint fFirstPointInContour;
340 SkPoint fPreviousPoint;
341 SkPath fCurrVerb;
342 SkPath::Iter fIter;
343 SkPathMeasure fMeas;
344 };
345
346 SkScalar PathVerbMeasure::totalLength() const {
347 SkPathMeasure meas(fPath, false);
348 return meas.getLength();
349 }
350
351 void PathVerbMeasure::nextVerb() {
352 SkPoint pts[4];
353 SkPath::Verb verb = fIter.next(pts);
354
355 while (verb == SkPath::kMove_Verb || verb == SkPath::kClose_Verb) {
356 if (verb == SkPath::kMove_Verb) {
357 fFirstPointInContour = pts[0];
358 fPreviousPoint = fFirstPointInContour;
359 }
360 verb = fIter.next(pts);
361 }
362
363 SkPathBuilder builder;
364 builder.moveTo(fPreviousPoint);
365 switch (verb) {
366 case SkPath::kLine_Verb:
367 builder.lineTo(pts[1]);
368 break;
369 case SkPath::kQuad_Verb:
370 builder.quadTo(pts[1], pts[2]);
371 break;
372 case SkPath::kCubic_Verb:
373 builder.cubicTo(pts[1], pts[2], pts[3]);
374 break;
375 case SkPath::kConic_Verb:
376 builder.conicTo(pts[1], pts[2], fIter.conicWeight());
377 break;
378 case SkPath::kDone_Verb:
379 break;
380 case SkPath::kClose_Verb:
381 case SkPath::kMove_Verb:
382 SkASSERT(false);
383 break;
384 }
385 fCurrVerb = builder.detach();
386
387 fPreviousPoint = fCurrVerb.getLastPt().value_or(SkPoint{0, 0});
388 fMeas.setPath(&fCurrVerb, false);
389 }
390
391 //////////////////////////////////////////////////////////////////////////////
392
393 // Several debug-only visualization helpers
394 namespace viz {
395 std::unique_ptr<ScalarBezCurve> outerErr;
396 SkPath outerFirstApprox;
397 } // namespace viz
398
399 /**
400 * Prototype variable-width path stroker.
401 *
402 * Takes as input a path to be stroked, and two distance functions (inside and outside).
403 * Produces a fill path with the stroked path geometry.
404 *
405 * The algorithms in use here are from:
406 *
407 * G. Elber, E. Cohen. "Error bounded variable distance offset operator for free form curves and
408 * surfaces." International Journal of Computational Geometry & Applications 1, no. 01 (1991)
409 *
410 * G. Elber. "Free form surface analysis using a hybrid of symbolic and numeric computation."
411 * PhD diss., Dept. of Computer Science, University of Utah, 1992.
412 */
413 class SkVarWidthStroker {
414 public:
415 /** Metric to use for interpolation of distance function across path segments. */
416 enum class LengthMetric {
417 /** Each path segment gets an equal interval of t in [0,1] */
418 kNumSegments,
419 /** Each path segment gets t interval equal to its percent of the total path length */
420 kPathLength,
421 };
422
423 /**
424 * Strokes the path with a fixed-width distance function. This produces a traditional stroked
425 * path.
426 */
427 SkPath getFillPath(const SkPath& path, const SkPaint& paint) {
428 return getFillPath(path, paint, identityVarWidth(paint.getStrokeWidth()),
429 identityVarWidth(paint.getStrokeWidth()));
430 }
431
432 /**
433 * Strokes the given path using the two given distance functions for inner and outer offsets.
434 */
435 SkPath getFillPath(const SkPath& path,
436 const SkPaint& paint,
437 const ScalarBezCurve& varWidth,
438 const ScalarBezCurve& varWidthInner,
439 LengthMetric lengthMetric = LengthMetric::kNumSegments);
440
441 private:
442 /** Helper struct referring to a single segment of an SkPath */
443 struct PathSegment {
444 SkPath::Verb fVerb;
445 std::array<SkPoint, 4> fPoints;
446 };
447
448 struct OffsetSegments {
449 std::vector<PathSegment> fInner;
450 std::vector<PathSegment> fOuter;
451 };
452
453 /** Initialize stroker state */
454 void initForPath(const SkPath& path, const SkPaint& paint);
455
456 /** Strokes a path segment */
457 OffsetSegments strokeSegment(const PathSegment& segment,
458 const ScalarBezCurve& varWidth,
459 const ScalarBezCurve& varWidthInner,
460 bool needsMove);
461
462 /**
463 * Strokes the given segment using the given distance function.
464 *
465 * Returns a list of quad segments that approximate the offset curve.
466 * TODO: no reason this needs to return a vector of quads, can just append to the path
467 */
468 std::vector<PathSegment> strokeSegment(const PathSegment& seg,
469 const ScalarBezCurve& distanceFunc) const;
470
471 /** Adds an endcap to fOuter */
472 enum class CapLocation { Start, End };
473 void endcap(CapLocation loc);
474
475 /** Adds a join between the two segments */
476 void join(const SkPoint& common,
477 float innerRadius,
478 float outerRadius,
479 const OffsetSegments& prev,
480 const OffsetSegments& curr);
481
482 /** Appends path in reverse to result */
483 static void appendPathReversed(const SkPath& path, SkPathBuilder* result);
484
485 /** Returns the segment unit normal and unit tangent if not nullptr */
486 static SkPoint unitNormal(const PathSegment& seg, float t, SkPoint* tangentOut);
487
488 /** Returns the degree of a segment curve */
489 static int segmentDegree(const PathSegment& seg);
490
491 /** Splits a path segment at t */
492 static void splitSegment(const PathSegment& seg, float t, PathSegment* segA, PathSegment* segB);
493
494 /**
495 * Returns a quadratic segment that approximates the given segment using the given distance
496 * function.
497 */
498 static void approximateSegment(const PathSegment& seg,
499 const ScalarBezCurve& distFnc,
500 PathSegment* approxQuad);
501
502 /** Returns a constant (deg 0) distance function for the given stroke width */
503 static ScalarBezCurve identityVarWidth(float strokeWidth) {
504 return ScalarBezCurve(0, {strokeWidth / 2.0f});
505 }
506
507 float fRadius;
508 SkPaint::Cap fCap;
509 SkPaint::Join fJoin;
510 SkPathBuilder fInner, fOuter;
511 ScalarBezCurve fVarWidth, fVarWidthInner;
512 float fCurrT;
513 };
514
515 void SkVarWidthStroker::initForPath(const SkPath& path, const SkPaint& paint) {
516 fRadius = paint.getStrokeWidth() / 2;
517 fCap = paint.getStrokeCap();
518 fJoin = paint.getStrokeJoin();
519 fInner.reset();
520 fOuter.reset();
521 fCurrT = 0;
522 }
523
524 SkPath SkVarWidthStroker::getFillPath(const SkPath& path,
525 const SkPaint& paint,
526 const ScalarBezCurve& varWidth,
527 const ScalarBezCurve& varWidthInner,
528 LengthMetric lengthMetric) {
529 const auto appendStrokes = [this](const OffsetSegments& strokes, bool needsMove) {
530 if (needsMove) {
531 fOuter.moveTo(strokes.fOuter.front().fPoints[0]);
532 fInner.moveTo(strokes.fInner.front().fPoints[0]);
533 }
534
535 for (const PathSegment& seg : strokes.fOuter) {
536 fOuter.quadTo(seg.fPoints[1], seg.fPoints[2]);
537 }
538
539 for (const PathSegment& seg : strokes.fInner) {
540 fInner.quadTo(seg.fPoints[1], seg.fPoints[2]);
541 }
542 };
543
544 initForPath(path, paint);
545 fVarWidth = varWidth;
546 fVarWidthInner = varWidthInner;
547
548 // TODO: this assumes one contour:
549 PathVerbMeasure meas(path);
550 const float totalPathLength = lengthMetric == LengthMetric::kPathLength
551 ? meas.totalLength()
552 : (path.countVerbs() - 1);
553
554 // Trace the inner and outer paths simultaneously. Inner will therefore be
555 // recorded in reverse from how we trace the outline.
556 SkPath::Iter it(path, false);
557 PathSegment segment, prevSegment;
558 OffsetSegments offsetSegs, prevOffsetSegs;
559 bool firstSegment = true, prevWasFirst = false;
560
561 float lenTraveled = 0;
562 while ((segment.fVerb = it.next(&segment.fPoints[0])) != SkPath::kDone_Verb) {
563 const float verbLength = lengthMetric == LengthMetric::kPathLength
564 ? (meas.currentVerbLength() / totalPathLength)
565 : (1.0f / totalPathLength);
566 const float tmin = lenTraveled;
567 const float tmax = lenTraveled + verbLength;
568
569 // Subset the distance function for the current interval.
570 ScalarBezCurve partVarWidth, partVarWidthInner;
571 fVarWidth.split(tmin, tmax, &partVarWidth);
572 fVarWidthInner.split(tmin, tmax, &partVarWidthInner);
573 partVarWidthInner = ScalarBezCurve::Mul(partVarWidthInner, -1);
574
575 // Stroke the current segment
576 switch (segment.fVerb) {
577 case SkPath::kLine_Verb:
578 case SkPath::kQuad_Verb:
579 case SkPath::kCubic_Verb:
580 offsetSegs = strokeSegment(segment, partVarWidth, partVarWidthInner, firstSegment);
581 break;
582 case SkPath::kMove_Verb:
583 // Don't care about multiple contours currently
584 continue;
585 default:
586 SkDebugf("Unhandled path verb %d\n", segment.fVerb);
587 SkASSERT(false);
588 break;
589 }
590
591 // Join to the previous segment
592 if (!firstSegment) {
593 // Append prev inner and outer strokes
594 appendStrokes(prevOffsetSegs, prevWasFirst);
595
596 // Append the join
597 const float innerRadius = varWidthInner.eval(tmin);
598 const float outerRadius = varWidth.eval(tmin);
599 join(segment.fPoints[0], innerRadius, outerRadius, prevOffsetSegs, offsetSegs);
600 }
601
602 std::swap(segment, prevSegment);
603 std::swap(offsetSegs, prevOffsetSegs);
604 prevWasFirst = firstSegment;
605 firstSegment = false;
606 lenTraveled += verbLength;
607 meas.nextVerb();
608 }
609
610 // Finish appending final offset segments
611 appendStrokes(prevOffsetSegs, prevWasFirst);
612
613 // Open contour => endcap at the end
614 const bool isClosed = path.isLastContourClosed();
615 if (isClosed) {
616 SkDebugf("Unhandled closed contour\n");
617 SkASSERT(false);
618 } else {
619 endcap(CapLocation::End);
620 }
621
622 // Walk inner path in reverse, appending to result
623 appendPathReversed(fInner.snapshot(), &fOuter);
624 endcap(CapLocation::Start);
625
626 return fOuter.snapshot();
627 }
628
629 SkVarWidthStroker::OffsetSegments SkVarWidthStroker::strokeSegment(
630 const PathSegment& segment,
631 const ScalarBezCurve& varWidth,
632 const ScalarBezCurve& varWidthInner,
633 bool needsMove) {
634 viz::outerErr.reset(nullptr);
635
636 std::vector<PathSegment> outer = strokeSegment(segment, varWidth);
637 std::vector<PathSegment> inner = strokeSegment(segment, varWidthInner);
638 return {inner, outer};
639 }
640
641 std::vector<SkVarWidthStroker::PathSegment> SkVarWidthStroker::strokeSegment(
642 const PathSegment& seg, const ScalarBezCurve& distanceFunc) const {
643 // Work item for the recursive splitting stack.
644 struct Item {
645 PathSegment fSeg;
646 ScalarBezCurve fDistFnc, fDistFncSqd;
647 ScalarBezCurve fSegX, fSegY;
648
649 Item(const PathSegment& seg,
650 const ScalarBezCurve& distFnc,
651 const ScalarBezCurve& distFncSqd)
652 : fSeg(seg), fDistFnc(distFnc), fDistFncSqd(distFncSqd) {
653 const int segDegree = segmentDegree(seg);
654 fSegX = ScalarBezCurve(segDegree);
655 fSegY = ScalarBezCurve(segDegree);
656 for (int i = 0; i <= segDegree; i++) {
657 fSegX[i] = seg.fPoints[i].fX;
658 fSegY[i] = seg.fPoints[i].fY;
659 }
660 }
661 };
662
663 // Push the initial segment and distance function
664 std::stack<Item> stack;
665 stack.push(Item(seg, distanceFunc, ScalarBezCurve::Mul(distanceFunc, distanceFunc)));
666
667 std::vector<PathSegment> result;
668 constexpr int kMaxIters = 5000; /** TODO: this is completely arbitrary */
669 int iter = 0;
670 while (!stack.empty()) {
671 if (iter++ >= kMaxIters) break;
672 const Item item = stack.top();
673 stack.pop();
674
675 const ScalarBezCurve& distFnc = item.fDistFnc;
676 ScalarBezCurve distFncSqd = item.fDistFncSqd;
677 const float kTol = std::abs(0.5f * distFnc.extremumWeight());
678
679 // Compute a quad that approximates stroke outline
680 PathSegment quadApprox;
681 approximateSegment(item.fSeg, distFnc, &quadApprox);
682 ScalarBezCurve quadApproxX(2), quadApproxY(2);
683 for (int i = 0; i < 3; i++) {
684 quadApproxX[i] = quadApprox.fPoints[i].fX;
685 quadApproxY[i] = quadApprox.fPoints[i].fY;
686 }
687
688 // Compute control polygon for the delta(t) curve. First must elevate to a common degree.
689 const int deltaDegree = std::max(quadApproxX.degree(), item.fSegX.degree());
690 ScalarBezCurve segX = item.fSegX, segY = item.fSegY;
691 segX.elevateDegree(deltaDegree);
692 segY.elevateDegree(deltaDegree);
693 quadApproxX.elevateDegree(deltaDegree);
694 quadApproxY.elevateDegree(deltaDegree);
695
696 ScalarBezCurve deltaX = ScalarBezCurve::Sub(quadApproxX, segX);
697 ScalarBezCurve deltaY = ScalarBezCurve::Sub(quadApproxY, segY);
698
699 // Compute psi(t) = delta_x(t)^2 + delta_y(t)^2.
700 ScalarBezCurve E = ScalarBezCurve::AddSquares(deltaX, deltaY);
701
702 // Promote E and d(t)^2 to a common degree.
703 const int commonDeg = std::max(distFncSqd.degree(), E.degree());
704 distFncSqd.elevateDegree(commonDeg);
705 E.elevateDegree(commonDeg);
706
707 // Subtract dist squared curve from E, resulting in:
708 // eps(t) = delta_x(t)^2 + delta_y(t)^2 - d(t)^2
709 E.sub(distFncSqd);
710
711 // Purely for debugging/testing, save the first approximation and error function:
712 if (viz::outerErr == nullptr) {
713 using namespace viz;
714 outerErr = std::make_unique<ScalarBezCurve>(E);
715 outerFirstApprox = SkPathBuilder()
716 .moveTo(quadApprox.fPoints[0])
717 .quadTo(quadApprox.fPoints[1], quadApprox.fPoints[2])
718 .detach();
719 }
720
721 // Compute maxErr, which is just the max coefficient of eps (using convex hull property
722 // of bez curves)
723 float maxAbsErr = std::abs(E.extremumWeight());
724
725 if (maxAbsErr > kTol) {
726 PathSegment left, right;
727 splitSegment(item.fSeg, 0.5f, &left, &right);
728
729 ScalarBezCurve distFncL, distFncR;
730 distFnc.split(0.5f, &distFncL, &distFncR);
731
732 ScalarBezCurve distFncSqdL, distFncSqdR;
733 distFncSqd.split(0.5f, &distFncSqdL, &distFncSqdR);
734
735 stack.push(Item(right, distFncR, distFncSqdR));
736 stack.push(Item(left, distFncL, distFncSqdL));
737 } else {
738 // Approximation is good enough.
739 quadApprox.fVerb = SkPath::kQuad_Verb;
740 result.push_back(quadApprox);
741 }
742 }
743 SkASSERT(!result.empty());
744 return result;
745 }
746
747 void SkVarWidthStroker::endcap(CapLocation loc) {
748 const auto buttCap = [this](CapLocation loc) {
749 if (loc == CapLocation::Start) {
750 // Back at the start of the path: just close the stroked outline
751 fOuter.close();
752 } else {
753 // Inner last pt == first pt when appending in reverse
754 SkPoint innerLastPt = fInner.getLastPt().value_or(SkPoint{0, 0});
755 fOuter.lineTo(innerLastPt);
756 }
757 };
758
759 switch (fCap) {
760 case SkPaint::kButt_Cap:
761 buttCap(loc);
762 break;
763 default:
764 SkDebugf("Unhandled endcap %d\n", fCap);
765 buttCap(loc);
766 break;
767 }
768 }
769
770 void SkVarWidthStroker::join(const SkPoint& common,
771 float innerRadius,
772 float outerRadius,
773 const OffsetSegments& prev,
774 const OffsetSegments& curr) {
775 const auto miterJoin = [this](const SkPoint& common,
776 float leftRadius,
777 float rightRadius,
778 const OffsetSegments& prev,
779 const OffsetSegments& curr) {
780 // With variable-width stroke you can actually have a situation where both sides
781 // need an "inner" or an "outer" join. So we call the two sides "left" and
782 // "right" and they can each independently get an inner or outer join.
783 const auto makeJoin = [this, &common, &prev, &curr](bool left, float radius) {
784 SkPathBuilder* path = left ? &fOuter : &fInner;
785 const auto& prevSegs = left ? prev.fOuter : prev.fInner;
786 const auto& currSegs = left ? curr.fOuter : curr.fInner;
787 SkASSERT(!prevSegs.empty());
788 SkASSERT(!currSegs.empty());
789 const SkPoint afterEndpt = currSegs.front().fPoints[0];
790 SkPoint before = unitNormal(prevSegs.back(), 1, nullptr);
791 SkPoint after = unitNormal(currSegs.front(), 0, nullptr);
792
793 // Don't create any join geometry if the normals are nearly identical.
794 const float cosTheta = before.dot(after);
795 if (!SkScalarNearlyZero(1 - cosTheta)) {
796 bool outerJoin;
797 if (left) {
798 outerJoin = isClockwise(before, after);
799 } else {
800 before = rotate180(before);
801 after = rotate180(after);
802 outerJoin = !isClockwise(before, after);
803 }
804
805 if (outerJoin) {
806 // Before and after have the same origin and magnitude, so before+after is the
807 // diagonal of their rhombus. Origin of this vector is the midpoint of the miter
808 // line.
809 SkPoint miterVec = before + after;
810
811 // Note the relationship (draw a right triangle with the miter line as its
812 // hypoteneuse):
813 // sin(theta/2) = strokeWidth / miterLength
814 // so miterLength = strokeWidth / sin(theta/2)
815 // where miterLength is the length of the miter from outer point to inner
816 // corner. miterVec's origin is the midpoint of the miter line, so we use
817 // strokeWidth/2. Sqrt is just an application of half-angle identities.
818 const float sinHalfTheta = sqrtf(0.5 * (1 + cosTheta));
819 const float halfMiterLength = radius / sinHalfTheta;
820 // TODO: miter length limit
821 miterVec = setLength(miterVec, halfMiterLength);
822
823 // Outer join: connect to the miter point, and then to t=0 of next segment.
824 path->lineTo(common + miterVec);
825 path->lineTo(afterEndpt);
826 } else {
827 // Connect to the miter midpoint (common path endpoint of the two segments),
828 // and then to t=0 of the next segment. This adds an interior "loop"
829 // of geometry that handles edge cases where segment lengths are shorter than
830 // the stroke width.
831 path->lineTo(common);
832 path->lineTo(afterEndpt);
833 }
834 }
835 };
836
837 makeJoin(true, leftRadius);
838 makeJoin(false, rightRadius);
839 };
840
841 switch (fJoin) {
842 case SkPaint::kMiter_Join:
843 miterJoin(common, innerRadius, outerRadius, prev, curr);
844 break;
845 default:
846 SkDebugf("Unhandled join %d\n", fJoin);
847 miterJoin(common, innerRadius, outerRadius, prev, curr);
848 break;
849 }
850 }
851
852 void SkVarWidthStroker::appendPathReversed(const SkPath& path, SkPathBuilder* result) {
853 SkSpan<const SkPoint> points = path.points();
854 SkSpan<const SkPathVerb> verbs = path.verbs();
855 const int numPoints = SkToInt(points.size());
856 const int numVerbs = SkToInt(verbs.size());
857
858 for (int i = numVerbs - 1, j = numPoints; i >= 0; i--) {
859 auto verb = verbs[i];
860 switch (verb) {
861 case SkPathVerb::kLine: {
862 j -= 1;
863 SkASSERT(j >= 1);
864 result->lineTo(points[j - 1]);
865 break;
866 }
867 case SkPathVerb::kQuad: {
868 j -= 1;
869 SkASSERT(j >= 2);
870 result->quadTo(points[j - 1], points[j - 2]);
871 j -= 1;
872 break;
873 }
874 case SkPathVerb::kMove:
875 // Ignore
876 break;
877 default:
878 SkASSERT(false);
879 break;
880 }
881 }
882 }
883
884 int SkVarWidthStroker::segmentDegree(const PathSegment& seg) {
885 static constexpr int lut[] = {
886 -1, // move,
887 1, // line
888 2, // quad
889 -1, // conic
890 3, // cubic
891 -1 // done
892 };
893 const int deg = lut[static_cast<uint8_t>(seg.fVerb)];
894 SkASSERT(deg > 0);
895 return deg;
896 }
897
898 void SkVarWidthStroker::splitSegment(const PathSegment& seg,
899 float t,
900 PathSegment* segA,
901 PathSegment* segB) {
902 // TODO: although general, this is a pretty slow way to do this
903 const int degree = segmentDegree(seg);
904 ScalarBezCurve x(degree), y(degree);
905 for (int i = 0; i <= degree; i++) {
906 x[i] = seg.fPoints[i].fX;
907 y[i] = seg.fPoints[i].fY;
908 }
909
910 ScalarBezCurve leftX(degree), rightX(degree), leftY(degree), rightY(degree);
911 x.split(t, &leftX, &rightX);
912 y.split(t, &leftY, &rightY);
913
914 segA->fVerb = segB->fVerb = seg.fVerb;
915 for (int i = 0; i <= degree; i++) {
916 segA->fPoints[i] = {leftX[i], leftY[i]};
917 segB->fPoints[i] = {rightX[i], rightY[i]};
918 }
919 }
920
921 void SkVarWidthStroker::approximateSegment(const PathSegment& seg,
922 const ScalarBezCurve& distFnc,
923 PathSegment* approxQuad) {
924 // This is a simple control polygon transformation.
925 // From F. Yzerman. "Precise offsetting of quadratic Bezier curves". 2019.
926 // TODO: detect and handle more degenerate cases (e.g. linear)
927 // TODO: Tiller-Hanson works better in many cases but does not generalize well
928 SkPoint tangentStart, tangentEnd;
929 SkPoint offsetStart = unitNormal(seg, 0, &tangentStart);
930 SkPoint offsetEnd = unitNormal(seg, 1, &tangentEnd);
931 SkPoint offsetMid = offsetStart + offsetEnd;
932
933 const float radiusStart = distFnc.eval(0);
934 const float radiusMid = distFnc.eval(0.5f);
935 const float radiusEnd = distFnc.eval(1);
936
937 offsetStart = radiusStart == 0 ? SkPoint::Make(0, 0) : setLength(offsetStart, radiusStart);
938 offsetMid = radiusMid == 0 ? SkPoint::Make(0, 0) : setLength(offsetMid, radiusMid);
939 offsetEnd = radiusEnd == 0 ? SkPoint::Make(0, 0) : setLength(offsetEnd, radiusEnd);
940
941 SkPoint start, mid, end;
942 switch (segmentDegree(seg)) {
943 case 1:
944 start = seg.fPoints[0];
945 end = seg.fPoints[1];
946 mid = (start + end) * 0.5f;
947 break;
948 case 2:
949 start = seg.fPoints[0];
950 mid = seg.fPoints[1];
951 end = seg.fPoints[2];
952 break;
953 case 3:
954 start = seg.fPoints[0];
955 mid = (seg.fPoints[1] + seg.fPoints[2]) * 0.5f;
956 end = seg.fPoints[3];
957 break;
958 default:
959 SkDebugf("Unhandled degree for segment approximation");
960 SkASSERT(false);
961 break;
962 }
963
964 approxQuad->fPoints[0] = start + offsetStart;
965 approxQuad->fPoints[1] = mid + offsetMid;
966 approxQuad->fPoints[2] = end + offsetEnd;
967 }
968
969 SkPoint SkVarWidthStroker::unitNormal(const PathSegment& seg, float t, SkPoint* tangentOut) {
970 switch (seg.fVerb) {
971 case SkPath::kLine_Verb: {
972 const SkPoint tangent = setLength(seg.fPoints[1] - seg.fPoints[0], 1);
973 const SkPoint normal = rotate90(tangent);
974 if (tangentOut) {
975 *tangentOut = tangent;
976 }
977 return normal;
978 }
979 case SkPath::kQuad_Verb: {
980 SkPoint tangent;
981 if (t == 0) {
982 tangent = seg.fPoints[1] - seg.fPoints[0];
983 } else if (t == 1) {
984 tangent = seg.fPoints[2] - seg.fPoints[1];
985 } else {
986 tangent = ((seg.fPoints[1] - seg.fPoints[0]) * (1 - t) +
987 (seg.fPoints[2] - seg.fPoints[1]) * t) *
988 2;
989 }
990 if (!tangent.normalize()) {
991 SkDebugf("Failed to normalize quad tangent\n");
992 SkASSERT(false);
993 }
994 if (tangentOut) {
995 *tangentOut = tangent;
996 }
997 return rotate90(tangent);
998 }
999 case SkPath::kCubic_Verb: {
1000 SkPoint tangent;
1001 SkEvalCubicAt(seg.fPoints.data(), t, nullptr, &tangent, nullptr);
1002 if (!tangent.normalize()) {
1003 SkDebugf("Failed to normalize cubic tangent\n");
1004 SkASSERT(false);
1005 }
1006 if (tangentOut) {
1007 *tangentOut = tangent;
1008 }
1009 return rotate90(tangent);
1010 }
1011 default:
1012 SkDebugf("Unhandled verb for unit normal %d\n", seg.fVerb);
1013 SkASSERT(false);
1014 return {};
1015 }
1016 }
1017
1018 } // namespace
1019
1020 //////////////////////////////////////////////////////////////////////////////
1021
1022 class VariableWidthStrokerSlide : public ClickHandlerSlide {
1023 public:
1024 VariableWidthStrokerSlide()
1025 : fShowHidden(true)
1026 , fShowSkeleton(true)
1027 , fShowStrokePoints(false)
1028 , fShowUI(false)
1029 , fDifferentInnerFunc(false)
1030 , fShowErrorCurve(false) {
1031 resetToDefaults();
1032
1033 fPtsPaint.setAntiAlias(true);
1034 fPtsPaint.setStrokeWidth(10);
1035 fPtsPaint.setStrokeCap(SkPaint::kRound_Cap);
1036
1037 fStrokePointsPaint.setAntiAlias(true);
1038 fStrokePointsPaint.setStrokeWidth(5);
1039 fStrokePointsPaint.setStrokeCap(SkPaint::kRound_Cap);
1040
1041 fStrokePaint.setAntiAlias(true);
1042 fStrokePaint.setStyle(SkPaint::kStroke_Style);
1043 fStrokePaint.setColor(0x80FF0000);
1044
1045 fNewFillPaint.setAntiAlias(true);
1046 fNewFillPaint.setColor(0x8000FF00);
1047
1048 fHiddenPaint.setAntiAlias(true);
1049 fHiddenPaint.setStyle(SkPaint::kStroke_Style);
1050 fHiddenPaint.setColor(0xFF0000FF);
1051
1052 fSkeletonPaint.setAntiAlias(true);
1053 fSkeletonPaint.setStyle(SkPaint::kStroke_Style);
1054 fSkeletonPaint.setColor(SK_ColorRED);
1055
1056 fName = "VariableWidthStroker";
1057 }
1058
1059 void load(SkScalar w, SkScalar h) override { fWinSize = {w, h}; }
1060
1061 void resize(SkScalar w, SkScalar h) override { fWinSize = {w, h}; }
1062
1063 bool onChar(SkUnichar uni) override {
1064 switch (uni) {
1065 case '0':
1066 this->toggle(fShowUI);
1067 return true;
1068 case '1':
1069 this->toggle(fShowSkeleton);
1070 return true;
1071 case '2':
1072 this->toggle(fShowHidden);
1073 return true;
1074 case '3':
1075 this->toggle(fShowStrokePoints);
1076 return true;
1077 case '4':
1078 this->toggle(fShowErrorCurve);
1079 return true;
1080 case '5':
1081 this->toggle(fLengthMetric);
1082 return true;
1083 case 'x':
1084 resetToDefaults();
1085 return true;
1086 case '-':
1087 fWidth -= 5;
1088 return true;
1089 case '=':
1090 fWidth += 5;
1091 return true;
1092 default:
1093 break;
1094 }
1095 return false;
1096 }
1097
1098 void draw(SkCanvas* canvas) override {
1099 canvas->drawColor(0xFFEEEEEE);
1100
1101 SkPath path = this->makePath();
1102
1103 fStrokePaint.setStrokeWidth(fWidth);
1104
1105 // Elber-Cohen stroker result
1106 ScalarBezCurve distFnc = makeDistFnc(fDistFncs, fWidth);
1107 ScalarBezCurve distFncInner =
1108 fDifferentInnerFunc ? makeDistFnc(fDistFncsInner, fWidth) : distFnc;
1109 SkVarWidthStroker stroker;
1110 SkPath fillPath =
1111 stroker.getFillPath(path, fStrokePaint, distFnc, distFncInner, fLengthMetric);
1112 fillPath.setFillType(SkPathFillType::kWinding);
1113 canvas->drawPath(fillPath, fNewFillPaint);
1114
1115 if (fShowHidden) {
1116 canvas->drawPath(fillPath, fHiddenPaint);
1117 }
1118
1119 if (fShowSkeleton) {
1120 canvas->drawPath(path, fSkeletonPaint);
1121 canvas->drawPoints(SkCanvas::kPoints_PointMode, fPathPts, fPtsPaint);
1122 }
1123
1124 if (fShowStrokePoints) {
1125 drawStrokePoints(canvas, fillPath);
1126 }
1127
1128 if (fShowUI) {
1129 drawUI();
1130 }
1131
1132 if (fShowErrorCurve && viz::outerErr != nullptr) {
1133 SkPaint firstApproxPaint;
1134 firstApproxPaint.setStrokeWidth(4);
1135 firstApproxPaint.setStyle(SkPaint::kStroke_Style);
1136 firstApproxPaint.setColor(SK_ColorRED);
1137 canvas->drawPath(viz::outerFirstApprox, firstApproxPaint);
1138 drawErrorCurve(canvas, *viz::outerErr);
1139 }
1140 }
1141
1142 protected:
1143 Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey modi) override {
1144 const SkScalar tol = 4;
1145 const SkRect r = SkRect::MakeXYWH(x - tol, y - tol, tol * 2, tol * 2);
1146 for (size_t i = 0; i < fPathPts.size(); ++i) {
1147 if (r.intersects(SkRect::MakeXYWH(fPathPts[i].fX, fPathPts[i].fY, 1, 1))) {
1148 return new Click([this, i](Click* c) {
1149 fPathPts[i] = c->fCurr;
1150 return true;
1151 });
1152 }
1153 }
1154 return nullptr;
1155 }
1156
1157 bool onClick(ClickHandlerSlide::Click *) override { return false; }
1158
1159 private:
1160 /** Selectable menu item for choosing distance functions */
1161 struct DistFncMenuItem {
1162 std::string fName;
1163 int fDegree;
1164 bool fSelected;
1165 std::vector<float> fWeights;
1166
1167 DistFncMenuItem(const std::string& name, int degree, bool selected) {
1168 fName = name;
1169 fDegree = degree;
1170 fSelected = selected;
1171 fWeights.resize(degree + 1, 1.0f);
1172 }
1173 };
1174
1175 void toggle(bool& value) { value = !value; }
1176 void toggle(SkVarWidthStroker::LengthMetric& value) {
1177 value = value == SkVarWidthStroker::LengthMetric::kPathLength
1178 ? SkVarWidthStroker::LengthMetric::kNumSegments
1179 : SkVarWidthStroker::LengthMetric::kPathLength;
1180 }
1181
1182 void resetToDefaults() {
1183 fPathPts[0] = {300, 400};
1184 fPathPts[1] = {500, 400};
1185 fPathPts[2] = {700, 400};
1186 fPathPts[3] = {900, 400};
1187 fPathPts[4] = {1100, 400};
1188
1189 fWidth = 175;
1190
1191 fLengthMetric = SkVarWidthStroker::LengthMetric::kPathLength;
1192 fDistFncs = fDefaultsDistFncs;
1193 fDistFncsInner = fDefaultsDistFncs;
1194 }
1195
1196 SkPath makePath() {
1197 return SkPathBuilder()
1198 .moveTo(fPathPts[0])
1199 .quadTo(fPathPts[1], fPathPts[2])
1200 .quadTo(fPathPts[3], fPathPts[4])
1201 .detach();
1202 }
1203
1204 static ScalarBezCurve makeDistFnc(const std::vector<DistFncMenuItem>& fncs, float strokeWidth) {
1205 const float radius = strokeWidth / 2;
1206 for (const auto& df : fncs) {
1207 if (df.fSelected) {
1208 return ScalarBezCurve::Mul(ScalarBezCurve(df.fDegree, df.fWeights), radius);
1209 }
1210 }
1211 SkASSERT(false);
1212 return ScalarBezCurve(0, {radius});
1213 }
1214
1215 void drawStrokePoints(SkCanvas* canvas, const SkPath& fillPath) {
1216 SkPath::Iter it(fillPath, false);
1217 SkPoint points[4];
1218 SkPath::Verb verb;
1219 std::vector<SkPoint> pointsVec, ctrlPts;
1220 while ((verb = it.next(&points[0])) != SkPath::kDone_Verb) {
1221 switch (verb) {
1222 case SkPath::kLine_Verb:
1223 pointsVec.push_back(points[1]);
1224 break;
1225 case SkPath::kQuad_Verb:
1226 ctrlPts.push_back(points[1]);
1227 pointsVec.push_back(points[2]);
1228 break;
1229 case SkPath::kMove_Verb:
1230 pointsVec.push_back(points[0]);
1231 break;
1232 case SkPath::kClose_Verb:
1233 break;
1234 default:
1235 SkDebugf("Unhandled path verb %d for stroke points\n", verb);
1236 SkASSERT(false);
1237 break;
1238 }
1239 }
1240
1241 canvas->drawPoints(SkCanvas::kPoints_PointMode, pointsVec, fStrokePointsPaint);
1242 fStrokePointsPaint.setColor(SK_ColorBLUE);
1243 fStrokePointsPaint.setStrokeWidth(3);
1244 canvas->drawPoints(SkCanvas::kPoints_PointMode, ctrlPts, fStrokePointsPaint);
1245 fStrokePointsPaint.setColor(SK_ColorBLACK);
1246 fStrokePointsPaint.setStrokeWidth(5);
1247 }
1248
1249 void drawErrorCurve(SkCanvas* canvas, const ScalarBezCurve& E) {
1250 const float winW = fWinSize.width() * 0.75f, winH = fWinSize.height() * 0.25f;
1251 const float padding = 25;
1252 const SkRect box = SkRect::MakeXYWH(padding, fWinSize.height() - winH - padding,
1253 winW - 2 * padding, winH);
1254 constexpr int nsegs = 100;
1255 constexpr float dt = 1.0f / nsegs;
1256 constexpr float dx = 10.0f;
1257 const int deg = E.degree();
1258 SkPathBuilder builder;
1259 for (int i = 0; i < nsegs; i++) {
1260 const float tmin = i * dt, tmax = (i + 1) * dt;
1261 ScalarBezCurve left(deg), right(deg);
1262 E.split(tmax, &left, &right);
1263 const float tRel = tmin / tmax;
1264 ScalarBezCurve rl(deg), rr(deg);
1265 left.split(tRel, &rl, &rr);
1266
1267 const float x = i * dx;
1268 if (i == 0) {
1269 builder.moveTo(x, -rr[0]);
1270 }
1271 builder.lineTo(x + dx, -rr[deg]);
1272 }
1273 SkPath path = builder.detach();
1274
1275 SkPaint paint;
1276 paint.setStyle(SkPaint::kStroke_Style);
1277 paint.setAntiAlias(true);
1278 paint.setStrokeWidth(0);
1279 paint.setColor(SK_ColorRED);
1280 const SkRect pathBounds = path.computeTightBounds();
1281 constexpr float yAxisMax = 8000;
1282 const float sx = box.width() / pathBounds.width();
1283 const float sy = box.height() / (2 * yAxisMax);
1284 canvas->save();
1285 canvas->translate(box.left(), box.top() + box.height() / 2);
1286 canvas->scale(sx, sy);
1287 canvas->drawPath(path, paint);
1288
1289 SkPath axes = SkPathBuilder()
1290 .moveTo(0, 0)
1291 .lineTo(pathBounds.width(), 0)
1292 .moveTo(0, -yAxisMax)
1293 .lineTo(0, yAxisMax)
1294 .detach();
1295 paint.setColor(SK_ColorBLACK);
1296 paint.setAntiAlias(false);
1297 canvas->drawPath(axes, paint);
1298
1299 canvas->restore();
1300 }
1301
1302 void drawUI() {
1303 static constexpr auto kUIOpacity = 0.35f;
1304 static constexpr float kUIWidth = 200.0f, kUIHeight = 400.0f;
1305 ImGui::SetNextWindowBgAlpha(kUIOpacity);
1306 if (ImGui::Begin("E-C Controls", nullptr,
1307 ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoResize |
1308 ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoSavedSettings |
1309 ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoNav)) {
1310 const SkRect uiArea = SkRect::MakeXYWH(10, 10, kUIWidth, kUIHeight);
1311 ImGui::SetWindowPos(ImVec2(uiArea.x(), uiArea.y()));
1312 ImGui::SetWindowSize(ImVec2(uiArea.width(), uiArea.height()));
1313
1314 const auto drawControls = [](std::vector<DistFncMenuItem>& distFncs,
1315 const std::string& menuPfx,
1316 const std::string& ptPfx) {
1317 std::string degreeMenuLabel = menuPfx + ": ";
1318 for (const auto& df : distFncs) {
1319 if (df.fSelected) {
1320 degreeMenuLabel += df.fName;
1321 break;
1322 }
1323 }
1324 if (ImGui::BeginMenu(degreeMenuLabel.c_str())) {
1325 for (size_t i = 0; i < distFncs.size(); i++) {
1326 if (ImGui::MenuItem(distFncs[i].fName.c_str(), nullptr,
1327 distFncs[i].fSelected)) {
1328 for (size_t j = 0; j < distFncs.size(); j++) {
1329 distFncs[j].fSelected = j == i;
1330 }
1331 }
1332 }
1333 ImGui::EndMenu();
1334 }
1335
1336 for (auto& df : distFncs) {
1337 if (df.fSelected) {
1338 for (int i = 0; i <= df.fDegree; i++) {
1339 const std::string label = ptPfx + std::to_string(i);
1340 ImGui::SliderFloat(label.c_str(), &(df.fWeights[i]), 0, 1);
1341 }
1342 }
1343 }
1344 };
1345
1346 const std::array<std::pair<std::string, SkVarWidthStroker::LengthMetric>, 2> metrics = {
1347 std::make_pair("% path length", SkVarWidthStroker::LengthMetric::kPathLength),
1348 std::make_pair("% segment count",
1349 SkVarWidthStroker::LengthMetric::kNumSegments),
1350 };
1351 if (ImGui::BeginMenu("Interpolation metric:")) {
1352 for (const auto& metric : metrics) {
1353 if (ImGui::MenuItem(metric.first.c_str(), nullptr,
1354 fLengthMetric == metric.second)) {
1355 fLengthMetric = metric.second;
1356 }
1357 }
1358 ImGui::EndMenu();
1359 }
1360
1361 drawControls(fDistFncs, "Degree", "P");
1362
1363 if (ImGui::CollapsingHeader("Inner stroke", true)) {
1364 fDifferentInnerFunc = true;
1365 drawControls(fDistFncsInner, "Degree (inner)", "Q");
1366 } else {
1367 fDifferentInnerFunc = false;
1368 }
1369 }
1370 ImGui::End();
1371 }
1372
1373 bool fShowHidden, fShowSkeleton, fShowStrokePoints, fShowUI, fDifferentInnerFunc,
1374 fShowErrorCurve;
1375 float fWidth = 175;
1376 SkPaint fPtsPaint, fStrokePaint, fNewFillPaint, fHiddenPaint, fSkeletonPaint,
1377 fStrokePointsPaint;
1378 inline static constexpr int kNPts = 5;
1379 std::array<SkPoint, kNPts> fPathPts;
1380 SkSize fWinSize;
1381 SkVarWidthStroker::LengthMetric fLengthMetric;
1382 const std::vector<DistFncMenuItem> fDefaultsDistFncs = {
1383 DistFncMenuItem("Linear", 1, true), DistFncMenuItem("Quadratic", 2, false),
1384 DistFncMenuItem("Cubic", 3, false), DistFncMenuItem("One Louder (11)", 11, false),
1385 DistFncMenuItem("30?!", 30, false)};
1386 std::vector<DistFncMenuItem> fDistFncs = fDefaultsDistFncs;
1387 std::vector<DistFncMenuItem> fDistFncsInner = fDefaultsDistFncs;
1388 };
1389
1390 DEF_SLIDE(return new VariableWidthStrokerSlide;)