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