• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2011 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/gpu/ganesh/ops/AAHairLinePathRenderer.h"
9 
10 #include "include/core/SkPoint3.h"
11 #include "include/private/base/SkTemplates.h"
12 #include "src/core/SkGeometry.h"
13 #include "src/core/SkMatrixPriv.h"
14 #include "src/core/SkPointPriv.h"
15 #include "src/core/SkRectPriv.h"
16 #include "src/core/SkStroke.h"
17 #include "src/gpu/ganesh/GrAuditTrail.h"
18 #include "src/gpu/ganesh/GrBuffer.h"
19 #include "src/gpu/ganesh/GrCaps.h"
20 #include "src/gpu/ganesh/GrDefaultGeoProcFactory.h"
21 #include "src/gpu/ganesh/GrDrawOpTest.h"
22 #include "src/gpu/ganesh/GrOpFlushState.h"
23 #include "src/gpu/ganesh/GrProcessor.h"
24 #include "src/gpu/ganesh/GrProgramInfo.h"
25 #include "src/gpu/ganesh/GrResourceProvider.h"
26 #include "src/gpu/ganesh/GrStyle.h"
27 #include "src/gpu/ganesh/GrUtil.h"
28 #include "src/gpu/ganesh/SurfaceDrawContext.h"
29 #include "src/gpu/ganesh/effects/GrBezierEffect.h"
30 #include "src/gpu/ganesh/geometry/GrPathUtils.h"
31 #include "src/gpu/ganesh/geometry/GrStyledShape.h"
32 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
33 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelperWithStencil.h"
34 
35 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true>
36 
37 using PtArray = SkTArray<SkPoint, true>;
38 using IntArray = SkTArray<int, true>;
39 using FloatArray = SkTArray<float, true>;
40 
41 namespace {
42 
43 // quadratics are rendered as 5-sided polys in order to bound the
44 // AA stroke around the center-curve. See comments in push_quad_index_buffer and
45 // bloat_quad. Quadratics and conics share an index buffer
46 
47 // lines are rendered as:
48 //      *______________*
49 //      |\ -_______   /|
50 //      | \        \ / |
51 //      |  *--------*  |
52 //      | /  ______/ \ |
53 //      */_-__________\*
54 // For: 6 vertices and 18 indices (for 6 triangles)
55 
56 // Each quadratic is rendered as a five sided polygon. This poly bounds
57 // the quadratic's bounding triangle but has been expanded so that the
58 // 1-pixel wide area around the curve is inside the poly.
59 // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1
60 // that is rendered would look like this:
61 //              b0
62 //              b
63 //
64 //     a0              c0
65 //      a            c
66 //       a1       c1
67 // Each is drawn as three triangles ((a0,a1,b0), (b0,c1,c0), (a1,c1,b0))
68 // specified by these 9 indices:
69 static const uint16_t kQuadIdxBufPattern[] = {
70     0, 1, 2,
71     2, 4, 3,
72     1, 4, 2
73 };
74 
75 static const int kIdxsPerQuad = std::size(kQuadIdxBufPattern);
76 static const int kQuadNumVertices = 5;
77 static const int kQuadsNumInIdxBuffer = 256;
78 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey);
79 
get_quads_index_buffer(GrResourceProvider * resourceProvider)80 sk_sp<const GrBuffer> get_quads_index_buffer(GrResourceProvider* resourceProvider) {
81     SKGPU_DEFINE_STATIC_UNIQUE_KEY(gQuadsIndexBufferKey);
82     return resourceProvider->findOrCreatePatternedIndexBuffer(
83         kQuadIdxBufPattern, kIdxsPerQuad, kQuadsNumInIdxBuffer, kQuadNumVertices,
84         gQuadsIndexBufferKey);
85 }
86 
87 
88 // Each line segment is rendered as two quads and two triangles.
89 // p0 and p1 have alpha = 1 while all other points have alpha = 0.
90 // The four external points are offset 1 pixel perpendicular to the
91 // line and half a pixel parallel to the line.
92 //
93 // p4                  p5
94 //      p0         p1
95 // p2                  p3
96 //
97 // Each is drawn as six triangles specified by these 18 indices:
98 
99 static const uint16_t kLineSegIdxBufPattern[] = {
100     0, 1, 3,
101     0, 3, 2,
102     0, 4, 5,
103     0, 5, 1,
104     0, 2, 4,
105     1, 5, 3
106 };
107 
108 static const int kIdxsPerLineSeg = std::size(kLineSegIdxBufPattern);
109 static const int kLineSegNumVertices = 6;
110 static const int kLineSegsNumInIdxBuffer = 256;
111 
112 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey);
113 
get_lines_index_buffer(GrResourceProvider * resourceProvider)114 sk_sp<const GrBuffer> get_lines_index_buffer(GrResourceProvider* resourceProvider) {
115     SKGPU_DEFINE_STATIC_UNIQUE_KEY(gLinesIndexBufferKey);
116     return resourceProvider->findOrCreatePatternedIndexBuffer(
117         kLineSegIdxBufPattern, kIdxsPerLineSeg,  kLineSegsNumInIdxBuffer, kLineSegNumVertices,
118         gLinesIndexBufferKey);
119 }
120 
121 // Takes 178th time of logf on Z600 / VC2010
get_float_exp(float x)122 int get_float_exp(float x) {
123     static_assert(sizeof(int) == sizeof(float));
124 #ifdef SK_DEBUG
125     static bool tested;
126     if (!tested) {
127         tested = true;
128         SkASSERT(get_float_exp(0.25f) == -2);
129         SkASSERT(get_float_exp(0.3f) == -2);
130         SkASSERT(get_float_exp(0.5f) == -1);
131         SkASSERT(get_float_exp(1.f) == 0);
132         SkASSERT(get_float_exp(2.f) == 1);
133         SkASSERT(get_float_exp(2.5f) == 1);
134         SkASSERT(get_float_exp(8.f) == 3);
135         SkASSERT(get_float_exp(100.f) == 6);
136         SkASSERT(get_float_exp(1000.f) == 9);
137         SkASSERT(get_float_exp(1024.f) == 10);
138         SkASSERT(get_float_exp(3000000.f) == 21);
139     }
140 #endif
141     const int* iptr = (const int*)&x;
142     return (((*iptr) & 0x7f800000) >> 23) - 127;
143 }
144 
145 // Uses the max curvature function for quads to estimate
146 // where to chop the conic. If the max curvature is not
147 // found along the curve segment it will return 1 and
148 // dst[0] is the original conic. If it returns 2 the dst[0]
149 // and dst[1] are the two new conics.
split_conic(const SkPoint src[3],SkConic dst[2],const SkScalar weight)150 int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) {
151     SkScalar t = SkFindQuadMaxCurvature(src);
152     // SkFindQuadMaxCurvature() returns either a value in [0, 1) or NaN.
153     // However, passing NaN to conic.chopAt() will assert. Checking to see if
154     // t is in (0,1) will also cover the NaN case since NaN comparisons are always
155     // false, so we'll drop down into the else block in that case.
156     if (0 < t && t < 1) {
157         if (dst) {
158             SkConic conic;
159             conic.set(src, weight);
160             if (!conic.chopAt(t, dst)) {
161                 dst[0].set(src, weight);
162                 return 1;
163             }
164         }
165         return 2;
166     } else {
167         if (dst) {
168             dst[0].set(src, weight);
169         }
170         return 1;
171     }
172 }
173 
174 // Calls split_conic on the entire conic and then once more on each subsection.
175 // Most cases will result in either 1 conic (chop point is not within t range)
176 // or 3 points (split once and then one subsection is split again).
chop_conic(const SkPoint src[3],SkConic dst[4],const SkScalar weight)177 int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) {
178     SkConic dstTemp[2];
179     int conicCnt = split_conic(src, dstTemp, weight);
180     if (2 == conicCnt) {
181         int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW);
182         conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW);
183     } else {
184         dst[0] = dstTemp[0];
185     }
186     return conicCnt;
187 }
188 
189 // returns 0 if quad/conic is degen or close to it
190 // in this case approx the path with lines
191 // otherwise returns 1
is_degen_quad_or_conic(const SkPoint p[3],SkScalar * dsqd)192 int is_degen_quad_or_conic(const SkPoint p[3], SkScalar* dsqd) {
193     static const SkScalar gDegenerateToLineTol = GrPathUtils::kDefaultTolerance;
194     static const SkScalar gDegenerateToLineTolSqd =
195         gDegenerateToLineTol * gDegenerateToLineTol;
196 
197     if (SkPointPriv::DistanceToSqd(p[0], p[1]) < gDegenerateToLineTolSqd ||
198         SkPointPriv::DistanceToSqd(p[1], p[2]) < gDegenerateToLineTolSqd) {
199         return 1;
200     }
201 
202     *dsqd = SkPointPriv::DistanceToLineBetweenSqd(p[1], p[0], p[2]);
203     if (*dsqd < gDegenerateToLineTolSqd) {
204         return 1;
205     }
206 
207     if (SkPointPriv::DistanceToLineBetweenSqd(p[2], p[1], p[0]) < gDegenerateToLineTolSqd) {
208         return 1;
209     }
210     return 0;
211 }
212 
is_degen_quad_or_conic(const SkPoint p[3])213 int is_degen_quad_or_conic(const SkPoint p[3]) {
214     SkScalar dsqd;
215     return is_degen_quad_or_conic(p, &dsqd);
216 }
217 
218 // we subdivide the quads to avoid huge overfill
219 // if it returns -1 then should be drawn as lines
num_quad_subdivs(const SkPoint p[3])220 int num_quad_subdivs(const SkPoint p[3]) {
221     SkScalar dsqd;
222     if (is_degen_quad_or_conic(p, &dsqd)) {
223         return -1;
224     }
225 
226     // tolerance of triangle height in pixels
227     // tuned on windows  Quadro FX 380 / Z600
228     // trade off of fill vs cpu time on verts
229     // maybe different when do this using gpu (geo or tess shaders)
230     static const SkScalar gSubdivTol = 175 * SK_Scalar1;
231 
232     if (dsqd <= gSubdivTol * gSubdivTol) {
233         return 0;
234     } else {
235         static const int kMaxSub = 4;
236         // subdividing the quad reduces d by 4. so we want x = log4(d/tol)
237         // = log4(d*d/tol*tol)/2
238         // = log2(d*d/tol*tol)
239 
240         // +1 since we're ignoring the mantissa contribution.
241         int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1;
242         log = std::min(std::max(0, log), kMaxSub);
243         return log;
244     }
245 }
246 
247 /**
248  * Generates the lines and quads to be rendered. Lines are always recorded in
249  * device space. We will do a device space bloat to account for the 1pixel
250  * thickness.
251  * Quads are recorded in device space unless m contains
252  * perspective, then in they are in src space. We do this because we will
253  * subdivide large quads to reduce over-fill. This subdivision has to be
254  * performed before applying the perspective matrix.
255  */
gather_lines_and_quads(const SkPath & path,const SkMatrix & m,const SkIRect & devClipBounds,SkScalar capLength,bool convertConicsToQuads,PtArray * lines,PtArray * quads,PtArray * conics,IntArray * quadSubdivCnts,FloatArray * conicWeights)256 int gather_lines_and_quads(const SkPath& path,
257                            const SkMatrix& m,
258                            const SkIRect& devClipBounds,
259                            SkScalar capLength,
260                            bool convertConicsToQuads,
261                            PtArray* lines,
262                            PtArray* quads,
263                            PtArray* conics,
264                            IntArray* quadSubdivCnts,
265                            FloatArray* conicWeights) {
266     SkPath::Iter iter(path, false);
267 
268     int totalQuadCount = 0;
269     SkRect bounds;
270     SkIRect ibounds;
271 
272     bool persp = m.hasPerspective();
273 
274     // Whenever a degenerate, zero-length contour is encountered, this code will insert a
275     // 'capLength' x-aligned line segment. Since this is rendering hairlines it is hoped this will
276     // suffice for AA square & circle capping.
277     int verbsInContour = 0; // Does not count moves
278     bool seenZeroLengthVerb = false;
279     SkPoint zeroVerbPt;
280 
281     // Adds a quad that has already been chopped to the list and checks for quads that are close to
282     // lines. Also does a bounding box check. It takes points that are in src space and device
283     // space. The src points are only required if the view matrix has perspective.
284     auto addChoppedQuad = [&](const SkPoint srcPts[3], const SkPoint devPts[4],
285                               bool isContourStart) {
286         SkRect bounds;
287         SkIRect ibounds;
288         bounds.setBounds(devPts, 3);
289         bounds.outset(SK_Scalar1, SK_Scalar1);
290         bounds.roundOut(&ibounds);
291         // We only need the src space space pts when not in perspective.
292         SkASSERT(srcPts || !persp);
293         if (SkIRect::Intersects(devClipBounds, ibounds)) {
294             int subdiv = num_quad_subdivs(devPts);
295             SkASSERT(subdiv >= -1);
296             if (-1 == subdiv) {
297                 SkPoint* pts = lines->push_back_n(4);
298                 pts[0] = devPts[0];
299                 pts[1] = devPts[1];
300                 pts[2] = devPts[1];
301                 pts[3] = devPts[2];
302                 if (isContourStart && pts[0] == pts[1] && pts[2] == pts[3]) {
303                     seenZeroLengthVerb = true;
304                     zeroVerbPt = pts[0];
305                 }
306             } else {
307                 // when in perspective keep quads in src space
308                 const SkPoint* qPts = persp ? srcPts : devPts;
309                 SkPoint* pts = quads->push_back_n(3);
310                 pts[0] = qPts[0];
311                 pts[1] = qPts[1];
312                 pts[2] = qPts[2];
313                 quadSubdivCnts->push_back() = subdiv;
314                 totalQuadCount += 1 << subdiv;
315             }
316         }
317     };
318 
319     // Applies the view matrix to quad src points and calls the above helper.
320     auto addSrcChoppedQuad = [&](const SkPoint srcSpaceQuadPts[3], bool isContourStart) {
321         SkPoint devPts[3];
322         m.mapPoints(devPts, srcSpaceQuadPts, 3);
323         addChoppedQuad(srcSpaceQuadPts, devPts, isContourStart);
324     };
325 
326     SkPoint pathPts[4] = {{0, 0}, {0, 0}, {0, 0}, {0, 0}};
327     for (;;) {
328         SkPath::Verb verb = iter.next(pathPts);
329         switch (verb) {
330             case SkPath::kConic_Verb:
331                 if (convertConicsToQuads) {
332                     SkScalar weight = iter.conicWeight();
333                     SkAutoConicToQuads converter;
334                     const SkPoint* quadPts = converter.computeQuads(pathPts, weight, 0.25f);
335                     for (int i = 0; i < converter.countQuads(); ++i) {
336                         addSrcChoppedQuad(quadPts + 2 * i, !verbsInContour && 0 == i);
337                     }
338                 } else {
339                     SkConic dst[4];
340                     // We chop the conics to create tighter clipping to hide error
341                     // that appears near max curvature of very thin conics. Thin
342                     // hyperbolas with high weight still show error.
343                     int conicCnt = chop_conic(pathPts, dst, iter.conicWeight());
344                     for (int i = 0; i < conicCnt; ++i) {
345                         SkPoint devPts[4];
346                         SkPoint* chopPnts = dst[i].fPts;
347                         m.mapPoints(devPts, chopPnts, 3);
348                         bounds.setBounds(devPts, 3);
349                         bounds.outset(SK_Scalar1, SK_Scalar1);
350                         bounds.roundOut(&ibounds);
351                         if (SkIRect::Intersects(devClipBounds, ibounds)) {
352                             if (is_degen_quad_or_conic(devPts)) {
353                                 SkPoint* pts = lines->push_back_n(4);
354                                 pts[0] = devPts[0];
355                                 pts[1] = devPts[1];
356                                 pts[2] = devPts[1];
357                                 pts[3] = devPts[2];
358                                 if (verbsInContour == 0 && i == 0 && pts[0] == pts[1] &&
359                                     pts[2] == pts[3]) {
360                                     seenZeroLengthVerb = true;
361                                     zeroVerbPt = pts[0];
362                                 }
363                             } else {
364                                 // when in perspective keep conics in src space
365                                 SkPoint* cPts = persp ? chopPnts : devPts;
366                                 SkPoint* pts = conics->push_back_n(3);
367                                 pts[0] = cPts[0];
368                                 pts[1] = cPts[1];
369                                 pts[2] = cPts[2];
370                                 conicWeights->push_back() = dst[i].fW;
371                             }
372                         }
373                     }
374                 }
375                 verbsInContour++;
376                 break;
377             case SkPath::kMove_Verb:
378                 // New contour (and last one was unclosed). If it was just a zero length drawing
379                 // operation, and we're supposed to draw caps, then add a tiny line.
380                 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) {
381                     SkPoint* pts = lines->push_back_n(2);
382                     pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
383                     pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
384                 }
385                 verbsInContour = 0;
386                 seenZeroLengthVerb = false;
387                 break;
388             case SkPath::kLine_Verb: {
389                 SkPoint devPts[2];
390                 m.mapPoints(devPts, pathPts, 2);
391                 bounds.setBounds(devPts, 2);
392                 bounds.outset(SK_Scalar1, SK_Scalar1);
393                 bounds.roundOut(&ibounds);
394                 if (SkIRect::Intersects(devClipBounds, ibounds)) {
395                     SkPoint* pts = lines->push_back_n(2);
396                     pts[0] = devPts[0];
397                     pts[1] = devPts[1];
398                     if (verbsInContour == 0 && pts[0] == pts[1]) {
399                         seenZeroLengthVerb = true;
400                         zeroVerbPt = pts[0];
401                     }
402                 }
403                 verbsInContour++;
404                 break;
405             }
406             case SkPath::kQuad_Verb: {
407                 SkPoint choppedPts[5];
408                 // Chopping the quad helps when the quad is either degenerate or nearly degenerate.
409                 // When it is degenerate it allows the approximation with lines to work since the
410                 // chop point (if there is one) will be at the parabola's vertex. In the nearly
411                 // degenerate the QuadUVMatrix computed for the points is almost singular which
412                 // can cause rendering artifacts.
413                 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts);
414                 for (int i = 0; i < n; ++i) {
415                     addSrcChoppedQuad(choppedPts + i * 2, !verbsInContour && 0 == i);
416                 }
417                 verbsInContour++;
418                 break;
419             }
420             case SkPath::kCubic_Verb: {
421                 SkPoint devPts[4];
422                 m.mapPoints(devPts, pathPts, 4);
423                 bounds.setBounds(devPts, 4);
424                 bounds.outset(SK_Scalar1, SK_Scalar1);
425                 bounds.roundOut(&ibounds);
426                 if (SkIRect::Intersects(devClipBounds, ibounds)) {
427                     PREALLOC_PTARRAY(32) q;
428                     // We convert cubics to quadratics (for now).
429                     // In perspective have to do conversion in src space.
430                     if (persp) {
431                         SkScalar tolScale =
432                             GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, path.getBounds());
433                         GrPathUtils::convertCubicToQuads(pathPts, tolScale, &q);
434                     } else {
435                         GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, &q);
436                     }
437                     for (int i = 0; i < q.size(); i += 3) {
438                         if (persp) {
439                             addSrcChoppedQuad(&q[i], !verbsInContour && 0 == i);
440                         } else {
441                             addChoppedQuad(nullptr, &q[i], !verbsInContour && 0 == i);
442                         }
443                     }
444                 }
445                 verbsInContour++;
446                 break;
447             }
448             case SkPath::kClose_Verb:
449                 // Contour is closed, so we don't need to grow the starting line, unless it's
450                 // *just* a zero length subpath. (SVG Spec 11.4, 'stroke').
451                 if (capLength > 0) {
452                     if (seenZeroLengthVerb && verbsInContour == 1) {
453                         SkPoint* pts = lines->push_back_n(2);
454                         pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
455                         pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
456                     } else if (verbsInContour == 0) {
457                         // Contour was (moveTo, close). Add a line.
458                         SkPoint devPts[2];
459                         m.mapPoints(devPts, pathPts, 1);
460                         devPts[1] = devPts[0];
461                         bounds.setBounds(devPts, 2);
462                         bounds.outset(SK_Scalar1, SK_Scalar1);
463                         bounds.roundOut(&ibounds);
464                         if (SkIRect::Intersects(devClipBounds, ibounds)) {
465                             SkPoint* pts = lines->push_back_n(2);
466                             pts[0] = SkPoint::Make(devPts[0].fX - capLength, devPts[0].fY);
467                             pts[1] = SkPoint::Make(devPts[1].fX + capLength, devPts[1].fY);
468                         }
469                     }
470                 }
471                 break;
472             case SkPath::kDone_Verb:
473                 if (seenZeroLengthVerb && verbsInContour == 1 && capLength > 0) {
474                     // Path ended with a dangling (moveTo, line|quad|etc). If the final verb is
475                     // degenerate, we need to draw a line.
476                     SkPoint* pts = lines->push_back_n(2);
477                     pts[0] = SkPoint::Make(zeroVerbPt.fX - capLength, zeroVerbPt.fY);
478                     pts[1] = SkPoint::Make(zeroVerbPt.fX + capLength, zeroVerbPt.fY);
479                 }
480                 return totalQuadCount;
481         }
482     }
483 }
484 
485 struct LineVertex {
486     SkPoint fPos;
487     float fCoverage;
488 };
489 
490 struct BezierVertex {
491     SkPoint fPos;
492     union {
493         struct {
494             SkScalar fKLM[3];
495         } fConic;
496         SkVector   fQuadCoord;
497         struct {
498             SkScalar fBogus[4];
499         };
500     };
501 };
502 
503 static_assert(sizeof(BezierVertex) == 3 * sizeof(SkPoint));
504 
intersect_lines(const SkPoint & ptA,const SkVector & normA,const SkPoint & ptB,const SkVector & normB,SkPoint * result)505 void intersect_lines(const SkPoint& ptA, const SkVector& normA,
506                      const SkPoint& ptB, const SkVector& normB,
507                      SkPoint* result) {
508 
509     SkScalar lineAW = -normA.dot(ptA);
510     SkScalar lineBW = -normB.dot(ptB);
511 
512     SkScalar wInv = normA.fX * normB.fY - normA.fY * normB.fX;
513     wInv = SkScalarInvert(wInv);
514     if (!SkScalarIsFinite(wInv)) {
515         // lines are parallel, pick the point in between
516         *result = (ptA + ptB)*SK_ScalarHalf;
517         *result += normA;
518     } else {
519         result->fX = normA.fY * lineBW - lineAW * normB.fY;
520         result->fX *= wInv;
521 
522         result->fY = lineAW * normB.fX - normA.fX * lineBW;
523         result->fY *= wInv;
524     }
525 }
526 
set_uv_quad(const SkPoint qpts[3],BezierVertex verts[kQuadNumVertices])527 void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kQuadNumVertices]) {
528     // this should be in the src space, not dev coords, when we have perspective
529     GrPathUtils::QuadUVMatrix DevToUV(qpts);
530     DevToUV.apply(verts, kQuadNumVertices, sizeof(BezierVertex), sizeof(SkPoint));
531 }
532 
bloat_quad(const SkPoint qpts[3],const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex verts[kQuadNumVertices])533 bool bloat_quad(const SkPoint qpts[3],
534                 const SkMatrix* toDevice,
535                 const SkMatrix* toSrc,
536                 BezierVertex verts[kQuadNumVertices]) {
537     SkASSERT(!toDevice == !toSrc);
538     // original quad is specified by tri a,b,c
539     SkPoint a = qpts[0];
540     SkPoint b = qpts[1];
541     SkPoint c = qpts[2];
542 
543     if (toDevice) {
544         toDevice->mapPoints(&a, 1);
545         toDevice->mapPoints(&b, 1);
546         toDevice->mapPoints(&c, 1);
547     }
548     // make a new poly where we replace a and c by a 1-pixel wide edges orthog
549     // to edges ab and bc:
550     //
551     //   before       |        after
552     //                |              b0
553     //         b      |
554     //                |
555     //                |     a0            c0
556     // a         c    |        a1       c1
557     //
558     // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c,
559     // respectively.
560     BezierVertex& a0 = verts[0];
561     BezierVertex& a1 = verts[1];
562     BezierVertex& b0 = verts[2];
563     BezierVertex& c0 = verts[3];
564     BezierVertex& c1 = verts[4];
565 
566     SkVector ab = b;
567     ab -= a;
568     SkVector ac = c;
569     ac -= a;
570     SkVector cb = b;
571     cb -= c;
572 
573     // After the transform (or due to floating point math) we might have a line,
574     // try to do something reasonable
575 
576     bool abNormalized = ab.normalize();
577     bool cbNormalized = cb.normalize();
578 
579     if (!abNormalized) {
580         if (!cbNormalized) {
581             return false;          // Quad is degenerate so we won't add it.
582         }
583 
584         ab = cb;
585     }
586 
587     if (!cbNormalized) {
588         cb = ab;
589     }
590 
591     // We should have already handled degenerates
592     SkASSERT(ab.length() > 0 && cb.length() > 0);
593 
594     SkVector abN = SkPointPriv::MakeOrthog(ab, SkPointPriv::kLeft_Side);
595     if (abN.dot(ac) > 0) {
596         abN.negate();
597     }
598 
599     SkVector cbN = SkPointPriv::MakeOrthog(cb, SkPointPriv::kLeft_Side);
600     if (cbN.dot(ac) < 0) {
601         cbN.negate();
602     }
603 
604     a0.fPos = a;
605     a0.fPos += abN;
606     a1.fPos = a;
607     a1.fPos -= abN;
608 
609     if (toDevice && SkPointPriv::LengthSqd(ac) <= SK_ScalarNearlyZero*SK_ScalarNearlyZero) {
610         c = b;
611     }
612     c0.fPos = c;
613     c0.fPos += cbN;
614     c1.fPos = c;
615     c1.fPos -= cbN;
616 
617     intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos);
618 
619     if (toSrc) {
620         SkMatrixPriv::MapPointsWithStride(*toSrc, &verts[0].fPos, sizeof(BezierVertex),
621                                           kQuadNumVertices);
622     }
623 
624     return true;
625 }
626 
627 // Equations based off of Loop-Blinn Quadratic GPU Rendering
628 // Input Parametric:
629 // P(t) = (P0*(1-t)^2 + 2*w*P1*t*(1-t) + P2*t^2) / (1-t)^2 + 2*w*t*(1-t) + t^2)
630 // Output Implicit:
631 // f(x, y, w) = f(P) = K^2 - LM
632 // K = dot(k, P), L = dot(l, P), M = dot(m, P)
633 // k, l, m are calculated in function GrPathUtils::getConicKLM
set_conic_coeffs(const SkPoint p[3],BezierVertex verts[kQuadNumVertices],const SkScalar weight)634 void set_conic_coeffs(const SkPoint p[3],
635                       BezierVertex verts[kQuadNumVertices],
636                       const SkScalar weight) {
637     SkMatrix klm;
638 
639     GrPathUtils::getConicKLM(p, weight, &klm);
640 
641     for (int i = 0; i < kQuadNumVertices; ++i) {
642         const SkPoint3 pt3 = {verts[i].fPos.x(), verts[i].fPos.y(), 1.f};
643         klm.mapHomogeneousPoints((SkPoint3* ) verts[i].fConic.fKLM, &pt3, 1);
644     }
645 }
646 
add_conics(const SkPoint p[3],const SkScalar weight,const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex ** vert)647 void add_conics(const SkPoint p[3],
648                 const SkScalar weight,
649                 const SkMatrix* toDevice,
650                 const SkMatrix* toSrc,
651                 BezierVertex** vert) {
652     if (bloat_quad(p, toDevice, toSrc, *vert)) {
653         set_conic_coeffs(p, *vert, weight);
654         *vert += kQuadNumVertices;
655     }
656 }
657 
add_quads(const SkPoint p[3],int subdiv,const SkMatrix * toDevice,const SkMatrix * toSrc,BezierVertex ** vert)658 void add_quads(const SkPoint p[3],
659                int subdiv,
660                const SkMatrix* toDevice,
661                const SkMatrix* toSrc,
662                BezierVertex** vert) {
663     SkASSERT(subdiv >= 0);
664     // temporary vertex storage to avoid reading the vertex buffer
665     BezierVertex outVerts[kQuadNumVertices] = {};
666 
667     // storage for the chopped quad
668     // pts 0,1,2 are the first quad, and 2,3,4 the second quad
669     SkPoint choppedQuadPts[5];
670     // start off with our original curve in the second quad slot
671     memcpy(&choppedQuadPts[2], p, 3*sizeof(SkPoint));
672 
673     int stepCount = 1 << subdiv;
674     while (stepCount > 1) {
675         // The general idea is:
676         // * chop the quad using pts 2,3,4 as the input
677         // * write out verts using pts 0,1,2
678         // * now 2,3,4 is the remainder of the curve, chop again until all subdivisions are done
679         SkScalar h = 1.f / stepCount;
680         SkChopQuadAt(&choppedQuadPts[2], choppedQuadPts, h);
681 
682         if (bloat_quad(choppedQuadPts, toDevice, toSrc, outVerts)) {
683             set_uv_quad(choppedQuadPts, outVerts);
684             memcpy(*vert, outVerts, kQuadNumVertices * sizeof(BezierVertex));
685             *vert += kQuadNumVertices;
686         }
687         --stepCount;
688     }
689 
690     // finish up, write out the final quad
691     if (bloat_quad(&choppedQuadPts[2], toDevice, toSrc, outVerts)) {
692         set_uv_quad(&choppedQuadPts[2], outVerts);
693         memcpy(*vert, outVerts, kQuadNumVertices * sizeof(BezierVertex));
694         *vert += kQuadNumVertices;
695     }
696 }
697 
add_line(const SkPoint p[2],const SkMatrix * toSrc,uint8_t coverage,LineVertex ** vert)698 void add_line(const SkPoint p[2],
699               const SkMatrix* toSrc,
700               uint8_t coverage,
701               LineVertex** vert) {
702     const SkPoint& a = p[0];
703     const SkPoint& b = p[1];
704 
705     SkVector ortho, vec = b;
706     vec -= a;
707 
708     SkScalar lengthSqd = SkPointPriv::LengthSqd(vec);
709 
710     if (vec.setLength(SK_ScalarHalf)) {
711         // Create a vector orthogonal to 'vec' and of unit length
712         ortho.fX = 2.0f * vec.fY;
713         ortho.fY = -2.0f * vec.fX;
714 
715         float floatCoverage = GrNormalizeByteToFloat(coverage);
716 
717         if (lengthSqd >= 1.0f) {
718             // Relative to points a and b:
719             // The inner vertices are inset half a pixel along the line a,b
720             (*vert)[0].fPos = a + vec;
721             (*vert)[0].fCoverage = floatCoverage;
722             (*vert)[1].fPos = b - vec;
723             (*vert)[1].fCoverage = floatCoverage;
724         } else {
725             // The inner vertices are inset a distance of length(a,b) from the outer edge of
726             // geometry. For the "a" inset this is the same as insetting from b by half a pixel.
727             // The coverage is then modulated by the length. This gives us the correct
728             // coverage for rects shorter than a pixel as they get translated subpixel amounts
729             // inside of a pixel.
730             SkScalar length = SkScalarSqrt(lengthSqd);
731             (*vert)[0].fPos = b - vec;
732             (*vert)[0].fCoverage = floatCoverage * length;
733             (*vert)[1].fPos = a + vec;
734             (*vert)[1].fCoverage = floatCoverage * length;
735         }
736         // Relative to points a and b:
737         // The outer vertices are outset half a pixel along the line a,b and then a whole pixel
738         // orthogonally.
739         (*vert)[2].fPos = a - vec + ortho;
740         (*vert)[2].fCoverage = 0;
741         (*vert)[3].fPos = b + vec + ortho;
742         (*vert)[3].fCoverage = 0;
743         (*vert)[4].fPos = a - vec - ortho;
744         (*vert)[4].fCoverage = 0;
745         (*vert)[5].fPos = b + vec - ortho;
746         (*vert)[5].fCoverage = 0;
747 
748         if (toSrc) {
749             SkMatrixPriv::MapPointsWithStride(*toSrc, &(*vert)->fPos, sizeof(LineVertex),
750                                               kLineSegNumVertices);
751         }
752     } else {
753         // just make it degenerate and likely offscreen
754         for (int i = 0; i < kLineSegNumVertices; ++i) {
755             (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax);
756         }
757     }
758 
759     *vert += kLineSegNumVertices;
760 }
761 
762 ///////////////////////////////////////////////////////////////////////////////
763 
764 class AAHairlineOp final : public GrMeshDrawOp {
765 private:
766     using Helper = GrSimpleMeshDrawOpHelperWithStencil;
767 
768 public:
769     DEFINE_OP_CLASS_ID
770 
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkPath & path,const GrStyle & style,const SkIRect & devClipBounds,const GrUserStencilSettings * stencilSettings)771     static GrOp::Owner Make(GrRecordingContext* context,
772                             GrPaint&& paint,
773                             const SkMatrix& viewMatrix,
774                             const SkPath& path,
775                             const GrStyle& style,
776                             const SkIRect& devClipBounds,
777                             const GrUserStencilSettings* stencilSettings) {
778         SkScalar hairlineCoverage;
779         uint8_t newCoverage = 0xff;
780         if (GrIsStrokeHairlineOrEquivalent(style, viewMatrix, &hairlineCoverage)) {
781             newCoverage = SkScalarRoundToInt(hairlineCoverage * 0xff);
782         }
783 
784         const SkStrokeRec& stroke = style.strokeRec();
785         SkScalar capLength = SkPaint::kButt_Cap != stroke.getCap() ? hairlineCoverage * 0.5f : 0.0f;
786 
787         return Helper::FactoryHelper<AAHairlineOp>(context, std::move(paint), newCoverage,
788                                                    viewMatrix, path,
789                                                    devClipBounds, capLength, stencilSettings);
790     }
791 
AAHairlineOp(GrProcessorSet * processorSet,const SkPMColor4f & color,uint8_t coverage,const SkMatrix & viewMatrix,const SkPath & path,SkIRect devClipBounds,SkScalar capLength,const GrUserStencilSettings * stencilSettings)792     AAHairlineOp(GrProcessorSet* processorSet,
793                  const SkPMColor4f& color,
794                  uint8_t coverage,
795                  const SkMatrix& viewMatrix,
796                  const SkPath& path,
797                  SkIRect devClipBounds,
798                  SkScalar capLength,
799                  const GrUserStencilSettings* stencilSettings)
800             : INHERITED(ClassID())
801             , fHelper(processorSet, GrAAType::kCoverage, stencilSettings)
802             , fColor(color)
803             , fCoverage(coverage) {
804         fPaths.emplace_back(PathData{viewMatrix, path, devClipBounds, capLength});
805 
806         this->setTransformedBounds(path.getBounds(), viewMatrix, HasAABloat::kYes,
807                                    IsHairline::kYes);
808     }
809 
name() const810     const char* name() const override { return "AAHairlineOp"; }
811 
visitProxies(const GrVisitProxyFunc & func) const812     void visitProxies(const GrVisitProxyFunc& func) const override {
813 
814         bool visited = false;
815         for (int i = 0; i < 3; ++i) {
816             if (fProgramInfos[i]) {
817                 fProgramInfos[i]->visitFPProxies(func);
818                 visited = true;
819             }
820         }
821 
822         if (!visited) {
823             fHelper.visitProxies(func);
824         }
825     }
826 
fixedFunctionFlags() const827     FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
828 
finalize(const GrCaps & caps,const GrAppliedClip * clip,GrClampType clampType)829     GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
830                                       GrClampType clampType) override {
831         // This Op uses uniform (not vertex) color, so doesn't need to track wide color.
832         return fHelper.finalizeProcessors(caps, clip, clampType,
833                                           GrProcessorAnalysisCoverage::kSingleChannel, &fColor,
834                                           nullptr);
835     }
836 
837     enum class Program : uint8_t {
838         kNone  = 0x0,
839         kLine  = 0x1,
840         kQuad  = 0x2,
841         kConic = 0x4,
842     };
843 
844 private:
845     void makeLineProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
846                              const GrSurfaceProxyView& writeView,
847                              bool usesMSAASurface,
848                              const SkMatrix* geometryProcessorViewM,
849                              const SkMatrix* geometryProcessorLocalM,
850                              GrXferBarrierFlags renderPassXferBarriers,
851                              GrLoadOp colorLoadOp);
852     void makeQuadProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
853                              const GrSurfaceProxyView& writeView,
854                              bool usesMSAASurface,
855                              const SkMatrix* geometryProcessorViewM,
856                              const SkMatrix* geometryProcessorLocalM,
857                              GrXferBarrierFlags renderPassXferBarriers,
858                              GrLoadOp colorLoadOp);
859     void makeConicProgramInfo(const GrCaps&, SkArenaAlloc*, const GrPipeline*,
860                               const GrSurfaceProxyView& writeView,
861                               bool usesMSAASurface,
862                               const SkMatrix* geometryProcessorViewM,
863                               const SkMatrix* geometryProcessorLocalM,
864                               GrXferBarrierFlags renderPassXferBarriers,
865                               GrLoadOp colorLoadOp);
866 
programInfo()867     GrProgramInfo* programInfo() override {
868         // This Op has 3 programInfos and implements its own onPrePrepareDraws so this entry point
869         // should really never be called.
870         SkASSERT(0);
871         return nullptr;
872     }
873 
874     Program predictPrograms(const GrCaps*) const;
875 
876     void onCreateProgramInfo(const GrCaps*,
877                              SkArenaAlloc*,
878                              const GrSurfaceProxyView& writeView,
879                              bool usesMSAASurface,
880                              GrAppliedClip&&,
881                              const GrDstProxyView&,
882                              GrXferBarrierFlags renderPassXferBarriers,
883                              GrLoadOp colorLoadOp) override;
884 
885     void onPrePrepareDraws(GrRecordingContext*,
886                            const GrSurfaceProxyView& writeView,
887                            GrAppliedClip*,
888                            const GrDstProxyView&,
889                            GrXferBarrierFlags renderPassXferBarriers,
890                            GrLoadOp colorLoadOp) override;
891 
892     void onPrepareDraws(GrMeshDrawTarget*) override;
893     void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
894 
onCombineIfPossible(GrOp * t,SkArenaAlloc *,const GrCaps & caps)895     CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
896         AAHairlineOp* that = t->cast<AAHairlineOp>();
897 
898         if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
899             return CombineResult::kCannotCombine;
900         }
901 
902         if (this->viewMatrix().hasPerspective() != that->viewMatrix().hasPerspective()) {
903             return CombineResult::kCannotCombine;
904         }
905 
906         // We go to identity if we don't have perspective
907         if (this->viewMatrix().hasPerspective() &&
908             !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix())) {
909             return CombineResult::kCannotCombine;
910         }
911 
912         // TODO we can actually combine hairlines if they are the same color in a kind of bulk
913         // method but we haven't implemented this yet
914         // TODO investigate going to vertex color and coverage?
915         if (this->coverage() != that->coverage()) {
916             return CombineResult::kCannotCombine;
917         }
918 
919         if (this->color() != that->color()) {
920             return CombineResult::kCannotCombine;
921         }
922 
923         if (fHelper.usesLocalCoords() && !SkMatrixPriv::CheapEqual(this->viewMatrix(),
924                                                                    that->viewMatrix())) {
925             return CombineResult::kCannotCombine;
926         }
927 
928         fPaths.push_back_n(that->fPaths.size(), that->fPaths.begin());
929         return CombineResult::kMerged;
930     }
931 
932 #if GR_TEST_UTILS
onDumpInfo() const933     SkString onDumpInfo() const override {
934         return SkStringPrintf("Color: 0x%08x Coverage: 0x%02x, Count: %d\n%s",
935                               fColor.toBytes_RGBA(), fCoverage, fPaths.size(),
936                               fHelper.dumpInfo().c_str());
937     }
938 #endif
939 
color() const940     const SkPMColor4f& color() const { return fColor; }
coverage() const941     uint8_t coverage() const { return fCoverage; }
viewMatrix() const942     const SkMatrix& viewMatrix() const { return fPaths[0].fViewMatrix; }
943 
944     struct PathData {
945         SkMatrix fViewMatrix;
946         SkPath fPath;
947         SkIRect fDevClipBounds;
948         SkScalar fCapLength;
949     };
950 
951     SkSTArray<1, PathData, true> fPaths;
952     Helper fHelper;
953     SkPMColor4f fColor;
954     uint8_t fCoverage;
955 
956     Program        fCharacterization = Program::kNone;       // holds a mask of required programs
957     GrSimpleMesh*  fMeshes[3] = { nullptr };
958     GrProgramInfo* fProgramInfos[3] = { nullptr };
959 
960     using INHERITED = GrMeshDrawOp;
961 };
962 
GR_MAKE_BITFIELD_CLASS_OPS(AAHairlineOp::Program)963 GR_MAKE_BITFIELD_CLASS_OPS(AAHairlineOp::Program)
964 
965 void AAHairlineOp::makeLineProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
966                                        const GrPipeline* pipeline,
967                                        const GrSurfaceProxyView& writeView,
968                                        bool usesMSAASurface,
969                                        const SkMatrix* geometryProcessorViewM,
970                                        const SkMatrix* geometryProcessorLocalM,
971                                        GrXferBarrierFlags renderPassXferBarriers,
972                                        GrLoadOp colorLoadOp) {
973     if (fProgramInfos[0]) {
974         return;
975     }
976 
977     GrGeometryProcessor* lineGP;
978     {
979         using namespace GrDefaultGeoProcFactory;
980 
981         Color color(this->color());
982         LocalCoords localCoords(fHelper.usesLocalCoords() ? LocalCoords::kUsePosition_Type
983                                                           : LocalCoords::kUnused_Type);
984         localCoords.fMatrix = geometryProcessorLocalM;
985 
986         lineGP = GrDefaultGeoProcFactory::Make(arena,
987                                                color,
988                                                Coverage::kAttribute_Type,
989                                                localCoords,
990                                                *geometryProcessorViewM);
991         SkASSERT(sizeof(LineVertex) == lineGP->vertexStride());
992     }
993 
994     fProgramInfos[0] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
995             &caps, arena, pipeline, writeView, usesMSAASurface, lineGP, GrPrimitiveType::kTriangles,
996             renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings());
997 }
998 
makeQuadProgramInfo(const GrCaps & caps,SkArenaAlloc * arena,const GrPipeline * pipeline,const GrSurfaceProxyView & writeView,bool usesMSAASurface,const SkMatrix * geometryProcessorViewM,const SkMatrix * geometryProcessorLocalM,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)999 void AAHairlineOp::makeQuadProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
1000                                        const GrPipeline* pipeline,
1001                                        const GrSurfaceProxyView& writeView,
1002                                        bool usesMSAASurface,
1003                                        const SkMatrix* geometryProcessorViewM,
1004                                        const SkMatrix* geometryProcessorLocalM,
1005                                        GrXferBarrierFlags renderPassXferBarriers,
1006                                        GrLoadOp colorLoadOp) {
1007     if (fProgramInfos[1]) {
1008         return;
1009     }
1010 
1011     GrGeometryProcessor* quadGP = GrQuadEffect::Make(arena,
1012                                                      this->color(),
1013                                                      *geometryProcessorViewM,
1014                                                      caps,
1015                                                      *geometryProcessorLocalM,
1016                                                      fHelper.usesLocalCoords(),
1017                                                      this->coverage());
1018     SkASSERT(sizeof(BezierVertex) == quadGP->vertexStride());
1019 
1020     fProgramInfos[1] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
1021             &caps, arena, pipeline, writeView, usesMSAASurface, quadGP, GrPrimitiveType::kTriangles,
1022             renderPassXferBarriers, colorLoadOp, fHelper.stencilSettings());
1023 }
1024 
makeConicProgramInfo(const GrCaps & caps,SkArenaAlloc * arena,const GrPipeline * pipeline,const GrSurfaceProxyView & writeView,bool usesMSAASurface,const SkMatrix * geometryProcessorViewM,const SkMatrix * geometryProcessorLocalM,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1025 void AAHairlineOp::makeConicProgramInfo(const GrCaps& caps, SkArenaAlloc* arena,
1026                                         const GrPipeline* pipeline,
1027                                         const GrSurfaceProxyView& writeView,
1028                                         bool usesMSAASurface,
1029                                         const SkMatrix* geometryProcessorViewM,
1030                                         const SkMatrix* geometryProcessorLocalM,
1031                                         GrXferBarrierFlags renderPassXferBarriers,
1032                                         GrLoadOp colorLoadOp) {
1033     if (fProgramInfos[2]) {
1034         return;
1035     }
1036 
1037     GrGeometryProcessor* conicGP = GrConicEffect::Make(arena,
1038                                                        this->color(),
1039                                                        *geometryProcessorViewM,
1040                                                        caps,
1041                                                        *geometryProcessorLocalM,
1042                                                        fHelper.usesLocalCoords(),
1043                                                        this->coverage());
1044     SkASSERT(sizeof(BezierVertex) == conicGP->vertexStride());
1045 
1046     fProgramInfos[2] = GrSimpleMeshDrawOpHelper::CreateProgramInfo(
1047             &caps, arena, pipeline, writeView, usesMSAASurface, conicGP,
1048             GrPrimitiveType::kTriangles, renderPassXferBarriers, colorLoadOp,
1049             fHelper.stencilSettings());
1050 }
1051 
predictPrograms(const GrCaps * caps) const1052 AAHairlineOp::Program AAHairlineOp::predictPrograms(const GrCaps* caps) const {
1053     bool convertConicsToQuads = !caps->shaderCaps()->fFloatIs32Bits;
1054 
1055     // When predicting the programs we always include the lineProgram bc it is used as a fallback
1056     // for quads and conics. In non-DDL mode there are cases where it sometimes isn't needed for a
1057     // given path.
1058     Program neededPrograms = Program::kLine;
1059 
1060     for (int i = 0; i < fPaths.size(); i++) {
1061         uint32_t mask = fPaths[i].fPath.getSegmentMasks();
1062 
1063         if (mask & (SkPath::kQuad_SegmentMask | SkPath::kCubic_SegmentMask)) {
1064             neededPrograms |= Program::kQuad;
1065         }
1066         if (mask & SkPath::kConic_SegmentMask) {
1067             if (convertConicsToQuads) {
1068                 neededPrograms |= Program::kQuad;
1069             } else {
1070                 neededPrograms |= Program::kConic;
1071             }
1072         }
1073     }
1074 
1075     return neededPrograms;
1076 }
1077 
onCreateProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView & writeView,bool usesMSAASurface,GrAppliedClip && appliedClip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1078 void AAHairlineOp::onCreateProgramInfo(const GrCaps* caps,
1079                                        SkArenaAlloc* arena,
1080                                        const GrSurfaceProxyView& writeView,
1081                                        bool usesMSAASurface,
1082                                        GrAppliedClip&& appliedClip,
1083                                        const GrDstProxyView& dstProxyView,
1084                                        GrXferBarrierFlags renderPassXferBarriers,
1085                                        GrLoadOp colorLoadOp) {
1086     // Setup the viewmatrix and localmatrix for the GrGeometryProcessor.
1087     SkMatrix invert;
1088     if (!this->viewMatrix().invert(&invert)) {
1089         return;
1090     }
1091 
1092     // we will transform to identity space if the viewmatrix does not have perspective
1093     bool hasPerspective = this->viewMatrix().hasPerspective();
1094     const SkMatrix* geometryProcessorViewM = &SkMatrix::I();
1095     const SkMatrix* geometryProcessorLocalM = &invert;
1096     if (hasPerspective) {
1097         geometryProcessorViewM = &this->viewMatrix();
1098         geometryProcessorLocalM = &SkMatrix::I();
1099     }
1100 
1101     auto pipeline = fHelper.createPipeline(caps, arena, writeView.swizzle(),
1102                                            std::move(appliedClip), dstProxyView);
1103 
1104     if (fCharacterization & Program::kLine) {
1105         this->makeLineProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1106                                   geometryProcessorViewM, geometryProcessorLocalM,
1107                                   renderPassXferBarriers, colorLoadOp);
1108     }
1109     if (fCharacterization & Program::kQuad) {
1110         this->makeQuadProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1111                                   geometryProcessorViewM, geometryProcessorLocalM,
1112                                   renderPassXferBarriers, colorLoadOp);
1113     }
1114     if (fCharacterization & Program::kConic) {
1115         this->makeConicProgramInfo(*caps, arena, pipeline, writeView, usesMSAASurface,
1116                                    geometryProcessorViewM, geometryProcessorLocalM,
1117                                    renderPassXferBarriers, colorLoadOp);
1118 
1119     }
1120 }
1121 
onPrePrepareDraws(GrRecordingContext * context,const GrSurfaceProxyView & writeView,GrAppliedClip * clip,const GrDstProxyView & dstProxyView,GrXferBarrierFlags renderPassXferBarriers,GrLoadOp colorLoadOp)1122 void AAHairlineOp::onPrePrepareDraws(GrRecordingContext* context,
1123                                      const GrSurfaceProxyView& writeView,
1124                                      GrAppliedClip* clip,
1125                                      const GrDstProxyView& dstProxyView,
1126                                      GrXferBarrierFlags renderPassXferBarriers,
1127                                      GrLoadOp colorLoadOp) {
1128     SkArenaAlloc* arena = context->priv().recordTimeAllocator();
1129     const GrCaps* caps = context->priv().caps();
1130 
1131     // http://skbug.com/12201 -- DDL does not yet support DMSAA.
1132     bool usesMSAASurface = writeView.asRenderTargetProxy()->numSamples() > 1;
1133 
1134     // This is equivalent to a GrOpFlushState::detachAppliedClip
1135     GrAppliedClip appliedClip = clip ? std::move(*clip) : GrAppliedClip::Disabled();
1136 
1137     // Conservatively predict which programs will be required
1138     fCharacterization = this->predictPrograms(caps);
1139 
1140     this->createProgramInfo(caps, arena, writeView, usesMSAASurface, std::move(appliedClip),
1141                             dstProxyView, renderPassXferBarriers, colorLoadOp);
1142 
1143     context->priv().recordProgramInfo(fProgramInfos[0]);
1144     context->priv().recordProgramInfo(fProgramInfos[1]);
1145     context->priv().recordProgramInfo(fProgramInfos[2]);
1146 }
1147 
onPrepareDraws(GrMeshDrawTarget * target)1148 void AAHairlineOp::onPrepareDraws(GrMeshDrawTarget* target) {
1149     // Setup the viewmatrix and localmatrix for the GrGeometryProcessor.
1150     SkMatrix invert;
1151     if (!this->viewMatrix().invert(&invert)) {
1152         return;
1153     }
1154 
1155     // we will transform to identity space if the viewmatrix does not have perspective
1156     const SkMatrix* toDevice = nullptr;
1157     const SkMatrix* toSrc = nullptr;
1158     if (this->viewMatrix().hasPerspective()) {
1159         toDevice = &this->viewMatrix();
1160         toSrc = &invert;
1161     }
1162 
1163     SkDEBUGCODE(Program predictedPrograms = this->predictPrograms(&target->caps()));
1164     Program actualPrograms = Program::kNone;
1165 
1166     // This is hand inlined for maximum performance.
1167     PREALLOC_PTARRAY(128) lines;
1168     PREALLOC_PTARRAY(128) quads;
1169     PREALLOC_PTARRAY(128) conics;
1170     IntArray qSubdivs;
1171     FloatArray cWeights;
1172     int quadCount = 0;
1173 
1174     int instanceCount = fPaths.size();
1175     bool convertConicsToQuads = !target->caps().shaderCaps()->fFloatIs32Bits;
1176     for (int i = 0; i < instanceCount; i++) {
1177         const PathData& args = fPaths[i];
1178         quadCount += gather_lines_and_quads(args.fPath, args.fViewMatrix, args.fDevClipBounds,
1179                                             args.fCapLength, convertConicsToQuads, &lines, &quads,
1180                                             &conics, &qSubdivs, &cWeights);
1181     }
1182 
1183     int lineCount = lines.size() / 2;
1184     int conicCount = conics.size() / 3;
1185     int quadAndConicCount = conicCount + quadCount;
1186 
1187     static constexpr int kMaxLines = SK_MaxS32 / kLineSegNumVertices;
1188     static constexpr int kMaxQuadsAndConics = SK_MaxS32 / kQuadNumVertices;
1189     if (lineCount > kMaxLines || quadAndConicCount > kMaxQuadsAndConics) {
1190         return;
1191     }
1192 
1193     // do lines first
1194     if (lineCount) {
1195         SkASSERT(predictedPrograms & Program::kLine);
1196         actualPrograms |= Program::kLine;
1197 
1198         sk_sp<const GrBuffer> linesIndexBuffer = get_lines_index_buffer(target->resourceProvider());
1199 
1200         GrMeshDrawOp::PatternHelper helper(target, GrPrimitiveType::kTriangles, sizeof(LineVertex),
1201                                            std::move(linesIndexBuffer), kLineSegNumVertices,
1202                                            kIdxsPerLineSeg, lineCount, kLineSegsNumInIdxBuffer);
1203 
1204         LineVertex* verts = reinterpret_cast<LineVertex*>(helper.vertices());
1205         if (!verts) {
1206             SkDebugf("Could not allocate vertices\n");
1207             return;
1208         }
1209 
1210         for (int i = 0; i < lineCount; ++i) {
1211             add_line(&lines[2*i], toSrc, this->coverage(), &verts);
1212         }
1213 
1214         fMeshes[0] = helper.mesh();
1215     }
1216 
1217     if (quadCount || conicCount) {
1218         sk_sp<const GrBuffer> vertexBuffer;
1219         int firstVertex;
1220 
1221         sk_sp<const GrBuffer> quadsIndexBuffer = get_quads_index_buffer(target->resourceProvider());
1222 
1223         int vertexCount = kQuadNumVertices * quadAndConicCount;
1224         void* vertices = target->makeVertexSpace(sizeof(BezierVertex), vertexCount, &vertexBuffer,
1225                                                  &firstVertex);
1226 
1227         if (!vertices || !quadsIndexBuffer) {
1228             SkDebugf("Could not allocate vertices\n");
1229             return;
1230         }
1231 
1232         // Setup vertices
1233         BezierVertex* bezVerts = reinterpret_cast<BezierVertex*>(vertices);
1234 
1235         int unsubdivQuadCnt = quads.size() / 3;
1236         for (int i = 0; i < unsubdivQuadCnt; ++i) {
1237             SkASSERT(qSubdivs[i] >= 0);
1238             if (!quads[3*i].isFinite() || !quads[3*i+1].isFinite() || !quads[3*i+2].isFinite()) {
1239                 return;
1240             }
1241             add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &bezVerts);
1242         }
1243 
1244         // Start Conics
1245         for (int i = 0; i < conicCount; ++i) {
1246             add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &bezVerts);
1247         }
1248 
1249         if (quadCount > 0) {
1250             SkASSERT(predictedPrograms & Program::kQuad);
1251             actualPrograms |= Program::kQuad;
1252 
1253             fMeshes[1] = target->allocMesh();
1254             fMeshes[1]->setIndexedPatterned(quadsIndexBuffer, kIdxsPerQuad, quadCount,
1255                                             kQuadsNumInIdxBuffer, vertexBuffer, kQuadNumVertices,
1256                                             firstVertex);
1257             firstVertex += quadCount * kQuadNumVertices;
1258         }
1259 
1260         if (conicCount > 0) {
1261             SkASSERT(predictedPrograms & Program::kConic);
1262             actualPrograms |= Program::kConic;
1263 
1264             fMeshes[2] = target->allocMesh();
1265             fMeshes[2]->setIndexedPatterned(std::move(quadsIndexBuffer), kIdxsPerQuad, conicCount,
1266                                             kQuadsNumInIdxBuffer, std::move(vertexBuffer),
1267                                             kQuadNumVertices, firstVertex);
1268         }
1269     }
1270 
1271     // In DDL mode this will replace the predicted program requirements with the actual ones.
1272     // However, we will already have surfaced the predicted programs to the DDL.
1273     fCharacterization = actualPrograms;
1274 }
1275 
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)1276 void AAHairlineOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
1277     this->createProgramInfo(flushState);
1278 
1279     for (int i = 0; i < 3; ++i) {
1280         if (fProgramInfos[i] && fMeshes[i]) {
1281             flushState->bindPipelineAndScissorClip(*fProgramInfos[i], chainBounds);
1282             flushState->bindTextures(fProgramInfos[i]->geomProc(), nullptr,
1283                                      fProgramInfos[i]->pipeline());
1284             flushState->drawMesh(*fMeshes[i]);
1285         }
1286     }
1287 }
1288 
1289 } // anonymous namespace
1290 
1291 ///////////////////////////////////////////////////////////////////////////////////////////////////
1292 
1293 #if GR_TEST_UTILS
1294 
GR_DRAW_OP_TEST_DEFINE(AAHairlineOp)1295 GR_DRAW_OP_TEST_DEFINE(AAHairlineOp) {
1296     SkMatrix viewMatrix = GrTest::TestMatrix(random);
1297     const SkPath& path = GrTest::TestPath(random);
1298     SkIRect devClipBounds;
1299     devClipBounds.setEmpty();
1300     return AAHairlineOp::Make(context, std::move(paint), viewMatrix, path,
1301                               GrStyle::SimpleHairline(), devClipBounds,
1302                               GrGetRandomStencil(random, context));
1303 }
1304 
1305 #endif
1306 
1307 ///////////////////////////////////////////////////////////////////////////////////////////////////
1308 
1309 namespace skgpu::v1 {
1310 
onCanDrawPath(const CanDrawPathArgs & args) const1311 PathRenderer::CanDrawPath AAHairLinePathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
1312     if (GrAAType::kCoverage != args.fAAType) {
1313         return CanDrawPath::kNo;
1314     }
1315 
1316     if (!GrIsStrokeHairlineOrEquivalent(args.fShape->style(), *args.fViewMatrix, nullptr)) {
1317         return CanDrawPath::kNo;
1318     }
1319 
1320     // We don't currently handle dashing in this class though perhaps we should.
1321     if (args.fShape->style().pathEffect()) {
1322         return CanDrawPath::kNo;
1323     }
1324 
1325     if (SkPath::kLine_SegmentMask == args.fShape->segmentMask() ||
1326         args.fCaps->shaderCaps()->fShaderDerivativeSupport) {
1327         return CanDrawPath::kYes;
1328     }
1329 
1330     return CanDrawPath::kNo;
1331 }
1332 
1333 
onDrawPath(const DrawPathArgs & args)1334 bool AAHairLinePathRenderer::onDrawPath(const DrawPathArgs& args) {
1335     GR_AUDIT_TRAIL_AUTO_FRAME(args.fContext->priv().auditTrail(),
1336                               "AAHairlinePathRenderer::onDrawPath");
1337     SkASSERT(args.fSurfaceDrawContext->numSamples() <= 1);
1338 
1339     SkPath path;
1340     args.fShape->asPath(&path);
1341     GrOp::Owner op =
1342             AAHairlineOp::Make(args.fContext, std::move(args.fPaint), *args.fViewMatrix, path,
1343                                args.fShape->style(), *args.fClipConservativeBounds,
1344                                args.fUserStencilSettings);
1345     args.fSurfaceDrawContext->addDrawOp(args.fClip, std::move(op));
1346     return true;
1347 }
1348 
1349 } // namespace skgpu::v1
1350