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