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 10 #include "GrContext.h" 11 #include "GrDrawState.h" 12 #include "GrDrawTargetCaps.h" 13 #include "GrEffect.h" 14 #include "GrGpu.h" 15 #include "GrIndexBuffer.h" 16 #include "GrPathUtils.h" 17 #include "GrTBackendEffectFactory.h" 18 #include "SkGeometry.h" 19 #include "SkStroke.h" 20 #include "SkTemplates.h" 21 22 #include "effects/GrBezierEffect.h" 23 24 namespace { 25 // quadratics are rendered as 5-sided polys in order to bound the 26 // AA stroke around the center-curve. See comments in push_quad_index_buffer and 27 // bloat_quad. Quadratics and conics share an index buffer 28 static const int kVertsPerQuad = 5; 29 static const int kIdxsPerQuad = 9; 30 31 // lines are rendered as: 32 // *______________* 33 // |\ -_______ /| 34 // | \ \ / | 35 // | *--------* | 36 // | / ______/ \ | 37 // */_-__________\* 38 // For: 6 vertices and 18 indices (for 6 triangles) 39 static const int kVertsPerLineSeg = 6; 40 static const int kIdxsPerLineSeg = 18; 41 42 static const int kNumQuadsInIdxBuffer = 256; 43 static const size_t kQuadIdxSBufize = kIdxsPerQuad * 44 sizeof(uint16_t) * 45 kNumQuadsInIdxBuffer; 46 47 static const int kNumLineSegsInIdxBuffer = 256; 48 static const size_t kLineSegIdxSBufize = kIdxsPerLineSeg * 49 sizeof(uint16_t) * 50 kNumLineSegsInIdxBuffer; 51 52 static bool push_quad_index_data(GrIndexBuffer* qIdxBuffer) { 53 uint16_t* data = (uint16_t*) qIdxBuffer->lock(); 54 bool tempData = NULL == data; 55 if (tempData) { 56 data = SkNEW_ARRAY(uint16_t, kNumQuadsInIdxBuffer * kIdxsPerQuad); 57 } 58 for (int i = 0; i < kNumQuadsInIdxBuffer; ++i) { 59 60 // Each quadratic is rendered as a five sided polygon. This poly bounds 61 // the quadratic's bounding triangle but has been expanded so that the 62 // 1-pixel wide area around the curve is inside the poly. 63 // If a,b,c are the original control points then the poly a0,b0,c0,c1,a1 64 // that is rendered would look like this: 65 // b0 66 // b 67 // 68 // a0 c0 69 // a c 70 // a1 c1 71 // Each is drawn as three triangles specified by these 9 indices: 72 int baseIdx = i * kIdxsPerQuad; 73 uint16_t baseVert = (uint16_t)(i * kVertsPerQuad); 74 data[0 + baseIdx] = baseVert + 0; // a0 75 data[1 + baseIdx] = baseVert + 1; // a1 76 data[2 + baseIdx] = baseVert + 2; // b0 77 data[3 + baseIdx] = baseVert + 2; // b0 78 data[4 + baseIdx] = baseVert + 4; // c1 79 data[5 + baseIdx] = baseVert + 3; // c0 80 data[6 + baseIdx] = baseVert + 1; // a1 81 data[7 + baseIdx] = baseVert + 4; // c1 82 data[8 + baseIdx] = baseVert + 2; // b0 83 } 84 if (tempData) { 85 bool ret = qIdxBuffer->updateData(data, kQuadIdxSBufize); 86 delete[] data; 87 return ret; 88 } else { 89 qIdxBuffer->unlock(); 90 return true; 91 } 92 } 93 94 static bool push_line_index_data(GrIndexBuffer* lIdxBuffer) { 95 uint16_t* data = (uint16_t*) lIdxBuffer->lock(); 96 bool tempData = NULL == data; 97 if (tempData) { 98 data = SkNEW_ARRAY(uint16_t, kNumLineSegsInIdxBuffer * kIdxsPerLineSeg); 99 } 100 for (int i = 0; i < kNumLineSegsInIdxBuffer; ++i) { 101 // Each line segment is rendered as two quads and two triangles. 102 // p0 and p1 have alpha = 1 while all other points have alpha = 0. 103 // The four external points are offset 1 pixel perpendicular to the 104 // line and half a pixel parallel to the line. 105 // 106 // p4 p5 107 // p0 p1 108 // p2 p3 109 // 110 // Each is drawn as six triangles specified by these 18 indices: 111 int baseIdx = i * kIdxsPerLineSeg; 112 uint16_t baseVert = (uint16_t)(i * kVertsPerLineSeg); 113 data[0 + baseIdx] = baseVert + 0; 114 data[1 + baseIdx] = baseVert + 1; 115 data[2 + baseIdx] = baseVert + 3; 116 117 data[3 + baseIdx] = baseVert + 0; 118 data[4 + baseIdx] = baseVert + 3; 119 data[5 + baseIdx] = baseVert + 2; 120 121 data[6 + baseIdx] = baseVert + 0; 122 data[7 + baseIdx] = baseVert + 4; 123 data[8 + baseIdx] = baseVert + 5; 124 125 data[9 + baseIdx] = baseVert + 0; 126 data[10+ baseIdx] = baseVert + 5; 127 data[11+ baseIdx] = baseVert + 1; 128 129 data[12 + baseIdx] = baseVert + 0; 130 data[13 + baseIdx] = baseVert + 2; 131 data[14 + baseIdx] = baseVert + 4; 132 133 data[15 + baseIdx] = baseVert + 1; 134 data[16 + baseIdx] = baseVert + 5; 135 data[17 + baseIdx] = baseVert + 3; 136 } 137 if (tempData) { 138 bool ret = lIdxBuffer->updateData(data, kLineSegIdxSBufize); 139 delete[] data; 140 return ret; 141 } else { 142 lIdxBuffer->unlock(); 143 return true; 144 } 145 } 146 } 147 148 GrPathRenderer* GrAAHairLinePathRenderer::Create(GrContext* context) { 149 GrGpu* gpu = context->getGpu(); 150 GrIndexBuffer* qIdxBuf = gpu->createIndexBuffer(kQuadIdxSBufize, false); 151 SkAutoTUnref<GrIndexBuffer> qIdxBuffer(qIdxBuf); 152 if (NULL == qIdxBuf || !push_quad_index_data(qIdxBuf)) { 153 return NULL; 154 } 155 GrIndexBuffer* lIdxBuf = gpu->createIndexBuffer(kLineSegIdxSBufize, false); 156 SkAutoTUnref<GrIndexBuffer> lIdxBuffer(lIdxBuf); 157 if (NULL == lIdxBuf || !push_line_index_data(lIdxBuf)) { 158 return NULL; 159 } 160 return SkNEW_ARGS(GrAAHairLinePathRenderer, 161 (context, lIdxBuf, qIdxBuf)); 162 } 163 164 GrAAHairLinePathRenderer::GrAAHairLinePathRenderer( 165 const GrContext* context, 166 const GrIndexBuffer* linesIndexBuffer, 167 const GrIndexBuffer* quadsIndexBuffer) { 168 fLinesIndexBuffer = linesIndexBuffer; 169 linesIndexBuffer->ref(); 170 fQuadsIndexBuffer = quadsIndexBuffer; 171 quadsIndexBuffer->ref(); 172 } 173 174 GrAAHairLinePathRenderer::~GrAAHairLinePathRenderer() { 175 fLinesIndexBuffer->unref(); 176 fQuadsIndexBuffer->unref(); 177 } 178 179 namespace { 180 181 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true> 182 183 // Takes 178th time of logf on Z600 / VC2010 184 int get_float_exp(float x) { 185 GR_STATIC_ASSERT(sizeof(int) == sizeof(float)); 186 #ifdef SK_DEBUG 187 static bool tested; 188 if (!tested) { 189 tested = true; 190 SkASSERT(get_float_exp(0.25f) == -2); 191 SkASSERT(get_float_exp(0.3f) == -2); 192 SkASSERT(get_float_exp(0.5f) == -1); 193 SkASSERT(get_float_exp(1.f) == 0); 194 SkASSERT(get_float_exp(2.f) == 1); 195 SkASSERT(get_float_exp(2.5f) == 1); 196 SkASSERT(get_float_exp(8.f) == 3); 197 SkASSERT(get_float_exp(100.f) == 6); 198 SkASSERT(get_float_exp(1000.f) == 9); 199 SkASSERT(get_float_exp(1024.f) == 10); 200 SkASSERT(get_float_exp(3000000.f) == 21); 201 } 202 #endif 203 const int* iptr = (const int*)&x; 204 return (((*iptr) & 0x7f800000) >> 23) - 127; 205 } 206 207 // Uses the max curvature function for quads to estimate 208 // where to chop the conic. If the max curvature is not 209 // found along the curve segment it will return 1 and 210 // dst[0] is the original conic. If it returns 2 the dst[0] 211 // and dst[1] are the two new conics. 212 int split_conic(const SkPoint src[3], SkConic dst[2], const SkScalar weight) { 213 SkScalar t = SkFindQuadMaxCurvature(src); 214 if (t == 0) { 215 if (dst) { 216 dst[0].set(src, weight); 217 } 218 return 1; 219 } else { 220 if (dst) { 221 SkConic conic; 222 conic.set(src, weight); 223 conic.chopAt(t, dst); 224 } 225 return 2; 226 } 227 } 228 229 // Calls split_conic on the entire conic and then once more on each subsection. 230 // Most cases will result in either 1 conic (chop point is not within t range) 231 // or 3 points (split once and then one subsection is split again). 232 int chop_conic(const SkPoint src[3], SkConic dst[4], const SkScalar weight) { 233 SkConic dstTemp[2]; 234 int conicCnt = split_conic(src, dstTemp, weight); 235 if (2 == conicCnt) { 236 int conicCnt2 = split_conic(dstTemp[0].fPts, dst, dstTemp[0].fW); 237 conicCnt = conicCnt2 + split_conic(dstTemp[1].fPts, &dst[conicCnt2], dstTemp[1].fW); 238 } else { 239 dst[0] = dstTemp[0]; 240 } 241 return conicCnt; 242 } 243 244 // returns 0 if quad/conic is degen or close to it 245 // in this case approx the path with lines 246 // otherwise returns 1 247 int is_degen_quad_or_conic(const SkPoint p[3]) { 248 static const SkScalar gDegenerateToLineTol = SK_Scalar1; 249 static const SkScalar gDegenerateToLineTolSqd = 250 SkScalarMul(gDegenerateToLineTol, gDegenerateToLineTol); 251 252 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd || 253 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) { 254 return 1; 255 } 256 257 SkScalar dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]); 258 if (dsqd < gDegenerateToLineTolSqd) { 259 return 1; 260 } 261 262 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) { 263 return 1; 264 } 265 return 0; 266 } 267 268 // we subdivide the quads to avoid huge overfill 269 // if it returns -1 then should be drawn as lines 270 int num_quad_subdivs(const SkPoint p[3]) { 271 static const SkScalar gDegenerateToLineTol = SK_Scalar1; 272 static const SkScalar gDegenerateToLineTolSqd = 273 SkScalarMul(gDegenerateToLineTol, gDegenerateToLineTol); 274 275 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd || 276 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) { 277 return -1; 278 } 279 280 SkScalar dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]); 281 if (dsqd < gDegenerateToLineTolSqd) { 282 return -1; 283 } 284 285 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) { 286 return -1; 287 } 288 289 // tolerance of triangle height in pixels 290 // tuned on windows Quadro FX 380 / Z600 291 // trade off of fill vs cpu time on verts 292 // maybe different when do this using gpu (geo or tess shaders) 293 static const SkScalar gSubdivTol = 175 * SK_Scalar1; 294 295 if (dsqd <= SkScalarMul(gSubdivTol, gSubdivTol)) { 296 return 0; 297 } else { 298 static const int kMaxSub = 4; 299 // subdividing the quad reduces d by 4. so we want x = log4(d/tol) 300 // = log4(d*d/tol*tol)/2 301 // = log2(d*d/tol*tol) 302 303 #ifdef SK_SCALAR_IS_FLOAT 304 // +1 since we're ignoring the mantissa contribution. 305 int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1; 306 log = GrMin(GrMax(0, log), kMaxSub); 307 return log; 308 #else 309 SkScalar log = SkScalarLog( 310 SkScalarDiv(dsqd, 311 SkScalarMul(gSubdivTol, gSubdivTol))); 312 static const SkScalar conv = SkScalarInvert(SkScalarLog(2)); 313 log = SkScalarMul(log, conv); 314 return GrMin(GrMax(0, SkScalarCeilToInt(log)),kMaxSub); 315 #endif 316 } 317 } 318 319 /** 320 * Generates the lines and quads to be rendered. Lines are always recorded in 321 * device space. We will do a device space bloat to account for the 1pixel 322 * thickness. 323 * Quads are recorded in device space unless m contains 324 * perspective, then in they are in src space. We do this because we will 325 * subdivide large quads to reduce over-fill. This subdivision has to be 326 * performed before applying the perspective matrix. 327 */ 328 int generate_lines_and_quads(const SkPath& path, 329 const SkMatrix& m, 330 const SkIRect& devClipBounds, 331 GrAAHairLinePathRenderer::PtArray* lines, 332 GrAAHairLinePathRenderer::PtArray* quads, 333 GrAAHairLinePathRenderer::PtArray* conics, 334 GrAAHairLinePathRenderer::IntArray* quadSubdivCnts, 335 GrAAHairLinePathRenderer::FloatArray* conicWeights) { 336 SkPath::Iter iter(path, false); 337 338 int totalQuadCount = 0; 339 SkRect bounds; 340 SkIRect ibounds; 341 342 bool persp = m.hasPerspective(); 343 344 for (;;) { 345 GrPoint pathPts[4]; 346 GrPoint devPts[4]; 347 SkPath::Verb verb = iter.next(pathPts); 348 switch (verb) { 349 case SkPath::kConic_Verb: { 350 SkConic dst[4]; 351 // We chop the conics to create tighter clipping to hide error 352 // that appears near max curvature of very thin conics. Thin 353 // hyperbolas with high weight still show error. 354 int conicCnt = chop_conic(pathPts, dst, iter.conicWeight()); 355 for (int i = 0; i < conicCnt; ++i) { 356 SkPoint* chopPnts = dst[i].fPts; 357 m.mapPoints(devPts, chopPnts, 3); 358 bounds.setBounds(devPts, 3); 359 bounds.outset(SK_Scalar1, SK_Scalar1); 360 bounds.roundOut(&ibounds); 361 if (SkIRect::Intersects(devClipBounds, ibounds)) { 362 if (is_degen_quad_or_conic(devPts)) { 363 SkPoint* pts = lines->push_back_n(4); 364 pts[0] = devPts[0]; 365 pts[1] = devPts[1]; 366 pts[2] = devPts[1]; 367 pts[3] = devPts[2]; 368 } else { 369 // when in perspective keep conics in src space 370 SkPoint* cPts = persp ? chopPnts : devPts; 371 SkPoint* pts = conics->push_back_n(3); 372 pts[0] = cPts[0]; 373 pts[1] = cPts[1]; 374 pts[2] = cPts[2]; 375 conicWeights->push_back() = dst[i].fW; 376 } 377 } 378 } 379 break; 380 } 381 case SkPath::kMove_Verb: 382 break; 383 case SkPath::kLine_Verb: 384 m.mapPoints(devPts, pathPts, 2); 385 bounds.setBounds(devPts, 2); 386 bounds.outset(SK_Scalar1, SK_Scalar1); 387 bounds.roundOut(&ibounds); 388 if (SkIRect::Intersects(devClipBounds, ibounds)) { 389 SkPoint* pts = lines->push_back_n(2); 390 pts[0] = devPts[0]; 391 pts[1] = devPts[1]; 392 } 393 break; 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 SkPoint* quadPts = choppedPts + i * 2; 404 m.mapPoints(devPts, quadPts, 3); 405 bounds.setBounds(devPts, 3); 406 bounds.outset(SK_Scalar1, SK_Scalar1); 407 bounds.roundOut(&ibounds); 408 409 if (SkIRect::Intersects(devClipBounds, ibounds)) { 410 int subdiv = num_quad_subdivs(devPts); 411 SkASSERT(subdiv >= -1); 412 if (-1 == subdiv) { 413 SkPoint* pts = lines->push_back_n(4); 414 pts[0] = devPts[0]; 415 pts[1] = devPts[1]; 416 pts[2] = devPts[1]; 417 pts[3] = devPts[2]; 418 } else { 419 // when in perspective keep quads in src space 420 SkPoint* qPts = persp ? quadPts : devPts; 421 SkPoint* pts = quads->push_back_n(3); 422 pts[0] = qPts[0]; 423 pts[1] = qPts[1]; 424 pts[2] = qPts[2]; 425 quadSubdivCnts->push_back() = subdiv; 426 totalQuadCount += 1 << subdiv; 427 } 428 } 429 } 430 break; 431 } 432 case SkPath::kCubic_Verb: 433 m.mapPoints(devPts, pathPts, 4); 434 bounds.setBounds(devPts, 4); 435 bounds.outset(SK_Scalar1, SK_Scalar1); 436 bounds.roundOut(&ibounds); 437 if (SkIRect::Intersects(devClipBounds, ibounds)) { 438 PREALLOC_PTARRAY(32) q; 439 // we don't need a direction if we aren't constraining the subdivision 440 static const SkPath::Direction kDummyDir = SkPath::kCCW_Direction; 441 // We convert cubics to quadratics (for now). 442 // In perspective have to do conversion in src space. 443 if (persp) { 444 SkScalar tolScale = 445 GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m, 446 path.getBounds()); 447 GrPathUtils::convertCubicToQuads(pathPts, tolScale, false, kDummyDir, &q); 448 } else { 449 GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, false, kDummyDir, &q); 450 } 451 for (int i = 0; i < q.count(); i += 3) { 452 SkPoint* qInDevSpace; 453 // bounds has to be calculated in device space, but q is 454 // in src space when there is perspective. 455 if (persp) { 456 m.mapPoints(devPts, &q[i], 3); 457 bounds.setBounds(devPts, 3); 458 qInDevSpace = devPts; 459 } else { 460 bounds.setBounds(&q[i], 3); 461 qInDevSpace = &q[i]; 462 } 463 bounds.outset(SK_Scalar1, SK_Scalar1); 464 bounds.roundOut(&ibounds); 465 if (SkIRect::Intersects(devClipBounds, ibounds)) { 466 int subdiv = num_quad_subdivs(qInDevSpace); 467 SkASSERT(subdiv >= -1); 468 if (-1 == subdiv) { 469 SkPoint* pts = lines->push_back_n(4); 470 // lines should always be in device coords 471 pts[0] = qInDevSpace[0]; 472 pts[1] = qInDevSpace[1]; 473 pts[2] = qInDevSpace[1]; 474 pts[3] = qInDevSpace[2]; 475 } else { 476 SkPoint* pts = quads->push_back_n(3); 477 // q is already in src space when there is no 478 // perspective and dev coords otherwise. 479 pts[0] = q[0 + i]; 480 pts[1] = q[1 + i]; 481 pts[2] = q[2 + i]; 482 quadSubdivCnts->push_back() = subdiv; 483 totalQuadCount += 1 << subdiv; 484 } 485 } 486 } 487 } 488 break; 489 case SkPath::kClose_Verb: 490 break; 491 case SkPath::kDone_Verb: 492 return totalQuadCount; 493 } 494 } 495 } 496 497 struct LineVertex { 498 GrPoint fPos; 499 GrColor fCoverage; 500 }; 501 502 struct BezierVertex { 503 GrPoint fPos; 504 union { 505 struct { 506 SkScalar fK; 507 SkScalar fL; 508 SkScalar fM; 509 } fConic; 510 GrVec fQuadCoord; 511 struct { 512 SkScalar fBogus[4]; 513 }; 514 }; 515 }; 516 517 GR_STATIC_ASSERT(sizeof(BezierVertex) == 3 * sizeof(GrPoint)); 518 519 void intersect_lines(const SkPoint& ptA, const SkVector& normA, 520 const SkPoint& ptB, const SkVector& normB, 521 SkPoint* result) { 522 523 SkScalar lineAW = -normA.dot(ptA); 524 SkScalar lineBW = -normB.dot(ptB); 525 526 SkScalar wInv = SkScalarMul(normA.fX, normB.fY) - 527 SkScalarMul(normA.fY, normB.fX); 528 wInv = SkScalarInvert(wInv); 529 530 result->fX = SkScalarMul(normA.fY, lineBW) - SkScalarMul(lineAW, normB.fY); 531 result->fX = SkScalarMul(result->fX, wInv); 532 533 result->fY = SkScalarMul(lineAW, normB.fX) - SkScalarMul(normA.fX, lineBW); 534 result->fY = SkScalarMul(result->fY, wInv); 535 } 536 537 void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kVertsPerQuad]) { 538 // this should be in the src space, not dev coords, when we have perspective 539 GrPathUtils::QuadUVMatrix DevToUV(qpts); 540 DevToUV.apply<kVertsPerQuad, sizeof(BezierVertex), sizeof(GrPoint)>(verts); 541 } 542 543 void bloat_quad(const SkPoint qpts[3], const SkMatrix* toDevice, 544 const SkMatrix* toSrc, BezierVertex verts[kVertsPerQuad], 545 SkRect* devBounds) { 546 SkASSERT(!toDevice == !toSrc); 547 // original quad is specified by tri a,b,c 548 SkPoint a = qpts[0]; 549 SkPoint b = qpts[1]; 550 SkPoint c = qpts[2]; 551 552 if (toDevice) { 553 toDevice->mapPoints(&a, 1); 554 toDevice->mapPoints(&b, 1); 555 toDevice->mapPoints(&c, 1); 556 } 557 // make a new poly where we replace a and c by a 1-pixel wide edges orthog 558 // to edges ab and bc: 559 // 560 // before | after 561 // | b0 562 // b | 563 // | 564 // | a0 c0 565 // a c | a1 c1 566 // 567 // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c, 568 // respectively. 569 BezierVertex& a0 = verts[0]; 570 BezierVertex& a1 = verts[1]; 571 BezierVertex& b0 = verts[2]; 572 BezierVertex& c0 = verts[3]; 573 BezierVertex& c1 = verts[4]; 574 575 SkVector ab = b; 576 ab -= a; 577 SkVector ac = c; 578 ac -= a; 579 SkVector cb = b; 580 cb -= c; 581 582 // We should have already handled degenerates 583 SkASSERT(ab.length() > 0 && cb.length() > 0); 584 585 ab.normalize(); 586 SkVector abN; 587 abN.setOrthog(ab, SkVector::kLeft_Side); 588 if (abN.dot(ac) > 0) { 589 abN.negate(); 590 } 591 592 cb.normalize(); 593 SkVector cbN; 594 cbN.setOrthog(cb, SkVector::kLeft_Side); 595 if (cbN.dot(ac) < 0) { 596 cbN.negate(); 597 } 598 599 a0.fPos = a; 600 a0.fPos += abN; 601 a1.fPos = a; 602 a1.fPos -= abN; 603 604 c0.fPos = c; 605 c0.fPos += cbN; 606 c1.fPos = c; 607 c1.fPos -= cbN; 608 609 intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos); 610 devBounds->growToInclude(&verts[0].fPos, sizeof(BezierVertex), kVertsPerQuad); 611 612 if (toSrc) { 613 toSrc->mapPointsWithStride(&verts[0].fPos, sizeof(BezierVertex), kVertsPerQuad); 614 } 615 } 616 617 // Equations based off of Loop-Blinn Quadratic GPU Rendering 618 // Input Parametric: 619 // 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) 620 // Output Implicit: 621 // f(x, y, w) = f(P) = K^2 - LM 622 // K = dot(k, P), L = dot(l, P), M = dot(m, P) 623 // k, l, m are calculated in function GrPathUtils::getConicKLM 624 void set_conic_coeffs(const SkPoint p[3], BezierVertex verts[kVertsPerQuad], 625 const SkScalar weight) { 626 SkScalar klm[9]; 627 628 GrPathUtils::getConicKLM(p, weight, klm); 629 630 for (int i = 0; i < kVertsPerQuad; ++i) { 631 const SkPoint pnt = verts[i].fPos; 632 verts[i].fConic.fK = pnt.fX * klm[0] + pnt.fY * klm[1] + klm[2]; 633 verts[i].fConic.fL = pnt.fX * klm[3] + pnt.fY * klm[4] + klm[5]; 634 verts[i].fConic.fM = pnt.fX * klm[6] + pnt.fY * klm[7] + klm[8]; 635 } 636 } 637 638 void add_conics(const SkPoint p[3], 639 const SkScalar weight, 640 const SkMatrix* toDevice, 641 const SkMatrix* toSrc, 642 BezierVertex** vert, 643 SkRect* devBounds) { 644 bloat_quad(p, toDevice, toSrc, *vert, devBounds); 645 set_conic_coeffs(p, *vert, weight); 646 *vert += kVertsPerQuad; 647 } 648 649 void add_quads(const SkPoint p[3], 650 int subdiv, 651 const SkMatrix* toDevice, 652 const SkMatrix* toSrc, 653 BezierVertex** vert, 654 SkRect* devBounds) { 655 SkASSERT(subdiv >= 0); 656 if (subdiv) { 657 SkPoint newP[5]; 658 SkChopQuadAtHalf(p, newP); 659 add_quads(newP + 0, subdiv-1, toDevice, toSrc, vert, devBounds); 660 add_quads(newP + 2, subdiv-1, toDevice, toSrc, vert, devBounds); 661 } else { 662 bloat_quad(p, toDevice, toSrc, *vert, devBounds); 663 set_uv_quad(p, *vert); 664 *vert += kVertsPerQuad; 665 } 666 } 667 668 void add_line(const SkPoint p[2], 669 const SkMatrix* toSrc, 670 GrColor coverage, 671 LineVertex** vert) { 672 const SkPoint& a = p[0]; 673 const SkPoint& b = p[1]; 674 675 SkVector ortho, vec = b; 676 vec -= a; 677 678 if (vec.setLength(SK_ScalarHalf)) { 679 // Create a vector orthogonal to 'vec' and of unit length 680 ortho.fX = 2.0f * vec.fY; 681 ortho.fY = -2.0f * vec.fX; 682 683 (*vert)[0].fPos = a; 684 (*vert)[0].fCoverage = coverage; 685 (*vert)[1].fPos = b; 686 (*vert)[1].fCoverage = coverage; 687 (*vert)[2].fPos = a - vec + ortho; 688 (*vert)[2].fCoverage = 0; 689 (*vert)[3].fPos = b + vec + ortho; 690 (*vert)[3].fCoverage = 0; 691 (*vert)[4].fPos = a - vec - ortho; 692 (*vert)[4].fCoverage = 0; 693 (*vert)[5].fPos = b + vec - ortho; 694 (*vert)[5].fCoverage = 0; 695 696 if (NULL != toSrc) { 697 toSrc->mapPointsWithStride(&(*vert)->fPos, 698 sizeof(LineVertex), 699 kVertsPerLineSeg); 700 } 701 } else { 702 // just make it degenerate and likely offscreen 703 for (int i = 0; i < kVertsPerLineSeg; ++i) { 704 (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax); 705 } 706 } 707 708 *vert += kVertsPerLineSeg; 709 } 710 711 } 712 713 /////////////////////////////////////////////////////////////////////////////// 714 715 namespace { 716 717 // position + edge 718 extern const GrVertexAttrib gHairlineBezierAttribs[] = { 719 {kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding}, 720 {kVec4f_GrVertexAttribType, sizeof(GrPoint), kEffect_GrVertexAttribBinding} 721 }; 722 723 // position + coverage 724 extern const GrVertexAttrib gHairlineLineAttribs[] = { 725 {kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding}, 726 {kVec4ub_GrVertexAttribType, sizeof(GrPoint), kCoverage_GrVertexAttribBinding}, 727 }; 728 729 }; 730 731 bool GrAAHairLinePathRenderer::createLineGeom(const SkPath& path, 732 GrDrawTarget* target, 733 const PtArray& lines, 734 int lineCnt, 735 GrDrawTarget::AutoReleaseGeometry* arg, 736 SkRect* devBounds) { 737 GrDrawState* drawState = target->drawState(); 738 739 const SkMatrix& viewM = drawState->getViewMatrix(); 740 741 int vertCnt = kVertsPerLineSeg * lineCnt; 742 743 drawState->setVertexAttribs<gHairlineLineAttribs>(SK_ARRAY_COUNT(gHairlineLineAttribs)); 744 SkASSERT(sizeof(LineVertex) == drawState->getVertexSize()); 745 746 if (!arg->set(target, vertCnt, 0)) { 747 return false; 748 } 749 750 LineVertex* verts = reinterpret_cast<LineVertex*>(arg->vertices()); 751 752 const SkMatrix* toSrc = NULL; 753 SkMatrix ivm; 754 755 if (viewM.hasPerspective()) { 756 if (viewM.invert(&ivm)) { 757 toSrc = &ivm; 758 } 759 } 760 devBounds->set(lines.begin(), lines.count()); 761 for (int i = 0; i < lineCnt; ++i) { 762 add_line(&lines[2*i], toSrc, drawState->getCoverageColor(), &verts); 763 } 764 // All the verts computed by add_line are within sqrt(1^2 + 0.5^2) of the end points. 765 static const SkScalar kSqrtOfOneAndAQuarter = 1.118f; 766 // Add a little extra to account for vector normalization precision. 767 static const SkScalar kOutset = kSqrtOfOneAndAQuarter + SK_Scalar1 / 20; 768 devBounds->outset(kOutset, kOutset); 769 770 return true; 771 } 772 773 bool GrAAHairLinePathRenderer::createBezierGeom( 774 const SkPath& path, 775 GrDrawTarget* target, 776 const PtArray& quads, 777 int quadCnt, 778 const PtArray& conics, 779 int conicCnt, 780 const IntArray& qSubdivs, 781 const FloatArray& cWeights, 782 GrDrawTarget::AutoReleaseGeometry* arg, 783 SkRect* devBounds) { 784 GrDrawState* drawState = target->drawState(); 785 786 const SkMatrix& viewM = drawState->getViewMatrix(); 787 788 int vertCnt = kVertsPerQuad * quadCnt + kVertsPerQuad * conicCnt; 789 790 target->drawState()->setVertexAttribs<gHairlineBezierAttribs>(SK_ARRAY_COUNT(gHairlineBezierAttribs)); 791 SkASSERT(sizeof(BezierVertex) == target->getDrawState().getVertexSize()); 792 793 if (!arg->set(target, vertCnt, 0)) { 794 return false; 795 } 796 797 BezierVertex* verts = reinterpret_cast<BezierVertex*>(arg->vertices()); 798 799 const SkMatrix* toDevice = NULL; 800 const SkMatrix* toSrc = NULL; 801 SkMatrix ivm; 802 803 if (viewM.hasPerspective()) { 804 if (viewM.invert(&ivm)) { 805 toDevice = &viewM; 806 toSrc = &ivm; 807 } 808 } 809 810 // Seed the dev bounds with some pts known to be inside. Each quad and conic grows the bounding 811 // box to include its vertices. 812 SkPoint seedPts[2]; 813 if (quadCnt) { 814 seedPts[0] = quads[0]; 815 seedPts[1] = quads[2]; 816 } else if (conicCnt) { 817 seedPts[0] = conics[0]; 818 seedPts[1] = conics[2]; 819 } 820 if (NULL != toDevice) { 821 toDevice->mapPoints(seedPts, 2); 822 } 823 devBounds->set(seedPts[0], seedPts[1]); 824 825 int unsubdivQuadCnt = quads.count() / 3; 826 for (int i = 0; i < unsubdivQuadCnt; ++i) { 827 SkASSERT(qSubdivs[i] >= 0); 828 add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &verts, devBounds); 829 } 830 831 // Start Conics 832 for (int i = 0; i < conicCnt; ++i) { 833 add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &verts, devBounds); 834 } 835 return true; 836 } 837 838 bool GrAAHairLinePathRenderer::canDrawPath(const SkPath& path, 839 const SkStrokeRec& stroke, 840 const GrDrawTarget* target, 841 bool antiAlias) const { 842 if (!antiAlias) { 843 return false; 844 } 845 846 if (!IsStrokeHairlineOrEquivalent(stroke, 847 target->getDrawState().getViewMatrix(), 848 NULL)) { 849 return false; 850 } 851 852 if (SkPath::kLine_SegmentMask == path.getSegmentMasks() || 853 target->caps()->shaderDerivativeSupport()) { 854 return true; 855 } 856 return false; 857 } 858 859 template <class VertexType> 860 bool check_bounds(GrDrawState* drawState, const SkRect& devBounds, void* vertices, int vCount) 861 { 862 SkRect tolDevBounds = devBounds; 863 // The bounds ought to be tight, but in perspective the below code runs the verts 864 // through the view matrix to get back to dev coords, which can introduce imprecision. 865 if (drawState->getViewMatrix().hasPerspective()) { 866 tolDevBounds.outset(SK_Scalar1 / 1000, SK_Scalar1 / 1000); 867 } else { 868 // Non-persp matrices cause this path renderer to draw in device space. 869 SkASSERT(drawState->getViewMatrix().isIdentity()); 870 } 871 SkRect actualBounds; 872 873 VertexType* verts = reinterpret_cast<VertexType*>(vertices); 874 bool first = true; 875 for (int i = 0; i < vCount; ++i) { 876 SkPoint pos = verts[i].fPos; 877 // This is a hack to workaround the fact that we move some degenerate segments offscreen. 878 if (SK_ScalarMax == pos.fX) { 879 continue; 880 } 881 drawState->getViewMatrix().mapPoints(&pos, 1); 882 if (first) { 883 actualBounds.set(pos.fX, pos.fY, pos.fX, pos.fY); 884 first = false; 885 } else { 886 actualBounds.growToInclude(pos.fX, pos.fY); 887 } 888 } 889 if (!first) { 890 return tolDevBounds.contains(actualBounds); 891 } 892 893 return true; 894 } 895 896 bool GrAAHairLinePathRenderer::onDrawPath(const SkPath& path, 897 const SkStrokeRec& stroke, 898 GrDrawTarget* target, 899 bool antiAlias) { 900 GrDrawState* drawState = target->drawState(); 901 902 SkScalar hairlineCoverage; 903 if (IsStrokeHairlineOrEquivalent(stroke, 904 target->getDrawState().getViewMatrix(), 905 &hairlineCoverage)) { 906 uint8_t newCoverage = SkScalarRoundToInt(hairlineCoverage * 907 target->getDrawState().getCoverage()); 908 target->drawState()->setCoverage(newCoverage); 909 } 910 911 SkIRect devClipBounds; 912 target->getClip()->getConservativeBounds(drawState->getRenderTarget(), &devClipBounds); 913 914 int lineCnt; 915 int quadCnt; 916 int conicCnt; 917 PREALLOC_PTARRAY(128) lines; 918 PREALLOC_PTARRAY(128) quads; 919 PREALLOC_PTARRAY(128) conics; 920 IntArray qSubdivs; 921 FloatArray cWeights; 922 quadCnt = generate_lines_and_quads(path, drawState->getViewMatrix(), devClipBounds, 923 &lines, &quads, &conics, &qSubdivs, &cWeights); 924 lineCnt = lines.count() / 2; 925 conicCnt = conics.count() / 3; 926 927 // do lines first 928 if (lineCnt) { 929 GrDrawTarget::AutoReleaseGeometry arg; 930 SkRect devBounds; 931 932 if (!this->createLineGeom(path, 933 target, 934 lines, 935 lineCnt, 936 &arg, 937 &devBounds)) { 938 return false; 939 } 940 941 GrDrawTarget::AutoStateRestore asr; 942 943 // createLineGeom transforms the geometry to device space when the matrix does not have 944 // perspective. 945 if (target->getDrawState().getViewMatrix().hasPerspective()) { 946 asr.set(target, GrDrawTarget::kPreserve_ASRInit); 947 } else if (!asr.setIdentity(target, GrDrawTarget::kPreserve_ASRInit)) { 948 return false; 949 } 950 GrDrawState* drawState = target->drawState(); 951 952 // Check devBounds 953 SkASSERT(check_bounds<LineVertex>(drawState, devBounds, arg.vertices(), 954 kVertsPerLineSeg * lineCnt)); 955 956 { 957 GrDrawState::AutoRestoreEffects are(drawState); 958 target->setIndexSourceToBuffer(fLinesIndexBuffer); 959 int lines = 0; 960 while (lines < lineCnt) { 961 int n = GrMin(lineCnt - lines, kNumLineSegsInIdxBuffer); 962 target->drawIndexed(kTriangles_GrPrimitiveType, 963 kVertsPerLineSeg*lines, // startV 964 0, // startI 965 kVertsPerLineSeg*n, // vCount 966 kIdxsPerLineSeg*n, // iCount 967 &devBounds); 968 lines += n; 969 } 970 } 971 } 972 973 // then quadratics/conics 974 if (quadCnt || conicCnt) { 975 GrDrawTarget::AutoReleaseGeometry arg; 976 SkRect devBounds; 977 978 if (!this->createBezierGeom(path, 979 target, 980 quads, 981 quadCnt, 982 conics, 983 conicCnt, 984 qSubdivs, 985 cWeights, 986 &arg, 987 &devBounds)) { 988 return false; 989 } 990 991 GrDrawTarget::AutoStateRestore asr; 992 993 // createGeom transforms the geometry to device space when the matrix does not have 994 // perspective. 995 if (target->getDrawState().getViewMatrix().hasPerspective()) { 996 asr.set(target, GrDrawTarget::kPreserve_ASRInit); 997 } else if (!asr.setIdentity(target, GrDrawTarget::kPreserve_ASRInit)) { 998 return false; 999 } 1000 GrDrawState* drawState = target->drawState(); 1001 1002 static const int kEdgeAttrIndex = 1; 1003 1004 // Check devBounds 1005 SkASSERT(check_bounds<BezierVertex>(drawState, devBounds, arg.vertices(), 1006 kVertsPerQuad * quadCnt + kVertsPerQuad * conicCnt)); 1007 1008 if (quadCnt > 0) { 1009 GrEffectRef* hairQuadEffect = GrQuadEffect::Create(kHairAA_GrBezierEdgeType, 1010 *target->caps()); 1011 SkASSERT(NULL != hairQuadEffect); 1012 GrDrawState::AutoRestoreEffects are(drawState); 1013 target->setIndexSourceToBuffer(fQuadsIndexBuffer); 1014 drawState->addCoverageEffect(hairQuadEffect, kEdgeAttrIndex)->unref(); 1015 int quads = 0; 1016 while (quads < quadCnt) { 1017 int n = GrMin(quadCnt - quads, kNumQuadsInIdxBuffer); 1018 target->drawIndexed(kTriangles_GrPrimitiveType, 1019 kVertsPerQuad*quads, // startV 1020 0, // startI 1021 kVertsPerQuad*n, // vCount 1022 kIdxsPerQuad*n, // iCount 1023 &devBounds); 1024 quads += n; 1025 } 1026 } 1027 1028 if (conicCnt > 0) { 1029 GrDrawState::AutoRestoreEffects are(drawState); 1030 GrEffectRef* hairConicEffect = GrConicEffect::Create(kHairAA_GrBezierEdgeType, 1031 *target->caps()); 1032 SkASSERT(NULL != hairConicEffect); 1033 drawState->addCoverageEffect(hairConicEffect, 1, 2)->unref(); 1034 int conics = 0; 1035 while (conics < conicCnt) { 1036 int n = GrMin(conicCnt - conics, kNumQuadsInIdxBuffer); 1037 target->drawIndexed(kTriangles_GrPrimitiveType, 1038 kVertsPerQuad*(quadCnt + conics), // startV 1039 0, // startI 1040 kVertsPerQuad*n, // vCount 1041 kIdxsPerQuad*n, // iCount 1042 &devBounds); 1043 conics += n; 1044 } 1045 } 1046 } 1047 1048 target->resetIndexSource(); 1049 1050 return true; 1051 } 1052