2 * Copyright 2014 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 "GrDashingEffect.h"
10 #include "../GrAARectRenderer.h"
12 #include "GrGeometryProcessor.h"
13 #include "gl/builders/GrGLProgramBuilder.h"
14 #include "gl/GrGLProcessor.h"
15 #include "gl/GrGLGeometryProcessor.h"
16 #include "gl/GrGLSL.h"
17 #include "GrContext.h"
18 #include "GrCoordTransform.h"
19 #include "GrDrawTarget.h"
20 #include "GrDrawTargetCaps.h"
21 #include "GrProcessor.h"
23 #include "GrStrokeInfo.h"
24 #include "GrTBackendProcessorFactory.h"
27 ///////////////////////////////////////////////////////////////////////////////
29 // Returns whether or not the gpu can fast path the dash line effect.
30 static bool can_fast_path_dash(const SkPoint pts[2], const GrStrokeInfo& strokeInfo,
31 const GrDrawTarget& target, const SkMatrix& viewMatrix) {
32 if (target.getDrawState().getRenderTarget()->isMultisampled()) {
36 // Pts must be either horizontal or vertical in src space
37 if (pts[0].fX != pts[1].fX && pts[0].fY != pts[1].fY) {
41 // May be able to relax this to include skew. As of now cannot do perspective
42 // because of the non uniform scaling of bloating a rect
43 if (!viewMatrix.preservesRightAngles()) {
47 if (!strokeInfo.isDashed() || 2 != strokeInfo.dashCount()) {
51 const SkPathEffect::DashInfo& info = strokeInfo.getDashInfo();
52 if (0 == info.fIntervals[0] && 0 == info.fIntervals[1]) {
56 SkPaint::Cap cap = strokeInfo.getStrokeRec().getCap();
57 // Current we do don't handle Round or Square cap dashes
58 if (SkPaint::kRound_Cap == cap && info.fIntervals[0] != 0.f) {
67 struct DashLineVertex {
72 extern const GrVertexAttrib gDashLineNoAAVertexAttribs[] = {
73 { kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding }
76 extern const GrVertexAttrib gDashLineVertexAttribs[] = {
77 { kVec2f_GrVertexAttribType, 0, kPosition_GrVertexAttribBinding },
78 { kVec2f_GrVertexAttribType, sizeof(SkPoint), kGeometryProcessor_GrVertexAttribBinding },
82 static void calc_dash_scaling(SkScalar* parallelScale, SkScalar* perpScale,
83 const SkMatrix& viewMatrix, const SkPoint pts[2]) {
84 SkVector vecSrc = pts[1] - pts[0];
85 SkScalar magSrc = vecSrc.length();
86 SkScalar invSrc = magSrc ? SkScalarInvert(magSrc) : 0;
90 vecSrc.rotateCW(&vecSrcPerp);
91 viewMatrix.mapVectors(&vecSrc, 1);
92 viewMatrix.mapVectors(&vecSrcPerp, 1);
94 // parallelScale tells how much to scale along the line parallel to the dash line
95 // perpScale tells how much to scale in the direction perpendicular to the dash line
96 *parallelScale = vecSrc.length();
97 *perpScale = vecSrcPerp.length();
100 // calculates the rotation needed to aligned pts to the x axis with pts[0] < pts[1]
101 // Stores the rotation matrix in rotMatrix, and the mapped points in ptsRot
102 static void align_to_x_axis(const SkPoint pts[2], SkMatrix* rotMatrix, SkPoint ptsRot[2] = NULL) {
103 SkVector vec = pts[1] - pts[0];
104 SkScalar mag = vec.length();
105 SkScalar inv = mag ? SkScalarInvert(mag) : 0;
108 rotMatrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
110 rotMatrix->mapPoints(ptsRot, pts, 2);
111 // correction for numerical issues if map doesn't make ptsRot exactly horizontal
112 ptsRot[1].fY = pts[0].fY;
116 // Assumes phase < sum of all intervals
117 static SkScalar calc_start_adjustment(const SkPathEffect::DashInfo& info) {
118 SkASSERT(info.fPhase < info.fIntervals[0] + info.fIntervals[1]);
119 if (info.fPhase >= info.fIntervals[0] && info.fPhase != 0) {
120 SkScalar srcIntervalLen = info.fIntervals[0] + info.fIntervals[1];
121 return srcIntervalLen - info.fPhase;
126 static SkScalar calc_end_adjustment(const SkPathEffect::DashInfo& info, const SkPoint pts[2],
127 SkScalar phase, SkScalar* endingInt) {
128 if (pts[1].fX <= pts[0].fX) {
131 SkScalar srcIntervalLen = info.fIntervals[0] + info.fIntervals[1];
132 SkScalar totalLen = pts[1].fX - pts[0].fX;
133 SkScalar temp = SkScalarDiv(totalLen, srcIntervalLen);
134 SkScalar numFullIntervals = SkScalarFloorToScalar(temp);
135 *endingInt = totalLen - numFullIntervals * srcIntervalLen + phase;
136 temp = SkScalarDiv(*endingInt, srcIntervalLen);
137 *endingInt = *endingInt - SkScalarFloorToScalar(temp) * srcIntervalLen;
138 if (0 == *endingInt) {
139 *endingInt = srcIntervalLen;
141 if (*endingInt > info.fIntervals[0]) {
142 if (0 == info.fIntervals[0]) {
143 *endingInt -= 0.01f; // make sure we capture the last zero size pnt (used if has caps)
145 return *endingInt - info.fIntervals[0];
150 static void setup_dashed_rect(const SkRect& rect, DashLineVertex* verts, int idx, const SkMatrix& matrix,
151 SkScalar offset, SkScalar bloat, SkScalar len, SkScalar stroke) {
153 SkScalar startDashX = offset - bloat;
154 SkScalar endDashX = offset + len + bloat;
155 SkScalar startDashY = -stroke - bloat;
156 SkScalar endDashY = stroke + bloat;
157 verts[idx].fDashPos = SkPoint::Make(startDashX , startDashY);
158 verts[idx + 1].fDashPos = SkPoint::Make(startDashX, endDashY);
159 verts[idx + 2].fDashPos = SkPoint::Make(endDashX, endDashY);
160 verts[idx + 3].fDashPos = SkPoint::Make(endDashX, startDashY);
162 verts[idx].fPos = SkPoint::Make(rect.fLeft, rect.fTop);
163 verts[idx + 1].fPos = SkPoint::Make(rect.fLeft, rect.fBottom);
164 verts[idx + 2].fPos = SkPoint::Make(rect.fRight, rect.fBottom);
165 verts[idx + 3].fPos = SkPoint::Make(rect.fRight, rect.fTop);
167 matrix.mapPointsWithStride(&verts[idx].fPos, sizeof(DashLineVertex), 4);
171 bool GrDashingEffect::DrawDashLine(const SkPoint pts[2], const GrPaint& paint,
172 const GrStrokeInfo& strokeInfo, GrGpu* gpu,
173 GrDrawTarget* target, const SkMatrix& vm) {
175 if (!can_fast_path_dash(pts, strokeInfo, *target, vm)) {
179 const SkPathEffect::DashInfo& info = strokeInfo.getDashInfo();
181 SkPaint::Cap cap = strokeInfo.getStrokeRec().getCap();
183 SkScalar srcStrokeWidth = strokeInfo.getStrokeRec().getWidth();
185 // the phase should be normalized to be [0, sum of all intervals)
186 SkASSERT(info.fPhase >= 0 && info.fPhase < info.fIntervals[0] + info.fIntervals[1]);
188 SkScalar srcPhase = info.fPhase;
190 // Rotate the src pts so they are aligned horizontally with pts[0].fX < pts[1].fX
193 if (pts[0].fY != pts[1].fY || pts[0].fX > pts[1].fX) {
195 align_to_x_axis(pts, &rotMatrix, ptsRot);
196 if(!rotMatrix.invert(&srcRotInv)) {
197 SkDebugf("Failed to create invertible rotation matrix!\n");
202 memcpy(ptsRot, pts, 2 * sizeof(SkPoint));
205 bool useAA = paint.isAntiAlias();
207 // Scale corrections of intervals and stroke from view matrix
208 SkScalar parallelScale;
210 calc_dash_scaling(¶llelScale, &perpScale, vm, ptsRot);
212 bool hasCap = SkPaint::kButt_Cap != cap && 0 != srcStrokeWidth;
214 // We always want to at least stroke out half a pixel on each side in device space
215 // so 0.5f / perpScale gives us this min in src space
216 SkScalar halfSrcStroke = SkMaxScalar(srcStrokeWidth * 0.5f, 0.5f / perpScale);
222 strokeAdj = halfSrcStroke;
225 SkScalar startAdj = 0;
227 SkMatrix combinedMatrix = srcRotInv;
228 combinedMatrix.postConcat(vm);
230 bool lineDone = false;
232 bool hasStartRect = false;
233 // If we are using AA, check to see if we are drawing a partial dash at the start. If so
234 // draw it separately here and adjust our start point accordingly
236 if (srcPhase > 0 && srcPhase < info.fIntervals[0]) {
238 startPts[0] = ptsRot[0];
239 startPts[1].fY = startPts[0].fY;
240 startPts[1].fX = SkMinScalar(startPts[0].fX + info.fIntervals[0] - srcPhase,
242 startRect.set(startPts, 2);
243 startRect.outset(strokeAdj, halfSrcStroke);
246 startAdj = info.fIntervals[0] + info.fIntervals[1] - srcPhase;
250 // adjustments for start and end of bounding rect so we only draw dash intervals
251 // contained in the original line segment.
252 startAdj += calc_start_adjustment(info);
254 ptsRot[0].fX += startAdj;
257 SkScalar endingInterval = 0;
258 SkScalar endAdj = calc_end_adjustment(info, ptsRot, srcPhase, &endingInterval);
259 ptsRot[1].fX -= endAdj;
260 if (ptsRot[0].fX >= ptsRot[1].fX) {
265 bool hasEndRect = false;
266 // If we are using AA, check to see if we are drawing a partial dash at then end. If so
267 // draw it separately here and adjust our end point accordingly
268 if (useAA && !lineDone) {
269 // If we adjusted the end then we will not be drawing a partial dash at the end.
270 // If we didn't adjust the end point then we just need to make sure the ending
271 // dash isn't a full dash
272 if (0 == endAdj && endingInterval != info.fIntervals[0]) {
274 endPts[1] = ptsRot[1];
275 endPts[0].fY = endPts[1].fY;
276 endPts[0].fX = endPts[1].fX - endingInterval;
278 endRect.set(endPts, 2);
279 endRect.outset(strokeAdj, halfSrcStroke);
282 endAdj = endingInterval + info.fIntervals[1];
284 ptsRot[1].fX -= endAdj;
285 if (ptsRot[0].fX >= ptsRot[1].fX) {
295 // Change the dashing info from src space into device space
296 SkScalar devIntervals[2];
297 devIntervals[0] = info.fIntervals[0] * parallelScale;
298 devIntervals[1] = info.fIntervals[1] * parallelScale;
299 SkScalar devPhase = srcPhase * parallelScale;
300 SkScalar strokeWidth = srcStrokeWidth * perpScale;
302 if ((strokeWidth < 1.f && !useAA) || 0.f == strokeWidth) {
306 SkScalar halfDevStroke = strokeWidth * 0.5f;
308 if (SkPaint::kSquare_Cap == cap && 0 != srcStrokeWidth) {
309 // add cap to on interveal and remove from off interval
310 devIntervals[0] += strokeWidth;
311 devIntervals[1] -= strokeWidth;
313 SkScalar startOffset = devIntervals[1] * 0.5f + devPhase;
315 SkScalar bloatX = useAA ? 0.5f / parallelScale : 0.f;
316 SkScalar bloatY = useAA ? 0.5f / perpScale : 0.f;
318 SkScalar devBloat = useAA ? 0.5f : 0.f;
320 GrDrawState* drawState = target->drawState();
321 if (devIntervals[1] <= 0.f && useAA) {
322 // Case when we end up drawing a solid AA rect
323 // Reset the start rect to draw this single solid rect
324 // but it requires to upload a new intervals uniform so we can mimic
326 ptsRot[0].fX -= hasStartRect ? startAdj : 0;
327 ptsRot[1].fX += hasEndRect ? endAdj : 0;
328 startRect.set(ptsRot, 2);
329 startRect.outset(strokeAdj, halfSrcStroke);
334 SkPoint devicePts[2];
335 vm.mapPoints(devicePts, ptsRot, 2);
336 SkScalar lineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
338 lineLength += 2.f * halfDevStroke;
340 devIntervals[0] = lineLength;
342 if (devIntervals[1] > 0.f || useAA) {
343 SkPathEffect::DashInfo devInfo;
344 devInfo.fPhase = devPhase;
346 devInfo.fIntervals = devIntervals;
347 GrPrimitiveEdgeType edgeType= useAA ? kFillAA_GrProcessorEdgeType :
348 kFillBW_GrProcessorEdgeType;
349 bool isRoundCap = SkPaint::kRound_Cap == cap;
350 GrDashingEffect::DashCap capType = isRoundCap ? GrDashingEffect::kRound_DashCap :
351 GrDashingEffect::kNonRound_DashCap;
352 drawState->setGeometryProcessor(
353 GrDashingEffect::Create(edgeType, devInfo, strokeWidth, capType))->unref();
355 // Set up the vertex data for the line and start/end dashes
356 drawState->setVertexAttribs<gDashLineVertexAttribs>(SK_ARRAY_COUNT(gDashLineVertexAttribs),
357 sizeof(DashLineVertex));
359 // Set up the vertex data for the line and start/end dashes
360 drawState->setVertexAttribs<gDashLineNoAAVertexAttribs>(
361 SK_ARRAY_COUNT(gDashLineNoAAVertexAttribs), sizeof(DashLineVertex));
364 int totalRectCnt = 0;
366 totalRectCnt += !lineDone ? 1 : 0;
367 totalRectCnt += hasStartRect ? 1 : 0;
368 totalRectCnt += hasEndRect ? 1 : 0;
370 GrDrawTarget::AutoReleaseGeometry geo(target, totalRectCnt * 4, 0);
371 if (!geo.succeeded()) {
372 SkDebugf("Failed to get space for vertices!\n");
376 DashLineVertex* verts = reinterpret_cast<DashLineVertex*>(geo.vertices());
380 if (SkPaint::kRound_Cap == cap && 0 != srcStrokeWidth) {
381 // need to adjust this for round caps to correctly set the dashPos attrib on vertices
382 startOffset -= halfDevStroke;
385 // Draw interior part of dashed line
387 SkPoint devicePts[2];
388 vm.mapPoints(devicePts, ptsRot, 2);
389 SkScalar lineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
391 lineLength += 2.f * halfDevStroke;
395 bounds.set(ptsRot[0].fX, ptsRot[0].fY, ptsRot[1].fX, ptsRot[1].fY);
396 bounds.outset(bloatX + strokeAdj, bloatY + halfSrcStroke);
397 setup_dashed_rect(bounds, verts, curVIdx, combinedMatrix, startOffset, devBloat,
398 lineLength, halfDevStroke);
403 SkASSERT(useAA); // so that we know bloatX and bloatY have been set
404 startRect.outset(bloatX, bloatY);
405 setup_dashed_rect(startRect, verts, curVIdx, combinedMatrix, startOffset, devBloat,
406 devIntervals[0], halfDevStroke);
411 SkASSERT(useAA); // so that we know bloatX and bloatY have been set
412 endRect.outset(bloatX, bloatY);
413 setup_dashed_rect(endRect, verts, curVIdx, combinedMatrix, startOffset, devBloat,
414 devIntervals[0], halfDevStroke);
417 target->setIndexSourceToBuffer(gpu->getContext()->getQuadIndexBuffer());
418 target->drawIndexedInstances(kTriangles_GrPrimitiveType, totalRectCnt, 4, 6);
419 target->resetIndexSource();
423 //////////////////////////////////////////////////////////////////////////////
425 class GLDashingCircleEffect;
427 * This effect will draw a dotted line (defined as a dashed lined with round caps and no on
428 * interval). The radius of the dots is given by the strokeWidth and the spacing by the DashInfo.
429 * Both of the previous two parameters are in device space. This effect also requires the setting of
430 * a vec2 vertex attribute for the the four corners of the bounding rect. This attribute is the
431 * "dash position" of each vertex. In other words it is the vertex coords (in device space) if we
432 * transform the line to be horizontal, with the start of line at the origin then shifted to the
433 * right by half the off interval. The line then goes in the positive x direction.
435 class DashingCircleEffect : public GrGeometryProcessor {
437 typedef SkPathEffect::DashInfo DashInfo;
439 static GrGeometryProcessor* Create(GrPrimitiveEdgeType edgeType,
440 const DashInfo& info,
443 virtual ~DashingCircleEffect();
445 static const char* Name() { return "DashingCircleEffect"; }
447 const GrShaderVar& inCoord() const { return fInCoord; }
449 GrPrimitiveEdgeType getEdgeType() const { return fEdgeType; }
451 SkScalar getRadius() const { return fRadius; }
453 SkScalar getCenterX() const { return fCenterX; }
455 SkScalar getIntervalLength() const { return fIntervalLength; }
457 typedef GLDashingCircleEffect GLProcessor;
459 virtual const GrBackendGeometryProcessorFactory& getFactory() const SK_OVERRIDE;
462 DashingCircleEffect(GrPrimitiveEdgeType edgeType, const DashInfo& info, SkScalar radius);
464 virtual bool onIsEqual(const GrGeometryProcessor& other) const SK_OVERRIDE;
466 virtual void onComputeInvariantOutput(InvariantOutput* inout) const SK_OVERRIDE;
468 GrPrimitiveEdgeType fEdgeType;
469 const GrShaderVar& fInCoord;
470 SkScalar fIntervalLength;
474 GR_DECLARE_GEOMETRY_PROCESSOR_TEST;
476 typedef GrGeometryProcessor INHERITED;
479 //////////////////////////////////////////////////////////////////////////////
481 class GLDashingCircleEffect : public GrGLGeometryProcessor {
483 GLDashingCircleEffect(const GrBackendProcessorFactory&, const GrProcessor&);
485 virtual void emitCode(const EmitArgs&) SK_OVERRIDE;
487 static inline void GenKey(const GrProcessor&, const GrGLCaps&, GrProcessorKeyBuilder*);
489 virtual void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE;
492 GrGLProgramDataManager::UniformHandle fParamUniform;
493 SkScalar fPrevRadius;
494 SkScalar fPrevCenterX;
495 SkScalar fPrevIntervalLength;
496 typedef GrGLGeometryProcessor INHERITED;
499 GLDashingCircleEffect::GLDashingCircleEffect(const GrBackendProcessorFactory& factory,
501 : INHERITED (factory) {
502 fPrevRadius = SK_ScalarMin;
503 fPrevCenterX = SK_ScalarMin;
504 fPrevIntervalLength = SK_ScalarMax;
507 void GLDashingCircleEffect::emitCode(const EmitArgs& args) {
508 const DashingCircleEffect& dce = args.fGP.cast<DashingCircleEffect>();
509 const char *paramName;
510 // The param uniforms, xyz, refer to circle radius - 0.5, cicles center x coord, and
511 // the total interval length of the dash.
512 fParamUniform = args.fPB->addUniform(GrGLProgramBuilder::kFragment_Visibility,
517 GrGLVertToFrag v(kVec2f_GrSLType);
518 args.fPB->addVarying("Coord", &v);
520 GrGLVertexBuilder* vsBuilder = args.fPB->getVertexShaderBuilder();
521 vsBuilder->codeAppendf("\t%s = %s;\n", v.vsOut(), dce.inCoord().c_str());
523 // transforms all points so that we can compare them to our test circle
524 GrGLGPFragmentBuilder* fsBuilder = args.fPB->getFragmentShaderBuilder();
525 fsBuilder->codeAppendf("\t\tfloat xShifted = %s.x - floor(%s.x / %s.z) * %s.z;\n",
526 v.fsIn(), v.fsIn(), paramName, paramName);
527 fsBuilder->codeAppendf("\t\tvec2 fragPosShifted = vec2(xShifted, %s.y);\n", v.fsIn());
528 fsBuilder->codeAppendf("\t\tvec2 center = vec2(%s.y, 0.0);\n", paramName);
529 fsBuilder->codeAppend("\t\tfloat dist = length(center - fragPosShifted);\n");
530 if (GrProcessorEdgeTypeIsAA(dce.getEdgeType())) {
531 fsBuilder->codeAppendf("\t\tfloat diff = dist - %s.x;\n", paramName);
532 fsBuilder->codeAppend("\t\tdiff = 1.0 - diff;\n");
533 fsBuilder->codeAppend("\t\tfloat alpha = clamp(diff, 0.0, 1.0);\n");
535 fsBuilder->codeAppendf("\t\tfloat alpha = 1.0;\n");
536 fsBuilder->codeAppendf("\t\talpha *= dist < %s.x + 0.5 ? 1.0 : 0.0;\n", paramName);
538 fsBuilder->codeAppendf("\t\t%s = %s;\n", args.fOutput,
539 (GrGLSLExpr4(args.fInput) * GrGLSLExpr1("alpha")).c_str());
542 void GLDashingCircleEffect::setData(const GrGLProgramDataManager& pdman
543 , const GrProcessor& processor) {
544 const DashingCircleEffect& dce = processor.cast<DashingCircleEffect>();
545 SkScalar radius = dce.getRadius();
546 SkScalar centerX = dce.getCenterX();
547 SkScalar intervalLength = dce.getIntervalLength();
548 if (radius != fPrevRadius || centerX != fPrevCenterX || intervalLength != fPrevIntervalLength) {
549 pdman.set3f(fParamUniform, radius - 0.5f, centerX, intervalLength);
550 fPrevRadius = radius;
551 fPrevCenterX = centerX;
552 fPrevIntervalLength = intervalLength;
556 void GLDashingCircleEffect::GenKey(const GrProcessor& processor, const GrGLCaps&,
557 GrProcessorKeyBuilder* b) {
558 const DashingCircleEffect& dce = processor.cast<DashingCircleEffect>();
559 b->add32(dce.getEdgeType());
562 //////////////////////////////////////////////////////////////////////////////
564 GrGeometryProcessor* DashingCircleEffect::Create(GrPrimitiveEdgeType edgeType, const DashInfo& info,
566 if (info.fCount != 2 || info.fIntervals[0] != 0) {
570 return SkNEW_ARGS(DashingCircleEffect, (edgeType, info, radius));
573 DashingCircleEffect::~DashingCircleEffect() {}
575 void DashingCircleEffect::onComputeInvariantOutput(InvariantOutput* inout) const {
576 inout->mulByUnknownAlpha();
579 const GrBackendGeometryProcessorFactory& DashingCircleEffect::getFactory() const {
580 return GrTBackendGeometryProcessorFactory<DashingCircleEffect>::getInstance();
583 DashingCircleEffect::DashingCircleEffect(GrPrimitiveEdgeType edgeType, const DashInfo& info,
585 : fEdgeType(edgeType)
586 , fInCoord(this->addVertexAttrib(GrShaderVar("inCoord",
588 GrShaderVar::kAttribute_TypeModifier))) {
589 SkScalar onLen = info.fIntervals[0];
590 SkScalar offLen = info.fIntervals[1];
591 fIntervalLength = onLen + offLen;
593 fCenterX = SkScalarHalf(offLen);
596 bool DashingCircleEffect::onIsEqual(const GrGeometryProcessor& other) const {
597 const DashingCircleEffect& dce = other.cast<DashingCircleEffect>();
598 return (fEdgeType == dce.fEdgeType &&
599 fIntervalLength == dce.fIntervalLength &&
600 fRadius == dce.fRadius &&
601 fCenterX == dce.fCenterX);
604 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingCircleEffect);
606 GrGeometryProcessor* DashingCircleEffect::TestCreate(SkRandom* random,
608 const GrDrawTargetCaps& caps,
610 GrPrimitiveEdgeType edgeType = static_cast<GrPrimitiveEdgeType>(random->nextULessThan(
611 kGrProcessorEdgeTypeCnt));
612 SkScalar strokeWidth = random->nextRangeScalar(0, 100.f);
615 SkAutoTArray<SkScalar> intervals(info.fCount);
616 info.fIntervals = intervals.get();
617 info.fIntervals[0] = 0;
618 info.fIntervals[1] = random->nextRangeScalar(0, 10.f);
619 info.fPhase = random->nextRangeScalar(0, info.fIntervals[1]);
621 return DashingCircleEffect::Create(edgeType, info, strokeWidth);
624 //////////////////////////////////////////////////////////////////////////////
626 class GLDashingLineEffect;
629 * This effect will draw a dashed line. The width of the dash is given by the strokeWidth and the
630 * length and spacing by the DashInfo. Both of the previous two parameters are in device space.
631 * This effect also requires the setting of a vec2 vertex attribute for the the four corners of the
632 * bounding rect. This attribute is the "dash position" of each vertex. In other words it is the
633 * vertex coords (in device space) if we transform the line to be horizontal, with the start of
634 * line at the origin then shifted to the right by half the off interval. The line then goes in the
635 * positive x direction.
637 class DashingLineEffect : public GrGeometryProcessor {
639 typedef SkPathEffect::DashInfo DashInfo;
641 static GrGeometryProcessor* Create(GrPrimitiveEdgeType edgeType,
642 const DashInfo& info,
643 SkScalar strokeWidth);
645 virtual ~DashingLineEffect();
647 static const char* Name() { return "DashingEffect"; }
649 const GrShaderVar& inCoord() const { return fInCoord; }
651 GrPrimitiveEdgeType getEdgeType() const { return fEdgeType; }
653 const SkRect& getRect() const { return fRect; }
655 SkScalar getIntervalLength() const { return fIntervalLength; }
657 typedef GLDashingLineEffect GLProcessor;
659 virtual const GrBackendGeometryProcessorFactory& getFactory() const SK_OVERRIDE;
662 DashingLineEffect(GrPrimitiveEdgeType edgeType, const DashInfo& info, SkScalar strokeWidth);
664 virtual bool onIsEqual(const GrGeometryProcessor& other) const SK_OVERRIDE;
666 virtual void onComputeInvariantOutput(InvariantOutput* inout) const SK_OVERRIDE;
668 GrPrimitiveEdgeType fEdgeType;
669 const GrShaderVar& fInCoord;
671 SkScalar fIntervalLength;
673 GR_DECLARE_GEOMETRY_PROCESSOR_TEST;
675 typedef GrGeometryProcessor INHERITED;
678 //////////////////////////////////////////////////////////////////////////////
680 class GLDashingLineEffect : public GrGLGeometryProcessor {
682 GLDashingLineEffect(const GrBackendProcessorFactory&, const GrProcessor&);
684 virtual void emitCode(const EmitArgs&) SK_OVERRIDE;
686 static inline void GenKey(const GrProcessor&, const GrGLCaps&, GrProcessorKeyBuilder*);
688 virtual void setData(const GrGLProgramDataManager&, const GrProcessor&) SK_OVERRIDE;
691 GrGLProgramDataManager::UniformHandle fRectUniform;
692 GrGLProgramDataManager::UniformHandle fIntervalUniform;
694 SkScalar fPrevIntervalLength;
695 typedef GrGLGeometryProcessor INHERITED;
698 GLDashingLineEffect::GLDashingLineEffect(const GrBackendProcessorFactory& factory,
700 : INHERITED (factory) {
701 fPrevRect.fLeft = SK_ScalarNaN;
702 fPrevIntervalLength = SK_ScalarMax;
705 void GLDashingLineEffect::emitCode(const EmitArgs& args) {
706 const DashingLineEffect& de = args.fGP.cast<DashingLineEffect>();
707 const char *rectName;
708 // The rect uniform's xyzw refer to (left + 0.5, top + 0.5, right - 0.5, bottom - 0.5),
710 fRectUniform = args.fPB->addUniform(GrGLProgramBuilder::kFragment_Visibility,
714 const char *intervalName;
715 // The interval uniform's refers to the total length of the interval (on + off)
716 fIntervalUniform = args.fPB->addUniform(GrGLProgramBuilder::kFragment_Visibility,
721 GrGLVertToFrag v(kVec2f_GrSLType);
722 args.fPB->addVarying("Coord", &v);
723 GrGLVertexBuilder* vsBuilder = args.fPB->getVertexShaderBuilder();
724 vsBuilder->codeAppendf("\t%s = %s;\n", v.vsOut(), de.inCoord().c_str());
726 // transforms all points so that we can compare them to our test rect
727 GrGLGPFragmentBuilder* fsBuilder = args.fPB->getFragmentShaderBuilder();
728 fsBuilder->codeAppendf("\t\tfloat xShifted = %s.x - floor(%s.x / %s) * %s;\n",
729 v.fsIn(), v.fsIn(), intervalName, intervalName);
730 fsBuilder->codeAppendf("\t\tvec2 fragPosShifted = vec2(xShifted, %s.y);\n", v.fsIn());
731 if (GrProcessorEdgeTypeIsAA(de.getEdgeType())) {
732 // The amount of coverage removed in x and y by the edges is computed as a pair of negative
733 // numbers, xSub and ySub.
734 fsBuilder->codeAppend("\t\tfloat xSub, ySub;\n");
735 fsBuilder->codeAppendf("\t\txSub = min(fragPosShifted.x - %s.x, 0.0);\n", rectName);
736 fsBuilder->codeAppendf("\t\txSub += min(%s.z - fragPosShifted.x, 0.0);\n", rectName);
737 fsBuilder->codeAppendf("\t\tySub = min(fragPosShifted.y - %s.y, 0.0);\n", rectName);
738 fsBuilder->codeAppendf("\t\tySub += min(%s.w - fragPosShifted.y, 0.0);\n", rectName);
739 // Now compute coverage in x and y and multiply them to get the fraction of the pixel
741 fsBuilder->codeAppendf("\t\tfloat alpha = (1.0 + max(xSub, -1.0)) * (1.0 + max(ySub, -1.0));\n");
743 // Assuming the bounding geometry is tight so no need to check y values
744 fsBuilder->codeAppendf("\t\tfloat alpha = 1.0;\n");
745 fsBuilder->codeAppendf("\t\talpha *= (fragPosShifted.x - %s.x) > -0.5 ? 1.0 : 0.0;\n", rectName);
746 fsBuilder->codeAppendf("\t\talpha *= (%s.z - fragPosShifted.x) >= -0.5 ? 1.0 : 0.0;\n", rectName);
748 fsBuilder->codeAppendf("\t\t%s = %s;\n", args.fOutput,
749 (GrGLSLExpr4(args.fInput) * GrGLSLExpr1("alpha")).c_str());
752 void GLDashingLineEffect::setData(const GrGLProgramDataManager& pdman,
753 const GrProcessor& processor) {
754 const DashingLineEffect& de = processor.cast<DashingLineEffect>();
755 const SkRect& rect = de.getRect();
756 SkScalar intervalLength = de.getIntervalLength();
757 if (rect != fPrevRect || intervalLength != fPrevIntervalLength) {
758 pdman.set4f(fRectUniform, rect.fLeft + 0.5f, rect.fTop + 0.5f,
759 rect.fRight - 0.5f, rect.fBottom - 0.5f);
760 pdman.set1f(fIntervalUniform, intervalLength);
762 fPrevIntervalLength = intervalLength;
766 void GLDashingLineEffect::GenKey(const GrProcessor& processor, const GrGLCaps&,
767 GrProcessorKeyBuilder* b) {
768 const DashingLineEffect& de = processor.cast<DashingLineEffect>();
769 b->add32(de.getEdgeType());
772 //////////////////////////////////////////////////////////////////////////////
774 GrGeometryProcessor* DashingLineEffect::Create(GrPrimitiveEdgeType edgeType,
775 const DashInfo& info,
776 SkScalar strokeWidth) {
777 if (info.fCount != 2) {
781 return SkNEW_ARGS(DashingLineEffect, (edgeType, info, strokeWidth));
784 DashingLineEffect::~DashingLineEffect() {}
786 void DashingLineEffect::onComputeInvariantOutput(InvariantOutput* inout) const {
787 inout->mulByUnknownAlpha();
790 const GrBackendGeometryProcessorFactory& DashingLineEffect::getFactory() const {
791 return GrTBackendGeometryProcessorFactory<DashingLineEffect>::getInstance();
794 DashingLineEffect::DashingLineEffect(GrPrimitiveEdgeType edgeType, const DashInfo& info,
795 SkScalar strokeWidth)
796 : fEdgeType(edgeType)
797 , fInCoord(this->addVertexAttrib(GrShaderVar("inCoord",
799 GrShaderVar::kAttribute_TypeModifier))) {
800 SkScalar onLen = info.fIntervals[0];
801 SkScalar offLen = info.fIntervals[1];
802 SkScalar halfOffLen = SkScalarHalf(offLen);
803 SkScalar halfStroke = SkScalarHalf(strokeWidth);
804 fIntervalLength = onLen + offLen;
805 fRect.set(halfOffLen, -halfStroke, halfOffLen + onLen, halfStroke);
808 bool DashingLineEffect::onIsEqual(const GrGeometryProcessor& other) const {
809 const DashingLineEffect& de = other.cast<DashingLineEffect>();
810 return (fEdgeType == de.fEdgeType &&
812 fIntervalLength == de.fIntervalLength);
815 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingLineEffect);
817 GrGeometryProcessor* DashingLineEffect::TestCreate(SkRandom* random,
819 const GrDrawTargetCaps& caps,
821 GrPrimitiveEdgeType edgeType = static_cast<GrPrimitiveEdgeType>(random->nextULessThan(
822 kGrProcessorEdgeTypeCnt));
823 SkScalar strokeWidth = random->nextRangeScalar(0, 100.f);
826 SkAutoTArray<SkScalar> intervals(info.fCount);
827 info.fIntervals = intervals.get();
828 info.fIntervals[0] = random->nextRangeScalar(0, 10.f);
829 info.fIntervals[1] = random->nextRangeScalar(0, 10.f);
830 info.fPhase = random->nextRangeScalar(0, info.fIntervals[0] + info.fIntervals[1]);
832 return DashingLineEffect::Create(edgeType, info, strokeWidth);
835 //////////////////////////////////////////////////////////////////////////////
837 GrGeometryProcessor* GrDashingEffect::Create(GrPrimitiveEdgeType edgeType,
838 const SkPathEffect::DashInfo& info,
839 SkScalar strokeWidth,
840 GrDashingEffect::DashCap cap) {
842 case GrDashingEffect::kRound_DashCap:
843 return DashingCircleEffect::Create(edgeType, info, SkScalarHalf(strokeWidth));
844 case GrDashingEffect::kNonRound_DashCap:
845 return DashingLineEffect::Create(edgeType, info, strokeWidth);
847 SkFAIL("Unexpected dashed cap.");