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