• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 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 "GrDashOp.h"
9 #include "GrAppliedClip.h"
10 #include "GrCaps.h"
11 #include "GrContext.h"
12 #include "GrContextPriv.h"
13 #include "GrCoordTransform.h"
14 #include "GrDefaultGeoProcFactory.h"
15 #include "GrDrawOpTest.h"
16 #include "GrGeometryProcessor.h"
17 #include "GrMemoryPool.h"
18 #include "GrOpFlushState.h"
19 #include "GrProcessor.h"
20 #include "GrQuad.h"
21 #include "GrStyle.h"
22 #include "GrVertexWriter.h"
23 #include "SkGr.h"
24 #include "SkMatrixPriv.h"
25 #include "SkPointPriv.h"
26 #include "glsl/GrGLSLFragmentShaderBuilder.h"
27 #include "glsl/GrGLSLGeometryProcessor.h"
28 #include "glsl/GrGLSLProgramDataManager.h"
29 #include "glsl/GrGLSLUniformHandler.h"
30 #include "glsl/GrGLSLVarying.h"
31 #include "glsl/GrGLSLVertexGeoBuilder.h"
32 #include "ops/GrMeshDrawOp.h"
33 
34 using AAMode = GrDashOp::AAMode;
35 
36 ///////////////////////////////////////////////////////////////////////////////
37 
38 // Returns whether or not the gpu can fast path the dash line effect.
CanDrawDashLine(const SkPoint pts[2],const GrStyle & style,const SkMatrix & viewMatrix)39 bool GrDashOp::CanDrawDashLine(const SkPoint pts[2], const GrStyle& style,
40                                const SkMatrix& viewMatrix) {
41     // Pts must be either horizontal or vertical in src space
42     if (pts[0].fX != pts[1].fX && pts[0].fY != pts[1].fY) {
43         return false;
44     }
45 
46     // May be able to relax this to include skew. As of now cannot do perspective
47     // because of the non uniform scaling of bloating a rect
48     if (!viewMatrix.preservesRightAngles()) {
49         return false;
50     }
51 
52     if (!style.isDashed() || 2 != style.dashIntervalCnt()) {
53         return false;
54     }
55 
56     const SkScalar* intervals = style.dashIntervals();
57     if (0 == intervals[0] && 0 == intervals[1]) {
58         return false;
59     }
60 
61     SkPaint::Cap cap = style.strokeRec().getCap();
62     if (SkPaint::kRound_Cap == cap) {
63         // Current we don't support round caps unless the on interval is zero
64         if (intervals[0] != 0.f) {
65             return false;
66         }
67         // If the width of the circle caps in greater than the off interval we will pick up unwanted
68         // segments of circles at the start and end of the dash line.
69         if (style.strokeRec().getWidth() > intervals[1]) {
70             return false;
71         }
72     }
73 
74     return true;
75 }
76 
calc_dash_scaling(SkScalar * parallelScale,SkScalar * perpScale,const SkMatrix & viewMatrix,const SkPoint pts[2])77 static void calc_dash_scaling(SkScalar* parallelScale, SkScalar* perpScale,
78                             const SkMatrix& viewMatrix, const SkPoint pts[2]) {
79     SkVector vecSrc = pts[1] - pts[0];
80     if (pts[1] == pts[0]) {
81         vecSrc.set(1.0, 0.0);
82     }
83     SkScalar magSrc = vecSrc.length();
84     SkScalar invSrc = magSrc ? SkScalarInvert(magSrc) : 0;
85     vecSrc.scale(invSrc);
86 
87     SkVector vecSrcPerp;
88     SkPointPriv::RotateCW(vecSrc, &vecSrcPerp);
89     viewMatrix.mapVectors(&vecSrc, 1);
90     viewMatrix.mapVectors(&vecSrcPerp, 1);
91 
92     // parallelScale tells how much to scale along the line parallel to the dash line
93     // perpScale tells how much to scale in the direction perpendicular to the dash line
94     *parallelScale = vecSrc.length();
95     *perpScale = vecSrcPerp.length();
96 }
97 
98 // calculates the rotation needed to aligned pts to the x axis with pts[0] < pts[1]
99 // Stores the rotation matrix in rotMatrix, and the mapped points in ptsRot
align_to_x_axis(const SkPoint pts[2],SkMatrix * rotMatrix,SkPoint ptsRot[2]=nullptr)100 static void align_to_x_axis(const SkPoint pts[2], SkMatrix* rotMatrix, SkPoint ptsRot[2] = nullptr) {
101     SkVector vec = pts[1] - pts[0];
102     if (pts[1] == pts[0]) {
103         vec.set(1.0, 0.0);
104     }
105     SkScalar mag = vec.length();
106     SkScalar inv = mag ? SkScalarInvert(mag) : 0;
107 
108     vec.scale(inv);
109     rotMatrix->setSinCos(-vec.fY, vec.fX, pts[0].fX, pts[0].fY);
110     if (ptsRot) {
111         rotMatrix->mapPoints(ptsRot, pts, 2);
112         // correction for numerical issues if map doesn't make ptsRot exactly horizontal
113         ptsRot[1].fY = pts[0].fY;
114     }
115 }
116 
117 // Assumes phase < sum of all intervals
calc_start_adjustment(const SkScalar intervals[2],SkScalar phase)118 static SkScalar calc_start_adjustment(const SkScalar intervals[2], SkScalar phase) {
119     SkASSERT(phase < intervals[0] + intervals[1]);
120     if (phase >= intervals[0] && phase != 0) {
121         SkScalar srcIntervalLen = intervals[0] + intervals[1];
122         return srcIntervalLen - phase;
123     }
124     return 0;
125 }
126 
calc_end_adjustment(const SkScalar intervals[2],const SkPoint pts[2],SkScalar phase,SkScalar * endingInt)127 static SkScalar calc_end_adjustment(const SkScalar intervals[2], const SkPoint pts[2],
128                                     SkScalar phase, SkScalar* endingInt) {
129     if (pts[1].fX <= pts[0].fX) {
130         return 0;
131     }
132     SkScalar srcIntervalLen = intervals[0] + intervals[1];
133     SkScalar totalLen = pts[1].fX - pts[0].fX;
134     SkScalar temp = totalLen / srcIntervalLen;
135     SkScalar numFullIntervals = SkScalarFloorToScalar(temp);
136     *endingInt = totalLen - numFullIntervals * srcIntervalLen + phase;
137     temp = *endingInt / srcIntervalLen;
138     *endingInt = *endingInt - SkScalarFloorToScalar(temp) * srcIntervalLen;
139     if (0 == *endingInt) {
140         *endingInt = srcIntervalLen;
141     }
142     if (*endingInt > intervals[0]) {
143         return *endingInt - intervals[0];
144     }
145     return 0;
146 }
147 
148 enum DashCap {
149     kRound_DashCap,
150     kNonRound_DashCap,
151 };
152 
setup_dashed_rect(const SkRect & rect,GrVertexWriter & vertices,const SkMatrix & matrix,SkScalar offset,SkScalar bloatX,SkScalar bloatY,SkScalar len,SkScalar stroke,SkScalar startInterval,SkScalar endInterval,SkScalar strokeWidth,DashCap cap)153 static void setup_dashed_rect(const SkRect& rect, GrVertexWriter& vertices, const SkMatrix& matrix,
154                               SkScalar offset, SkScalar bloatX, SkScalar bloatY, SkScalar len,
155                               SkScalar stroke, SkScalar startInterval, SkScalar endInterval,
156                               SkScalar strokeWidth, DashCap cap) {
157     SkScalar intervalLength = startInterval + endInterval;
158     SkRect dashRect = { offset       - bloatX, -stroke - bloatY,
159                         offset + len + bloatX,  stroke + bloatY };
160 
161     if (kRound_DashCap == cap) {
162         SkScalar radius = SkScalarHalf(strokeWidth) - 0.5f;
163         SkScalar centerX = SkScalarHalf(endInterval);
164 
165         vertices.writeQuad(GrQuad(rect, matrix),
166                            GrVertexWriter::TriStripFromRect(dashRect),
167                            intervalLength,
168                            radius,
169                            centerX);
170     } else {
171         SkASSERT(kNonRound_DashCap == cap);
172         SkScalar halfOffLen = SkScalarHalf(endInterval);
173         SkScalar halfStroke = SkScalarHalf(strokeWidth);
174         SkRect rectParam;
175         rectParam.set(halfOffLen                 + 0.5f, -halfStroke + 0.5f,
176                       halfOffLen + startInterval - 0.5f,  halfStroke - 0.5f);
177 
178         vertices.writeQuad(GrQuad(rect, matrix),
179                            GrVertexWriter::TriStripFromRect(dashRect),
180                            intervalLength,
181                            rectParam);
182     }
183 }
184 
185 /**
186  * An GrGeometryProcessor that renders a dashed line.
187  * This GrGeometryProcessor is meant for dashed lines that only have a single on/off interval pair.
188  * Bounding geometry is rendered and the effect computes coverage based on the fragment's
189  * position relative to the dashed line.
190  */
191 static sk_sp<GrGeometryProcessor> make_dash_gp(const SkPMColor4f&,
192                                                AAMode aaMode,
193                                                DashCap cap,
194                                                const SkMatrix& localMatrix,
195                                                bool usesLocalCoords);
196 
197 class DashOp final : public GrMeshDrawOp {
198 public:
199     DEFINE_OP_CLASS_ID
200 
201     struct LineData {
202         SkMatrix fViewMatrix;
203         SkMatrix fSrcRotInv;
204         SkPoint fPtsRot[2];
205         SkScalar fSrcStrokeWidth;
206         SkScalar fPhase;
207         SkScalar fIntervals[2];
208         SkScalar fParallelScale;
209         SkScalar fPerpendicularScale;
210     };
211 
Make(GrContext * context,GrPaint && paint,const LineData & geometry,SkPaint::Cap cap,AAMode aaMode,bool fullDash,const GrUserStencilSettings * stencilSettings)212     static std::unique_ptr<GrDrawOp> Make(GrContext* context,
213                                           GrPaint&& paint,
214                                           const LineData& geometry,
215                                           SkPaint::Cap cap,
216                                           AAMode aaMode, bool fullDash,
217                                           const GrUserStencilSettings* stencilSettings) {
218         GrOpMemoryPool* pool = context->contextPriv().opMemoryPool();
219 
220         return pool->allocate<DashOp>(std::move(paint), geometry, cap,
221                                       aaMode, fullDash, stencilSettings);
222     }
223 
name() const224     const char* name() const override { return "DashOp"; }
225 
visitProxies(const VisitProxyFunc & func,VisitorType) const226     void visitProxies(const VisitProxyFunc& func, VisitorType) const override {
227         fProcessorSet.visitProxies(func);
228     }
229 
230 #ifdef SK_DEBUG
dumpInfo() const231     SkString dumpInfo() const override {
232         SkString string;
233         for (const auto& geo : fLines) {
234             string.appendf("Pt0: [%.2f, %.2f], Pt1: [%.2f, %.2f], Width: %.2f, Ival0: %.2f, "
235                            "Ival1 : %.2f, Phase: %.2f\n",
236                            geo.fPtsRot[0].fX, geo.fPtsRot[0].fY,
237                            geo.fPtsRot[1].fX, geo.fPtsRot[1].fY,
238                            geo.fSrcStrokeWidth,
239                            geo.fIntervals[0],
240                            geo.fIntervals[1],
241                            geo.fPhase);
242         }
243         string += fProcessorSet.dumpProcessors();
244         string += INHERITED::dumpInfo();
245         return string;
246     }
247 #endif
248 
fixedFunctionFlags() const249     FixedFunctionFlags fixedFunctionFlags() const override {
250         FixedFunctionFlags flags = FixedFunctionFlags::kNone;
251         if (AAMode::kCoverageWithMSAA == fAAMode) {
252             flags |= FixedFunctionFlags::kUsesHWAA;
253         }
254         if (fStencilSettings != &GrUserStencilSettings::kUnused) {
255             flags |= FixedFunctionFlags::kUsesStencil;
256         }
257         return flags;
258     }
259 
finalize(const GrCaps & caps,const GrAppliedClip * clip)260     GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip) override {
261         GrProcessorAnalysisCoverage coverage;
262         if (AAMode::kNone == fAAMode && !clip->numClipCoverageFragmentProcessors()) {
263             coverage = GrProcessorAnalysisCoverage::kNone;
264         } else {
265             coverage = GrProcessorAnalysisCoverage::kSingleChannel;
266         }
267         auto analysis = fProcessorSet.finalize(fColor, coverage, clip, false, caps, &fColor);
268         fUsesLocalCoords = analysis.usesLocalCoords();
269         return analysis;
270     }
271 
272 private:
273     friend class GrOpMemoryPool; // for ctor
274 
DashOp(GrPaint && paint,const LineData & geometry,SkPaint::Cap cap,AAMode aaMode,bool fullDash,const GrUserStencilSettings * stencilSettings)275     DashOp(GrPaint&& paint, const LineData& geometry, SkPaint::Cap cap, AAMode aaMode,
276            bool fullDash, const GrUserStencilSettings* stencilSettings)
277             : INHERITED(ClassID())
278             , fColor(paint.getColor4f())
279             , fFullDash(fullDash)
280             , fCap(cap)
281             , fAAMode(aaMode)
282             , fProcessorSet(std::move(paint))
283             , fStencilSettings(stencilSettings) {
284         fLines.push_back(geometry);
285 
286         // compute bounds
287         SkScalar halfStrokeWidth = 0.5f * geometry.fSrcStrokeWidth;
288         SkScalar xBloat = SkPaint::kButt_Cap == cap ? 0 : halfStrokeWidth;
289         SkRect bounds;
290         bounds.set(geometry.fPtsRot[0], geometry.fPtsRot[1]);
291         bounds.outset(xBloat, halfStrokeWidth);
292 
293         // Note, we actually create the combined matrix here, and save the work
294         SkMatrix& combinedMatrix = fLines[0].fSrcRotInv;
295         combinedMatrix.postConcat(geometry.fViewMatrix);
296 
297         IsZeroArea zeroArea = geometry.fSrcStrokeWidth ? IsZeroArea::kNo : IsZeroArea::kYes;
298         HasAABloat aaBloat = (aaMode == AAMode::kNone) ? HasAABloat ::kNo : HasAABloat::kYes;
299         this->setTransformedBounds(bounds, combinedMatrix, aaBloat, zeroArea);
300     }
301 
302     struct DashDraw {
DashDrawDashOp::DashDraw303         DashDraw(const LineData& geo) {
304             memcpy(fPtsRot, geo.fPtsRot, sizeof(geo.fPtsRot));
305             memcpy(fIntervals, geo.fIntervals, sizeof(geo.fIntervals));
306             fPhase = geo.fPhase;
307         }
308         SkPoint fPtsRot[2];
309         SkScalar fIntervals[2];
310         SkScalar fPhase;
311         SkScalar fStartOffset;
312         SkScalar fStrokeWidth;
313         SkScalar fLineLength;
314         SkScalar fHalfDevStroke;
315         SkScalar fDevBloatX;
316         SkScalar fDevBloatY;
317         bool fLineDone;
318         bool fHasStartRect;
319         bool fHasEndRect;
320     };
321 
onPrepareDraws(Target * target)322     void onPrepareDraws(Target* target) override {
323         int instanceCount = fLines.count();
324         SkPaint::Cap cap = this->cap();
325         bool isRoundCap = SkPaint::kRound_Cap == cap;
326         DashCap capType = isRoundCap ? kRound_DashCap : kNonRound_DashCap;
327 
328         sk_sp<GrGeometryProcessor> gp;
329         if (this->fullDash()) {
330             gp = make_dash_gp(this->color(), this->aaMode(), capType, this->viewMatrix(),
331                               fUsesLocalCoords);
332         } else {
333             // Set up the vertex data for the line and start/end dashes
334             using namespace GrDefaultGeoProcFactory;
335             Color color(this->color());
336             LocalCoords::Type localCoordsType =
337                     fUsesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
338             gp = MakeForDeviceSpace(target->caps().shaderCaps(),
339                                     color,
340                                     Coverage::kSolid_Type,
341                                     localCoordsType,
342                                     this->viewMatrix());
343         }
344 
345         if (!gp) {
346             SkDebugf("Could not create GrGeometryProcessor\n");
347             return;
348         }
349 
350         // useAA here means Edge AA or MSAA
351         bool useAA = this->aaMode() != AAMode::kNone;
352         bool fullDash = this->fullDash();
353 
354         // We do two passes over all of the dashes.  First we setup the start, end, and bounds,
355         // rectangles.  We preserve all of this work in the rects / draws arrays below.  Then we
356         // iterate again over these decomposed dashes to generate vertices
357         static const int kNumStackDashes = 128;
358         SkSTArray<kNumStackDashes, SkRect, true> rects;
359         SkSTArray<kNumStackDashes, DashDraw, true> draws;
360 
361         int totalRectCount = 0;
362         int rectOffset = 0;
363         rects.push_back_n(3 * instanceCount);
364         for (int i = 0; i < instanceCount; i++) {
365             const LineData& args = fLines[i];
366 
367             DashDraw& draw = draws.push_back(args);
368 
369             bool hasCap = SkPaint::kButt_Cap != cap;
370 
371             // We always want to at least stroke out half a pixel on each side in device space
372             // so 0.5f / perpScale gives us this min in src space
373             SkScalar halfSrcStroke =
374                     SkMaxScalar(args.fSrcStrokeWidth * 0.5f, 0.5f / args.fPerpendicularScale);
375 
376             SkScalar strokeAdj;
377             if (!hasCap) {
378                 strokeAdj = 0.f;
379             } else {
380                 strokeAdj = halfSrcStroke;
381             }
382 
383             SkScalar startAdj = 0;
384 
385             bool lineDone = false;
386 
387             // Too simplify the algorithm, we always push back rects for start and end rect.
388             // Otherwise we'd have to track start / end rects for each individual geometry
389             SkRect& bounds = rects[rectOffset++];
390             SkRect& startRect = rects[rectOffset++];
391             SkRect& endRect = rects[rectOffset++];
392 
393             bool hasStartRect = false;
394             // If we are using AA, check to see if we are drawing a partial dash at the start. If so
395             // draw it separately here and adjust our start point accordingly
396             if (useAA) {
397                 if (draw.fPhase > 0 && draw.fPhase < draw.fIntervals[0]) {
398                     SkPoint startPts[2];
399                     startPts[0] = draw.fPtsRot[0];
400                     startPts[1].fY = startPts[0].fY;
401                     startPts[1].fX = SkMinScalar(startPts[0].fX + draw.fIntervals[0] - draw.fPhase,
402                                                  draw.fPtsRot[1].fX);
403                     startRect.set(startPts, 2);
404                     startRect.outset(strokeAdj, halfSrcStroke);
405 
406                     hasStartRect = true;
407                     startAdj = draw.fIntervals[0] + draw.fIntervals[1] - draw.fPhase;
408                 }
409             }
410 
411             // adjustments for start and end of bounding rect so we only draw dash intervals
412             // contained in the original line segment.
413             startAdj += calc_start_adjustment(draw.fIntervals, draw.fPhase);
414             if (startAdj != 0) {
415                 draw.fPtsRot[0].fX += startAdj;
416                 draw.fPhase = 0;
417             }
418             SkScalar endingInterval = 0;
419             SkScalar endAdj = calc_end_adjustment(draw.fIntervals, draw.fPtsRot, draw.fPhase,
420                                                   &endingInterval);
421             draw.fPtsRot[1].fX -= endAdj;
422             if (draw.fPtsRot[0].fX >= draw.fPtsRot[1].fX) {
423                 lineDone = true;
424             }
425 
426             bool hasEndRect = false;
427             // If we are using AA, check to see if we are drawing a partial dash at then end. If so
428             // draw it separately here and adjust our end point accordingly
429             if (useAA && !lineDone) {
430                 // If we adjusted the end then we will not be drawing a partial dash at the end.
431                 // If we didn't adjust the end point then we just need to make sure the ending
432                 // dash isn't a full dash
433                 if (0 == endAdj && endingInterval != draw.fIntervals[0]) {
434                     SkPoint endPts[2];
435                     endPts[1] = draw.fPtsRot[1];
436                     endPts[0].fY = endPts[1].fY;
437                     endPts[0].fX = endPts[1].fX - endingInterval;
438 
439                     endRect.set(endPts, 2);
440                     endRect.outset(strokeAdj, halfSrcStroke);
441 
442                     hasEndRect = true;
443                     endAdj = endingInterval + draw.fIntervals[1];
444 
445                     draw.fPtsRot[1].fX -= endAdj;
446                     if (draw.fPtsRot[0].fX >= draw.fPtsRot[1].fX) {
447                         lineDone = true;
448                     }
449                 }
450             }
451 
452             if (draw.fPtsRot[0].fX == draw.fPtsRot[1].fX &&
453                 (0 != endAdj || 0 == startAdj) &&
454                 hasCap) {
455                 // At this point the fPtsRot[0]/[1] represent the start and end of the inner rect of
456                 // dashes that we want to draw. The only way they can be equal is if the on interval
457                 // is zero (or an edge case if the end of line ends at a full off interval, but this
458                 // is handled as well). Thus if the on interval is zero then we need to draw a cap
459                 // at this position if the stroke has caps. The spec says we only draw this point if
460                 // point lies between [start of line, end of line). Thus we check if we are at the
461                 // end (but not the start), and if so we don't draw the cap.
462                 lineDone = false;
463             }
464 
465             if (startAdj != 0) {
466                 draw.fPhase = 0;
467             }
468 
469             // Change the dashing info from src space into device space
470             SkScalar* devIntervals = draw.fIntervals;
471             devIntervals[0] = draw.fIntervals[0] * args.fParallelScale;
472             devIntervals[1] = draw.fIntervals[1] * args.fParallelScale;
473             SkScalar devPhase = draw.fPhase * args.fParallelScale;
474             SkScalar strokeWidth = args.fSrcStrokeWidth * args.fPerpendicularScale;
475 
476             if ((strokeWidth < 1.f && useAA) || 0.f == strokeWidth) {
477                 strokeWidth = 1.f;
478             }
479 
480             SkScalar halfDevStroke = strokeWidth * 0.5f;
481 
482             if (SkPaint::kSquare_Cap == cap) {
483                 // add cap to on interval and remove from off interval
484                 devIntervals[0] += strokeWidth;
485                 devIntervals[1] -= strokeWidth;
486             }
487             SkScalar startOffset = devIntervals[1] * 0.5f + devPhase;
488 
489             // For EdgeAA, we bloat in X & Y for both square and round caps.
490             // For MSAA, we don't bloat at all for square caps, and bloat in Y only for round caps.
491             SkScalar devBloatX = this->aaMode() == AAMode::kCoverage ? 0.5f : 0.0f;
492             SkScalar devBloatY;
493             if (SkPaint::kRound_Cap == cap && this->aaMode() == AAMode::kCoverageWithMSAA) {
494                 devBloatY = 0.5f;
495             } else {
496                 devBloatY = devBloatX;
497             }
498 
499             SkScalar bloatX = devBloatX / args.fParallelScale;
500             SkScalar bloatY = devBloatY / args.fPerpendicularScale;
501 
502             if (devIntervals[1] <= 0.f && useAA) {
503                 // Case when we end up drawing a solid AA rect
504                 // Reset the start rect to draw this single solid rect
505                 // but it requires to upload a new intervals uniform so we can mimic
506                 // one giant dash
507                 draw.fPtsRot[0].fX -= hasStartRect ? startAdj : 0;
508                 draw.fPtsRot[1].fX += hasEndRect ? endAdj : 0;
509                 startRect.set(draw.fPtsRot, 2);
510                 startRect.outset(strokeAdj, halfSrcStroke);
511                 hasStartRect = true;
512                 hasEndRect = false;
513                 lineDone = true;
514 
515                 SkPoint devicePts[2];
516                 args.fViewMatrix.mapPoints(devicePts, draw.fPtsRot, 2);
517                 SkScalar lineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
518                 if (hasCap) {
519                     lineLength += 2.f * halfDevStroke;
520                 }
521                 devIntervals[0] = lineLength;
522             }
523 
524             totalRectCount += !lineDone ? 1 : 0;
525             totalRectCount += hasStartRect ? 1 : 0;
526             totalRectCount += hasEndRect ? 1 : 0;
527 
528             if (SkPaint::kRound_Cap == cap && 0 != args.fSrcStrokeWidth) {
529                 // need to adjust this for round caps to correctly set the dashPos attrib on
530                 // vertices
531                 startOffset -= halfDevStroke;
532             }
533 
534             if (!lineDone) {
535                 SkPoint devicePts[2];
536                 args.fViewMatrix.mapPoints(devicePts, draw.fPtsRot, 2);
537                 draw.fLineLength = SkPoint::Distance(devicePts[0], devicePts[1]);
538                 if (hasCap) {
539                     draw.fLineLength += 2.f * halfDevStroke;
540                 }
541 
542                 bounds.set(draw.fPtsRot[0].fX, draw.fPtsRot[0].fY,
543                            draw.fPtsRot[1].fX, draw.fPtsRot[1].fY);
544                 bounds.outset(bloatX + strokeAdj, bloatY + halfSrcStroke);
545             }
546 
547             if (hasStartRect) {
548                 SkASSERT(useAA);  // so that we know bloatX and bloatY have been set
549                 startRect.outset(bloatX, bloatY);
550             }
551 
552             if (hasEndRect) {
553                 SkASSERT(useAA);  // so that we know bloatX and bloatY have been set
554                 endRect.outset(bloatX, bloatY);
555             }
556 
557             draw.fStartOffset = startOffset;
558             draw.fDevBloatX = devBloatX;
559             draw.fDevBloatY = devBloatY;
560             draw.fHalfDevStroke = halfDevStroke;
561             draw.fStrokeWidth = strokeWidth;
562             draw.fHasStartRect = hasStartRect;
563             draw.fLineDone = lineDone;
564             draw.fHasEndRect = hasEndRect;
565         }
566 
567         if (!totalRectCount) {
568             return;
569         }
570 
571         QuadHelper helper(target, gp->vertexStride(), totalRectCount);
572         GrVertexWriter vertices{ helper.vertices() };
573         if (!vertices.fPtr) {
574             return;
575         }
576 
577         int rectIndex = 0;
578         for (int i = 0; i < instanceCount; i++) {
579             const LineData& geom = fLines[i];
580 
581             if (!draws[i].fLineDone) {
582                 if (fullDash) {
583                     setup_dashed_rect(
584                             rects[rectIndex], vertices, geom.fSrcRotInv,
585                             draws[i].fStartOffset, draws[i].fDevBloatX, draws[i].fDevBloatY,
586                             draws[i].fLineLength, draws[i].fHalfDevStroke, draws[i].fIntervals[0],
587                             draws[i].fIntervals[1], draws[i].fStrokeWidth, capType);
588                 } else {
589                     vertices.writeQuad(GrQuad(rects[rectIndex], geom.fSrcRotInv));
590                 }
591             }
592             rectIndex++;
593 
594             if (draws[i].fHasStartRect) {
595                 if (fullDash) {
596                     setup_dashed_rect(
597                             rects[rectIndex], vertices, geom.fSrcRotInv,
598                             draws[i].fStartOffset, draws[i].fDevBloatX, draws[i].fDevBloatY,
599                             draws[i].fIntervals[0], draws[i].fHalfDevStroke, draws[i].fIntervals[0],
600                             draws[i].fIntervals[1], draws[i].fStrokeWidth, capType);
601                 } else {
602                     vertices.writeQuad(GrQuad(rects[rectIndex], geom.fSrcRotInv));
603                 }
604             }
605             rectIndex++;
606 
607             if (draws[i].fHasEndRect) {
608                 if (fullDash) {
609                     setup_dashed_rect(
610                             rects[rectIndex], vertices, geom.fSrcRotInv,
611                             draws[i].fStartOffset, draws[i].fDevBloatX, draws[i].fDevBloatY,
612                             draws[i].fIntervals[0], draws[i].fHalfDevStroke, draws[i].fIntervals[0],
613                             draws[i].fIntervals[1], draws[i].fStrokeWidth, capType);
614                 } else {
615                     vertices.writeQuad(GrQuad(rects[rectIndex], geom.fSrcRotInv));
616                 }
617             }
618             rectIndex++;
619         }
620         uint32_t pipelineFlags = 0;
621         if (AAMode::kCoverageWithMSAA == fAAMode) {
622             pipelineFlags |= GrPipeline::kHWAntialias_Flag;
623         }
624         auto pipe = target->makePipeline(pipelineFlags, std::move(fProcessorSet),
625                                          target->detachAppliedClip());
626         helper.recordDraw(target, std::move(gp), pipe.fPipeline, pipe.fFixedDynamicState);
627     }
628 
onCombineIfPossible(GrOp * t,const GrCaps & caps)629     CombineResult onCombineIfPossible(GrOp* t, const GrCaps& caps) override {
630         DashOp* that = t->cast<DashOp>();
631         if (fProcessorSet != that->fProcessorSet) {
632             return CombineResult::kCannotCombine;
633         }
634 
635         if (this->aaMode() != that->aaMode()) {
636             return CombineResult::kCannotCombine;
637         }
638 
639         if (this->fullDash() != that->fullDash()) {
640             return CombineResult::kCannotCombine;
641         }
642 
643         if (this->cap() != that->cap()) {
644             return CombineResult::kCannotCombine;
645         }
646 
647         // TODO vertex color
648         if (this->color() != that->color()) {
649             return CombineResult::kCannotCombine;
650         }
651 
652         if (fUsesLocalCoords && !this->viewMatrix().cheapEqualTo(that->viewMatrix())) {
653             return CombineResult::kCannotCombine;
654         }
655 
656         fLines.push_back_n(that->fLines.count(), that->fLines.begin());
657         return CombineResult::kMerged;
658     }
659 
color() const660     const SkPMColor4f& color() const { return fColor; }
viewMatrix() const661     const SkMatrix& viewMatrix() const { return fLines[0].fViewMatrix; }
aaMode() const662     AAMode aaMode() const { return fAAMode; }
fullDash() const663     bool fullDash() const { return fFullDash; }
cap() const664     SkPaint::Cap cap() const { return fCap; }
665 
666     static const int kVertsPerDash = 4;
667     static const int kIndicesPerDash = 6;
668 
669     SkSTArray<1, LineData, true> fLines;
670     SkPMColor4f fColor;
671     bool fUsesLocalCoords : 1;
672     bool fFullDash : 1;
673     // We use 3 bits for this 3-value enum because MSVS makes the underlying types signed.
674     SkPaint::Cap fCap : 3;
675     AAMode fAAMode;
676     GrProcessorSet fProcessorSet;
677     const GrUserStencilSettings* fStencilSettings;
678 
679     typedef GrMeshDrawOp INHERITED;
680 };
681 
MakeDashLineOp(GrContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkPoint pts[2],AAMode aaMode,const GrStyle & style,const GrUserStencilSettings * stencilSettings)682 std::unique_ptr<GrDrawOp> GrDashOp::MakeDashLineOp(GrContext* context,
683                                                    GrPaint&& paint,
684                                                    const SkMatrix& viewMatrix,
685                                                    const SkPoint pts[2],
686                                                    AAMode aaMode,
687                                                    const GrStyle& style,
688                                                    const GrUserStencilSettings* stencilSettings) {
689     SkASSERT(GrDashOp::CanDrawDashLine(pts, style, viewMatrix));
690     const SkScalar* intervals = style.dashIntervals();
691     SkScalar phase = style.dashPhase();
692 
693     SkPaint::Cap cap = style.strokeRec().getCap();
694 
695     DashOp::LineData lineData;
696     lineData.fSrcStrokeWidth = style.strokeRec().getWidth();
697 
698     // the phase should be normalized to be [0, sum of all intervals)
699     SkASSERT(phase >= 0 && phase < intervals[0] + intervals[1]);
700 
701     // Rotate the src pts so they are aligned horizontally with pts[0].fX < pts[1].fX
702     if (pts[0].fY != pts[1].fY || pts[0].fX > pts[1].fX) {
703         SkMatrix rotMatrix;
704         align_to_x_axis(pts, &rotMatrix, lineData.fPtsRot);
705         if (!rotMatrix.invert(&lineData.fSrcRotInv)) {
706             SkDebugf("Failed to create invertible rotation matrix!\n");
707             return nullptr;
708         }
709     } else {
710         lineData.fSrcRotInv.reset();
711         memcpy(lineData.fPtsRot, pts, 2 * sizeof(SkPoint));
712     }
713 
714     // Scale corrections of intervals and stroke from view matrix
715     calc_dash_scaling(&lineData.fParallelScale, &lineData.fPerpendicularScale, viewMatrix,
716                       lineData.fPtsRot);
717     if (SkScalarNearlyZero(lineData.fParallelScale) ||
718         SkScalarNearlyZero(lineData.fPerpendicularScale)) {
719         return nullptr;
720     }
721 
722     SkScalar offInterval = intervals[1] * lineData.fParallelScale;
723     SkScalar strokeWidth = lineData.fSrcStrokeWidth * lineData.fPerpendicularScale;
724 
725     if (SkPaint::kSquare_Cap == cap && 0 != lineData.fSrcStrokeWidth) {
726         // add cap to on interveal and remove from off interval
727         offInterval -= strokeWidth;
728     }
729 
730     // TODO we can do a real rect call if not using fulldash(ie no off interval, not using AA)
731     bool fullDash = offInterval > 0.f || aaMode != AAMode::kNone;
732 
733     lineData.fViewMatrix = viewMatrix;
734     lineData.fPhase = phase;
735     lineData.fIntervals[0] = intervals[0];
736     lineData.fIntervals[1] = intervals[1];
737 
738     return DashOp::Make(context, std::move(paint), lineData, cap, aaMode, fullDash,
739                         stencilSettings);
740 }
741 
742 //////////////////////////////////////////////////////////////////////////////
743 
744 class GLDashingCircleEffect;
745 
746 /*
747  * This effect will draw a dotted line (defined as a dashed lined with round caps and no on
748  * interval). The radius of the dots is given by the strokeWidth and the spacing by the DashInfo.
749  * Both of the previous two parameters are in device space. This effect also requires the setting of
750  * a float2 vertex attribute for the the four corners of the bounding rect. This attribute is the
751  * "dash position" of each vertex. In other words it is the vertex coords (in device space) if we
752  * transform the line to be horizontal, with the start of line at the origin then shifted to the
753  * right by half the off interval. The line then goes in the positive x direction.
754  */
755 class DashingCircleEffect : public GrGeometryProcessor {
756 public:
757     typedef SkPathEffect::DashInfo DashInfo;
758 
759     static sk_sp<GrGeometryProcessor> Make(const SkPMColor4f&,
760                                            AAMode aaMode,
761                                            const SkMatrix& localMatrix,
762                                            bool usesLocalCoords);
763 
name() const764     const char* name() const override { return "DashingCircleEffect"; }
765 
aaMode() const766     AAMode aaMode() const { return fAAMode; }
767 
color() const768     const SkPMColor4f& color() const { return fColor; }
769 
localMatrix() const770     const SkMatrix& localMatrix() const { return fLocalMatrix; }
771 
usesLocalCoords() const772     bool usesLocalCoords() const { return fUsesLocalCoords; }
773 
774     void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override;
775 
776     GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const override;
777 
778 private:
779     DashingCircleEffect(const SkPMColor4f&, AAMode aaMode, const SkMatrix& localMatrix,
780                         bool usesLocalCoords);
781 
782     SkPMColor4f         fColor;
783     SkMatrix            fLocalMatrix;
784     bool                fUsesLocalCoords;
785     AAMode              fAAMode;
786 
787     Attribute fInPosition;
788     Attribute fInDashParams;
789     Attribute fInCircleParams;
790 
791     GR_DECLARE_GEOMETRY_PROCESSOR_TEST
792 
793     friend class GLDashingCircleEffect;
794     typedef GrGeometryProcessor INHERITED;
795 };
796 
797 //////////////////////////////////////////////////////////////////////////////
798 
799 class GLDashingCircleEffect : public GrGLSLGeometryProcessor {
800 public:
801     GLDashingCircleEffect();
802 
803     void onEmitCode(EmitArgs&, GrGPArgs*) override;
804 
805     static inline void GenKey(const GrGeometryProcessor&,
806                               const GrShaderCaps&,
807                               GrProcessorKeyBuilder*);
808 
809     void setData(const GrGLSLProgramDataManager&, const GrPrimitiveProcessor&,
810                  FPCoordTransformIter&& transformIter) override;
811 private:
812     UniformHandle fParamUniform;
813     UniformHandle fColorUniform;
814     SkPMColor4f   fColor;
815     SkScalar      fPrevRadius;
816     SkScalar      fPrevCenterX;
817     SkScalar      fPrevIntervalLength;
818     typedef GrGLSLGeometryProcessor INHERITED;
819 };
820 
GLDashingCircleEffect()821 GLDashingCircleEffect::GLDashingCircleEffect() {
822     fColor = SK_PMColor4fILLEGAL;
823     fPrevRadius = SK_ScalarMin;
824     fPrevCenterX = SK_ScalarMin;
825     fPrevIntervalLength = SK_ScalarMax;
826 }
827 
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)828 void GLDashingCircleEffect::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
829     const DashingCircleEffect& dce = args.fGP.cast<DashingCircleEffect>();
830     GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
831     GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
832     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
833 
834     // emit attributes
835     varyingHandler->emitAttributes(dce);
836 
837     // XY are dashPos, Z is dashInterval
838     GrGLSLVarying dashParams(kHalf3_GrSLType);
839     varyingHandler->addVarying("DashParam", &dashParams);
840     vertBuilder->codeAppendf("%s = %s;", dashParams.vsOut(), dce.fInDashParams.name());
841 
842     // x refers to circle radius - 0.5, y refers to cicle's center x coord
843     GrGLSLVarying circleParams(kHalf2_GrSLType);
844     varyingHandler->addVarying("CircleParams", &circleParams);
845     vertBuilder->codeAppendf("%s = %s;", circleParams.vsOut(), dce.fInCircleParams.name());
846 
847     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
848     // Setup pass through color
849     this->setupUniformColor(fragBuilder, uniformHandler, args.fOutputColor, &fColorUniform);
850 
851     // Setup position
852     this->writeOutputPosition(vertBuilder, gpArgs, dce.fInPosition.name());
853 
854     // emit transforms
855     this->emitTransforms(vertBuilder,
856                          varyingHandler,
857                          uniformHandler,
858                          dce.fInPosition.asShaderVar(),
859                          dce.localMatrix(),
860                          args.fFPCoordTransformHandler);
861 
862     // transforms all points so that we can compare them to our test circle
863     fragBuilder->codeAppendf("half xShifted = %s.x - floor(%s.x / %s.z) * %s.z;",
864                              dashParams.fsIn(), dashParams.fsIn(), dashParams.fsIn(),
865                              dashParams.fsIn());
866     fragBuilder->codeAppendf("half2 fragPosShifted = half2(xShifted, %s.y);", dashParams.fsIn());
867     fragBuilder->codeAppendf("half2 center = half2(%s.y, 0.0);", circleParams.fsIn());
868     fragBuilder->codeAppend("half dist = length(center - fragPosShifted);");
869     if (dce.aaMode() != AAMode::kNone) {
870         fragBuilder->codeAppendf("half diff = dist - %s.x;", circleParams.fsIn());
871         fragBuilder->codeAppend("diff = 1.0 - diff;");
872         fragBuilder->codeAppend("half alpha = saturate(diff);");
873     } else {
874         fragBuilder->codeAppendf("half alpha = 1.0;");
875         fragBuilder->codeAppendf("alpha *=  dist < %s.x + 0.5 ? 1.0 : 0.0;", circleParams.fsIn());
876     }
877     fragBuilder->codeAppendf("%s = half4(alpha);", args.fOutputCoverage);
878 }
879 
setData(const GrGLSLProgramDataManager & pdman,const GrPrimitiveProcessor & processor,FPCoordTransformIter && transformIter)880 void GLDashingCircleEffect::setData(const GrGLSLProgramDataManager& pdman,
881                                     const GrPrimitiveProcessor& processor,
882                                     FPCoordTransformIter&& transformIter)  {
883     const DashingCircleEffect& dce = processor.cast<DashingCircleEffect>();
884     if (dce.color() != fColor) {
885         pdman.set4fv(fColorUniform, 1, dce.color().vec());
886         fColor = dce.color();
887     }
888     this->setTransformDataHelper(dce.localMatrix(), pdman, &transformIter);
889 }
890 
GenKey(const GrGeometryProcessor & gp,const GrShaderCaps &,GrProcessorKeyBuilder * b)891 void GLDashingCircleEffect::GenKey(const GrGeometryProcessor& gp,
892                                    const GrShaderCaps&,
893                                    GrProcessorKeyBuilder* b) {
894     const DashingCircleEffect& dce = gp.cast<DashingCircleEffect>();
895     uint32_t key = 0;
896     key |= dce.usesLocalCoords() && dce.localMatrix().hasPerspective() ? 0x1 : 0x0;
897     key |= static_cast<uint32_t>(dce.aaMode()) << 1;
898     b->add32(key);
899 }
900 
901 //////////////////////////////////////////////////////////////////////////////
902 
Make(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)903 sk_sp<GrGeometryProcessor> DashingCircleEffect::Make(const SkPMColor4f& color,
904                                                      AAMode aaMode,
905                                                      const SkMatrix& localMatrix,
906                                                      bool usesLocalCoords) {
907     return sk_sp<GrGeometryProcessor>(
908         new DashingCircleEffect(color, aaMode, localMatrix, usesLocalCoords));
909 }
910 
getGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const911 void DashingCircleEffect::getGLSLProcessorKey(const GrShaderCaps& caps,
912                                               GrProcessorKeyBuilder* b) const {
913     GLDashingCircleEffect::GenKey(*this, caps, b);
914 }
915 
createGLSLInstance(const GrShaderCaps &) const916 GrGLSLPrimitiveProcessor* DashingCircleEffect::createGLSLInstance(const GrShaderCaps&) const {
917     return new GLDashingCircleEffect();
918 }
919 
DashingCircleEffect(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)920 DashingCircleEffect::DashingCircleEffect(const SkPMColor4f& color,
921                                          AAMode aaMode,
922                                          const SkMatrix& localMatrix,
923                                          bool usesLocalCoords)
924     : INHERITED(kDashingCircleEffect_ClassID)
925     , fColor(color)
926     , fLocalMatrix(localMatrix)
927     , fUsesLocalCoords(usesLocalCoords)
928     , fAAMode(aaMode) {
929     fInPosition = {"inPosition", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
930     fInDashParams = {"inDashParams", kFloat3_GrVertexAttribType, kHalf3_GrSLType};
931     fInCircleParams = {"inCircleParams", kFloat2_GrVertexAttribType, kHalf2_GrSLType};
932     this->setVertexAttributes(&fInPosition, 3);
933 }
934 
935 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingCircleEffect);
936 
937 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)938 sk_sp<GrGeometryProcessor> DashingCircleEffect::TestCreate(GrProcessorTestData* d) {
939     AAMode aaMode = static_cast<AAMode>(d->fRandom->nextULessThan(GrDashOp::kAAModeCnt));
940     return DashingCircleEffect::Make(SkPMColor4f::FromBytes_RGBA(GrRandomColor(d->fRandom)),
941                                      aaMode, GrTest::TestMatrix(d->fRandom),
942                                      d->fRandom->nextBool());
943 }
944 #endif
945 
946 //////////////////////////////////////////////////////////////////////////////
947 
948 class GLDashingLineEffect;
949 
950 /*
951  * This effect will draw a dashed line. The width of the dash is given by the strokeWidth and the
952  * length and spacing by the DashInfo. Both of the previous two parameters are in device space.
953  * This effect also requires the setting of a float2 vertex attribute for the the four corners of the
954  * bounding rect. This attribute is the "dash position" of each vertex. In other words it is the
955  * vertex coords (in device space) if we transform the line to be horizontal, with the start of
956  * line at the origin then shifted to the right by half the off interval. The line then goes in the
957  * positive x direction.
958  */
959 class DashingLineEffect : public GrGeometryProcessor {
960 public:
961     typedef SkPathEffect::DashInfo DashInfo;
962 
963     static sk_sp<GrGeometryProcessor> Make(const SkPMColor4f&,
964                                            AAMode aaMode,
965                                            const SkMatrix& localMatrix,
966                                            bool usesLocalCoords);
967 
name() const968     const char* name() const override { return "DashingEffect"; }
969 
aaMode() const970     AAMode aaMode() const { return fAAMode; }
971 
color() const972     const SkPMColor4f& color() const { return fColor; }
973 
localMatrix() const974      const SkMatrix& localMatrix() const { return fLocalMatrix; }
975 
usesLocalCoords() const976     bool usesLocalCoords() const { return fUsesLocalCoords; }
977 
978     void getGLSLProcessorKey(const GrShaderCaps& caps, GrProcessorKeyBuilder* b) const override;
979 
980     GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const override;
981 
982 private:
983     DashingLineEffect(const SkPMColor4f&, AAMode aaMode, const SkMatrix& localMatrix,
984                       bool usesLocalCoords);
985 
986     SkPMColor4f         fColor;
987     SkMatrix            fLocalMatrix;
988     bool                fUsesLocalCoords;
989     AAMode              fAAMode;
990 
991     Attribute fInPosition;
992     Attribute fInDashParams;
993     Attribute fInRect;
994 
995     GR_DECLARE_GEOMETRY_PROCESSOR_TEST
996 
997     friend class GLDashingLineEffect;
998 
999     typedef GrGeometryProcessor INHERITED;
1000 };
1001 
1002 //////////////////////////////////////////////////////////////////////////////
1003 
1004 class GLDashingLineEffect : public GrGLSLGeometryProcessor {
1005 public:
1006     GLDashingLineEffect();
1007 
1008     void onEmitCode(EmitArgs&, GrGPArgs*) override;
1009 
1010     static inline void GenKey(const GrGeometryProcessor&,
1011                               const GrShaderCaps&,
1012                               GrProcessorKeyBuilder*);
1013 
1014     void setData(const GrGLSLProgramDataManager&, const GrPrimitiveProcessor&,
1015                  FPCoordTransformIter&& iter) override;
1016 
1017 private:
1018     SkPMColor4f   fColor;
1019     UniformHandle fColorUniform;
1020     typedef GrGLSLGeometryProcessor INHERITED;
1021 };
1022 
GLDashingLineEffect()1023 GLDashingLineEffect::GLDashingLineEffect() : fColor(SK_PMColor4fILLEGAL) {}
1024 
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)1025 void GLDashingLineEffect::onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) {
1026     const DashingLineEffect& de = args.fGP.cast<DashingLineEffect>();
1027 
1028     GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
1029     GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
1030     GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
1031 
1032     // emit attributes
1033     varyingHandler->emitAttributes(de);
1034 
1035     // XY refers to dashPos, Z is the dash interval length
1036     GrGLSLVarying inDashParams(kFloat3_GrSLType);
1037     varyingHandler->addVarying("DashParams", &inDashParams);
1038     vertBuilder->codeAppendf("%s = %s;", inDashParams.vsOut(), de.fInDashParams.name());
1039 
1040     // The rect uniform's xyzw refer to (left + 0.5, top + 0.5, right - 0.5, bottom - 0.5),
1041     // respectively.
1042     GrGLSLVarying inRectParams(kFloat4_GrSLType);
1043     varyingHandler->addVarying("RectParams", &inRectParams);
1044     vertBuilder->codeAppendf("%s = %s;", inRectParams.vsOut(), de.fInRect.name());
1045 
1046     GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
1047     // Setup pass through color
1048     this->setupUniformColor(fragBuilder, uniformHandler, args.fOutputColor, &fColorUniform);
1049 
1050     // Setup position
1051     this->writeOutputPosition(vertBuilder, gpArgs, de.fInPosition.name());
1052 
1053     // emit transforms
1054     this->emitTransforms(vertBuilder,
1055                          varyingHandler,
1056                          uniformHandler,
1057                          de.fInPosition.asShaderVar(),
1058                          de.localMatrix(),
1059                          args.fFPCoordTransformHandler);
1060 
1061     // transforms all points so that we can compare them to our test rect
1062     fragBuilder->codeAppendf("half xShifted = %s.x - floor(%s.x / %s.z) * %s.z;",
1063                              inDashParams.fsIn(), inDashParams.fsIn(), inDashParams.fsIn(),
1064                              inDashParams.fsIn());
1065     fragBuilder->codeAppendf("half2 fragPosShifted = half2(xShifted, %s.y);", inDashParams.fsIn());
1066     if (de.aaMode() == AAMode::kCoverage) {
1067         // The amount of coverage removed in x and y by the edges is computed as a pair of negative
1068         // numbers, xSub and ySub.
1069         fragBuilder->codeAppend("half xSub, ySub;");
1070         fragBuilder->codeAppendf("xSub = min(fragPosShifted.x - %s.x, 0.0);", inRectParams.fsIn());
1071         fragBuilder->codeAppendf("xSub += min(%s.z - fragPosShifted.x, 0.0);", inRectParams.fsIn());
1072         fragBuilder->codeAppendf("ySub = min(fragPosShifted.y - %s.y, 0.0);", inRectParams.fsIn());
1073         fragBuilder->codeAppendf("ySub += min(%s.w - fragPosShifted.y, 0.0);", inRectParams.fsIn());
1074         // Now compute coverage in x and y and multiply them to get the fraction of the pixel
1075         // covered.
1076         fragBuilder->codeAppendf(
1077             "half alpha = (1.0 + max(xSub, -1.0)) * (1.0 + max(ySub, -1.0));");
1078     } else if (de.aaMode() == AAMode::kCoverageWithMSAA) {
1079         // For MSAA, we don't modulate the alpha by the Y distance, since MSAA coverage will handle
1080         // AA on the the top and bottom edges. The shader is only responsible for intra-dash alpha.
1081         fragBuilder->codeAppend("half xSub;");
1082         fragBuilder->codeAppendf("xSub = min(fragPosShifted.x - %s.x, 0.0);", inRectParams.fsIn());
1083         fragBuilder->codeAppendf("xSub += min(%s.z - fragPosShifted.x, 0.0);", inRectParams.fsIn());
1084         // Now compute coverage in x to get the fraction of the pixel covered.
1085         fragBuilder->codeAppendf("half alpha = (1.0 + max(xSub, -1.0));");
1086     } else {
1087         // Assuming the bounding geometry is tight so no need to check y values
1088         fragBuilder->codeAppendf("half alpha = 1.0;");
1089         fragBuilder->codeAppendf("alpha *= (fragPosShifted.x - %s.x) > -0.5 ? 1.0 : 0.0;",
1090                                  inRectParams.fsIn());
1091         fragBuilder->codeAppendf("alpha *= (%s.z - fragPosShifted.x) >= -0.5 ? 1.0 : 0.0;",
1092                                  inRectParams.fsIn());
1093     }
1094     fragBuilder->codeAppendf("%s = half4(alpha);", args.fOutputCoverage);
1095 }
1096 
setData(const GrGLSLProgramDataManager & pdman,const GrPrimitiveProcessor & processor,FPCoordTransformIter && transformIter)1097 void GLDashingLineEffect::setData(const GrGLSLProgramDataManager& pdman,
1098                                   const GrPrimitiveProcessor& processor,
1099                                   FPCoordTransformIter&& transformIter) {
1100     const DashingLineEffect& de = processor.cast<DashingLineEffect>();
1101     if (de.color() != fColor) {
1102         pdman.set4fv(fColorUniform, 1, de.color().vec());
1103         fColor = de.color();
1104     }
1105     this->setTransformDataHelper(de.localMatrix(), pdman, &transformIter);
1106 }
1107 
GenKey(const GrGeometryProcessor & gp,const GrShaderCaps &,GrProcessorKeyBuilder * b)1108 void GLDashingLineEffect::GenKey(const GrGeometryProcessor& gp,
1109                                  const GrShaderCaps&,
1110                                  GrProcessorKeyBuilder* b) {
1111     const DashingLineEffect& de = gp.cast<DashingLineEffect>();
1112     uint32_t key = 0;
1113     key |= de.usesLocalCoords() && de.localMatrix().hasPerspective() ? 0x1 : 0x0;
1114     key |= static_cast<int>(de.aaMode()) << 8;
1115     b->add32(key);
1116 }
1117 
1118 //////////////////////////////////////////////////////////////////////////////
1119 
Make(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)1120 sk_sp<GrGeometryProcessor> DashingLineEffect::Make(const SkPMColor4f& color,
1121                                                    AAMode aaMode,
1122                                                    const SkMatrix& localMatrix,
1123                                                    bool usesLocalCoords) {
1124     return sk_sp<GrGeometryProcessor>(
1125         new DashingLineEffect(color, aaMode, localMatrix, usesLocalCoords));
1126 }
1127 
getGLSLProcessorKey(const GrShaderCaps & caps,GrProcessorKeyBuilder * b) const1128 void DashingLineEffect::getGLSLProcessorKey(const GrShaderCaps& caps,
1129                                             GrProcessorKeyBuilder* b) const {
1130     GLDashingLineEffect::GenKey(*this, caps, b);
1131 }
1132 
createGLSLInstance(const GrShaderCaps &) const1133 GrGLSLPrimitiveProcessor* DashingLineEffect::createGLSLInstance(const GrShaderCaps&) const {
1134     return new GLDashingLineEffect();
1135 }
1136 
DashingLineEffect(const SkPMColor4f & color,AAMode aaMode,const SkMatrix & localMatrix,bool usesLocalCoords)1137 DashingLineEffect::DashingLineEffect(const SkPMColor4f& color,
1138                                      AAMode aaMode,
1139                                      const SkMatrix& localMatrix,
1140                                      bool usesLocalCoords)
1141     : INHERITED(kDashingLineEffect_ClassID)
1142     , fColor(color)
1143     , fLocalMatrix(localMatrix)
1144     , fUsesLocalCoords(usesLocalCoords)
1145     , fAAMode(aaMode) {
1146     fInPosition = {"inPosition", kFloat2_GrVertexAttribType, kFloat2_GrSLType};
1147     fInDashParams = {"inDashParams", kFloat3_GrVertexAttribType, kHalf3_GrSLType};
1148     fInRect = {"inRect", kFloat4_GrVertexAttribType, kHalf4_GrSLType};
1149     this->setVertexAttributes(&fInPosition, 3);
1150 }
1151 
1152 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DashingLineEffect);
1153 
1154 #if GR_TEST_UTILS
TestCreate(GrProcessorTestData * d)1155 sk_sp<GrGeometryProcessor> DashingLineEffect::TestCreate(GrProcessorTestData* d) {
1156     AAMode aaMode = static_cast<AAMode>(d->fRandom->nextULessThan(GrDashOp::kAAModeCnt));
1157     return DashingLineEffect::Make(SkPMColor4f::FromBytes_RGBA(GrRandomColor(d->fRandom)),
1158                                    aaMode, GrTest::TestMatrix(d->fRandom),
1159                                    d->fRandom->nextBool());
1160 }
1161 
1162 #endif
1163 //////////////////////////////////////////////////////////////////////////////
1164 
make_dash_gp(const SkPMColor4f & color,AAMode aaMode,DashCap cap,const SkMatrix & viewMatrix,bool usesLocalCoords)1165 static sk_sp<GrGeometryProcessor> make_dash_gp(const SkPMColor4f& color,
1166                                                AAMode aaMode,
1167                                                DashCap cap,
1168                                                const SkMatrix& viewMatrix,
1169                                                bool usesLocalCoords) {
1170     SkMatrix invert;
1171     if (usesLocalCoords && !viewMatrix.invert(&invert)) {
1172         SkDebugf("Failed to invert\n");
1173         return nullptr;
1174     }
1175 
1176     switch (cap) {
1177         case kRound_DashCap:
1178             return DashingCircleEffect::Make(color, aaMode, invert, usesLocalCoords);
1179         case kNonRound_DashCap:
1180             return DashingLineEffect::Make(color, aaMode, invert, usesLocalCoords);
1181     }
1182     return nullptr;
1183 }
1184 
1185 /////////////////////////////////////////////////////////////////////////////////////////////////
1186 
1187 #if GR_TEST_UTILS
1188 
GR_DRAW_OP_TEST_DEFINE(DashOp)1189 GR_DRAW_OP_TEST_DEFINE(DashOp) {
1190     SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
1191     AAMode aaMode;
1192     do {
1193         aaMode = static_cast<AAMode>(random->nextULessThan(GrDashOp::kAAModeCnt));
1194     } while (AAMode::kCoverageWithMSAA == aaMode && GrFSAAType::kUnifiedMSAA != fsaaType);
1195 
1196     // We can only dash either horizontal or vertical lines
1197     SkPoint pts[2];
1198     if (random->nextBool()) {
1199         // vertical
1200         pts[0].fX = 1.f;
1201         pts[0].fY = random->nextF() * 10.f;
1202         pts[1].fX = 1.f;
1203         pts[1].fY = random->nextF() * 10.f;
1204     } else {
1205         // horizontal
1206         pts[0].fX = random->nextF() * 10.f;
1207         pts[0].fY = 1.f;
1208         pts[1].fX = random->nextF() * 10.f;
1209         pts[1].fY = 1.f;
1210     }
1211 
1212     // pick random cap
1213     SkPaint::Cap cap = SkPaint::Cap(random->nextULessThan(SkPaint::kCapCount));
1214 
1215     SkScalar intervals[2];
1216 
1217     // We can only dash with the following intervals
1218     enum Intervals {
1219         kOpenOpen_Intervals ,
1220         kOpenClose_Intervals,
1221         kCloseOpen_Intervals,
1222     };
1223 
1224     Intervals intervalType = SkPaint::kRound_Cap == cap ?
1225                              kOpenClose_Intervals :
1226                              Intervals(random->nextULessThan(kCloseOpen_Intervals + 1));
1227     static const SkScalar kIntervalMin = 0.1f;
1228     static const SkScalar kIntervalMinCircles = 1.f; // Must be >= to stroke width
1229     static const SkScalar kIntervalMax = 10.f;
1230     switch (intervalType) {
1231         case kOpenOpen_Intervals:
1232             intervals[0] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1233             intervals[1] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1234             break;
1235         case kOpenClose_Intervals: {
1236             intervals[0] = 0.f;
1237             SkScalar min = SkPaint::kRound_Cap == cap ? kIntervalMinCircles : kIntervalMin;
1238             intervals[1] = random->nextRangeScalar(min, kIntervalMax);
1239             break;
1240         }
1241         case kCloseOpen_Intervals:
1242             intervals[0] = random->nextRangeScalar(kIntervalMin, kIntervalMax);
1243             intervals[1] = 0.f;
1244             break;
1245 
1246     }
1247 
1248     // phase is 0 < sum (i0, i1)
1249     SkScalar phase = random->nextRangeScalar(0, intervals[0] + intervals[1]);
1250 
1251     SkPaint p;
1252     p.setStyle(SkPaint::kStroke_Style);
1253     p.setStrokeWidth(SkIntToScalar(1));
1254     p.setStrokeCap(cap);
1255     p.setPathEffect(GrTest::TestDashPathEffect::Make(intervals, 2, phase));
1256 
1257     GrStyle style(p);
1258 
1259     return GrDashOp::MakeDashLineOp(context, std::move(paint), viewMatrix, pts, aaMode, style,
1260                                     GrGetRandomStencil(random, context));
1261 }
1262 
1263 #endif
1264