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