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