2 * Copyright 2011 Google Inc.
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
8 #include "GrAAHairLinePathRenderer.h"
10 #include "GrContext.h"
11 #include "GrDrawState.h"
12 #include "GrDrawTargetCaps.h"
15 #include "GrIndexBuffer.h"
16 #include "GrPathUtils.h"
17 #include "GrTBackendEffectFactory.h"
18 #include "SkGeometry.h"
20 #include "SkTemplates.h"
22 #include "effects/GrBezierEffect.h"
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;
31 // lines are rendered as:
38 // For: 6 vertices and 18 indices (for 6 triangles)
39 static const int kVertsPerLineSeg = 6;
40 static const int kIdxsPerLineSeg = 18;
42 static const int kNumQuadsInIdxBuffer = 256;
43 static const size_t kQuadIdxSBufize = kIdxsPerQuad *
47 static const int kNumLineSegsInIdxBuffer = 256;
48 static const size_t kLineSegIdxSBufize = kIdxsPerLineSeg *
50 kNumLineSegsInIdxBuffer;
52 static bool push_quad_index_data(GrIndexBuffer* qIdxBuffer) {
53 uint16_t* data = (uint16_t*) qIdxBuffer->lock();
54 bool tempData = NULL == data;
56 data = SkNEW_ARRAY(uint16_t, kNumQuadsInIdxBuffer * kIdxsPerQuad);
58 for (int i = 0; i < kNumQuadsInIdxBuffer; ++i) {
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:
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
85 bool ret = qIdxBuffer->updateData(data, kQuadIdxSBufize);
94 static bool push_line_index_data(GrIndexBuffer* lIdxBuffer) {
95 uint16_t* data = (uint16_t*) lIdxBuffer->lock();
96 bool tempData = NULL == data;
98 data = SkNEW_ARRAY(uint16_t, kNumLineSegsInIdxBuffer * kIdxsPerLineSeg);
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.
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;
117 data[3 + baseIdx] = baseVert + 0;
118 data[4 + baseIdx] = baseVert + 3;
119 data[5 + baseIdx] = baseVert + 2;
121 data[6 + baseIdx] = baseVert + 0;
122 data[7 + baseIdx] = baseVert + 4;
123 data[8 + baseIdx] = baseVert + 5;
125 data[9 + baseIdx] = baseVert + 0;
126 data[10+ baseIdx] = baseVert + 5;
127 data[11+ baseIdx] = baseVert + 1;
129 data[12 + baseIdx] = baseVert + 0;
130 data[13 + baseIdx] = baseVert + 2;
131 data[14 + baseIdx] = baseVert + 4;
133 data[15 + baseIdx] = baseVert + 1;
134 data[16 + baseIdx] = baseVert + 5;
135 data[17 + baseIdx] = baseVert + 3;
138 bool ret = lIdxBuffer->updateData(data, kLineSegIdxSBufize);
142 lIdxBuffer->unlock();
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)) {
155 GrIndexBuffer* lIdxBuf = gpu->createIndexBuffer(kLineSegIdxSBufize, false);
156 SkAutoTUnref<GrIndexBuffer> lIdxBuffer(lIdxBuf);
157 if (NULL == lIdxBuf || !push_line_index_data(lIdxBuf)) {
160 return SkNEW_ARGS(GrAAHairLinePathRenderer,
161 (context, lIdxBuf, qIdxBuf));
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();
174 GrAAHairLinePathRenderer::~GrAAHairLinePathRenderer() {
175 fLinesIndexBuffer->unref();
176 fQuadsIndexBuffer->unref();
181 #define PREALLOC_PTARRAY(N) SkSTArray<(N),SkPoint, true>
183 // Takes 178th time of logf on Z600 / VC2010
184 int get_float_exp(float x) {
185 GR_STATIC_ASSERT(sizeof(int) == sizeof(float));
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);
203 const int* iptr = (const int*)&x;
204 return (((*iptr) & 0x7f800000) >> 23) - 127;
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);
216 dst[0].set(src, weight);
222 conic.set(src, weight);
223 conic.chopAt(t, dst);
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) {
234 int conicCnt = split_conic(src, dstTemp, weight);
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);
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);
252 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd ||
253 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) {
257 SkScalar dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]);
258 if (dsqd < gDegenerateToLineTolSqd) {
262 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) {
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);
275 if (p[0].distanceToSqd(p[1]) < gDegenerateToLineTolSqd ||
276 p[1].distanceToSqd(p[2]) < gDegenerateToLineTolSqd) {
280 SkScalar dsqd = p[1].distanceToLineBetweenSqd(p[0], p[2]);
281 if (dsqd < gDegenerateToLineTolSqd) {
285 if (p[2].distanceToLineBetweenSqd(p[1], p[0]) < gDegenerateToLineTolSqd) {
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;
295 if (dsqd <= SkScalarMul(gSubdivTol, gSubdivTol)) {
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)
303 // +1 since we're ignoring the mantissa contribution.
304 int log = get_float_exp(dsqd/(gSubdivTol*gSubdivTol)) + 1;
305 log = SkTMin(SkTMax(0, log), kMaxSub);
311 * Generates the lines and quads to be rendered. Lines are always recorded in
312 * device space. We will do a device space bloat to account for the 1pixel
314 * Quads are recorded in device space unless m contains
315 * perspective, then in they are in src space. We do this because we will
316 * subdivide large quads to reduce over-fill. This subdivision has to be
317 * performed before applying the perspective matrix.
319 int generate_lines_and_quads(const SkPath& path,
321 const SkIRect& devClipBounds,
322 GrAAHairLinePathRenderer::PtArray* lines,
323 GrAAHairLinePathRenderer::PtArray* quads,
324 GrAAHairLinePathRenderer::PtArray* conics,
325 GrAAHairLinePathRenderer::IntArray* quadSubdivCnts,
326 GrAAHairLinePathRenderer::FloatArray* conicWeights) {
327 SkPath::Iter iter(path, false);
329 int totalQuadCount = 0;
333 bool persp = m.hasPerspective();
338 SkPath::Verb verb = iter.next(pathPts);
340 case SkPath::kConic_Verb: {
342 // We chop the conics to create tighter clipping to hide error
343 // that appears near max curvature of very thin conics. Thin
344 // hyperbolas with high weight still show error.
345 int conicCnt = chop_conic(pathPts, dst, iter.conicWeight());
346 for (int i = 0; i < conicCnt; ++i) {
347 SkPoint* chopPnts = dst[i].fPts;
348 m.mapPoints(devPts, chopPnts, 3);
349 bounds.setBounds(devPts, 3);
350 bounds.outset(SK_Scalar1, SK_Scalar1);
351 bounds.roundOut(&ibounds);
352 if (SkIRect::Intersects(devClipBounds, ibounds)) {
353 if (is_degen_quad_or_conic(devPts)) {
354 SkPoint* pts = lines->push_back_n(4);
360 // when in perspective keep conics in src space
361 SkPoint* cPts = persp ? chopPnts : devPts;
362 SkPoint* pts = conics->push_back_n(3);
366 conicWeights->push_back() = dst[i].fW;
372 case SkPath::kMove_Verb:
374 case SkPath::kLine_Verb:
375 m.mapPoints(devPts, pathPts, 2);
376 bounds.setBounds(devPts, 2);
377 bounds.outset(SK_Scalar1, SK_Scalar1);
378 bounds.roundOut(&ibounds);
379 if (SkIRect::Intersects(devClipBounds, ibounds)) {
380 SkPoint* pts = lines->push_back_n(2);
385 case SkPath::kQuad_Verb: {
386 SkPoint choppedPts[5];
387 // Chopping the quad helps when the quad is either degenerate or nearly degenerate.
388 // When it is degenerate it allows the approximation with lines to work since the
389 // chop point (if there is one) will be at the parabola's vertex. In the nearly
390 // degenerate the QuadUVMatrix computed for the points is almost singular which
391 // can cause rendering artifacts.
392 int n = SkChopQuadAtMaxCurvature(pathPts, choppedPts);
393 for (int i = 0; i < n; ++i) {
394 SkPoint* quadPts = choppedPts + i * 2;
395 m.mapPoints(devPts, quadPts, 3);
396 bounds.setBounds(devPts, 3);
397 bounds.outset(SK_Scalar1, SK_Scalar1);
398 bounds.roundOut(&ibounds);
400 if (SkIRect::Intersects(devClipBounds, ibounds)) {
401 int subdiv = num_quad_subdivs(devPts);
402 SkASSERT(subdiv >= -1);
404 SkPoint* pts = lines->push_back_n(4);
410 // when in perspective keep quads in src space
411 SkPoint* qPts = persp ? quadPts : devPts;
412 SkPoint* pts = quads->push_back_n(3);
416 quadSubdivCnts->push_back() = subdiv;
417 totalQuadCount += 1 << subdiv;
423 case SkPath::kCubic_Verb:
424 m.mapPoints(devPts, pathPts, 4);
425 bounds.setBounds(devPts, 4);
426 bounds.outset(SK_Scalar1, SK_Scalar1);
427 bounds.roundOut(&ibounds);
428 if (SkIRect::Intersects(devClipBounds, ibounds)) {
429 PREALLOC_PTARRAY(32) q;
430 // we don't need a direction if we aren't constraining the subdivision
431 static const SkPath::Direction kDummyDir = SkPath::kCCW_Direction;
432 // We convert cubics to quadratics (for now).
433 // In perspective have to do conversion in src space.
436 GrPathUtils::scaleToleranceToSrc(SK_Scalar1, m,
438 GrPathUtils::convertCubicToQuads(pathPts, tolScale, false, kDummyDir, &q);
440 GrPathUtils::convertCubicToQuads(devPts, SK_Scalar1, false, kDummyDir, &q);
442 for (int i = 0; i < q.count(); i += 3) {
443 SkPoint* qInDevSpace;
444 // bounds has to be calculated in device space, but q is
445 // in src space when there is perspective.
447 m.mapPoints(devPts, &q[i], 3);
448 bounds.setBounds(devPts, 3);
449 qInDevSpace = devPts;
451 bounds.setBounds(&q[i], 3);
454 bounds.outset(SK_Scalar1, SK_Scalar1);
455 bounds.roundOut(&ibounds);
456 if (SkIRect::Intersects(devClipBounds, ibounds)) {
457 int subdiv = num_quad_subdivs(qInDevSpace);
458 SkASSERT(subdiv >= -1);
460 SkPoint* pts = lines->push_back_n(4);
461 // lines should always be in device coords
462 pts[0] = qInDevSpace[0];
463 pts[1] = qInDevSpace[1];
464 pts[2] = qInDevSpace[1];
465 pts[3] = qInDevSpace[2];
467 SkPoint* pts = quads->push_back_n(3);
468 // q is already in src space when there is no
469 // perspective and dev coords otherwise.
473 quadSubdivCnts->push_back() = subdiv;
474 totalQuadCount += 1 << subdiv;
480 case SkPath::kClose_Verb:
482 case SkPath::kDone_Verb:
483 return totalQuadCount;
493 struct BezierVertex {
508 GR_STATIC_ASSERT(sizeof(BezierVertex) == 3 * sizeof(SkPoint));
510 void intersect_lines(const SkPoint& ptA, const SkVector& normA,
511 const SkPoint& ptB, const SkVector& normB,
514 SkScalar lineAW = -normA.dot(ptA);
515 SkScalar lineBW = -normB.dot(ptB);
517 SkScalar wInv = SkScalarMul(normA.fX, normB.fY) -
518 SkScalarMul(normA.fY, normB.fX);
519 wInv = SkScalarInvert(wInv);
521 result->fX = SkScalarMul(normA.fY, lineBW) - SkScalarMul(lineAW, normB.fY);
522 result->fX = SkScalarMul(result->fX, wInv);
524 result->fY = SkScalarMul(lineAW, normB.fX) - SkScalarMul(normA.fX, lineBW);
525 result->fY = SkScalarMul(result->fY, wInv);
528 void set_uv_quad(const SkPoint qpts[3], BezierVertex verts[kVertsPerQuad]) {
529 // this should be in the src space, not dev coords, when we have perspective
530 GrPathUtils::QuadUVMatrix DevToUV(qpts);
531 DevToUV.apply<kVertsPerQuad, sizeof(BezierVertex), sizeof(SkPoint)>(verts);
534 void bloat_quad(const SkPoint qpts[3], const SkMatrix* toDevice,
535 const SkMatrix* toSrc, BezierVertex verts[kVertsPerQuad],
537 SkASSERT(!toDevice == !toSrc);
538 // original quad is specified by tri a,b,c
544 toDevice->mapPoints(&a, 1);
545 toDevice->mapPoints(&b, 1);
546 toDevice->mapPoints(&c, 1);
548 // make a new poly where we replace a and c by a 1-pixel wide edges orthog
549 // to edges ab and bc:
558 // edges a0->b0 and b0->c0 are parallel to original edges a->b and b->c,
560 BezierVertex& a0 = verts[0];
561 BezierVertex& a1 = verts[1];
562 BezierVertex& b0 = verts[2];
563 BezierVertex& c0 = verts[3];
564 BezierVertex& c1 = verts[4];
573 // We should have already handled degenerates
574 SkASSERT(ab.length() > 0 && cb.length() > 0);
578 abN.setOrthog(ab, SkVector::kLeft_Side);
579 if (abN.dot(ac) > 0) {
585 cbN.setOrthog(cb, SkVector::kLeft_Side);
586 if (cbN.dot(ac) < 0) {
600 intersect_lines(a0.fPos, abN, c0.fPos, cbN, &b0.fPos);
601 devBounds->growToInclude(&verts[0].fPos, sizeof(BezierVertex), kVertsPerQuad);
604 toSrc->mapPointsWithStride(&verts[0].fPos, sizeof(BezierVertex), kVertsPerQuad);
608 // Equations based off of Loop-Blinn Quadratic GPU Rendering
610 // 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)
612 // f(x, y, w) = f(P) = K^2 - LM
613 // K = dot(k, P), L = dot(l, P), M = dot(m, P)
614 // k, l, m are calculated in function GrPathUtils::getConicKLM
615 void set_conic_coeffs(const SkPoint p[3], BezierVertex verts[kVertsPerQuad],
616 const SkScalar weight) {
619 GrPathUtils::getConicKLM(p, weight, klm);
621 for (int i = 0; i < kVertsPerQuad; ++i) {
622 const SkPoint pnt = verts[i].fPos;
623 verts[i].fConic.fK = pnt.fX * klm[0] + pnt.fY * klm[1] + klm[2];
624 verts[i].fConic.fL = pnt.fX * klm[3] + pnt.fY * klm[4] + klm[5];
625 verts[i].fConic.fM = pnt.fX * klm[6] + pnt.fY * klm[7] + klm[8];
629 void add_conics(const SkPoint p[3],
630 const SkScalar weight,
631 const SkMatrix* toDevice,
632 const SkMatrix* toSrc,
635 bloat_quad(p, toDevice, toSrc, *vert, devBounds);
636 set_conic_coeffs(p, *vert, weight);
637 *vert += kVertsPerQuad;
640 void add_quads(const SkPoint p[3],
642 const SkMatrix* toDevice,
643 const SkMatrix* toSrc,
646 SkASSERT(subdiv >= 0);
649 SkChopQuadAtHalf(p, newP);
650 add_quads(newP + 0, subdiv-1, toDevice, toSrc, vert, devBounds);
651 add_quads(newP + 2, subdiv-1, toDevice, toSrc, vert, devBounds);
653 bloat_quad(p, toDevice, toSrc, *vert, devBounds);
654 set_uv_quad(p, *vert);
655 *vert += kVertsPerQuad;
659 void add_line(const SkPoint p[2],
660 const SkMatrix* toSrc,
663 const SkPoint& a = p[0];
664 const SkPoint& b = p[1];
666 SkVector ortho, vec = b;
669 if (vec.setLength(SK_ScalarHalf)) {
670 // Create a vector orthogonal to 'vec' and of unit length
671 ortho.fX = 2.0f * vec.fY;
672 ortho.fY = -2.0f * vec.fX;
675 (*vert)[0].fCoverage = coverage;
677 (*vert)[1].fCoverage = coverage;
678 (*vert)[2].fPos = a - vec + ortho;
679 (*vert)[2].fCoverage = 0;
680 (*vert)[3].fPos = b + vec + ortho;
681 (*vert)[3].fCoverage = 0;
682 (*vert)[4].fPos = a - vec - ortho;
683 (*vert)[4].fCoverage = 0;
684 (*vert)[5].fPos = b + vec - ortho;
685 (*vert)[5].fCoverage = 0;
688 toSrc->mapPointsWithStride(&(*vert)->fPos,
693 // just make it degenerate and likely offscreen
694 for (int i = 0; i < kVertsPerLineSeg; ++i) {
695 (*vert)[i].fPos.set(SK_ScalarMax, SK_ScalarMax);
699 *vert += kVertsPerLineSeg;
704 ///////////////////////////////////////////////////////////////////////////////
709 extern const GrVertexAttrib gHairlineBezierAttribs[] = {
710 {kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding},
711 {kVec4f_GrVertexAttribType, sizeof(SkPoint), kEffect_GrVertexAttribBinding}
714 // position + coverage
715 extern const GrVertexAttrib gHairlineLineAttribs[] = {
716 {kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding},
717 {kVec4ub_GrVertexAttribType, sizeof(SkPoint), kCoverage_GrVertexAttribBinding},
722 bool GrAAHairLinePathRenderer::createLineGeom(const SkPath& path,
723 GrDrawTarget* target,
724 const PtArray& lines,
726 GrDrawTarget::AutoReleaseGeometry* arg,
728 GrDrawState* drawState = target->drawState();
730 const SkMatrix& viewM = drawState->getViewMatrix();
732 int vertCnt = kVertsPerLineSeg * lineCnt;
734 drawState->setVertexAttribs<gHairlineLineAttribs>(SK_ARRAY_COUNT(gHairlineLineAttribs));
735 SkASSERT(sizeof(LineVertex) == drawState->getVertexSize());
737 if (!arg->set(target, vertCnt, 0)) {
741 LineVertex* verts = reinterpret_cast<LineVertex*>(arg->vertices());
743 const SkMatrix* toSrc = NULL;
746 if (viewM.hasPerspective()) {
747 if (viewM.invert(&ivm)) {
751 devBounds->set(lines.begin(), lines.count());
752 for (int i = 0; i < lineCnt; ++i) {
753 add_line(&lines[2*i], toSrc, drawState->getCoverageColor(), &verts);
755 // All the verts computed by add_line are within sqrt(1^2 + 0.5^2) of the end points.
756 static const SkScalar kSqrtOfOneAndAQuarter = 1.118f;
757 // Add a little extra to account for vector normalization precision.
758 static const SkScalar kOutset = kSqrtOfOneAndAQuarter + SK_Scalar1 / 20;
759 devBounds->outset(kOutset, kOutset);
764 bool GrAAHairLinePathRenderer::createBezierGeom(
766 GrDrawTarget* target,
767 const PtArray& quads,
769 const PtArray& conics,
771 const IntArray& qSubdivs,
772 const FloatArray& cWeights,
773 GrDrawTarget::AutoReleaseGeometry* arg,
775 GrDrawState* drawState = target->drawState();
777 const SkMatrix& viewM = drawState->getViewMatrix();
779 int vertCnt = kVertsPerQuad * quadCnt + kVertsPerQuad * conicCnt;
781 target->drawState()->setVertexAttribs<gHairlineBezierAttribs>(SK_ARRAY_COUNT(gHairlineBezierAttribs));
782 SkASSERT(sizeof(BezierVertex) == target->getDrawState().getVertexSize());
784 if (!arg->set(target, vertCnt, 0)) {
788 BezierVertex* verts = reinterpret_cast<BezierVertex*>(arg->vertices());
790 const SkMatrix* toDevice = NULL;
791 const SkMatrix* toSrc = NULL;
794 if (viewM.hasPerspective()) {
795 if (viewM.invert(&ivm)) {
801 // Seed the dev bounds with some pts known to be inside. Each quad and conic grows the bounding
802 // box to include its vertices.
805 seedPts[0] = quads[0];
806 seedPts[1] = quads[2];
807 } else if (conicCnt) {
808 seedPts[0] = conics[0];
809 seedPts[1] = conics[2];
811 if (NULL != toDevice) {
812 toDevice->mapPoints(seedPts, 2);
814 devBounds->set(seedPts[0], seedPts[1]);
816 int unsubdivQuadCnt = quads.count() / 3;
817 for (int i = 0; i < unsubdivQuadCnt; ++i) {
818 SkASSERT(qSubdivs[i] >= 0);
819 add_quads(&quads[3*i], qSubdivs[i], toDevice, toSrc, &verts, devBounds);
823 for (int i = 0; i < conicCnt; ++i) {
824 add_conics(&conics[3*i], cWeights[i], toDevice, toSrc, &verts, devBounds);
829 bool GrAAHairLinePathRenderer::canDrawPath(const SkPath& path,
830 const SkStrokeRec& stroke,
831 const GrDrawTarget* target,
832 bool antiAlias) const {
837 if (!IsStrokeHairlineOrEquivalent(stroke,
838 target->getDrawState().getViewMatrix(),
843 if (SkPath::kLine_SegmentMask == path.getSegmentMasks() ||
844 target->caps()->shaderDerivativeSupport()) {
850 template <class VertexType>
851 bool check_bounds(GrDrawState* drawState, const SkRect& devBounds, void* vertices, int vCount)
853 SkRect tolDevBounds = devBounds;
854 // The bounds ought to be tight, but in perspective the below code runs the verts
855 // through the view matrix to get back to dev coords, which can introduce imprecision.
856 if (drawState->getViewMatrix().hasPerspective()) {
857 tolDevBounds.outset(SK_Scalar1 / 1000, SK_Scalar1 / 1000);
859 // Non-persp matrices cause this path renderer to draw in device space.
860 SkASSERT(drawState->getViewMatrix().isIdentity());
864 VertexType* verts = reinterpret_cast<VertexType*>(vertices);
866 for (int i = 0; i < vCount; ++i) {
867 SkPoint pos = verts[i].fPos;
868 // This is a hack to workaround the fact that we move some degenerate segments offscreen.
869 if (SK_ScalarMax == pos.fX) {
872 drawState->getViewMatrix().mapPoints(&pos, 1);
874 actualBounds.set(pos.fX, pos.fY, pos.fX, pos.fY);
877 actualBounds.growToInclude(pos.fX, pos.fY);
881 return tolDevBounds.contains(actualBounds);
887 bool GrAAHairLinePathRenderer::onDrawPath(const SkPath& path,
888 const SkStrokeRec& stroke,
889 GrDrawTarget* target,
891 GrDrawState* drawState = target->drawState();
893 SkScalar hairlineCoverage;
894 if (IsStrokeHairlineOrEquivalent(stroke,
895 target->getDrawState().getViewMatrix(),
896 &hairlineCoverage)) {
897 uint8_t newCoverage = SkScalarRoundToInt(hairlineCoverage *
898 target->getDrawState().getCoverage());
899 target->drawState()->setCoverage(newCoverage);
902 SkIRect devClipBounds;
903 target->getClip()->getConservativeBounds(drawState->getRenderTarget(), &devClipBounds);
908 PREALLOC_PTARRAY(128) lines;
909 PREALLOC_PTARRAY(128) quads;
910 PREALLOC_PTARRAY(128) conics;
913 quadCnt = generate_lines_and_quads(path, drawState->getViewMatrix(), devClipBounds,
914 &lines, &quads, &conics, &qSubdivs, &cWeights);
915 lineCnt = lines.count() / 2;
916 conicCnt = conics.count() / 3;
920 GrDrawTarget::AutoReleaseGeometry arg;
923 if (!this->createLineGeom(path,
932 GrDrawTarget::AutoStateRestore asr;
934 // createLineGeom transforms the geometry to device space when the matrix does not have
936 if (target->getDrawState().getViewMatrix().hasPerspective()) {
937 asr.set(target, GrDrawTarget::kPreserve_ASRInit);
938 } else if (!asr.setIdentity(target, GrDrawTarget::kPreserve_ASRInit)) {
941 GrDrawState* drawState = target->drawState();
944 SkASSERT(check_bounds<LineVertex>(drawState, devBounds, arg.vertices(),
945 kVertsPerLineSeg * lineCnt));
948 GrDrawState::AutoRestoreEffects are(drawState);
949 target->setIndexSourceToBuffer(fLinesIndexBuffer);
951 while (lines < lineCnt) {
952 int n = SkTMin(lineCnt - lines, kNumLineSegsInIdxBuffer);
953 target->drawIndexed(kTriangles_GrPrimitiveType,
954 kVertsPerLineSeg*lines, // startV
956 kVertsPerLineSeg*n, // vCount
957 kIdxsPerLineSeg*n, // iCount
964 // then quadratics/conics
965 if (quadCnt || conicCnt) {
966 GrDrawTarget::AutoReleaseGeometry arg;
969 if (!this->createBezierGeom(path,
982 GrDrawTarget::AutoStateRestore asr;
984 // createGeom transforms the geometry to device space when the matrix does not have
986 if (target->getDrawState().getViewMatrix().hasPerspective()) {
987 asr.set(target, GrDrawTarget::kPreserve_ASRInit);
988 } else if (!asr.setIdentity(target, GrDrawTarget::kPreserve_ASRInit)) {
991 GrDrawState* drawState = target->drawState();
993 static const int kEdgeAttrIndex = 1;
996 SkASSERT(check_bounds<BezierVertex>(drawState, devBounds, arg.vertices(),
997 kVertsPerQuad * quadCnt + kVertsPerQuad * conicCnt));
1000 GrEffectRef* hairQuadEffect = GrQuadEffect::Create(kHairlineAA_GrEffectEdgeType,
1002 SkASSERT(NULL != hairQuadEffect);
1003 GrDrawState::AutoRestoreEffects are(drawState);
1004 target->setIndexSourceToBuffer(fQuadsIndexBuffer);
1005 drawState->addCoverageEffect(hairQuadEffect, kEdgeAttrIndex)->unref();
1007 while (quads < quadCnt) {
1008 int n = SkTMin(quadCnt - quads, kNumQuadsInIdxBuffer);
1009 target->drawIndexed(kTriangles_GrPrimitiveType,
1010 kVertsPerQuad*quads, // startV
1012 kVertsPerQuad*n, // vCount
1013 kIdxsPerQuad*n, // iCount
1020 GrDrawState::AutoRestoreEffects are(drawState);
1021 GrEffectRef* hairConicEffect = GrConicEffect::Create(kHairlineAA_GrEffectEdgeType,
1023 SkASSERT(NULL != hairConicEffect);
1024 drawState->addCoverageEffect(hairConicEffect, 1, 2)->unref();
1026 while (conics < conicCnt) {
1027 int n = SkTMin(conicCnt - conics, kNumQuadsInIdxBuffer);
1028 target->drawIndexed(kTriangles_GrPrimitiveType,
1029 kVertsPerQuad*(quadCnt + conics), // startV
1031 kVertsPerQuad*n, // vCount
1032 kIdxsPerQuad*n, // iCount
1039 target->resetIndexSource();