1/*
2 * Copyright 2018 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8#include "src/gpu/ops/GrStrokeRectOp.h"
9
10#include "include/core/SkStrokeRec.h"
11#include "include/private/GrResourceKey.h"
12#include "include/utils/SkRandom.h"
13#include "src/core/SkMatrixPriv.h"
14#include "src/gpu/GrCaps.h"
15#include "src/gpu/GrColor.h"
16#include "src/gpu/GrDefaultGeoProcFactory.h"
17#include "src/gpu/GrDrawOpTest.h"
18#include "src/gpu/GrOpFlushState.h"
19#include "src/gpu/GrProgramInfo.h"
20#include "src/gpu/GrResourceProvider.h"
21#include "src/gpu/GrVertexWriter.h"
22#include "src/gpu/ops/GrFillRectOp.h"
23#include "src/gpu/ops/GrMeshDrawOp.h"
24#include "src/gpu/ops/GrSimpleMeshDrawOpHelper.h"
25
26namespace {
27
28// We support all hairlines, bevels, and miters, but not round joins. Also, check whether the miter
29// limit makes a miter join effectively beveled. If the miter is effectively beveled, it is only
30// supported when using an AA stroke.
31inline static bool allowed_stroke(const SkStrokeRec& stroke, GrAA aa, bool* isMiter) {
32 SkASSERT(stroke.getStyle() == SkStrokeRec::kStroke_Style ||
33 stroke.getStyle() == SkStrokeRec::kHairline_Style);
34 // For hairlines, make bevel and round joins appear the same as mitered ones.
35 if (!stroke.getWidth()) {
36 *isMiter = true;
37 return true;
38 }
39 if (stroke.getJoin() == SkPaint::kBevel_Join) {
40 *isMiter = false;
41 return aa == GrAA::kYes; // bevel only supported with AA
42 }
43 if (stroke.getJoin() == SkPaint::kMiter_Join) {
44 *isMiter = stroke.getMiter() >= SK_ScalarSqrt2;
45 // Supported under non-AA only if it remains mitered
46 return aa == GrAA::kYes || *isMiter;
47 }
48 return false;
49}
50
51
52///////////////////////////////////////////////////////////////////////////////////////////////////
53// Non-AA Stroking
54///////////////////////////////////////////////////////////////////////////////////////////////////
55
56/* create a triangle strip that strokes the specified rect. There are 8
57 unique vertices, but we repeat the last 2 to close up. Alternatively we
58 could use an indices array, and then only send 8 verts, but not sure that
59 would be faster.
60 */
61static void init_nonaa_stroke_rect_strip(SkPoint verts[10], const SkRect& rect, SkScalar width) {
62 const SkScalar rad = SkScalarHalf(width);
63
64 verts[0].set(rect.fLeft + rad, rect.fTop + rad);
65 verts[1].set(rect.fLeft - rad, rect.fTop - rad);
66 verts[2].set(rect.fRight - rad, rect.fTop + rad);
67 verts[3].set(rect.fRight + rad, rect.fTop - rad);
68 verts[4].set(rect.fRight - rad, rect.fBottom - rad);
69 verts[5].set(rect.fRight + rad, rect.fBottom + rad);
70 verts[6].set(rect.fLeft + rad, rect.fBottom - rad);
71 verts[7].set(rect.fLeft - rad, rect.fBottom + rad);
72 verts[8] = verts[0];
73 verts[9] = verts[1];
74
75 // TODO: we should be catching this higher up the call stack and just draw a single
76 // non-AA rect
77 if (2*rad >= rect.width()) {
78 verts[0].fX = verts[2].fX = verts[4].fX = verts[6].fX = verts[8].fX = rect.centerX();
79 }
80 if (2*rad >= rect.height()) {
81 verts[0].fY = verts[2].fY = verts[4].fY = verts[6].fY = verts[8].fY = rect.centerY();
82 }
83}
84
85class NonAAStrokeRectOp final : public GrMeshDrawOp {
86private:
87 using Helper = GrSimpleMeshDrawOpHelper;
88
89public:
90 DEFINE_OP_CLASS_ID
91
92 const char* name() const override { return "NonAAStrokeRectOp"; }
93
94 void visitProxies(const VisitProxyFunc& func) const override {
95 if (fProgramInfo) {
96 fProgramInfo->visitFPProxies(func);
97 } else {
98 fHelper.visitProxies(func);
99 }
100 }
101
102 static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
103 GrPaint&& paint,
104 const SkMatrix& viewMatrix,
105 const SkRect& rect,
106 const SkStrokeRec& stroke,
107 GrAAType aaType) {
108 bool isMiter;
109 if (!allowed_stroke(stroke, GrAA::kNo, &isMiter)) {
110 return nullptr;
111 }
112 Helper::InputFlags inputFlags = Helper::InputFlags::kNone;
113 // Depending on sub-pixel coordinates and the particular GPU, we may lose a corner of
114 // hairline rects. We jam all the vertices to pixel centers to avoid this, but not
115 // when MSAA is enabled because it can cause ugly artifacts.
116 if (stroke.getStyle() == SkStrokeRec::kHairline_Style && aaType != GrAAType::kMSAA) {
117 inputFlags |= Helper::InputFlags::kSnapVerticesToPixelCenters;
118 }
119 return Helper::FactoryHelper<NonAAStrokeRectOp>(context, std::move(paint), inputFlags,
120 viewMatrix, rect,
121 stroke, aaType);
122 }
123
124 NonAAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
125 Helper::InputFlags inputFlags, const SkMatrix& viewMatrix, const SkRect& rect,
126 const SkStrokeRec& stroke, GrAAType aaType)
127 : INHERITED(ClassID())
128 , fHelper(helperArgs, aaType, inputFlags) {
129 fColor = color;
130 fViewMatrix = viewMatrix;
131 fRect = rect;
132 // Sort the rect for hairlines
133 fRect.sort();
134 fStrokeWidth = stroke.getWidth();
135
136 SkScalar rad = SkScalarHalf(fStrokeWidth);
137 SkRect bounds = rect;
138 bounds.outset(rad, rad);
139
140 // If our caller snaps to pixel centers then we have to round out the bounds
141 if (inputFlags & Helper::InputFlags::kSnapVerticesToPixelCenters) {
142 SkASSERT(!fStrokeWidth || aaType == GrAAType::kNone);
143 viewMatrix.mapRect(&bounds);
144 // We want to be consistent with how we snap non-aa lines. To match what we do in
145 // GrGLSLVertexShaderBuilder, we first floor all the vertex values and then add half a
146 // pixel to force us to pixel centers.
147 bounds.setLTRB(SkScalarFloorToScalar(bounds.fLeft),
148 SkScalarFloorToScalar(bounds.fTop),
149 SkScalarFloorToScalar(bounds.fRight),
150 SkScalarFloorToScalar(bounds.fBottom));
151 bounds.offset(0.5f, 0.5f);
152 this->setBounds(bounds, HasAABloat::kNo, IsHairline::kNo);
153 } else {
154 HasAABloat aaBloat = (aaType == GrAAType::kNone) ? HasAABloat ::kNo : HasAABloat::kYes;
155 this->setTransformedBounds(bounds, fViewMatrix, aaBloat,
156 fStrokeWidth ? IsHairline::kNo : IsHairline::kYes);
157 }
158 }
159
160 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
161
162 GrProcessorSet::Analysis finalize(
163 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
164 GrClampType clampType) override {
165 // This Op uses uniform (not vertex) color, so doesn't need to track wide color.
166 return fHelper.finalizeProcessors(caps, clip, hasMixedSampledCoverage, clampType,
167 GrProcessorAnalysisCoverage::kNone, &fColor, nullptr);
168 }
169
170private:
171 GrProgramInfo* programInfo() override { return fProgramInfo; }
172
173 void onCreateProgramInfo(const GrCaps* caps,
174 SkArenaAlloc* arena,
175 const GrSurfaceProxyView* writeView,
176 GrAppliedClip&& clip,
177 const GrXferProcessor::DstProxyView& dstProxyView) override {
178 GrGeometryProcessor* gp;
179 {
180 using namespace GrDefaultGeoProcFactory;
181 Color color(fColor);
182 LocalCoords::Type localCoordsType = fHelper.usesLocalCoords()
183 ? LocalCoords::kUsePosition_Type
184 : LocalCoords::kUnused_Type;
185 gp = GrDefaultGeoProcFactory::Make(arena, color, Coverage::kSolid_Type, localCoordsType,
186 fViewMatrix);
187 }
188
189 GrPrimitiveType primType = (fStrokeWidth > 0) ? GrPrimitiveType::kTriangleStrip
190 : GrPrimitiveType::kLineStrip;
191
192 fProgramInfo = fHelper.createProgramInfo(caps, arena, writeView, std::move(clip),
193 dstProxyView, gp, primType);
194 }
195
196 void onPrepareDraws(Target* target) override {
197 if (!fProgramInfo) {
198 this->createProgramInfo(target);
199 }
200
201 size_t kVertexStride = fProgramInfo->primProc().vertexStride();
202 int vertexCount = kVertsPerHairlineRect;
203 if (fStrokeWidth > 0) {
204 vertexCount = kVertsPerStrokeRect;
205 }
206
207 sk_sp<const GrBuffer> vertexBuffer;
208 int firstVertex;
209
210 void* verts =
211 target->makeVertexSpace(kVertexStride, vertexCount, &vertexBuffer, &firstVertex);
212
213 if (!verts) {
214 SkDebugf("Could not allocate vertices\n");
215 return;
216 }
217
218 SkPoint* vertex = reinterpret_cast<SkPoint*>(verts);
219
220 if (fStrokeWidth > 0) {
221 init_nonaa_stroke_rect_strip(vertex, fRect, fStrokeWidth);
222 } else {
223 // hairline
224 vertex[0].set(fRect.fLeft, fRect.fTop);
225 vertex[1].set(fRect.fRight, fRect.fTop);
226 vertex[2].set(fRect.fRight, fRect.fBottom);
227 vertex[3].set(fRect.fLeft, fRect.fBottom);
228 vertex[4].set(fRect.fLeft, fRect.fTop);
229 }
230
231 fMesh = target->allocMesh();
232 fMesh->set(std::move(vertexBuffer), vertexCount, firstVertex);
233 }
234
235 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
236 if (!fMesh) {
237 return;
238 }
239
240 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
241 flushState->bindTextures(fProgramInfo->primProc(), nullptr, fProgramInfo->pipeline());
242 flushState->drawMesh(*fMesh);
243 }
244
245#if GR_TEST_UTILS
246 SkString onDumpInfo() const override {
247 return SkStringPrintf("Color: 0x%08x, Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
248 "StrokeWidth: %.2f\n%s",
249 fColor.toBytes_RGBA(), fRect.fLeft, fRect.fTop, fRect.fRight,
250 fRect.fBottom, fStrokeWidth, fHelper.dumpInfo().c_str());
251 }
252#endif
253
254 // TODO: override onCombineIfPossible
255
256 Helper fHelper;
257 SkPMColor4f fColor;
258 SkMatrix fViewMatrix;
259 SkRect fRect;
260 SkScalar fStrokeWidth;
261 GrSimpleMesh* fMesh = nullptr;
262 GrProgramInfo* fProgramInfo = nullptr;
263
264 const static int kVertsPerHairlineRect = 5;
265 const static int kVertsPerStrokeRect = 10;
266
267 typedef GrMeshDrawOp INHERITED;
268};
269
270///////////////////////////////////////////////////////////////////////////////////////////////////
271// AA Stroking
272///////////////////////////////////////////////////////////////////////////////////////////////////
273
274GR_DECLARE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
275GR_DECLARE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
276
277static void compute_aa_rects(SkRect* devOutside, SkRect* devOutsideAssist, SkRect* devInside,
278 bool* isDegenerate, const SkMatrix& viewMatrix, const SkRect& rect,
279 SkScalar strokeWidth, bool miterStroke, SkVector* devHalfStrokeSize) {
280 SkRect devRect;
281 viewMatrix.mapRect(&devRect, rect);
282
283 SkVector devStrokeSize;
284 if (strokeWidth > 0) {
285 devStrokeSize.set(strokeWidth, strokeWidth);
286 viewMatrix.mapVectors(&devStrokeSize, 1);
287 devStrokeSize.setAbs(devStrokeSize);
288 } else {
289 devStrokeSize.set(SK_Scalar1, SK_Scalar1);
290 }
291
292 const SkScalar dx = devStrokeSize.fX;
293 const SkScalar dy = devStrokeSize.fY;
294 const SkScalar rx = SkScalarHalf(dx);
295 const SkScalar ry = SkScalarHalf(dy);
296
297 devHalfStrokeSize->fX = rx;
298 devHalfStrokeSize->fY = ry;
299
300 *devOutside = devRect;
301 *devOutsideAssist = devRect;
302 *devInside = devRect;
303
304 devOutside->outset(rx, ry);
305 devInside->inset(rx, ry);
306
307 // If we have a degenerate stroking rect(ie the stroke is larger than inner rect) then we
308 // make a degenerate inside rect to avoid double hitting. We will also jam all of the points
309 // together when we render these rects.
310 SkScalar spare;
311 {
312 SkScalar w = devRect.width() - dx;
313 SkScalar h = devRect.height() - dy;
314 spare = std::min(w, h);
315 }
316
317 *isDegenerate = spare <= 0;
318 if (*isDegenerate) {
319 devInside->fLeft = devInside->fRight = devRect.centerX();
320 devInside->fTop = devInside->fBottom = devRect.centerY();
321 }
322
323 // For bevel-stroke, use 2 SkRect instances(devOutside and devOutsideAssist)
324 // to draw the outside of the octagon. Because there are 8 vertices on the outer
325 // edge, while vertex number of inner edge is 4, the same as miter-stroke.
326 if (!miterStroke) {
327 devOutside->inset(0, ry);
328 devOutsideAssist->outset(0, ry);
329 }
330}
331
332static GrGeometryProcessor* create_aa_stroke_rect_gp(SkArenaAlloc* arena,
333 bool tweakAlphaForCoverage,
334 const SkMatrix& viewMatrix,
335 bool usesLocalCoords,
336 bool wideColor) {
337 using namespace GrDefaultGeoProcFactory;
338
339 Coverage::Type coverageType =
340 tweakAlphaForCoverage ? Coverage::kSolid_Type : Coverage::kAttribute_Type;
341 LocalCoords::Type localCoordsType =
342 usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
343 Color::Type colorType =
344 wideColor ? Color::kPremulWideColorAttribute_Type: Color::kPremulGrColorAttribute_Type;
345
346 return MakeForDeviceSpace(arena, colorType, coverageType, localCoordsType, viewMatrix);
347}
348
349class AAStrokeRectOp final : public GrMeshDrawOp {
350private:
351 using Helper = GrSimpleMeshDrawOpHelper;
352
353public:
354 DEFINE_OP_CLASS_ID
355
356 static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
357 GrPaint&& paint,
358 const SkMatrix& viewMatrix,
359 const SkRect& devOutside,
360 const SkRect& devInside,
361 const SkVector& devHalfStrokeSize) {
362 return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix,
363 devOutside, devInside, devHalfStrokeSize);
364 }
365
366 AAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
367 const SkMatrix& viewMatrix, const SkRect& devOutside, const SkRect& devInside,
368 const SkVector& devHalfStrokeSize)
369 : INHERITED(ClassID())
370 , fHelper(helperArgs, GrAAType::kCoverage)
371 , fViewMatrix(viewMatrix) {
372 SkASSERT(!devOutside.isEmpty());
373 SkASSERT(!devInside.isEmpty());
374
375 fRects.emplace_back(RectInfo{color, devOutside, devOutside, devInside, devHalfStrokeSize, false});
376 this->setBounds(devOutside, HasAABloat::kYes, IsHairline::kNo);
377 fMiterStroke = true;
378 }
379
380 static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
381 GrPaint&& paint,
382 const SkMatrix& viewMatrix,
383 const SkRect& rect,
384 const SkStrokeRec& stroke) {
385 bool isMiter;
386 if (!allowed_stroke(stroke, GrAA::kYes, &isMiter)) {
387 return nullptr;
388 }
389 return Helper::FactoryHelper<AAStrokeRectOp>(context, std::move(paint), viewMatrix, rect,
390 stroke, isMiter);
391 }
392
393 AAStrokeRectOp(const Helper::MakeArgs& helperArgs, const SkPMColor4f& color,
394 const SkMatrix& viewMatrix, const SkRect& rect, const SkStrokeRec& stroke,
395 bool isMiter)
396 : INHERITED(ClassID())
397 , fHelper(helperArgs, GrAAType::kCoverage)
398 , fViewMatrix(viewMatrix) {
399 fMiterStroke = isMiter;
400 RectInfo& info = fRects.push_back();
401 compute_aa_rects(&info.fDevOutside, &info.fDevOutsideAssist, &info.fDevInside,
402 &info.fDegenerate, viewMatrix, rect, stroke.getWidth(), isMiter,
403 &info.fDevHalfStrokeSize);
404 info.fColor = color;
405 if (isMiter) {
406 this->setBounds(info.fDevOutside, HasAABloat::kYes, IsHairline::kNo);
407 } else {
408 // The outer polygon of the bevel stroke is an octagon specified by the points of a
409 // pair of overlapping rectangles where one is wide and the other is narrow.
410 SkRect bounds = info.fDevOutside;
411 bounds.joinPossiblyEmptyRect(info.fDevOutsideAssist);
412 this->setBounds(bounds, HasAABloat::kYes, IsHairline::kNo);
413 }
414 }
415
416 const char* name() const override { return "AAStrokeRect"; }
417
418 void visitProxies(const VisitProxyFunc& func) const override {
419 if (fProgramInfo) {
420 fProgramInfo->visitFPProxies(func);
421 } else {
422 fHelper.visitProxies(func);
423 }
424 }
425
426 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
427
428 GrProcessorSet::Analysis finalize(
429 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
430 GrClampType clampType) override {
431 return fHelper.finalizeProcessors(
432 caps, clip, hasMixedSampledCoverage, clampType,
433 GrProcessorAnalysisCoverage::kSingleChannel, &fRects.back().fColor, &fWideColor);
434 }
435
436private:
437 GrProgramInfo* programInfo() override { return fProgramInfo; }
438
439 void onCreateProgramInfo(const GrCaps*,
440 SkArenaAlloc*,
441 const GrSurfaceProxyView* writeView,
442 GrAppliedClip&&,
443 const GrXferProcessor::DstProxyView&) override;
444
445 void onPrepareDraws(Target*) override;
446 void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
447
448#if GR_TEST_UTILS
449 SkString onDumpInfo() const override {
450 SkString string;
451 for (const auto& info : fRects) {
452 string.appendf(
453 "Color: 0x%08x, ORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
454 "AssistORect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
455 "IRect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], Degen: %d",
456 info.fColor.toBytes_RGBA(), info.fDevOutside.fLeft, info.fDevOutside.fTop,
457 info.fDevOutside.fRight, info.fDevOutside.fBottom, info.fDevOutsideAssist.fLeft,
458 info.fDevOutsideAssist.fTop, info.fDevOutsideAssist.fRight,
459 info.fDevOutsideAssist.fBottom, info.fDevInside.fLeft, info.fDevInside.fTop,
460 info.fDevInside.fRight, info.fDevInside.fBottom, info.fDegenerate);
461 }
462 string += fHelper.dumpInfo();
463 return string;
464 }
465#endif
466
467 static const int kMiterIndexCnt = 3 * 24;
468 static const int kMiterVertexCnt = 16;
469 static const int kNumMiterRectsInIndexBuffer = 256;
470
471 static const int kBevelIndexCnt = 48 + 36 + 24;
472 static const int kBevelVertexCnt = 24;
473 static const int kNumBevelRectsInIndexBuffer = 256;
474
475 static sk_sp<const GrGpuBuffer> GetIndexBuffer(GrResourceProvider*, bool miterStroke);
476
477 const SkMatrix& viewMatrix() const { return fViewMatrix; }
478 bool miterStroke() const { return fMiterStroke; }
479
480 CombineResult onCombineIfPossible(GrOp* t, GrRecordingContext::Arenas*, const GrCaps&) override;
481
482 void generateAAStrokeRectGeometry(GrVertexWriter& vertices,
483 const SkPMColor4f& color,
484 bool wideColor,
485 const SkRect& devOutside,
486 const SkRect& devOutsideAssist,
487 const SkRect& devInside,
488 bool miterStroke,
489 bool degenerate,
490 bool tweakAlphaForCoverage,
491 const SkVector& devHalfStrokeSize) const;
492
493 // TODO support AA rotated stroke rects by copying around view matrices
494 struct RectInfo {
495 SkPMColor4f fColor;
496 SkRect fDevOutside;
497 SkRect fDevOutsideAssist;
498 SkRect fDevInside;
499 SkVector fDevHalfStrokeSize;
500 bool fDegenerate;
501 };
502
503 Helper fHelper;
504 SkSTArray<1, RectInfo, true> fRects;
505 SkMatrix fViewMatrix;
506 GrSimpleMesh* fMesh = nullptr;
507 GrProgramInfo* fProgramInfo = nullptr;
508 bool fMiterStroke;
509 bool fWideColor;
510
511 typedef GrMeshDrawOp INHERITED;
512};
513
514void AAStrokeRectOp::onCreateProgramInfo(const GrCaps* caps,
515 SkArenaAlloc* arena,
516 const GrSurfaceProxyView* writeView,
517 GrAppliedClip&& appliedClip,
518 const GrXferProcessor::DstProxyView& dstProxyView) {
519
520 GrGeometryProcessor* gp = create_aa_stroke_rect_gp(arena,
521 fHelper.compatibleWithCoverageAsAlpha(),
522 this->viewMatrix(),
523 fHelper.usesLocalCoords(),
524 fWideColor);
525 if (!gp) {
526 SkDebugf("Couldn't create GrGeometryProcessor\n");
527 return;
528 }
529
530 fProgramInfo = fHelper.createProgramInfo(caps,
531 arena,
532 writeView,
533 std::move(appliedClip),
534 dstProxyView,
535 gp,
536 GrPrimitiveType::kTriangles);
537}
538
539void AAStrokeRectOp::onPrepareDraws(Target* target) {
540
541 if (!fProgramInfo) {
542 this->createProgramInfo(target);
543 if (!fProgramInfo) {
544 return;
545 }
546 }
547
548 int innerVertexNum = 4;
549 int outerVertexNum = this->miterStroke() ? 4 : 8;
550 int verticesPerInstance = (outerVertexNum + innerVertexNum) * 2;
551 int indicesPerInstance = this->miterStroke() ? kMiterIndexCnt : kBevelIndexCnt;
552 int instanceCount = fRects.count();
553 int maxQuads = this->miterStroke() ? kNumMiterRectsInIndexBuffer : kNumBevelRectsInIndexBuffer;
554
555 sk_sp<const GrGpuBuffer> indexBuffer =
556 GetIndexBuffer(target->resourceProvider(), this->miterStroke());
557 if (!indexBuffer) {
558 SkDebugf("Could not allocate indices\n");
559 return;
560 }
561 PatternHelper helper(target, GrPrimitiveType::kTriangles,
562 fProgramInfo->primProc().vertexStride(), std::move(indexBuffer),
563 verticesPerInstance, indicesPerInstance, instanceCount, maxQuads);
564 GrVertexWriter vertices{ helper.vertices() };
565 if (!vertices.fPtr) {
566 SkDebugf("Could not allocate vertices\n");
567 return;
568 }
569
570 for (int i = 0; i < instanceCount; i++) {
571 const RectInfo& info = fRects[i];
572 this->generateAAStrokeRectGeometry(vertices,
573 info.fColor,
574 fWideColor,
575 info.fDevOutside,
576 info.fDevOutsideAssist,
577 info.fDevInside,
578 fMiterStroke,
579 info.fDegenerate,
580 fHelper.compatibleWithCoverageAsAlpha(),
581 info.fDevHalfStrokeSize);
582 }
583 fMesh = helper.mesh();
584}
585
586void AAStrokeRectOp::onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) {
587 if (!fProgramInfo || !fMesh) {
588 return;
589 }
590
591 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
592 flushState->bindTextures(fProgramInfo->primProc(), nullptr, fProgramInfo->pipeline());
593 flushState->drawMesh(*fMesh);
594}
595
596sk_sp<const GrGpuBuffer> AAStrokeRectOp::GetIndexBuffer(GrResourceProvider* resourceProvider,
597 bool miterStroke) {
598 if (miterStroke) {
599 // clang-format off
600 static const uint16_t gMiterIndices[] = {
601 0 + 0, 1 + 0, 5 + 0, 5 + 0, 4 + 0, 0 + 0,
602 1 + 0, 2 + 0, 6 + 0, 6 + 0, 5 + 0, 1 + 0,
603 2 + 0, 3 + 0, 7 + 0, 7 + 0, 6 + 0, 2 + 0,
604 3 + 0, 0 + 0, 4 + 0, 4 + 0, 7 + 0, 3 + 0,
605
606 0 + 4, 1 + 4, 5 + 4, 5 + 4, 4 + 4, 0 + 4,
607 1 + 4, 2 + 4, 6 + 4, 6 + 4, 5 + 4, 1 + 4,
608 2 + 4, 3 + 4, 7 + 4, 7 + 4, 6 + 4, 2 + 4,
609 3 + 4, 0 + 4, 4 + 4, 4 + 4, 7 + 4, 3 + 4,
610
611 0 + 8, 1 + 8, 5 + 8, 5 + 8, 4 + 8, 0 + 8,
612 1 + 8, 2 + 8, 6 + 8, 6 + 8, 5 + 8, 1 + 8,
613 2 + 8, 3 + 8, 7 + 8, 7 + 8, 6 + 8, 2 + 8,
614 3 + 8, 0 + 8, 4 + 8, 4 + 8, 7 + 8, 3 + 8,
615 };
616 // clang-format on
617 static_assert(SK_ARRAY_COUNT(gMiterIndices) == kMiterIndexCnt);
618 GR_DEFINE_STATIC_UNIQUE_KEY(gMiterIndexBufferKey);
619 return resourceProvider->findOrCreatePatternedIndexBuffer(
620 gMiterIndices, kMiterIndexCnt, kNumMiterRectsInIndexBuffer, kMiterVertexCnt,
621 gMiterIndexBufferKey);
622 } else {
623 /**
624 * As in miter-stroke, index = a + b, and a is the current index, b is the shift
625 * from the first index. The index layout:
626 * outer AA line: 0~3, 4~7
627 * outer edge: 8~11, 12~15
628 * inner edge: 16~19
629 * inner AA line: 20~23
630 * Following comes a bevel-stroke rect and its indices:
631 *
632 * 4 7
633 * *********************************
634 * * ______________________________ *
635 * * / 12 15 \ *
636 * * / \ *
637 * 0 * |8 16_____________________19 11 | * 3
638 * * | | | | *
639 * * | | **************** | | *
640 * * | | * 20 23 * | | *
641 * * | | * * | | *
642 * * | | * 21 22 * | | *
643 * * | | **************** | | *
644 * * | |____________________| | *
645 * 1 * |9 17 18 10| * 2
646 * * \ / *
647 * * \13 __________________________14/ *
648 * * *
649 * **********************************
650 * 5 6
651 */
652 // clang-format off
653 static const uint16_t gBevelIndices[] = {
654 // Draw outer AA, from outer AA line to outer edge, shift is 0.
655 0 + 0, 1 + 0, 9 + 0, 9 + 0, 8 + 0, 0 + 0,
656 1 + 0, 5 + 0, 13 + 0, 13 + 0, 9 + 0, 1 + 0,
657 5 + 0, 6 + 0, 14 + 0, 14 + 0, 13 + 0, 5 + 0,
658 6 + 0, 2 + 0, 10 + 0, 10 + 0, 14 + 0, 6 + 0,
659 2 + 0, 3 + 0, 11 + 0, 11 + 0, 10 + 0, 2 + 0,
660 3 + 0, 7 + 0, 15 + 0, 15 + 0, 11 + 0, 3 + 0,
661 7 + 0, 4 + 0, 12 + 0, 12 + 0, 15 + 0, 7 + 0,
662 4 + 0, 0 + 0, 8 + 0, 8 + 0, 12 + 0, 4 + 0,
663
664 // Draw the stroke, from outer edge to inner edge, shift is 8.
665 0 + 8, 1 + 8, 9 + 8, 9 + 8, 8 + 8, 0 + 8,
666 1 + 8, 5 + 8, 9 + 8,
667 5 + 8, 6 + 8, 10 + 8, 10 + 8, 9 + 8, 5 + 8,
668 6 + 8, 2 + 8, 10 + 8,
669 2 + 8, 3 + 8, 11 + 8, 11 + 8, 10 + 8, 2 + 8,
670 3 + 8, 7 + 8, 11 + 8,
671 7 + 8, 4 + 8, 8 + 8, 8 + 8, 11 + 8, 7 + 8,
672 4 + 8, 0 + 8, 8 + 8,
673
674 // Draw the inner AA, from inner edge to inner AA line, shift is 16.
675 0 + 16, 1 + 16, 5 + 16, 5 + 16, 4 + 16, 0 + 16,
676 1 + 16, 2 + 16, 6 + 16, 6 + 16, 5 + 16, 1 + 16,
677 2 + 16, 3 + 16, 7 + 16, 7 + 16, 6 + 16, 2 + 16,
678 3 + 16, 0 + 16, 4 + 16, 4 + 16, 7 + 16, 3 + 16,
679 };
680 // clang-format on
681 static_assert(SK_ARRAY_COUNT(gBevelIndices) == kBevelIndexCnt);
682
683 GR_DEFINE_STATIC_UNIQUE_KEY(gBevelIndexBufferKey);
684 return resourceProvider->findOrCreatePatternedIndexBuffer(
685 gBevelIndices, kBevelIndexCnt, kNumBevelRectsInIndexBuffer, kBevelVertexCnt,
686 gBevelIndexBufferKey);
687 }
688}
689
690GrOp::CombineResult AAStrokeRectOp::onCombineIfPossible(GrOp* t, GrRecordingContext::Arenas*,
691 const GrCaps& caps) {
692 AAStrokeRectOp* that = t->cast<AAStrokeRectOp>();
693
694 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
695 return CombineResult::kCannotCombine;
696 }
697
698 // TODO combine across miterstroke changes
699 if (this->miterStroke() != that->miterStroke()) {
700 return CombineResult::kCannotCombine;
701 }
702
703 // We apply the viewmatrix to the rect points on the cpu. However, if the pipeline uses
704 // local coords then we won't be able to combine. TODO: Upload local coords as an attribute.
705 if (fHelper.usesLocalCoords() &&
706 !SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix()))
707 {
708 return CombineResult::kCannotCombine;
709 }
710
711 fRects.push_back_n(that->fRects.count(), that->fRects.begin());
712 fWideColor |= that->fWideColor;
713 return CombineResult::kMerged;
714}
715
716// Compute the coverage for the inner two rects.
717static float compute_inner_coverage(SkScalar maxDevHalfStrokeSize) {
718 if (maxDevHalfStrokeSize < SK_ScalarHalf) {
719 return 2.0f * maxDevHalfStrokeSize / (maxDevHalfStrokeSize + SK_ScalarHalf);
720 }
721
722 return 1.0f;
723}
724
725void AAStrokeRectOp::generateAAStrokeRectGeometry(GrVertexWriter& vertices,
726 const SkPMColor4f& color,
727 bool wideColor,
728 const SkRect& devOutside,
729 const SkRect& devOutsideAssist,
730 const SkRect& devInside,
731 bool miterStroke,
732 bool degenerate,
733 bool tweakAlphaForCoverage,
734 const SkVector& devHalfStrokeSize) const {
735 // We create vertices for four nested rectangles. There are two ramps from 0 to full
736 // coverage, one on the exterior of the stroke and the other on the interior.
737
738 // The following code only really works if either devStrokeSize's fX and fY are
739 // equal (in which case innerCoverage is same for all sides of the rects) or
740 // if devStrokeSize's fX and fY are both greater than 1.0 (in which case
741 // innerCoverage will always be 1). The most problematic case is when one of
742 // fX and fY is greater than 1.0 and the other is less than 1.0. In this case
743 // the smaller side should have a partial coverage but the larger side will
744 // force the coverage to be 1.0.
745
746 auto inset_fan = [](const SkRect& r, SkScalar dx, SkScalar dy) {
747 return GrVertexWriter::TriFanFromRect(r.makeInset(dx, dy));
748 };
749
750 auto maybe_coverage = [tweakAlphaForCoverage](float coverage) {
751 return GrVertexWriter::If(!tweakAlphaForCoverage, coverage);
752 };
753
754 GrVertexColor outerColor(tweakAlphaForCoverage ? SK_PMColor4fTRANSPARENT : color, wideColor);
755
756 // For device-space stroke widths less than one we can't inset more than the original
757 // device space stroke width if we want to keep the sizing of all the rects correct.
758 const SkScalar insetX = std::min(SK_ScalarHalf, devHalfStrokeSize.fX);
759 const SkScalar insetY = std::min(SK_ScalarHalf, devHalfStrokeSize.fY);
760
761 // But, correspondingly, we always want to keep the AA picture frame one pixel wide.
762 const SkScalar outsetX = SK_Scalar1 - insetX;
763 const SkScalar outsetY = SK_Scalar1 - insetY;
764
765 // Outermost rect
766 vertices.writeQuad(inset_fan(devOutside, -outsetX, -outsetY),
767 outerColor,
768 maybe_coverage(0.0f));
769
770 if (!miterStroke) {
771 // Second outermost
772 vertices.writeQuad(inset_fan(devOutsideAssist, -outsetX, -outsetY),
773 outerColor,
774 maybe_coverage(0.0f));
775 }
776
777 float innerCoverage = compute_inner_coverage(std::max(devHalfStrokeSize.fX,
778 devHalfStrokeSize.fY));
779
780 SkPMColor4f scaledColor = color * innerCoverage;
781 GrVertexColor innerColor(tweakAlphaForCoverage ? scaledColor : color, wideColor);
782
783 // Inner rect
784 vertices.writeQuad(inset_fan(devOutside, insetX, insetY),
785 innerColor,
786 maybe_coverage(innerCoverage));
787
788 if (!miterStroke) {
789 // Second inner
790 vertices.writeQuad(inset_fan(devOutsideAssist, insetX, insetY),
791 innerColor,
792 maybe_coverage(innerCoverage));
793 }
794
795 if (!degenerate) {
796 vertices.writeQuad(inset_fan(devInside, -insetX, -insetY),
797 innerColor,
798 maybe_coverage(innerCoverage));
799
800 // The innermost rect has 0 coverage...
801 vertices.writeQuad(inset_fan(devInside, outsetX, outsetY),
802 outerColor,
803 maybe_coverage(0.0f));
804 } else {
805 // When the interior rect has become degenerate we smoosh to a single point
806 SkASSERT(devInside.fLeft == devInside.fRight && devInside.fTop == devInside.fBottom);
807
808 vertices.writeQuad(GrVertexWriter::TriFanFromRect(devInside),
809 innerColor,
810 maybe_coverage(innerCoverage));
811
812 // ... unless we are degenerate, in which case we must apply the scaled coverage
813 vertices.writeQuad(GrVertexWriter::TriFanFromRect(devInside),
814 innerColor,
815 maybe_coverage(innerCoverage));
816 }
817}
818
819} // anonymous namespace
820
821namespace GrStrokeRectOp {
822
823std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
824 GrPaint&& paint,
825 GrAAType aaType,
826 const SkMatrix& viewMatrix,
827 const SkRect& rect,
828 const SkStrokeRec& stroke) {
829 if (aaType == GrAAType::kCoverage) {
830 // The AA op only supports axis-aligned rectangles
831 if (!viewMatrix.rectStaysRect()) {
832 return nullptr;
833 }
834 return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke);
835 } else {
836 return NonAAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, stroke, aaType);
837 }
838}
839
840std::unique_ptr<GrDrawOp> MakeNested(GrRecordingContext* context,
841 GrPaint&& paint,
842 const SkMatrix& viewMatrix,
843 const SkRect rects[2]) {
844 SkASSERT(viewMatrix.rectStaysRect());
845 SkASSERT(!rects[0].isEmpty() && !rects[1].isEmpty());
846
847 SkRect devOutside, devInside;
848 viewMatrix.mapRect(&devOutside, rects[0]);
849 viewMatrix.mapRect(&devInside, rects[1]);
850 if (devInside.isEmpty()) {
851 if (devOutside.isEmpty()) {
852 return nullptr;
853 }
854 DrawQuad quad{GrQuad::MakeFromRect(rects[0], viewMatrix), GrQuad(rects[0]),
855 GrQuadAAFlags::kAll};
856 return GrFillRectOp::Make(context, std::move(paint), GrAAType::kCoverage, &quad);
857 }
858
859 SkVector devHalfStrokeSize{ SkScalarHalf(devOutside.fRight - devInside.fRight),
860 SkScalarHalf(devOutside.fBottom - devInside.fBottom) };
861 return AAStrokeRectOp::Make(context, std::move(paint), viewMatrix, devOutside,
862 devInside, devHalfStrokeSize);
863}
864
865} // namespace GrStrokeRectOp
866
867#if GR_TEST_UTILS
868
869#include "src/gpu/GrDrawOpTest.h"
870
871GR_DRAW_OP_TEST_DEFINE(NonAAStrokeRectOp) {
872 SkMatrix viewMatrix = GrTest::TestMatrix(random);
873 SkRect rect = GrTest::TestRect(random);
874 SkScalar strokeWidth = random->nextBool() ? 0.0f : 2.0f;
875 SkPaint strokePaint;
876 strokePaint.setStrokeWidth(strokeWidth);
877 strokePaint.setStyle(SkPaint::kStroke_Style);
878 strokePaint.setStrokeJoin(SkPaint::kMiter_Join);
879 SkStrokeRec strokeRec(strokePaint);
880 GrAAType aaType = GrAAType::kNone;
881 if (numSamples > 1) {
882 aaType = random->nextBool() ? GrAAType::kMSAA : GrAAType::kNone;
883 }
884 return NonAAStrokeRectOp::Make(context, std::move(paint), viewMatrix, rect, strokeRec, aaType);
885}
886
887GR_DRAW_OP_TEST_DEFINE(AAStrokeRectOp) {
888 bool miterStroke = random->nextBool();
889
890 // Create either a empty rect or a non-empty rect.
891 SkRect rect =
892 random->nextBool() ? SkRect::MakeXYWH(10, 10, 50, 40) : SkRect::MakeXYWH(6, 7, 0, 0);
893 SkScalar minDim = std::min(rect.width(), rect.height());
894 SkScalar strokeWidth = random->nextUScalar1() * minDim;
895
896 SkStrokeRec rec(SkStrokeRec::kFill_InitStyle);
897 rec.setStrokeStyle(strokeWidth);
898 rec.setStrokeParams(SkPaint::kButt_Cap,
899 miterStroke ? SkPaint::kMiter_Join : SkPaint::kBevel_Join, 1.f);
900 SkMatrix matrix = GrTest::TestMatrixRectStaysRect(random);
901 return AAStrokeRectOp::Make(context, std::move(paint), matrix, rect, rec);
902}
903
904#endif
905