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