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