Debian Codegraph @

src/gpu/ganesh/ops/GrOvalOpFactory.cpp

raw
1 /*
2 * Copyright 2013 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 #include "src/gpu/ganesh/ops/GrOvalOpFactory.h"
8
9 #include "include/core/SkMatrix.h"
10 #include "include/core/SkPaint.h"
11 #include "include/core/SkPathEffect.h"
12 #include "include/core/SkPoint.h"
13 #include "include/core/SkRRect.h"
14 #include "include/core/SkRect.h"
15 #include "include/core/SkRefCnt.h"
16 #include "include/core/SkString.h"
17 #include "include/core/SkStrokeRec.h"
18 #include "include/gpu/ganesh/GrRecordingContext.h"
19 #include "include/private/base/SkAlignedStorage.h"
20 #include "include/private/base/SkDebug.h"
21 #include "include/private/base/SkFloatingPoint.h"
22 #include "include/private/base/SkOnce.h"
23 #include "include/private/base/SkTArray.h"
24 #include "include/private/base/SkTo.h"
25 #include "include/private/gpu/ganesh/GrTypesPriv.h"
26 #include "src/base/SkArenaAlloc.h"
27 #include "src/core/SkColorData.h"
28 #include "src/core/SkMatrixPriv.h"
29 #include "src/core/SkRRectPriv.h"
30 #include "src/core/SkSLTypeShared.h"
31 #include "src/gpu/BufferWriter.h"
32 #include "src/gpu/KeyBuilder.h"
33 #include "src/gpu/ResourceKey.h"
34 #include "src/gpu/ganesh/GrAppliedClip.h"
35 #include "src/gpu/ganesh/GrBuffer.h"
36 #include "src/gpu/ganesh/GrCaps.h"
37 #include "src/gpu/ganesh/GrGeometryProcessor.h"
38 #include "src/gpu/ganesh/GrMeshDrawTarget.h"
39 #include "src/gpu/ganesh/GrOpFlushState.h"
40 #include "src/gpu/ganesh/GrPaint.h"
41 #include "src/gpu/ganesh/GrProcessorAnalysis.h"
42 #include "src/gpu/ganesh/GrProcessorSet.h"
43 #include "src/gpu/ganesh/GrProcessorUnitTest.h"
44 #include "src/gpu/ganesh/GrProgramInfo.h"
45 #include "src/gpu/ganesh/GrRecordingContextPriv.h"
46 #include "src/gpu/ganesh/GrResourceProvider.h"
47 #include "src/gpu/ganesh/GrShaderCaps.h"
48 #include "src/gpu/ganesh/GrShaderVar.h"
49 #include "src/gpu/ganesh/GrSimpleMesh.h"
50 #include "src/gpu/ganesh/GrStyle.h"
51 #include "src/gpu/ganesh/glsl/GrGLSLFragmentShaderBuilder.h"
52 #include "src/gpu/ganesh/glsl/GrGLSLVarying.h"
53 #include "src/gpu/ganesh/glsl/GrGLSLVertexGeoBuilder.h"
54 #include "src/gpu/ganesh/ops/GrMeshDrawOp.h"
55 #include "src/gpu/ganesh/ops/GrSimpleMeshDrawOpHelper.h"
56
57 #if defined(GPU_TEST_UTILS)
58 #include "src/base/SkRandom.h"
59 #include "src/gpu/ganesh/GrDrawOpTest.h"
60 #include "src/gpu/ganesh/GrTestUtils.h"
61 #endif
62
63 #include <algorithm>
64 #include <array>
65 #include <climits>
66 #include <cstdint>
67 #include <memory>
68 #include <utility>
69
70 class GrDstProxyView;
71 class GrGLSLProgramDataManager;
72 class GrGLSLUniformHandler;
73 class GrSurfaceProxyView;
74 enum class GrXferBarrierFlags;
75 namespace skgpu::ganesh {
76 class SurfaceDrawContext;
77 }
78
79 using namespace skia_private;
80
81 #if !defined(SK_ENABLE_OPTIMIZE_SIZE)
82
83 using skgpu::VertexWriter;
84 using skgpu::VertexColor;
85
86 namespace {
87
88 static inline bool circle_stays_circle(const SkMatrix& m) { return m.isSimilarity(); }
89
90 // Produces TriStrip vertex data for an origin-centered rectangle from [-x, -y] to [x, y]
91 static inline VertexWriter::TriStrip<float> origin_centered_tri_strip(float x, float y) {
92 return VertexWriter::TriStrip<float>{ -x, -y, x, y };
93 }
94
95 } // namespace
96
97 ///////////////////////////////////////////////////////////////////////////////
98
99 /**
100 * The output of this effect is a modulation of the input color and coverage for a circle. It
101 * operates in a space normalized by the circle radius (outer radius in the case of a stroke)
102 * with origin at the circle center. Three vertex attributes are used:
103 * vec2f : position in device space of the bounding geometry vertices
104 * vec4ub: color
105 * vec4f : (p.xy, outerRad, innerRad)
106 * p is the position in the normalized space.
107 * outerRad is the outerRadius in device space.
108 * innerRad is the innerRadius in normalized space (ignored if not stroking).
109 * Additional clip planes are supported for rendering circular arcs. The additional planes are
110 * either intersected or unioned together. Up to three planes are supported (an initial plane,
111 * a plane intersected with the initial plane, and a plane unioned with the first two). Only two
112 * are useful for any given arc, but having all three in one instance allows combining different
113 * types of arcs.
114 * Round caps for stroking are allowed as well. The caps are specified as two circle center points
115 * in the same space as p.xy.
116 */
117
118 class CircleGeometryProcessor : public GrGeometryProcessor {
119 public:
120 static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool stroke, bool clipPlane,
121 bool isectPlane, bool unionPlane, bool roundCaps,
122 bool wideColor, const SkMatrix& localMatrix) {
123 return arena->make([&](void* ptr) {
124 return new (ptr) CircleGeometryProcessor(stroke, clipPlane, isectPlane, unionPlane,
125 roundCaps, wideColor, localMatrix);
126 });
127 }
128
129 const char* name() const override { return "CircleGeometryProcessor"; }
130
131 void addToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override {
132 b->addBool(fStroke, "stroked" );
133 b->addBool(fInClipPlane.isInitialized(), "clipPlane" );
134 b->addBool(fInIsectPlane.isInitialized(), "isectPlane" );
135 b->addBool(fInUnionPlane.isInitialized(), "unionPlane" );
136 b->addBool(fInRoundCapCenters.isInitialized(), "roundCapCenters");
137 b->addBits(ProgramImpl::kMatrixKeyBits,
138 ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix),
139 "localMatrixType");
140 }
141
142 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override {
143 return std::make_unique<Impl>();
144 }
145
146 private:
147 CircleGeometryProcessor(bool stroke, bool clipPlane, bool isectPlane, bool unionPlane,
148 bool roundCaps, bool wideColor, const SkMatrix& localMatrix)
149 : INHERITED(kCircleGeometryProcessor_ClassID)
150 , fLocalMatrix(localMatrix)
151 , fStroke(stroke) {
152 fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
153 fInColor = MakeColorAttribute("inColor", wideColor);
154 fInCircleEdge = {"inCircleEdge", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
155
156 if (clipPlane) {
157 fInClipPlane = {"inClipPlane", kFloat3_GrVertexAttribType, SkSLType::kHalf3};
158 }
159 if (isectPlane) {
160 fInIsectPlane = {"inIsectPlane", kFloat3_GrVertexAttribType, SkSLType::kHalf3};
161 }
162 if (unionPlane) {
163 fInUnionPlane = {"inUnionPlane", kFloat3_GrVertexAttribType, SkSLType::kHalf3};
164 }
165 if (roundCaps) {
166 SkASSERT(clipPlane);
167 fInRoundCapCenters =
168 {"inRoundCapCenters", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
169 }
170 this->setVertexAttributesWithImplicitOffsets(&fInPosition, 7);
171 }
172
173 class Impl : public ProgramImpl {
174 public:
175 void setData(const GrGLSLProgramDataManager& pdman,
176 const GrShaderCaps& shaderCaps,
177 const GrGeometryProcessor& geomProc) override {
178 SetTransform(pdman,
179 shaderCaps,
180 fLocalMatrixUniform,
181 geomProc.cast<CircleGeometryProcessor>().fLocalMatrix,
182 &fLocalMatrix);
183 }
184
185 private:
186 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
187 const CircleGeometryProcessor& cgp = args.fGeomProc.cast<CircleGeometryProcessor>();
188 GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
189 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
190 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
191 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
192
193 // emit attributes
194 varyingHandler->emitAttributes(cgp);
195 fragBuilder->codeAppend("float4 circleEdge;");
196 varyingHandler->addPassThroughAttribute(cgp.fInCircleEdge.asShaderVar(), "circleEdge");
197 if (cgp.fInClipPlane.isInitialized()) {
198 fragBuilder->codeAppend("half3 clipPlane;");
199 varyingHandler->addPassThroughAttribute(cgp.fInClipPlane.asShaderVar(),
200 "clipPlane");
201 }
202 if (cgp.fInIsectPlane.isInitialized()) {
203 fragBuilder->codeAppend("half3 isectPlane;");
204 varyingHandler->addPassThroughAttribute(cgp.fInIsectPlane.asShaderVar(),
205 "isectPlane");
206 }
207 if (cgp.fInUnionPlane.isInitialized()) {
208 SkASSERT(cgp.fInClipPlane.isInitialized());
209 fragBuilder->codeAppend("half3 unionPlane;");
210 varyingHandler->addPassThroughAttribute(cgp.fInUnionPlane.asShaderVar(),
211 "unionPlane");
212 }
213 GrGLSLVarying capRadius(SkSLType::kFloat);
214 if (cgp.fInRoundCapCenters.isInitialized()) {
215 fragBuilder->codeAppend("float4 roundCapCenters;");
216 varyingHandler->addPassThroughAttribute(cgp.fInRoundCapCenters.asShaderVar(),
217 "roundCapCenters");
218 varyingHandler->addVarying("capRadius", &capRadius,
219 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
220 // This is the cap radius in normalized space where the outer radius is 1 and
221 // circledEdge.w is the normalized inner radius.
222 vertBuilder->codeAppendf("%s = (1.0 - %s.w) / 2.0;", capRadius.vsOut(),
223 cgp.fInCircleEdge.name());
224 }
225
226 // setup pass through color
227 fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
228 varyingHandler->addPassThroughAttribute(cgp.fInColor.asShaderVar(), args.fOutputColor);
229
230 // Setup position
231 WriteOutputPosition(vertBuilder, gpArgs, cgp.fInPosition.name());
232 WriteLocalCoord(vertBuilder,
233 uniformHandler,
234 *args.fShaderCaps,
235 gpArgs,
236 cgp.fInPosition.asShaderVar(),
237 cgp.fLocalMatrix,
238 &fLocalMatrixUniform);
239
240 fragBuilder->codeAppend("float d = length(circleEdge.xy);");
241 fragBuilder->codeAppend("half distanceToOuterEdge = half(circleEdge.z * (1.0 - d));");
242 fragBuilder->codeAppend("half edgeAlpha = saturate(distanceToOuterEdge);");
243 if (cgp.fStroke) {
244 fragBuilder->codeAppend(
245 "half distanceToInnerEdge = half(circleEdge.z * (d - circleEdge.w));");
246 fragBuilder->codeAppend("half innerAlpha = saturate(distanceToInnerEdge);");
247 fragBuilder->codeAppend("edgeAlpha *= innerAlpha;");
248 }
249
250 if (cgp.fInClipPlane.isInitialized()) {
251 fragBuilder->codeAppend(
252 "half clip = half(saturate(circleEdge.z * dot(circleEdge.xy, "
253 "clipPlane.xy) + clipPlane.z));");
254 if (cgp.fInIsectPlane.isInitialized()) {
255 fragBuilder->codeAppend(
256 "clip *= half(saturate(circleEdge.z * dot(circleEdge.xy, "
257 "isectPlane.xy) + isectPlane.z));");
258 }
259 if (cgp.fInUnionPlane.isInitialized()) {
260 fragBuilder->codeAppend(
261 "clip = saturate(clip + half(saturate(circleEdge.z * dot(circleEdge.xy,"
262 " unionPlane.xy) + unionPlane.z)));");
263 }
264 fragBuilder->codeAppend("edgeAlpha *= clip;");
265 if (cgp.fInRoundCapCenters.isInitialized()) {
266 // We compute coverage of the round caps as circles at the butt caps produced
267 // by the clip planes. The inverse of the clip planes is applied so that there
268 // is no double counting.
269 fragBuilder->codeAppendf(
270 "half dcap1 = half(circleEdge.z * (%s - length(circleEdge.xy - "
271 "roundCapCenters.xy)));"
272 "half dcap2 = half(circleEdge.z * (%s - length(circleEdge.xy - "
273 "roundCapCenters.zw)));"
274 "half capAlpha = (1 - clip) * (max(dcap1, 0) + max(dcap2, 0));"
275 "edgeAlpha = min(edgeAlpha + capAlpha, 1.0);",
276 capRadius.fsIn(), capRadius.fsIn());
277 }
278 }
279 fragBuilder->codeAppendf("half4 %s = half4(edgeAlpha);", args.fOutputCoverage);
280 }
281
282 SkMatrix fLocalMatrix = SkMatrix::InvalidMatrix();
283 UniformHandle fLocalMatrixUniform;
284 };
285
286 SkMatrix fLocalMatrix;
287
288 Attribute fInPosition;
289 Attribute fInColor;
290 Attribute fInCircleEdge;
291 // Optional attributes.
292 Attribute fInClipPlane;
293 Attribute fInIsectPlane;
294 Attribute fInUnionPlane;
295 Attribute fInRoundCapCenters;
296
297 bool fStroke;
298 GR_DECLARE_GEOMETRY_PROCESSOR_TEST
299
300 using INHERITED = GrGeometryProcessor;
301 };
302
303 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(CircleGeometryProcessor)
304
305 #if defined(GPU_TEST_UTILS)
306 GrGeometryProcessor* CircleGeometryProcessor::TestCreate(GrProcessorTestData* d) {
307 bool stroke = d->fRandom->nextBool();
308 bool roundCaps = stroke ? d->fRandom->nextBool() : false;
309 bool wideColor = d->fRandom->nextBool();
310 bool clipPlane = d->fRandom->nextBool();
311 bool isectPlane = d->fRandom->nextBool();
312 bool unionPlane = d->fRandom->nextBool();
313 const SkMatrix& matrix = GrTest::TestMatrix(d->fRandom);
314 return CircleGeometryProcessor::Make(d->allocator(), stroke, clipPlane, isectPlane,
315 unionPlane, roundCaps, wideColor, matrix);
316 }
317 #endif
318
319 class ButtCapDashedCircleGeometryProcessor : public GrGeometryProcessor {
320 public:
321 static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool wideColor,
322 const SkMatrix& localMatrix) {
323 return arena->make([&](void* ptr) {
324 return new (ptr) ButtCapDashedCircleGeometryProcessor(wideColor, localMatrix);
325 });
326 }
327
328 ~ButtCapDashedCircleGeometryProcessor() override {}
329
330 const char* name() const override { return "ButtCapDashedCircleGeometryProcessor"; }
331
332 void addToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override {
333 b->addBits(ProgramImpl::kMatrixKeyBits,
334 ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix),
335 "localMatrixType");
336 }
337
338 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override {
339 return std::make_unique<Impl>();
340 }
341
342 private:
343 ButtCapDashedCircleGeometryProcessor(bool wideColor, const SkMatrix& localMatrix)
344 : INHERITED(kButtCapStrokedCircleGeometryProcessor_ClassID)
345 , fLocalMatrix(localMatrix) {
346 fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
347 fInColor = MakeColorAttribute("inColor", wideColor);
348 fInCircleEdge = {"inCircleEdge", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
349 fInDashParams = {"inDashParams", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
350 this->setVertexAttributesWithImplicitOffsets(&fInPosition, 4);
351 }
352
353 class Impl : public ProgramImpl {
354 public:
355 void setData(const GrGLSLProgramDataManager& pdman,
356 const GrShaderCaps& shaderCaps,
357 const GrGeometryProcessor& geomProc) override {
358 SetTransform(pdman,
359 shaderCaps,
360 fLocalMatrixUniform,
361 geomProc.cast<ButtCapDashedCircleGeometryProcessor>().fLocalMatrix,
362 &fLocalMatrix);
363 }
364
365 private:
366 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
367 const ButtCapDashedCircleGeometryProcessor& bcscgp =
368 args.fGeomProc.cast<ButtCapDashedCircleGeometryProcessor>();
369 GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
370 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
371 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
372 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
373
374 // emit attributes
375 varyingHandler->emitAttributes(bcscgp);
376 fragBuilder->codeAppend("float4 circleEdge;");
377 varyingHandler->addPassThroughAttribute(bcscgp.fInCircleEdge.asShaderVar(),
378 "circleEdge");
379
380 fragBuilder->codeAppend("float4 dashParams;");
381 varyingHandler->addPassThroughAttribute(
382 bcscgp.fInDashParams.asShaderVar(),
383 "dashParams",
384 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
385 GrGLSLVarying wrapDashes(SkSLType::kHalf4);
386 varyingHandler->addVarying("wrapDashes", &wrapDashes,
387 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
388 GrGLSLVarying lastIntervalLength(SkSLType::kHalf);
389 varyingHandler->addVarying("lastIntervalLength", &lastIntervalLength,
390 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
391 vertBuilder->codeAppendf("float4 dashParams = %s;", bcscgp.fInDashParams.name());
392 // Our fragment shader works in on/off intervals as specified by dashParams.xy:
393 // x = length of on interval, y = length of on + off.
394 // There are two other parameters in dashParams.zw:
395 // z = start angle in radians, w = phase offset in radians in range -y/2..y/2.
396 // Each interval has a "corresponding" dash which may be shifted partially or
397 // fully out of its interval by the phase. So there may be up to two "visual"
398 // dashes in an interval.
399 // When computing coverage in an interval we look at three dashes. These are the
400 // "corresponding" dashes from the current, previous, and next intervals. Any of these
401 // may be phase shifted into our interval or even when phase=0 they may be within half a
402 // pixel distance of a pixel center in the interval.
403 // When in the first interval we need to check the dash from the last interval. And
404 // similarly when in the last interval we need to check the dash from the first
405 // interval. When 2pi is not perfectly divisible dashParams.y this is a boundary case.
406 // We compute the dash begin/end angles in the vertex shader and apply them in the
407 // fragment shader when we detect we're in the first/last interval.
408 vertBuilder->codeAppend(
409 // The two boundary dash intervals are stored in wrapDashes.xy and .zw and fed
410 // to the fragment shader as a varying.
411 "float4 wrapDashes;"
412 "half lastIntervalLength = mod(6.28318530718, half(dashParams.y));"
413 // We can happen to be perfectly divisible.
414 "if (0 == lastIntervalLength) {"
415 "lastIntervalLength = half(dashParams.y);"
416 "}"
417 // Let 'l' be the last interval before reaching 2 pi.
418 // Based on the phase determine whether (l-1)th, l-th, or (l+1)th interval's
419 // "corresponding" dash appears in the l-th interval and is closest to the 0-th
420 // interval.
421 "half offset = 0;"
422 "if (-dashParams.w >= lastIntervalLength) {"
423 "offset = half(-dashParams.y);"
424 "} else if (dashParams.w > dashParams.y - lastIntervalLength) {"
425 "offset = half(dashParams.y);"
426 "}"
427 "wrapDashes.x = -lastIntervalLength + offset - dashParams.w;"
428 // The end of this dash may be beyond the 2 pi and therefore clipped. Hence the
429 // min.
430 "wrapDashes.y = min(wrapDashes.x + dashParams.x, 0);"
431
432 // Based on the phase determine whether the -1st, 0th, or 1st interval's
433 // "corresponding" dash appears in the 0th interval and is closest to l.
434 "offset = 0;"
435 "if (dashParams.w >= dashParams.x) {"
436 "offset = half(dashParams.y);"
437 "} else if (-dashParams.w > dashParams.y - dashParams.x) {"
438 "offset = half(-dashParams.y);"
439 "}"
440 "wrapDashes.z = lastIntervalLength + offset - dashParams.w;"
441 "wrapDashes.w = wrapDashes.z + dashParams.x;"
442 // The start of the dash we're considering may be clipped by the start of the
443 // circle.
444 "wrapDashes.z = max(wrapDashes.z, lastIntervalLength);"
445 );
446 vertBuilder->codeAppendf("%s = half4(wrapDashes);", wrapDashes.vsOut());
447 vertBuilder->codeAppendf("%s = lastIntervalLength;", lastIntervalLength.vsOut());
448 fragBuilder->codeAppendf("half4 wrapDashes = %s;", wrapDashes.fsIn());
449 fragBuilder->codeAppendf("half lastIntervalLength = %s;", lastIntervalLength.fsIn());
450
451 // setup pass through color
452 fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
453 varyingHandler->addPassThroughAttribute(
454 bcscgp.fInColor.asShaderVar(),
455 args.fOutputColor,
456 GrGLSLVaryingHandler::Interpolation::kCanBeFlat);
457
458 // Setup position
459 WriteOutputPosition(vertBuilder, gpArgs, bcscgp.fInPosition.name());
460 WriteLocalCoord(vertBuilder,
461 uniformHandler,
462 *args.fShaderCaps,
463 gpArgs,
464 bcscgp.fInPosition.asShaderVar(),
465 bcscgp.fLocalMatrix,
466 &fLocalMatrixUniform);
467
468 GrShaderVar fnArgs[] = {
469 GrShaderVar("angleToEdge", SkSLType::kFloat),
470 GrShaderVar("diameter", SkSLType::kFloat),
471 };
472 SkString fnName = fragBuilder->getMangledFunctionName("coverage_from_dash_edge");
473 fragBuilder->emitFunction(SkSLType::kFloat, fnName.c_str(),
474 {fnArgs, std::size(fnArgs)},
475 "float linearDist;"
476 "angleToEdge = clamp(angleToEdge, -3.1415, 3.1415);"
477 "linearDist = diameter * sin(angleToEdge / 2);"
478 "return saturate(linearDist + 0.5);"
479 );
480 fragBuilder->codeAppend(
481 "float d = length(circleEdge.xy) * circleEdge.z;"
482
483 // Compute coverage from outer/inner edges of the stroke.
484 "half distanceToOuterEdge = half(circleEdge.z - d);"
485 "half edgeAlpha = saturate(distanceToOuterEdge);"
486 "half distanceToInnerEdge = half(d - circleEdge.z * circleEdge.w);"
487 "half innerAlpha = saturate(distanceToInnerEdge);"
488 "edgeAlpha *= innerAlpha;"
489
490 "half angleFromStart = half(atan(circleEdge.y, circleEdge.x) - dashParams.z);"
491 "angleFromStart = mod(angleFromStart, 6.28318530718);"
492 "float x = mod(angleFromStart, dashParams.y);"
493 // Convert the radial distance from center to pixel into a diameter.
494 "d *= 2;"
495 "half2 currDash = half2(half(-dashParams.w), half(dashParams.x) -"
496 "half(dashParams.w));"
497 "half2 nextDash = half2(half(dashParams.y) - half(dashParams.w),"
498 "half(dashParams.y) + half(dashParams.x) -"
499 "half(dashParams.w));"
500 "half2 prevDash = half2(half(-dashParams.y) - half(dashParams.w),"
501 "half(-dashParams.y) + half(dashParams.x) -"
502 "half(dashParams.w));"
503 "const half kDashBoundsEpsilon = 0.01;"
504 "half dashAlpha = 0;"
505 );
506 fragBuilder->codeAppendf(
507 "if (angleFromStart - x + dashParams.y >= 6.28318530718 + kDashBoundsEpsilon) {"
508 "dashAlpha += half(%s(x - wrapDashes.z, d) * %s(wrapDashes.w - x, d));"
509 "currDash.y = min(currDash.y, lastIntervalLength);"
510 "if (nextDash.x >= lastIntervalLength) {"
511 // The next dash is outside the 0..2pi range, throw it away
512 "nextDash.xy = half2(1000);"
513 "} else {"
514 // Clip the end of the next dash to the end of the circle
515 "nextDash.y = min(nextDash.y, lastIntervalLength);"
516 "}"
517 "}"
518 , fnName.c_str(), fnName.c_str());
519 fragBuilder->codeAppendf(
520 "if (angleFromStart - x - dashParams.y < -kDashBoundsEpsilon) {"
521 "dashAlpha += half(%s(x - wrapDashes.x, d) * %s(wrapDashes.y - x, d));"
522 "currDash.x = max(currDash.x, 0);"
523 "if (prevDash.y <= 0) {"
524 // The previous dash is outside the 0..2pi range, throw it away
525 "prevDash.xy = half2(1000);"
526 "} else {"
527 // Clip the start previous dash to the start of the circle
528 "prevDash.x = max(prevDash.x, 0);"
529 "}"
530 "}"
531 , fnName.c_str(), fnName.c_str());
532 fragBuilder->codeAppendf(
533 "dashAlpha += half(%s(x - currDash.x, d) * %s(currDash.y - x, d));"
534 "dashAlpha += half(%s(x - nextDash.x, d) * %s(nextDash.y - x, d));"
535 "dashAlpha += half(%s(x - prevDash.x, d) * %s(prevDash.y - x, d));"
536 "dashAlpha = min(dashAlpha, 1);"
537 "edgeAlpha *= dashAlpha;"
538 , fnName.c_str(), fnName.c_str(), fnName.c_str(), fnName.c_str(), fnName.c_str(),
539 fnName.c_str());
540 fragBuilder->codeAppendf("half4 %s = half4(edgeAlpha);", args.fOutputCoverage);
541 }
542
543 SkMatrix fLocalMatrix = SkMatrix::InvalidMatrix();
544 UniformHandle fLocalMatrixUniform;
545 };
546
547 SkMatrix fLocalMatrix;
548 Attribute fInPosition;
549 Attribute fInColor;
550 Attribute fInCircleEdge;
551 Attribute fInDashParams;
552
553 GR_DECLARE_GEOMETRY_PROCESSOR_TEST
554
555 using INHERITED = GrGeometryProcessor;
556 };
557
558 #if defined(GPU_TEST_UTILS)
559 GrGeometryProcessor* ButtCapDashedCircleGeometryProcessor::TestCreate(GrProcessorTestData* d) {
560 bool wideColor = d->fRandom->nextBool();
561 const SkMatrix& matrix = GrTest::TestMatrix(d->fRandom);
562 return ButtCapDashedCircleGeometryProcessor::Make(d->allocator(), wideColor, matrix);
563 }
564 #endif
565
566 ///////////////////////////////////////////////////////////////////////////////
567
568 /**
569 * The output of this effect is a modulation of the input color and coverage for an axis-aligned
570 * ellipse, specified as a 2D offset from center, and the reciprocals of the outer and inner radii,
571 * in both x and y directions.
572 *
573 * We are using an implicit function of x^2/a^2 + y^2/b^2 - 1 = 0.
574 */
575
576 class EllipseGeometryProcessor : public GrGeometryProcessor {
577 public:
578 static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool stroke, bool wideColor,
579 bool useScale, const SkMatrix& localMatrix) {
580 return arena->make([&](void* ptr) {
581 return new (ptr) EllipseGeometryProcessor(stroke, wideColor, useScale, localMatrix);
582 });
583 }
584
585 ~EllipseGeometryProcessor() override {}
586
587 const char* name() const override { return "EllipseGeometryProcessor"; }
588
589 void addToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override {
590 b->addBool(fStroke, "stroked");
591 b->addBits(ProgramImpl::kMatrixKeyBits,
592 ProgramImpl::ComputeMatrixKey(caps, fLocalMatrix),
593 "localMatrixType");
594 }
595
596 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override {
597 return std::make_unique<Impl>();
598 }
599
600 private:
601 EllipseGeometryProcessor(bool stroke, bool wideColor, bool useScale,
602 const SkMatrix& localMatrix)
603 : INHERITED(kEllipseGeometryProcessor_ClassID)
604 , fLocalMatrix(localMatrix)
605 , fStroke(stroke)
606 , fUseScale(useScale) {
607 fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
608 fInColor = MakeColorAttribute("inColor", wideColor);
609 if (useScale) {
610 fInEllipseOffset = {"inEllipseOffset", kFloat3_GrVertexAttribType, SkSLType::kFloat3};
611 } else {
612 fInEllipseOffset = {"inEllipseOffset", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
613 }
614 fInEllipseRadii = {"inEllipseRadii", kFloat4_GrVertexAttribType, SkSLType::kFloat4};
615 this->setVertexAttributesWithImplicitOffsets(&fInPosition, 4);
616 }
617
618 class Impl : public ProgramImpl {
619 public:
620 void setData(const GrGLSLProgramDataManager& pdman,
621 const GrShaderCaps& shaderCaps,
622 const GrGeometryProcessor& geomProc) override {
623 const EllipseGeometryProcessor& egp = geomProc.cast<EllipseGeometryProcessor>();
624 SetTransform(pdman, shaderCaps, fLocalMatrixUniform, egp.fLocalMatrix, &fLocalMatrix);
625 }
626
627 private:
628 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
629 const EllipseGeometryProcessor& egp = args.fGeomProc.cast<EllipseGeometryProcessor>();
630 GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
631 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
632 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
633
634 // emit attributes
635 varyingHandler->emitAttributes(egp);
636
637 SkSLType offsetType = egp.fUseScale ? SkSLType::kFloat3 : SkSLType::kFloat2;
638 GrGLSLVarying ellipseOffsets(offsetType);
639 varyingHandler->addVarying("EllipseOffsets", &ellipseOffsets);
640 vertBuilder->codeAppendf("%s = %s;", ellipseOffsets.vsOut(),
641 egp.fInEllipseOffset.name());
642
643 GrGLSLVarying ellipseRadii(SkSLType::kFloat4);
644 varyingHandler->addVarying("EllipseRadii", &ellipseRadii);
645 vertBuilder->codeAppendf("%s = %s;", ellipseRadii.vsOut(), egp.fInEllipseRadii.name());
646
647 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
648 // setup pass through color
649 fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
650 varyingHandler->addPassThroughAttribute(egp.fInColor.asShaderVar(), args.fOutputColor);
651
652 // Setup position
653 WriteOutputPosition(vertBuilder, gpArgs, egp.fInPosition.name());
654 WriteLocalCoord(vertBuilder,
655 uniformHandler,
656 *args.fShaderCaps,
657 gpArgs,
658 egp.fInPosition.asShaderVar(),
659 egp.fLocalMatrix,
660 &fLocalMatrixUniform);
661
662 // For stroked ellipses, we use the full ellipse equation (x^2/a^2 + y^2/b^2 = 1)
663 // to compute both the edges because we need two separate test equations for
664 // the single offset.
665 // For filled ellipses we can use a unit circle equation (x^2 + y^2 = 1), and warp
666 // the distance by the gradient, non-uniformly scaled by the inverse of the
667 // ellipse size.
668
669 // On medium precision devices, we scale the denominator of the distance equation
670 // before taking the inverse square root to minimize the chance that we're dividing
671 // by zero, then we scale the result back.
672
673 // for outer curve
674 fragBuilder->codeAppendf("float2 offset = %s.xy;", ellipseOffsets.fsIn());
675 if (egp.fStroke) {
676 fragBuilder->codeAppendf("offset *= %s.xy;", ellipseRadii.fsIn());
677 }
678 fragBuilder->codeAppend("float test = dot(offset, offset) - 1.0;");
679 if (egp.fUseScale) {
680 fragBuilder->codeAppendf("float2 grad = 2.0*offset*(%s.z*%s.xy);",
681 ellipseOffsets.fsIn(), ellipseRadii.fsIn());
682 } else {
683 fragBuilder->codeAppendf("float2 grad = 2.0*offset*%s.xy;", ellipseRadii.fsIn());
684 }
685 fragBuilder->codeAppend("float grad_dot = dot(grad, grad);");
686
687 // avoid calling inversesqrt on zero.
688 if (args.fShaderCaps->fFloatIs32Bits) {
689 fragBuilder->codeAppend("grad_dot = max(grad_dot, 1.1755e-38);");
690 } else {
691 fragBuilder->codeAppend("grad_dot = max(grad_dot, 6.1036e-5);");
692 }
693 if (egp.fUseScale) {
694 fragBuilder->codeAppendf("float invlen = %s.z*inversesqrt(grad_dot);",
695 ellipseOffsets.fsIn());
696 } else {
697 fragBuilder->codeAppend("float invlen = inversesqrt(grad_dot);");
698 }
699 fragBuilder->codeAppend("float edgeAlpha = saturate(0.5-test*invlen);");
700
701 // for inner curve
702 if (egp.fStroke) {
703 fragBuilder->codeAppendf("offset = %s.xy*%s.zw;", ellipseOffsets.fsIn(),
704 ellipseRadii.fsIn());
705 fragBuilder->codeAppend("test = dot(offset, offset) - 1.0;");
706 if (egp.fUseScale) {
707 fragBuilder->codeAppendf("grad = 2.0*offset*(%s.z*%s.zw);",
708 ellipseOffsets.fsIn(), ellipseRadii.fsIn());
709 } else {
710 fragBuilder->codeAppendf("grad = 2.0*offset*%s.zw;", ellipseRadii.fsIn());
711 }
712 fragBuilder->codeAppend("grad_dot = dot(grad, grad);");
713 if (!args.fShaderCaps->fFloatIs32Bits) {
714 fragBuilder->codeAppend("grad_dot = max(grad_dot, 6.1036e-5);");
715 }
716 if (egp.fUseScale) {
717 fragBuilder->codeAppendf("invlen = %s.z*inversesqrt(grad_dot);",
718 ellipseOffsets.fsIn());
719 } else {
720 fragBuilder->codeAppend("invlen = inversesqrt(grad_dot);");
721 }
722 fragBuilder->codeAppend("edgeAlpha *= saturate(0.5+test*invlen);");
723 }
724
725 fragBuilder->codeAppendf("half4 %s = half4(half(edgeAlpha));", args.fOutputCoverage);
726 }
727
728 using INHERITED = ProgramImpl;
729
730 SkMatrix fLocalMatrix = SkMatrix::InvalidMatrix();
731 UniformHandle fLocalMatrixUniform;
732 };
733
734 Attribute fInPosition;
735 Attribute fInColor;
736 Attribute fInEllipseOffset;
737 Attribute fInEllipseRadii;
738
739 SkMatrix fLocalMatrix;
740 bool fStroke;
741 bool fUseScale;
742
743 GR_DECLARE_GEOMETRY_PROCESSOR_TEST
744
745 using INHERITED = GrGeometryProcessor;
746 };
747
748 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(EllipseGeometryProcessor)
749
750 #if defined(GPU_TEST_UTILS)
751 GrGeometryProcessor* EllipseGeometryProcessor::TestCreate(GrProcessorTestData* d) {
752 bool stroke = d->fRandom->nextBool();
753 bool wideColor = d->fRandom->nextBool();
754 bool useScale = d->fRandom->nextBool();
755 SkMatrix matrix = GrTest::TestMatrix(d->fRandom);
756 return EllipseGeometryProcessor::Make(d->allocator(), stroke, wideColor, useScale, matrix);
757 }
758 #endif
759
760 ///////////////////////////////////////////////////////////////////////////////
761
762 /**
763 * The output of this effect is a modulation of the input color and coverage for an ellipse,
764 * specified as a 2D offset from center for both the outer and inner paths (if stroked). The
765 * implict equation used is for a unit circle (x^2 + y^2 - 1 = 0) and the edge corrected by
766 * using differentials.
767 *
768 * The result is device-independent and can be used with any affine matrix.
769 */
770
771 enum class DIEllipseStyle { kStroke = 0, kHairline, kFill };
772
773 class DIEllipseGeometryProcessor : public GrGeometryProcessor {
774 public:
775 static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool wideColor, bool useScale,
776 const SkMatrix& viewMatrix, DIEllipseStyle style) {
777 return arena->make([&](void* ptr) {
778 return new (ptr) DIEllipseGeometryProcessor(wideColor, useScale, viewMatrix, style);
779 });
780 }
781
782 ~DIEllipseGeometryProcessor() override {}
783
784 const char* name() const override { return "DIEllipseGeometryProcessor"; }
785
786 void addToKey(const GrShaderCaps& caps, skgpu::KeyBuilder* b) const override {
787 b->addBits(2, static_cast<uint32_t>(fStyle), "style");
788 b->addBits(ProgramImpl::kMatrixKeyBits,
789 ProgramImpl::ComputeMatrixKey(caps, fViewMatrix),
790 "viewMatrixType");
791 }
792
793 std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const override {
794 return std::make_unique<Impl>();
795 }
796
797 private:
798 DIEllipseGeometryProcessor(bool wideColor, bool useScale, const SkMatrix& viewMatrix,
799 DIEllipseStyle style)
800 : INHERITED(kDIEllipseGeometryProcessor_ClassID)
801 , fViewMatrix(viewMatrix)
802 , fUseScale(useScale)
803 , fStyle(style) {
804 fInPosition = {"inPosition", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
805 fInColor = MakeColorAttribute("inColor", wideColor);
806 if (useScale) {
807 fInEllipseOffsets0 = {"inEllipseOffsets0", kFloat3_GrVertexAttribType,
808 SkSLType::kFloat3};
809 } else {
810 fInEllipseOffsets0 = {"inEllipseOffsets0", kFloat2_GrVertexAttribType,
811 SkSLType::kFloat2};
812 }
813 fInEllipseOffsets1 = {"inEllipseOffsets1", kFloat2_GrVertexAttribType, SkSLType::kFloat2};
814 this->setVertexAttributesWithImplicitOffsets(&fInPosition, 4);
815 }
816
817 class Impl : public ProgramImpl {
818 public:
819 void setData(const GrGLSLProgramDataManager& pdman,
820 const GrShaderCaps& shaderCaps,
821 const GrGeometryProcessor& geomProc) override {
822 const auto& diegp = geomProc.cast<DIEllipseGeometryProcessor>();
823
824 SetTransform(pdman, shaderCaps, fViewMatrixUniform, diegp.fViewMatrix, &fViewMatrix);
825 }
826
827 private:
828 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
829 const auto& diegp = args.fGeomProc.cast<DIEllipseGeometryProcessor>();
830 GrGLSLVertexBuilder* vertBuilder = args.fVertBuilder;
831 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
832 GrGLSLUniformHandler* uniformHandler = args.fUniformHandler;
833
834 // emit attributes
835 varyingHandler->emitAttributes(diegp);
836
837 SkSLType offsetType = (diegp.fUseScale) ? SkSLType::kFloat3 : SkSLType::kFloat2;
838 GrGLSLVarying offsets0(offsetType);
839 varyingHandler->addVarying("EllipseOffsets0", &offsets0);
840 vertBuilder->codeAppendf("%s = %s;", offsets0.vsOut(), diegp.fInEllipseOffsets0.name());
841
842 GrGLSLVarying offsets1(SkSLType::kFloat2);
843 varyingHandler->addVarying("EllipseOffsets1", &offsets1);
844 vertBuilder->codeAppendf("%s = %s;", offsets1.vsOut(), diegp.fInEllipseOffsets1.name());
845
846 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
847 fragBuilder->codeAppendf("half4 %s;", args.fOutputColor);
848 varyingHandler->addPassThroughAttribute(diegp.fInColor.asShaderVar(),
849 args.fOutputColor);
850
851 // Setup position
852 WriteOutputPosition(vertBuilder,
853 uniformHandler,
854 *args.fShaderCaps,
855 gpArgs,
856 diegp.fInPosition.name(),
857 diegp.fViewMatrix,
858 &fViewMatrixUniform);
859 gpArgs->fLocalCoordVar = diegp.fInPosition.asShaderVar();
860
861 // for outer curve
862 fragBuilder->codeAppendf("float2 scaledOffset = %s.xy;", offsets0.fsIn());
863 fragBuilder->codeAppend("float test = dot(scaledOffset, scaledOffset) - 1.0;");
864 fragBuilder->codeAppendf("float2 duvdx = dFdx(%s.xy);", offsets0.fsIn());
865 fragBuilder->codeAppendf("float2 duvdy = dFdy(%s.xy);", offsets0.fsIn());
866 fragBuilder->codeAppendf(
867 "float2 grad = float2(%s.x*duvdx.x + %s.y*duvdx.y,"
868 " %s.x*duvdy.x + %s.y*duvdy.y);",
869 offsets0.fsIn(), offsets0.fsIn(), offsets0.fsIn(), offsets0.fsIn());
870 if (diegp.fUseScale) {
871 fragBuilder->codeAppendf("grad *= %s.z;", offsets0.fsIn());
872 }
873
874 fragBuilder->codeAppend("float grad_dot = 4.0*dot(grad, grad);");
875 // avoid calling inversesqrt on zero.
876 if (args.fShaderCaps->fFloatIs32Bits) {
877 fragBuilder->codeAppend("grad_dot = max(grad_dot, 1.1755e-38);");
878 } else {
879 fragBuilder->codeAppend("grad_dot = max(grad_dot, 6.1036e-5);");
880 }
881 fragBuilder->codeAppend("float invlen = inversesqrt(grad_dot);");
882 if (diegp.fUseScale) {
883 fragBuilder->codeAppendf("invlen *= %s.z;", offsets0.fsIn());
884 }
885 if (DIEllipseStyle::kHairline == diegp.fStyle) {
886 // can probably do this with one step
887 fragBuilder->codeAppend("float edgeAlpha = saturate(1.0-test*invlen);");
888 fragBuilder->codeAppend("edgeAlpha *= saturate(1.0+test*invlen);");
889 } else {
890 fragBuilder->codeAppend("float edgeAlpha = saturate(0.5-test*invlen);");
891 }
892
893 // for inner curve
894 if (DIEllipseStyle::kStroke == diegp.fStyle) {
895 fragBuilder->codeAppendf("scaledOffset = %s.xy;", offsets1.fsIn());
896 fragBuilder->codeAppend("test = dot(scaledOffset, scaledOffset) - 1.0;");
897 fragBuilder->codeAppendf("duvdx = float2(dFdx(%s));", offsets1.fsIn());
898 fragBuilder->codeAppendf("duvdy = float2(dFdy(%s));", offsets1.fsIn());
899 fragBuilder->codeAppendf(
900 "grad = float2(%s.x*duvdx.x + %s.y*duvdx.y,"
901 " %s.x*duvdy.x + %s.y*duvdy.y);",
902 offsets1.fsIn(), offsets1.fsIn(), offsets1.fsIn(), offsets1.fsIn());
903 if (diegp.fUseScale) {
904 fragBuilder->codeAppendf("grad *= %s.z;", offsets0.fsIn());
905 }
906 fragBuilder->codeAppend("grad_dot = 4.0*dot(grad, grad);");
907 if (!args.fShaderCaps->fFloatIs32Bits) {
908 fragBuilder->codeAppend("grad_dot = max(grad_dot, 6.1036e-5);");
909 }
910 fragBuilder->codeAppend("invlen = inversesqrt(grad_dot);");
911 if (diegp.fUseScale) {
912 fragBuilder->codeAppendf("invlen *= %s.z;", offsets0.fsIn());
913 }
914 fragBuilder->codeAppend("edgeAlpha *= saturate(0.5+test*invlen);");
915 }
916
917 fragBuilder->codeAppendf("half4 %s = half4(half(edgeAlpha));", args.fOutputCoverage);
918 }
919
920 SkMatrix fViewMatrix = SkMatrix::InvalidMatrix();
921 UniformHandle fViewMatrixUniform;
922 };
923
924 Attribute fInPosition;
925 Attribute fInColor;
926 Attribute fInEllipseOffsets0;
927 Attribute fInEllipseOffsets1;
928
929 SkMatrix fViewMatrix;
930 bool fUseScale;
931 DIEllipseStyle fStyle;
932
933 GR_DECLARE_GEOMETRY_PROCESSOR_TEST
934
935 using INHERITED = GrGeometryProcessor;
936 };
937
938 GR_DEFINE_GEOMETRY_PROCESSOR_TEST(DIEllipseGeometryProcessor)
939
940 #if defined(GPU_TEST_UTILS)
941 GrGeometryProcessor* DIEllipseGeometryProcessor::TestCreate(GrProcessorTestData* d) {
942 bool wideColor = d->fRandom->nextBool();
943 bool useScale = d->fRandom->nextBool();
944 SkMatrix matrix = GrTest::TestMatrix(d->fRandom);
945 auto style = (DIEllipseStyle)(d->fRandom->nextRangeU(0, 2));
946 return DIEllipseGeometryProcessor::Make(d->allocator(), wideColor, useScale, matrix, style);
947 }
948 #endif
949
950 ///////////////////////////////////////////////////////////////////////////////
951
952 // We have two possible cases for geometry for a circle:
953
954 // In the case of a normal fill, we draw geometry for the circle as an octagon.
955 static const uint16_t gFillCircleIndices[] = {
956 // enter the octagon
957 // clang-format off
958 0, 1, 8, 1, 2, 8,
959 2, 3, 8, 3, 4, 8,
960 4, 5, 8, 5, 6, 8,
961 6, 7, 8, 7, 0, 8
962 // clang-format on
963 };
964
965 // For stroked circles, we use two nested octagons.
966 static const uint16_t gStrokeCircleIndices[] = {
967 // enter the octagon
968 // clang-format off
969 0, 1, 9, 0, 9, 8,
970 1, 2, 10, 1, 10, 9,
971 2, 3, 11, 2, 11, 10,
972 3, 4, 12, 3, 12, 11,
973 4, 5, 13, 4, 13, 12,
974 5, 6, 14, 5, 14, 13,
975 6, 7, 15, 6, 15, 14,
976 7, 0, 8, 7, 8, 15,
977 // clang-format on
978 };
979
980 // Normalized geometry for octagons that circumscribe and lie on a circle:
981
982 static constexpr SkScalar kOctOffset = 0.41421356237f; // sqrt(2) - 1
983 static constexpr SkPoint kOctagonOuter[] = {
984 SkPoint::Make(-kOctOffset, -1),
985 SkPoint::Make( kOctOffset, -1),
986 SkPoint::Make( 1, -kOctOffset),
987 SkPoint::Make( 1, kOctOffset),
988 SkPoint::Make( kOctOffset, 1),
989 SkPoint::Make(-kOctOffset, 1),
990 SkPoint::Make(-1, kOctOffset),
991 SkPoint::Make(-1, -kOctOffset),
992 };
993
994 // cosine and sine of pi/8
995 static constexpr SkScalar kCosPi8 = 0.923579533f;
996 static constexpr SkScalar kSinPi8 = 0.382683432f;
997 static constexpr SkPoint kOctagonInner[] = {
998 SkPoint::Make(-kSinPi8, -kCosPi8),
999 SkPoint::Make( kSinPi8, -kCosPi8),
1000 SkPoint::Make( kCosPi8, -kSinPi8),
1001 SkPoint::Make( kCosPi8, kSinPi8),
1002 SkPoint::Make( kSinPi8, kCosPi8),
1003 SkPoint::Make(-kSinPi8, kCosPi8),
1004 SkPoint::Make(-kCosPi8, kSinPi8),
1005 SkPoint::Make(-kCosPi8, -kSinPi8),
1006 };
1007
1008 static const int kIndicesPerFillCircle = std::size(gFillCircleIndices);
1009 static const int kIndicesPerStrokeCircle = std::size(gStrokeCircleIndices);
1010 static const int kVertsPerStrokeCircle = 16;
1011 static const int kVertsPerFillCircle = 9;
1012
1013 static int circle_type_to_vert_count(bool stroked) {
1014 return stroked ? kVertsPerStrokeCircle : kVertsPerFillCircle;
1015 }
1016
1017 static int circle_type_to_index_count(bool stroked) {
1018 return stroked ? kIndicesPerStrokeCircle : kIndicesPerFillCircle;
1019 }
1020
1021 static const uint16_t* circle_type_to_indices(bool stroked) {
1022 return stroked ? gStrokeCircleIndices : gFillCircleIndices;
1023 }
1024
1025 ///////////////////////////////////////////////////////////////////////////////
1026
1027 class CircleOp final : public GrMeshDrawOp {
1028 private:
1029 using Helper = GrSimpleMeshDrawOpHelper;
1030
1031 public:
1032 DEFINE_OP_CLASS_ID
1033
1034 /** Optional extra params to render a partial arc rather than a full circle. */
1035 struct ArcParams {
1036 SkScalar fStartAngleRadians;
1037 SkScalar fSweepAngleRadians;
1038 bool fUseCenter;
1039 };
1040
1041 static GrOp::Owner Make(GrRecordingContext* context,
1042 GrPaint&& paint,
1043 const SkMatrix& viewMatrix,
1044 SkPoint center,
1045 SkScalar radius,
1046 const GrStyle& style,
1047 const ArcParams* arcParams = nullptr) {
1048 SkASSERT(circle_stays_circle(viewMatrix));
1049 if (style.hasPathEffect()) {
1050 return nullptr;
1051 }
1052 const SkStrokeRec& stroke = style.strokeRec();
1053 SkStrokeRec::Style recStyle = stroke.getStyle();
1054 if (arcParams) {
1055 // Arc support depends on the style.
1056 switch (recStyle) {
1057 case SkStrokeRec::kStrokeAndFill_Style:
1058 // This produces a strange result that this op doesn't implement.
1059 return nullptr;
1060 case SkStrokeRec::kFill_Style:
1061 // This supports all fills.
1062 break;
1063 case SkStrokeRec::kStroke_Style:
1064 // Strokes that don't use the center point are supported with butt and round
1065 // caps.
1066 if (arcParams->fUseCenter || stroke.getCap() == SkPaint::kSquare_Cap) {
1067 return nullptr;
1068 }
1069 break;
1070 case SkStrokeRec::kHairline_Style:
1071 // Hairline only supports butt cap. Round caps could be emulated by slightly
1072 // extending the angle range if we ever care to.
1073 if (arcParams->fUseCenter || stroke.getCap() != SkPaint::kButt_Cap) {
1074 return nullptr;
1075 }
1076 break;
1077 }
1078 }
1079 return Helper::FactoryHelper<CircleOp>(context, std::move(paint), viewMatrix, center,
1080 radius, style, arcParams);
1081 }
1082
1083 CircleOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
1084 const SkMatrix& viewMatrix, SkPoint center, SkScalar radius, const GrStyle& style,
1085 const ArcParams* arcParams)
1086 : GrMeshDrawOp(ClassID())
1087 , fHelper(processorSet, GrAAType::kCoverage) {
1088 const SkStrokeRec& stroke = style.strokeRec();
1089 SkStrokeRec::Style recStyle = stroke.getStyle();
1090
1091 fRoundCaps = false;
1092
1093 center = viewMatrix.mapPoint(center);
1094 radius = viewMatrix.mapRadius(radius);
1095 SkScalar strokeWidth = viewMatrix.mapRadius(stroke.getWidth());
1096
1097 bool isStrokeOnly =
1098 SkStrokeRec::kStroke_Style == recStyle || SkStrokeRec::kHairline_Style == recStyle;
1099 bool hasStroke = isStrokeOnly || SkStrokeRec::kStrokeAndFill_Style == recStyle;
1100
1101 SkScalar innerRadius = -SK_ScalarHalf;
1102 SkScalar outerRadius = radius;
1103 SkScalar halfWidth = 0;
1104 if (hasStroke) {
1105 if (SkScalarNearlyZero(strokeWidth)) {
1106 halfWidth = SK_ScalarHalf;
1107 } else {
1108 halfWidth = SkScalarHalf(strokeWidth);
1109 }
1110
1111 outerRadius += halfWidth;
1112 if (isStrokeOnly) {
1113 innerRadius = radius - halfWidth;
1114 }
1115 }
1116
1117 // The radii are outset for two reasons. First, it allows the shader to simply perform
1118 // simpler computation because the computed alpha is zero, rather than 50%, at the radius.
1119 // Second, the outer radius is used to compute the verts of the bounding box that is
1120 // rendered and the outset ensures the box will cover all partially covered by the circle.
1121 outerRadius += SK_ScalarHalf;
1122 innerRadius -= SK_ScalarHalf;
1123 bool stroked = isStrokeOnly && innerRadius > 0.0f;
1124 fViewMatrixIfUsingLocalCoords = viewMatrix;
1125
1126 // This makes every point fully inside the intersection plane.
1127 static constexpr SkScalar kUnusedIsectPlane[] = {0.f, 0.f, 1.f};
1128 // This makes every point fully outside the union plane.
1129 static constexpr SkScalar kUnusedUnionPlane[] = {0.f, 0.f, 0.f};
1130 static constexpr SkPoint kUnusedRoundCaps[] = {{1e10f, 1e10f}, {1e10f, 1e10f}};
1131 SkRect devBounds = SkRect::MakeLTRB(center.fX - outerRadius, center.fY - outerRadius,
1132 center.fX + outerRadius, center.fY + outerRadius);
1133 if (arcParams) {
1134 // The shader operates in a space where the circle is translated to be centered at the
1135 // origin. Here we compute points on the unit circle at the starting and ending angles.
1136 SkPoint startPoint, stopPoint;
1137 startPoint.fY = SkScalarSin(arcParams->fStartAngleRadians);
1138 startPoint.fX = SkScalarCos(arcParams->fStartAngleRadians);
1139 SkScalar endAngle = arcParams->fStartAngleRadians + arcParams->fSweepAngleRadians;
1140 stopPoint.fY = SkScalarSin(endAngle);
1141 stopPoint.fX = SkScalarCos(endAngle);
1142
1143 // Adjust the start and end points based on the view matrix (to handle rotated arcs)
1144 startPoint = viewMatrix.mapVector(startPoint);
1145 stopPoint = viewMatrix.mapVector(stopPoint);
1146 startPoint.normalize();
1147 stopPoint.normalize();
1148
1149 // We know the matrix is a similarity here. Detect mirroring which will affect how we
1150 // should orient the clip planes for arcs.
1151 SkASSERT(viewMatrix.isSimilarity());
1152 auto upperLeftDet = viewMatrix.getScaleX()*viewMatrix.getScaleY() -
1153 viewMatrix.getSkewX() *viewMatrix.getSkewY();
1154 if (upperLeftDet < 0) {
1155 std::swap(startPoint, stopPoint);
1156 }
1157
1158 fRoundCaps = hasStroke &&
1159 style.strokeRec().getWidth() > 0 &&
1160 style.strokeRec().getCap() == SkPaint::kRound_Cap;
1161 SkPoint roundCaps[2];
1162 if (fRoundCaps) {
1163 // Compute the cap center points in the normalized space.
1164 SkScalar midRadius = (innerRadius + outerRadius) / (2 * outerRadius);
1165 roundCaps[0] = startPoint * midRadius;
1166 roundCaps[1] = stopPoint * midRadius;
1167 } else {
1168 roundCaps[0] = kUnusedRoundCaps[0];
1169 roundCaps[1] = kUnusedRoundCaps[1];
1170 }
1171
1172 // Like a fill without useCenter, butt-cap stroke can be implemented by clipping against
1173 // radial lines. We treat round caps the same way, but tack coverage of circles at the
1174 // center of the butts.
1175 // However, in both cases we have to be careful about the half-circle.
1176 // case. In that case the two radial lines are equal and so that edge gets clipped
1177 // twice. Since the shared edge goes through the center we fall back on the !useCenter
1178 // case.
1179 auto absSweep = SkScalarAbs(arcParams->fSweepAngleRadians);
1180 bool useCenter = (arcParams->fUseCenter || isStrokeOnly) &&
1181 !SkScalarNearlyEqual(absSweep, SK_ScalarPI);
1182 if (useCenter) {
1183 SkVector norm0 = {startPoint.fY, -startPoint.fX};
1184 SkVector norm1 = {stopPoint.fY, -stopPoint.fX};
1185 // This ensures that norm0 is always the clockwise plane, and norm1 is CCW.
1186 if (arcParams->fSweepAngleRadians < 0) {
1187 std::swap(norm0, norm1);
1188 }
1189 norm0.negate();
1190 fClipPlane = true;
1191 if (absSweep > SK_ScalarPI) {
1192 fCircles.emplace_back(Circle{
1193 color,
1194 innerRadius,
1195 outerRadius,
1196 {norm0.fX, norm0.fY, 0.5f},
1197 {kUnusedIsectPlane[0], kUnusedIsectPlane[1], kUnusedIsectPlane[2]},
1198 {norm1.fX, norm1.fY, 0.5f},
1199 {roundCaps[0], roundCaps[1]},
1200 devBounds,
1201 stroked});
1202 fClipPlaneIsect = false;
1203 fClipPlaneUnion = true;
1204 } else {
1205 fCircles.emplace_back(Circle{
1206 color,
1207 innerRadius,
1208 outerRadius,
1209 {norm0.fX, norm0.fY, 0.5f},
1210 {norm1.fX, norm1.fY, 0.5f},
1211 {kUnusedUnionPlane[0], kUnusedUnionPlane[1], kUnusedUnionPlane[2]},
1212 {roundCaps[0], roundCaps[1]},
1213 devBounds,
1214 stroked});
1215 fClipPlaneIsect = true;
1216 fClipPlaneUnion = false;
1217 }
1218 } else {
1219 // We clip to a secant of the original circle.
1220 startPoint.scale(radius);
1221 stopPoint.scale(radius);
1222 SkVector norm = {startPoint.fY - stopPoint.fY, stopPoint.fX - startPoint.fX};
1223 norm.normalize();
1224 if (arcParams->fSweepAngleRadians > 0) {
1225 norm.negate();
1226 }
1227 SkScalar d = -norm.dot(startPoint) + 0.5f;
1228
1229 fCircles.emplace_back(
1230 Circle{color,
1231 innerRadius,
1232 outerRadius,
1233 {norm.fX, norm.fY, d},
1234 {kUnusedIsectPlane[0], kUnusedIsectPlane[1], kUnusedIsectPlane[2]},
1235 {kUnusedUnionPlane[0], kUnusedUnionPlane[1], kUnusedUnionPlane[2]},
1236 {roundCaps[0], roundCaps[1]},
1237 devBounds,
1238 stroked});
1239 fClipPlane = true;
1240 fClipPlaneIsect = false;
1241 fClipPlaneUnion = false;
1242 }
1243 } else {
1244 fCircles.emplace_back(
1245 Circle{color,
1246 innerRadius,
1247 outerRadius,
1248 {kUnusedIsectPlane[0], kUnusedIsectPlane[1], kUnusedIsectPlane[2]},
1249 {kUnusedIsectPlane[0], kUnusedIsectPlane[1], kUnusedIsectPlane[2]},
1250 {kUnusedUnionPlane[0], kUnusedUnionPlane[1], kUnusedUnionPlane[2]},
1251 {kUnusedRoundCaps[0], kUnusedRoundCaps[1]},
1252 devBounds,
1253 stroked});
1254 fClipPlane = false;
1255 fClipPlaneIsect = false;
1256 fClipPlaneUnion = false;
1257 }
1258 // Use the original radius and stroke radius for the bounds so that it does not include the
1259 // AA bloat.
1260 radius += halfWidth;
1261 this->setBounds(
1262 {center.fX - radius, center.fY - radius, center.fX + radius, center.fY + radius},
1263 HasAABloat::kYes, IsHairline::kNo);
1264 fVertCount = circle_type_to_vert_count(stroked);
1265 fIndexCount = circle_type_to_index_count(stroked);
1266 fAllFill = !stroked;
1267 }
1268
1269 const char* name() const override { return "CircleOp"; }
1270
1271 void visitProxies(const GrVisitProxyFunc& func) const override {
1272 if (fProgramInfo) {
1273 fProgramInfo->visitFPProxies(func);
1274 } else {
1275 fHelper.visitProxies(func);
1276 }
1277 }
1278
1279 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
1280 GrClampType clampType) override {
1281 SkPMColor4f* color = &fCircles.front().fColor;
1282 return fHelper.finalizeProcessors(caps, clip, clampType,
1283 GrProcessorAnalysisCoverage::kSingleChannel, color,
1284 &fWideColor);
1285 }
1286
1287 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
1288
1289 private:
1290 GrProgramInfo* programInfo() override { return fProgramInfo; }
1291
1292 void onCreateProgramInfo(const GrCaps* caps,
1293 SkArenaAlloc* arena,
1294 const GrSurfaceProxyView& writeView,
1295 bool usesMSAASurface,
1296 GrAppliedClip&& appliedClip,
1297 const GrDstProxyView& dstProxyView,
1298 GrXferBarrierFlags renderPassXferBarriers,
1299 GrLoadOp colorLoadOp) override {
1300 SkASSERT(!usesMSAASurface);
1301
1302 SkMatrix localMatrix;
1303 if (!fViewMatrixIfUsingLocalCoords.invert(&localMatrix)) {
1304 return;
1305 }
1306
1307 GrGeometryProcessor* gp = CircleGeometryProcessor::Make(arena, !fAllFill, fClipPlane,
1308 fClipPlaneIsect, fClipPlaneUnion,
1309 fRoundCaps, fWideColor,
1310 localMatrix);
1311
1312 fProgramInfo = fHelper.createProgramInfo(caps,
1313 arena,
1314 writeView,
1315 usesMSAASurface,
1316 std::move(appliedClip),
1317 dstProxyView,
1318 gp,
1319 GrPrimitiveType::kTriangles,
1320 renderPassXferBarriers,
1321 colorLoadOp);
1322 }
1323
1324 void onPrepareDraws(GrMeshDrawTarget* target) override {
1325 if (!fProgramInfo) {
1326 this->createProgramInfo(target);
1327 if (!fProgramInfo) {
1328 return;
1329 }
1330 }
1331
1332 sk_sp<const GrBuffer> vertexBuffer;
1333 int firstVertex;
1334 VertexWriter vertices = target->makeVertexWriter(fProgramInfo->geomProc().vertexStride(),
1335 fVertCount, &vertexBuffer, &firstVertex);
1336 if (!vertices) SK_UNLIKELY {
1337 SkDebugf("Could not allocate vertices\n");
1338 return;
1339 }
1340
1341 sk_sp<const GrBuffer> indexBuffer = nullptr;
1342 int firstIndex = 0;
1343 uint16_t* indices = target->makeIndexSpace(fIndexCount, &indexBuffer, &firstIndex);
1344 if (!indices) SK_UNLIKELY {
1345 SkDebugf("Could not allocate indices\n");
1346 return;
1347 }
1348
1349 int currStartVertex = 0;
1350 for (const auto& circle : fCircles) {
1351 SkScalar innerRadius = circle.fInnerRadius;
1352 SkScalar outerRadius = circle.fOuterRadius;
1353 VertexColor color(circle.fColor, fWideColor);
1354 const SkRect& bounds = circle.fDevBounds;
1355
1356 // The inner radius in the vertex data must be specified in normalized space.
1357 innerRadius = innerRadius / outerRadius;
1358 SkPoint radii = { outerRadius, innerRadius };
1359
1360 SkPoint center = SkPoint::Make(bounds.centerX(), bounds.centerY());
1361 SkScalar halfWidth = 0.5f * bounds.width();
1362
1363 SkVector geoClipPlane = { 0, 0 };
1364 SkScalar offsetClipDist = SK_Scalar1;
1365 if (!circle.fStroked && fClipPlane && fClipPlaneIsect &&
1366 (circle.fClipPlane[0] * circle.fIsectPlane[0] +
1367 circle.fClipPlane[1] * circle.fIsectPlane[1]) < 0.0f) {
1368 // Acute arc. Clip the vertices to the perpendicular half-plane. We've constructed
1369 // fClipPlane to be clockwise, and fISectPlane to be CCW, so we can can rotate them
1370 // each 90 degrees to point "out", then average them. We back off by 1/2 pixel so
1371 // the AA can extend just past the center of the circle.
1372 geoClipPlane.set(circle.fClipPlane[1] - circle.fIsectPlane[1],
1373 circle.fIsectPlane[0] - circle.fClipPlane[0]);
1374 SkAssertResult(geoClipPlane.normalize());
1375 offsetClipDist = 0.5f / halfWidth;
1376 }
1377
1378 for (int i = 0; i < 8; ++i) {
1379 // This clips the normalized offset to the half-plane we computed above. Then we
1380 // compute the vertex position from this.
1381 SkScalar dist = std::min(kOctagonOuter[i].dot(geoClipPlane) + offsetClipDist, 0.0f);
1382 SkVector offset = kOctagonOuter[i] - geoClipPlane * dist;
1383 vertices << (center + offset * halfWidth)
1384 << color
1385 << offset
1386 << radii;
1387 if (fClipPlane) {
1388 vertices << circle.fClipPlane;
1389 }
1390 if (fClipPlaneIsect) {
1391 vertices << circle.fIsectPlane;
1392 }
1393 if (fClipPlaneUnion) {
1394 vertices << circle.fUnionPlane;
1395 }
1396 if (fRoundCaps) {
1397 vertices << circle.fRoundCapCenters;
1398 }
1399 }
1400
1401 if (circle.fStroked) {
1402 // compute the inner ring
1403
1404 for (int i = 0; i < 8; ++i) {
1405 vertices << (center + kOctagonInner[i] * circle.fInnerRadius)
1406 << color
1407 << kOctagonInner[i] * innerRadius
1408 << radii;
1409 if (fClipPlane) {
1410 vertices << circle.fClipPlane;
1411 }
1412 if (fClipPlaneIsect) {
1413 vertices << circle.fIsectPlane;
1414 }
1415 if (fClipPlaneUnion) {
1416 vertices << circle.fUnionPlane;
1417 }
1418 if (fRoundCaps) {
1419 vertices << circle.fRoundCapCenters;
1420 }
1421 }
1422 } else {
1423 // filled
1424 vertices << center << color << SkPoint::Make(0, 0) << radii;
1425 if (fClipPlane) {
1426 vertices << circle.fClipPlane;
1427 }
1428 if (fClipPlaneIsect) {
1429 vertices << circle.fIsectPlane;
1430 }
1431 if (fClipPlaneUnion) {
1432 vertices << circle.fUnionPlane;
1433 }
1434 if (fRoundCaps) {
1435 vertices << circle.fRoundCapCenters;
1436 }
1437 }
1438
1439 const uint16_t* primIndices = circle_type_to_indices(circle.fStroked);
1440 const int primIndexCount = circle_type_to_index_count(circle.fStroked);
1441 for (int i = 0; i < primIndexCount; ++i) {
1442 *indices++ = primIndices[i] + currStartVertex;
1443 }
1444
1445 currStartVertex += circle_type_to_vert_count(circle.fStroked);
1446 }
1447
1448 fMesh = target->allocMesh();
1449 fMesh->setIndexed(std::move(indexBuffer), fIndexCount, firstIndex, 0, fVertCount - 1,
1450 GrPrimitiveRestart::kNo, std::move(vertexBuffer), firstVertex);
1451 }
1452
1453 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
1454 if (!fProgramInfo || !fMesh) {
1455 return;
1456 }
1457
1458 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
1459 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
1460 flushState->drawMesh(*fMesh);
1461 }
1462
1463 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
1464 CircleOp* that = t->cast<CircleOp>();
1465
1466 // can only represent 65535 unique vertices with 16-bit indices
1467 if (fVertCount + that->fVertCount > 65536) {
1468 return CombineResult::kCannotCombine;
1469 }
1470
1471 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
1472 return CombineResult::kCannotCombine;
1473 }
1474
1475 if (fHelper.usesLocalCoords() &&
1476 !SkMatrixPriv::CheapEqual(fViewMatrixIfUsingLocalCoords,
1477 that->fViewMatrixIfUsingLocalCoords)) {
1478 return CombineResult::kCannotCombine;
1479 }
1480
1481 // Because we've set up the ops that don't use the planes with noop values
1482 // we can just accumulate used planes by later ops.
1483 fClipPlane |= that->fClipPlane;
1484 fClipPlaneIsect |= that->fClipPlaneIsect;
1485 fClipPlaneUnion |= that->fClipPlaneUnion;
1486 fRoundCaps |= that->fRoundCaps;
1487 fWideColor |= that->fWideColor;
1488
1489 fCircles.push_back_n(that->fCircles.size(), that->fCircles.begin());
1490 fVertCount += that->fVertCount;
1491 fIndexCount += that->fIndexCount;
1492 fAllFill = fAllFill && that->fAllFill;
1493 return CombineResult::kMerged;
1494 }
1495
1496 #if defined(GPU_TEST_UTILS)
1497 SkString onDumpInfo() const override {
1498 SkString string;
1499 for (int i = 0; i < fCircles.size(); ++i) {
1500 string.appendf(
1501 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f],"
1502 "InnerRad: %.2f, OuterRad: %.2f\n",
1503 fCircles[i].fColor.toBytes_RGBA(), fCircles[i].fDevBounds.fLeft,
1504 fCircles[i].fDevBounds.fTop, fCircles[i].fDevBounds.fRight,
1505 fCircles[i].fDevBounds.fBottom, fCircles[i].fInnerRadius,
1506 fCircles[i].fOuterRadius);
1507 }
1508 string += fHelper.dumpInfo();
1509 return string;
1510 }
1511 #endif
1512
1513 struct Circle {
1514 SkPMColor4f fColor;
1515 SkScalar fInnerRadius;
1516 SkScalar fOuterRadius;
1517 SkScalar fClipPlane[3];
1518 SkScalar fIsectPlane[3];
1519 SkScalar fUnionPlane[3];
1520 SkPoint fRoundCapCenters[2];
1521 SkRect fDevBounds;
1522 bool fStroked;
1523 };
1524
1525 SkMatrix fViewMatrixIfUsingLocalCoords;
1526 Helper fHelper;
1527 STArray<1, Circle, true> fCircles;
1528 int fVertCount;
1529 int fIndexCount;
1530 bool fAllFill;
1531 bool fClipPlane;
1532 bool fClipPlaneIsect;
1533 bool fClipPlaneUnion;
1534 bool fRoundCaps;
1535 bool fWideColor;
1536
1537 GrSimpleMesh* fMesh = nullptr;
1538 GrProgramInfo* fProgramInfo = nullptr;
1539
1540 using INHERITED = GrMeshDrawOp;
1541 };
1542
1543 class ButtCapDashedCircleOp final : public GrMeshDrawOp {
1544 private:
1545 using Helper = GrSimpleMeshDrawOpHelper;
1546
1547 public:
1548 DEFINE_OP_CLASS_ID
1549
1550 static GrOp::Owner Make(GrRecordingContext* context,
1551 GrPaint&& paint,
1552 const SkMatrix& viewMatrix,
1553 SkPoint center,
1554 SkScalar radius,
1555 SkScalar strokeWidth,
1556 SkScalar startAngle,
1557 SkScalar onAngle,
1558 SkScalar offAngle,
1559 SkScalar phaseAngle) {
1560 SkASSERT(circle_stays_circle(viewMatrix));
1561 SkASSERT(strokeWidth < 2 * radius);
1562 return Helper::FactoryHelper<ButtCapDashedCircleOp>(context, std::move(paint), viewMatrix,
1563 center, radius, strokeWidth, startAngle,
1564 onAngle, offAngle, phaseAngle);
1565 }
1566
1567 ButtCapDashedCircleOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
1568 const SkMatrix& viewMatrix, SkPoint center, SkScalar radius,
1569 SkScalar strokeWidth, SkScalar startAngle, SkScalar onAngle,
1570 SkScalar offAngle, SkScalar phaseAngle)
1571 : GrMeshDrawOp(ClassID())
1572 , fHelper(processorSet, GrAAType::kCoverage) {
1573 SkASSERT(circle_stays_circle(viewMatrix));
1574 center = viewMatrix.mapPoint(center);
1575 radius = viewMatrix.mapRadius(radius);
1576 strokeWidth = viewMatrix.mapRadius(strokeWidth);
1577
1578 // Determine the angle where the circle starts in device space and whether its orientation
1579 // has been reversed.
1580 SkVector start;
1581 bool reflection;
1582 if (!startAngle) {
1583 start = {1, 0};
1584 } else {
1585 start.fY = SkScalarSin(startAngle);
1586 start.fX = SkScalarCos(startAngle);
1587 }
1588 start = viewMatrix.mapVector(start);
1589 startAngle = SkScalarATan2(start.fY, start.fX);
1590 reflection = (viewMatrix.getScaleX() * viewMatrix.getScaleY() -
1591 viewMatrix.getSkewX() * viewMatrix.getSkewY()) < 0;
1592
1593 auto totalAngle = onAngle + offAngle;
1594 phaseAngle = SkScalarMod(phaseAngle + totalAngle / 2, totalAngle) - totalAngle / 2;
1595
1596 SkScalar halfWidth = 0;
1597 if (SkScalarNearlyZero(strokeWidth)) {
1598 halfWidth = SK_ScalarHalf;
1599 } else {
1600 halfWidth = SkScalarHalf(strokeWidth);
1601 }
1602
1603 SkScalar outerRadius = radius + halfWidth;
1604 SkScalar innerRadius = radius - halfWidth;
1605
1606 // The radii are outset for two reasons. First, it allows the shader to simply perform
1607 // simpler computation because the computed alpha is zero, rather than 50%, at the radius.
1608 // Second, the outer radius is used to compute the verts of the bounding box that is
1609 // rendered and the outset ensures the box will cover all partially covered by the circle.
1610 outerRadius += SK_ScalarHalf;
1611 innerRadius -= SK_ScalarHalf;
1612 fViewMatrixIfUsingLocalCoords = viewMatrix;
1613
1614 SkRect devBounds = SkRect::MakeLTRB(center.fX - outerRadius, center.fY - outerRadius,
1615 center.fX + outerRadius, center.fY + outerRadius);
1616
1617 // We store whether there is a reflection as a negative total angle.
1618 if (reflection) {
1619 totalAngle = -totalAngle;
1620 }
1621 fCircles.push_back(Circle{
1622 color,
1623 outerRadius,
1624 innerRadius,
1625 onAngle,
1626 totalAngle,
1627 startAngle,
1628 phaseAngle,
1629 devBounds
1630 });
1631 // Use the original radius and stroke radius for the bounds so that it does not include the
1632 // AA bloat.
1633 radius += halfWidth;
1634 this->setBounds(
1635 {center.fX - radius, center.fY - radius, center.fX + radius, center.fY + radius},
1636 HasAABloat::kYes, IsHairline::kNo);
1637 fVertCount = circle_type_to_vert_count(true);
1638 fIndexCount = circle_type_to_index_count(true);
1639 }
1640
1641 const char* name() const override { return "ButtCappedDashedCircleOp"; }
1642
1643 void visitProxies(const GrVisitProxyFunc& func) const override {
1644 if (fProgramInfo) {
1645 fProgramInfo->visitFPProxies(func);
1646 } else {
1647 fHelper.visitProxies(func);
1648 }
1649 }
1650
1651 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
1652 GrClampType clampType) override {
1653 SkPMColor4f* color = &fCircles.front().fColor;
1654 return fHelper.finalizeProcessors(caps, clip, clampType,
1655 GrProcessorAnalysisCoverage::kSingleChannel, color,
1656 &fWideColor);
1657 }
1658
1659 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
1660
1661 private:
1662 GrProgramInfo* programInfo() override { return fProgramInfo; }
1663
1664 void onCreateProgramInfo(const GrCaps* caps,
1665 SkArenaAlloc* arena,
1666 const GrSurfaceProxyView& writeView,
1667 bool usesMSAASurface,
1668 GrAppliedClip&& appliedClip,
1669 const GrDstProxyView& dstProxyView,
1670 GrXferBarrierFlags renderPassXferBarriers,
1671 GrLoadOp colorLoadOp) override {
1672 SkASSERT(!usesMSAASurface);
1673
1674 SkMatrix localMatrix;
1675 if (!fViewMatrixIfUsingLocalCoords.invert(&localMatrix)) {
1676 return;
1677 }
1678
1679 // Setup geometry processor
1680 GrGeometryProcessor* gp = ButtCapDashedCircleGeometryProcessor::Make(arena,
1681 fWideColor,
1682 localMatrix);
1683
1684 fProgramInfo = fHelper.createProgramInfo(caps,
1685 arena,
1686 writeView,
1687 usesMSAASurface,
1688 std::move(appliedClip),
1689 dstProxyView,
1690 gp,
1691 GrPrimitiveType::kTriangles,
1692 renderPassXferBarriers,
1693 colorLoadOp);
1694 }
1695
1696 void onPrepareDraws(GrMeshDrawTarget* target) override {
1697 if (!fProgramInfo) {
1698 this->createProgramInfo(target);
1699 if (!fProgramInfo) {
1700 return;
1701 }
1702 }
1703
1704 sk_sp<const GrBuffer> vertexBuffer;
1705 int firstVertex;
1706 VertexWriter vertices = target->makeVertexWriter(fProgramInfo->geomProc().vertexStride(),
1707 fVertCount, &vertexBuffer, &firstVertex);
1708 if (!vertices) SK_UNLIKELY {
1709 SkDebugf("Could not allocate vertices\n");
1710 return;
1711 }
1712
1713 sk_sp<const GrBuffer> indexBuffer;
1714 int firstIndex = 0;
1715 uint16_t* indices = target->makeIndexSpace(fIndexCount, &indexBuffer, &firstIndex);
1716 if (!indices) SK_UNLIKELY {
1717 SkDebugf("Could not allocate indices\n");
1718 return;
1719 }
1720
1721 int currStartVertex = 0;
1722 for (const auto& circle : fCircles) {
1723 // The inner radius in the vertex data must be specified in normalized space so that
1724 // length() can be called with smaller values to avoid precision issues with half
1725 // floats.
1726 auto normInnerRadius = circle.fInnerRadius / circle.fOuterRadius;
1727 const SkRect& bounds = circle.fDevBounds;
1728 bool reflect = false;
1729 struct { float onAngle, totalAngle, startAngle, phaseAngle; } dashParams = {
1730 circle.fOnAngle, circle.fTotalAngle, circle.fStartAngle, circle.fPhaseAngle
1731 };
1732 if (dashParams.totalAngle < 0) {
1733 reflect = true;
1734 dashParams.totalAngle = -dashParams.totalAngle;
1735 dashParams.startAngle = -dashParams.startAngle;
1736 }
1737
1738 VertexColor color(circle.fColor, fWideColor);
1739
1740 // The bounding geometry for the circle is composed of an outer bounding octagon and
1741 // an inner bounded octagon.
1742
1743 // Compute the vertices of the outer octagon.
1744 SkPoint center = SkPoint::Make(bounds.centerX(), bounds.centerY());
1745 SkScalar halfWidth = 0.5f * bounds.width();
1746
1747 auto reflectY = [=](const SkPoint& p) {
1748 return SkPoint{ p.fX, reflect ? -p.fY : p.fY };
1749 };
1750
1751 for (int i = 0; i < 8; ++i) {
1752 vertices << (center + kOctagonOuter[i] * halfWidth)
1753 << color
1754 << reflectY(kOctagonOuter[i])
1755 << circle.fOuterRadius
1756 << normInnerRadius
1757 << dashParams;
1758 }
1759
1760 // Compute the vertices of the inner octagon.
1761 for (int i = 0; i < 8; ++i) {
1762 vertices << (center + kOctagonInner[i] * circle.fInnerRadius)
1763 << color
1764 << (reflectY(kOctagonInner[i]) * normInnerRadius)
1765 << circle.fOuterRadius
1766 << normInnerRadius
1767 << dashParams;
1768 }
1769
1770 const uint16_t* primIndices = circle_type_to_indices(true);
1771 const int primIndexCount = circle_type_to_index_count(true);
1772 for (int i = 0; i < primIndexCount; ++i) {
1773 *indices++ = primIndices[i] + currStartVertex;
1774 }
1775
1776 currStartVertex += circle_type_to_vert_count(true);
1777 }
1778
1779 fMesh = target->allocMesh();
1780 fMesh->setIndexed(std::move(indexBuffer), fIndexCount, firstIndex, 0, fVertCount - 1,
1781 GrPrimitiveRestart::kNo, std::move(vertexBuffer), firstVertex);
1782 }
1783
1784 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
1785 if (!fProgramInfo || !fMesh) {
1786 return;
1787 }
1788
1789 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
1790 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
1791 flushState->drawMesh(*fMesh);
1792 }
1793
1794 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
1795 ButtCapDashedCircleOp* that = t->cast<ButtCapDashedCircleOp>();
1796
1797 // can only represent 65535 unique vertices with 16-bit indices
1798 if (fVertCount + that->fVertCount > 65536) {
1799 return CombineResult::kCannotCombine;
1800 }
1801
1802 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
1803 return CombineResult::kCannotCombine;
1804 }
1805
1806 if (fHelper.usesLocalCoords() &&
1807 !SkMatrixPriv::CheapEqual(fViewMatrixIfUsingLocalCoords,
1808 that->fViewMatrixIfUsingLocalCoords)) {
1809 return CombineResult::kCannotCombine;
1810 }
1811
1812 fCircles.push_back_n(that->fCircles.size(), that->fCircles.begin());
1813 fVertCount += that->fVertCount;
1814 fIndexCount += that->fIndexCount;
1815 fWideColor |= that->fWideColor;
1816 return CombineResult::kMerged;
1817 }
1818
1819 #if defined(GPU_TEST_UTILS)
1820 SkString onDumpInfo() const override {
1821 SkString string;
1822 for (int i = 0; i < fCircles.size(); ++i) {
1823 string.appendf(
1824 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f],"
1825 "InnerRad: %.2f, OuterRad: %.2f, OnAngle: %.2f, TotalAngle: %.2f, "
1826 "Phase: %.2f\n",
1827 fCircles[i].fColor.toBytes_RGBA(), fCircles[i].fDevBounds.fLeft,
1828 fCircles[i].fDevBounds.fTop, fCircles[i].fDevBounds.fRight,
1829 fCircles[i].fDevBounds.fBottom, fCircles[i].fInnerRadius,
1830 fCircles[i].fOuterRadius, fCircles[i].fOnAngle, fCircles[i].fTotalAngle,
1831 fCircles[i].fPhaseAngle);
1832 }
1833 string += fHelper.dumpInfo();
1834 return string;
1835 }
1836 #endif
1837
1838 struct Circle {
1839 SkPMColor4f fColor;
1840 SkScalar fOuterRadius;
1841 SkScalar fInnerRadius;
1842 SkScalar fOnAngle;
1843 SkScalar fTotalAngle;
1844 SkScalar fStartAngle;
1845 SkScalar fPhaseAngle;
1846 SkRect fDevBounds;
1847 };
1848
1849 SkMatrix fViewMatrixIfUsingLocalCoords;
1850 Helper fHelper;
1851 STArray<1, Circle, true> fCircles;
1852 int fVertCount;
1853 int fIndexCount;
1854 bool fWideColor;
1855
1856 GrSimpleMesh* fMesh = nullptr;
1857 GrProgramInfo* fProgramInfo = nullptr;
1858
1859 using INHERITED = GrMeshDrawOp;
1860 };
1861
1862 ///////////////////////////////////////////////////////////////////////////////
1863
1864 class EllipseOp final : public GrMeshDrawOp {
1865 private:
1866 using Helper = GrSimpleMeshDrawOpHelper;
1867
1868 struct DeviceSpaceParams {
1869 SkPoint fCenter;
1870 SkScalar fXRadius;
1871 SkScalar fYRadius;
1872 SkScalar fInnerXRadius;
1873 SkScalar fInnerYRadius;
1874 };
1875
1876 public:
1877 DEFINE_OP_CLASS_ID
1878
1879 static GrOp::Owner Make(GrRecordingContext* context,
1880 GrPaint&& paint,
1881 const SkMatrix& viewMatrix,
1882 const SkRect& ellipse,
1883 const SkStrokeRec& stroke) {
1884 DeviceSpaceParams params;
1885 // do any matrix crunching before we reset the draw state for device coords
1886 params.fCenter = viewMatrix.mapPoint(ellipse.center());
1887 SkScalar ellipseXRadius = SkScalarHalf(ellipse.width());
1888 SkScalar ellipseYRadius = SkScalarHalf(ellipse.height());
1889 params.fXRadius = SkScalarAbs(viewMatrix[SkMatrix::kMScaleX] * ellipseXRadius +
1890 viewMatrix[SkMatrix::kMSkewX] * ellipseYRadius);
1891 params.fYRadius = SkScalarAbs(viewMatrix[SkMatrix::kMSkewY] * ellipseXRadius +
1892 viewMatrix[SkMatrix::kMScaleY] * ellipseYRadius);
1893
1894 // do (potentially) anisotropic mapping of stroke
1895 SkVector scaledStroke;
1896 SkScalar strokeWidth = stroke.getWidth();
1897 scaledStroke.fX = SkScalarAbs(
1898 strokeWidth * (viewMatrix[SkMatrix::kMScaleX] + viewMatrix[SkMatrix::kMSkewY]));
1899 scaledStroke.fY = SkScalarAbs(
1900 strokeWidth * (viewMatrix[SkMatrix::kMSkewX] + viewMatrix[SkMatrix::kMScaleY]));
1901
1902 SkStrokeRec::Style style = stroke.getStyle();
1903 bool isStrokeOnly =
1904 SkStrokeRec::kStroke_Style == style || SkStrokeRec::kHairline_Style == style;
1905 bool hasStroke = isStrokeOnly || SkStrokeRec::kStrokeAndFill_Style == style;
1906
1907 params.fInnerXRadius = 0;
1908 params.fInnerYRadius = 0;
1909 if (hasStroke) {
1910 if (SkScalarNearlyZero(scaledStroke.length())) {
1911 scaledStroke.set(SK_ScalarHalf, SK_ScalarHalf);
1912 } else {
1913 scaledStroke.scale(SK_ScalarHalf);
1914 }
1915
1916 // we only handle thick strokes for near-circular ellipses
1917 if (scaledStroke.length() > SK_ScalarHalf &&
1918 (0.5f * params.fXRadius > params.fYRadius ||
1919 0.5f * params.fYRadius > params.fXRadius)) {
1920 return nullptr;
1921 }
1922
1923 // we don't handle it if curvature of the stroke is less than curvature of the ellipse
1924 if (scaledStroke.fX * (params.fYRadius * params.fYRadius) <
1925 (scaledStroke.fY * scaledStroke.fY) * params.fXRadius ||
1926 scaledStroke.fY * (params.fXRadius * params.fXRadius) <
1927 (scaledStroke.fX * scaledStroke.fX) * params.fYRadius) {
1928 return nullptr;
1929 }
1930
1931 // this is legit only if scale & translation (which should be the case at the moment)
1932 if (isStrokeOnly) {
1933 params.fInnerXRadius = params.fXRadius - scaledStroke.fX;
1934 params.fInnerYRadius = params.fYRadius - scaledStroke.fY;
1935 }
1936
1937 params.fXRadius += scaledStroke.fX;
1938 params.fYRadius += scaledStroke.fY;
1939 }
1940
1941 // For large ovals with low precision floats, we fall back to the path renderer.
1942 // To compute the AA at the edge we divide by the gradient, which is clamped to a
1943 // minimum value to avoid divides by zero. With large ovals and low precision this
1944 // leads to blurring at the edge of the oval.
1945 const SkScalar kMaxOvalRadius = 16384;
1946 if (!context->priv().caps()->shaderCaps()->fFloatIs32Bits &&
1947 (params.fXRadius >= kMaxOvalRadius || params.fYRadius >= kMaxOvalRadius)) {
1948 return nullptr;
1949 }
1950
1951 return Helper::FactoryHelper<EllipseOp>(context, std::move(paint), viewMatrix,
1952 params, stroke);
1953 }
1954
1955 EllipseOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
1956 const SkMatrix& viewMatrix, const DeviceSpaceParams& params,
1957 const SkStrokeRec& stroke)
1958 : INHERITED(ClassID())
1959 , fHelper(processorSet, GrAAType::kCoverage)
1960 , fUseScale(false) {
1961 SkStrokeRec::Style style = stroke.getStyle();
1962 bool isStrokeOnly =
1963 SkStrokeRec::kStroke_Style == style || SkStrokeRec::kHairline_Style == style;
1964
1965 fEllipses.emplace_back(Ellipse{color, params.fXRadius, params.fYRadius,
1966 params.fInnerXRadius, params.fInnerYRadius,
1967 SkRect::MakeLTRB(params.fCenter.fX - params.fXRadius,
1968 params.fCenter.fY - params.fYRadius,
1969 params.fCenter.fX + params.fXRadius,
1970 params.fCenter.fY + params.fYRadius)});
1971
1972 this->setBounds(fEllipses.back().fDevBounds, HasAABloat::kYes, IsHairline::kNo);
1973
1974 fStroked = isStrokeOnly && params.fInnerXRadius > 0 && params.fInnerYRadius > 0;
1975 fViewMatrixIfUsingLocalCoords = viewMatrix;
1976 }
1977
1978 const char* name() const override { return "EllipseOp"; }
1979
1980 void visitProxies(const GrVisitProxyFunc& func) const override {
1981 if (fProgramInfo) {
1982 fProgramInfo->visitFPProxies(func);
1983 } else {
1984 fHelper.visitProxies(func);
1985 }
1986 }
1987
1988 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
1989 GrClampType clampType) override {
1990 fUseScale = !caps.shaderCaps()->fFloatIs32Bits &&
1991 !caps.shaderCaps()->fHasLowFragmentPrecision;
1992 SkPMColor4f* color = &fEllipses.front().fColor;
1993 return fHelper.finalizeProcessors(caps, clip, clampType,
1994 GrProcessorAnalysisCoverage::kSingleChannel, color,
1995 &fWideColor);
1996 }
1997
1998 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
1999
2000 private:
2001 GrProgramInfo* programInfo() override { return fProgramInfo; }
2002
2003 void onCreateProgramInfo(const GrCaps* caps,
2004 SkArenaAlloc* arena,
2005 const GrSurfaceProxyView& writeView,
2006 bool usesMSAASurface,
2007 GrAppliedClip&& appliedClip,
2008 const GrDstProxyView& dstProxyView,
2009 GrXferBarrierFlags renderPassXferBarriers,
2010 GrLoadOp colorLoadOp) override {
2011 SkMatrix localMatrix;
2012 if (!fViewMatrixIfUsingLocalCoords.invert(&localMatrix)) {
2013 return;
2014 }
2015
2016 GrGeometryProcessor* gp = EllipseGeometryProcessor::Make(arena, fStroked, fWideColor,
2017 fUseScale, localMatrix);
2018
2019 fProgramInfo = fHelper.createProgramInfo(caps,
2020 arena,
2021 writeView,
2022 usesMSAASurface,
2023 std::move(appliedClip),
2024 dstProxyView,
2025 gp,
2026 GrPrimitiveType::kTriangles,
2027 renderPassXferBarriers,
2028 colorLoadOp);
2029 }
2030
2031 void onPrepareDraws(GrMeshDrawTarget* target) override {
2032 if (!fProgramInfo) {
2033 this->createProgramInfo(target);
2034 if (!fProgramInfo) {
2035 return;
2036 }
2037 }
2038
2039 QuadHelper helper(target, fProgramInfo->geomProc().vertexStride(), fEllipses.size());
2040 VertexWriter verts{helper.vertices()};
2041 if (!verts) {
2042 SkDebugf("Could not allocate vertices\n");
2043 return;
2044 }
2045
2046 // On MSAA, bloat enough to guarantee any pixel that might be touched by the ellipse has
2047 // full sample coverage.
2048 float aaBloat = target->usesMSAASurface() ? SK_ScalarSqrt2 : .5f;
2049
2050 for (const auto& ellipse : fEllipses) {
2051 VertexColor color(ellipse.fColor, fWideColor);
2052 SkScalar xRadius = ellipse.fXRadius;
2053 SkScalar yRadius = ellipse.fYRadius;
2054
2055 // Compute the reciprocals of the radii here to save time in the shader
2056 struct { float xOuter, yOuter, xInner, yInner; } invRadii = {
2057 SkScalarInvert(xRadius),
2058 SkScalarInvert(yRadius),
2059 sk_ieee_float_divide(1.0f, ellipse.fInnerXRadius),
2060 sk_ieee_float_divide(1.0f, ellipse.fInnerYRadius)
2061 };
2062 SkScalar xMaxOffset = xRadius + aaBloat;
2063 SkScalar yMaxOffset = yRadius + aaBloat;
2064
2065 if (!fStroked) {
2066 // For filled ellipses we map a unit circle in the vertex attributes rather than
2067 // computing an ellipse and modifying that distance, so we normalize to 1
2068 xMaxOffset /= xRadius;
2069 yMaxOffset /= yRadius;
2070 }
2071
2072 // The inner radius in the vertex data must be specified in normalized space.
2073 verts.writeQuad(VertexWriter::TriStripFromRect(
2074 ellipse.fDevBounds.makeOutset(aaBloat, aaBloat)),
2075 color,
2076 origin_centered_tri_strip(xMaxOffset, yMaxOffset),
2077 VertexWriter::If(fUseScale, std::max(xRadius, yRadius)),
2078 invRadii);
2079 }
2080 fMesh = helper.mesh();
2081 }
2082
2083 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
2084 if (!fProgramInfo || !fMesh) {
2085 return;
2086 }
2087
2088 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
2089 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
2090 flushState->drawMesh(*fMesh);
2091 }
2092
2093 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
2094 EllipseOp* that = t->cast<EllipseOp>();
2095
2096 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
2097 return CombineResult::kCannotCombine;
2098 }
2099
2100 if (fStroked != that->fStroked) {
2101 return CombineResult::kCannotCombine;
2102 }
2103
2104 if (fHelper.usesLocalCoords() &&
2105 !SkMatrixPriv::CheapEqual(fViewMatrixIfUsingLocalCoords,
2106 that->fViewMatrixIfUsingLocalCoords)) {
2107 return CombineResult::kCannotCombine;
2108 }
2109
2110 fEllipses.push_back_n(that->fEllipses.size(), that->fEllipses.begin());
2111 fWideColor |= that->fWideColor;
2112 return CombineResult::kMerged;
2113 }
2114
2115 #if defined(GPU_TEST_UTILS)
2116 SkString onDumpInfo() const override {
2117 SkString string = SkStringPrintf("Stroked: %d\n", fStroked);
2118 for (const auto& geo : fEllipses) {
2119 string.appendf(
2120 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
2121 "XRad: %.2f, YRad: %.2f, InnerXRad: %.2f, InnerYRad: %.2f\n",
2122 geo.fColor.toBytes_RGBA(), geo.fDevBounds.fLeft, geo.fDevBounds.fTop,
2123 geo.fDevBounds.fRight, geo.fDevBounds.fBottom, geo.fXRadius, geo.fYRadius,
2124 geo.fInnerXRadius, geo.fInnerYRadius);
2125 }
2126 string += fHelper.dumpInfo();
2127 return string;
2128 }
2129 #endif
2130
2131 struct Ellipse {
2132 SkPMColor4f fColor;
2133 SkScalar fXRadius;
2134 SkScalar fYRadius;
2135 SkScalar fInnerXRadius;
2136 SkScalar fInnerYRadius;
2137 SkRect fDevBounds;
2138 };
2139
2140 SkMatrix fViewMatrixIfUsingLocalCoords;
2141 Helper fHelper;
2142 bool fStroked;
2143 bool fWideColor;
2144 bool fUseScale;
2145 STArray<1, Ellipse, true> fEllipses;
2146
2147 GrSimpleMesh* fMesh = nullptr;
2148 GrProgramInfo* fProgramInfo = nullptr;
2149
2150 using INHERITED = GrMeshDrawOp;
2151 };
2152
2153 /////////////////////////////////////////////////////////////////////////////////////////////////
2154
2155 class DIEllipseOp final : public GrMeshDrawOp {
2156 private:
2157 using Helper = GrSimpleMeshDrawOpHelper;
2158
2159 struct DeviceSpaceParams {
2160 SkPoint fCenter;
2161 SkScalar fXRadius;
2162 SkScalar fYRadius;
2163 SkScalar fInnerXRadius;
2164 SkScalar fInnerYRadius;
2165 DIEllipseStyle fStyle;
2166 };
2167
2168 public:
2169 DEFINE_OP_CLASS_ID
2170
2171 static GrOp::Owner Make(GrRecordingContext* context,
2172 GrPaint&& paint,
2173 const SkMatrix& viewMatrix,
2174 const SkRect& ellipse,
2175 const SkStrokeRec& stroke) {
2176 DeviceSpaceParams params;
2177 params.fCenter = SkPoint::Make(ellipse.centerX(), ellipse.centerY());
2178 params.fXRadius = SkScalarHalf(ellipse.width());
2179 params.fYRadius = SkScalarHalf(ellipse.height());
2180
2181 SkStrokeRec::Style style = stroke.getStyle();
2182 params.fStyle = (SkStrokeRec::kStroke_Style == style)
2183 ? DIEllipseStyle::kStroke
2184 : (SkStrokeRec::kHairline_Style == style)
2185 ? DIEllipseStyle::kHairline
2186 : DIEllipseStyle::kFill;
2187
2188 params.fInnerXRadius = 0;
2189 params.fInnerYRadius = 0;
2190 if (SkStrokeRec::kFill_Style != style && SkStrokeRec::kHairline_Style != style) {
2191 SkScalar strokeWidth = stroke.getWidth();
2192
2193 if (SkScalarNearlyZero(strokeWidth)) {
2194 strokeWidth = SK_ScalarHalf;
2195 } else {
2196 strokeWidth *= SK_ScalarHalf;
2197 }
2198
2199 // we only handle thick strokes for near-circular ellipses
2200 if (strokeWidth > SK_ScalarHalf &&
2201 (SK_ScalarHalf * params.fXRadius > params.fYRadius ||
2202 SK_ScalarHalf * params.fYRadius > params.fXRadius)) {
2203 return nullptr;
2204 }
2205
2206 // we don't handle it if curvature of the stroke is less than curvature of the ellipse
2207 if (strokeWidth * (params.fYRadius * params.fYRadius) <
2208 (strokeWidth * strokeWidth) * params.fXRadius) {
2209 return nullptr;
2210 }
2211 if (strokeWidth * (params.fXRadius * params.fXRadius) <
2212 (strokeWidth * strokeWidth) * params.fYRadius) {
2213 return nullptr;
2214 }
2215
2216 // set inner radius (if needed)
2217 if (SkStrokeRec::kStroke_Style == style) {
2218 params.fInnerXRadius = params.fXRadius - strokeWidth;
2219 params.fInnerYRadius = params.fYRadius - strokeWidth;
2220 }
2221
2222 params.fXRadius += strokeWidth;
2223 params.fYRadius += strokeWidth;
2224 }
2225
2226 // For large ovals with low precision floats, we fall back to the path renderer.
2227 // To compute the AA at the edge we divide by the gradient, which is clamped to a
2228 // minimum value to avoid divides by zero. With large ovals and low precision this
2229 // leads to blurring at the edge of the oval.
2230 const SkScalar kMaxOvalRadius = 16384;
2231 if (!context->priv().caps()->shaderCaps()->fFloatIs32Bits &&
2232 (params.fXRadius >= kMaxOvalRadius || params.fYRadius >= kMaxOvalRadius)) {
2233 return nullptr;
2234 }
2235
2236 if (DIEllipseStyle::kStroke == params.fStyle &&
2237 (params.fInnerXRadius <= 0 || params.fInnerYRadius <= 0)) {
2238 params.fStyle = DIEllipseStyle::kFill;
2239 }
2240 return Helper::FactoryHelper<DIEllipseOp>(context, std::move(paint), params, viewMatrix);
2241 }
2242
2243 DIEllipseOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
2244 const DeviceSpaceParams& params, const SkMatrix& viewMatrix)
2245 : INHERITED(ClassID())
2246 , fHelper(processorSet, GrAAType::kCoverage)
2247 , fUseScale(false) {
2248 // This expands the outer rect so that after CTM we end up with a half-pixel border
2249 SkScalar a = viewMatrix[SkMatrix::kMScaleX];
2250 SkScalar b = viewMatrix[SkMatrix::kMSkewX];
2251 SkScalar c = viewMatrix[SkMatrix::kMSkewY];
2252 SkScalar d = viewMatrix[SkMatrix::kMScaleY];
2253 SkScalar geoDx = 1.f / SkScalarSqrt(a * a + c * c);
2254 SkScalar geoDy = 1.f / SkScalarSqrt(b * b + d * d);
2255
2256 fEllipses.emplace_back(
2257 Ellipse{viewMatrix, color, params.fXRadius, params.fYRadius, params.fInnerXRadius,
2258 params.fInnerYRadius, geoDx, geoDy, params.fStyle,
2259 SkRect::MakeLTRB(params.fCenter.fX - params.fXRadius,
2260 params.fCenter.fY - params.fYRadius,
2261 params.fCenter.fX + params.fXRadius,
2262 params.fCenter.fY + params.fYRadius)});
2263 this->setTransformedBounds(fEllipses[0].fBounds, viewMatrix, HasAABloat::kYes,
2264 IsHairline::kNo);
2265 }
2266
2267 const char* name() const override { return "DIEllipseOp"; }
2268
2269 void visitProxies(const GrVisitProxyFunc& func) const override {
2270 if (fProgramInfo) {
2271 fProgramInfo->visitFPProxies(func);
2272 } else {
2273 fHelper.visitProxies(func);
2274 }
2275 }
2276
2277 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
2278 GrClampType clampType) override {
2279 fUseScale = !caps.shaderCaps()->fFloatIs32Bits &&
2280 !caps.shaderCaps()->fHasLowFragmentPrecision;
2281 SkPMColor4f* color = &fEllipses.front().fColor;
2282 return fHelper.finalizeProcessors(caps, clip, clampType,
2283 GrProcessorAnalysisCoverage::kSingleChannel, color,
2284 &fWideColor);
2285 }
2286
2287 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
2288
2289 private:
2290 GrProgramInfo* programInfo() override { return fProgramInfo; }
2291
2292 void onCreateProgramInfo(const GrCaps* caps,
2293 SkArenaAlloc* arena,
2294 const GrSurfaceProxyView& writeView,
2295 bool usesMSAASurface,
2296 GrAppliedClip&& appliedClip,
2297 const GrDstProxyView& dstProxyView,
2298 GrXferBarrierFlags renderPassXferBarriers,
2299 GrLoadOp colorLoadOp) override {
2300 GrGeometryProcessor* gp = DIEllipseGeometryProcessor::Make(arena, fWideColor, fUseScale,
2301 this->viewMatrix(),
2302 this->style());
2303
2304 fProgramInfo = fHelper.createProgramInfo(caps, arena, writeView, usesMSAASurface,
2305 std::move(appliedClip), dstProxyView, gp,
2306 GrPrimitiveType::kTriangles,
2307 renderPassXferBarriers, colorLoadOp);
2308 }
2309
2310 void onPrepareDraws(GrMeshDrawTarget* target) override {
2311 if (!fProgramInfo) {
2312 this->createProgramInfo(target);
2313 }
2314
2315 QuadHelper helper(target, fProgramInfo->geomProc().vertexStride(), fEllipses.size());
2316 VertexWriter verts{helper.vertices()};
2317 if (!verts) {
2318 return;
2319 }
2320
2321 for (const auto& ellipse : fEllipses) {
2322 VertexColor color(ellipse.fColor, fWideColor);
2323 SkScalar xRadius = ellipse.fXRadius;
2324 SkScalar yRadius = ellipse.fYRadius;
2325
2326 // On MSAA, bloat enough to guarantee any pixel that might be touched by the ellipse has
2327 // full sample coverage.
2328 float aaBloat = target->usesMSAASurface() ? SK_ScalarSqrt2 : .5f;
2329 SkRect drawBounds = ellipse.fBounds.makeOutset(ellipse.fGeoDx * aaBloat,
2330 ellipse.fGeoDy * aaBloat);
2331
2332 // Normalize the "outer radius" coordinates within drawBounds so that the outer edge
2333 // occurs at x^2 + y^2 == 1.
2334 float outerCoordX = drawBounds.width() / (xRadius * 2);
2335 float outerCoordY = drawBounds.height() / (yRadius * 2);
2336
2337 // By default, constructed so that inner coord is (0, 0) for all points
2338 float innerCoordX = 0;
2339 float innerCoordY = 0;
2340
2341 // ... unless we're stroked. Then normalize the "inner radius" coordinates within
2342 // drawBounds so that the inner edge occurs at x2^2 + y2^2 == 1.
2343 if (DIEllipseStyle::kStroke == this->style()) {
2344 innerCoordX = drawBounds.width() / (ellipse.fInnerXRadius * 2);
2345 innerCoordY = drawBounds.height() / (ellipse.fInnerYRadius * 2);
2346 }
2347
2348 verts.writeQuad(VertexWriter::TriStripFromRect(drawBounds),
2349 color,
2350 origin_centered_tri_strip(outerCoordX, outerCoordY),
2351 VertexWriter::If(fUseScale, std::max(xRadius, yRadius)),
2352 origin_centered_tri_strip(innerCoordX, innerCoordY));
2353 }
2354 fMesh = helper.mesh();
2355 }
2356
2357 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
2358 if (!fProgramInfo || !fMesh) {
2359 return;
2360 }
2361
2362 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
2363 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
2364 flushState->drawMesh(*fMesh);
2365 }
2366
2367 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
2368 DIEllipseOp* that = t->cast<DIEllipseOp>();
2369 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
2370 return CombineResult::kCannotCombine;
2371 }
2372
2373 if (this->style() != that->style()) {
2374 return CombineResult::kCannotCombine;
2375 }
2376
2377 // TODO rewrite to allow positioning on CPU
2378 if (!SkMatrixPriv::CheapEqual(this->viewMatrix(), that->viewMatrix())) {
2379 return CombineResult::kCannotCombine;
2380 }
2381
2382 fEllipses.push_back_n(that->fEllipses.size(), that->fEllipses.begin());
2383 fWideColor |= that->fWideColor;
2384 return CombineResult::kMerged;
2385 }
2386
2387 #if defined(GPU_TEST_UTILS)
2388 SkString onDumpInfo() const override {
2389 SkString string;
2390 for (const auto& geo : fEllipses) {
2391 string.appendf(
2392 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], XRad: %.2f, "
2393 "YRad: %.2f, InnerXRad: %.2f, InnerYRad: %.2f, GeoDX: %.2f, "
2394 "GeoDY: %.2f\n",
2395 geo.fColor.toBytes_RGBA(), geo.fBounds.fLeft, geo.fBounds.fTop,
2396 geo.fBounds.fRight, geo.fBounds.fBottom, geo.fXRadius, geo.fYRadius,
2397 geo.fInnerXRadius, geo.fInnerYRadius, geo.fGeoDx, geo.fGeoDy);
2398 }
2399 string += fHelper.dumpInfo();
2400 return string;
2401 }
2402 #endif
2403
2404 const SkMatrix& viewMatrix() const { return fEllipses[0].fViewMatrix; }
2405 DIEllipseStyle style() const { return fEllipses[0].fStyle; }
2406
2407 struct Ellipse {
2408 SkMatrix fViewMatrix;
2409 SkPMColor4f fColor;
2410 SkScalar fXRadius;
2411 SkScalar fYRadius;
2412 SkScalar fInnerXRadius;
2413 SkScalar fInnerYRadius;
2414 SkScalar fGeoDx;
2415 SkScalar fGeoDy;
2416 DIEllipseStyle fStyle;
2417 SkRect fBounds;
2418 };
2419
2420 Helper fHelper;
2421 bool fWideColor;
2422 bool fUseScale;
2423 STArray<1, Ellipse, true> fEllipses;
2424
2425 GrSimpleMesh* fMesh = nullptr;
2426 GrProgramInfo* fProgramInfo = nullptr;
2427
2428 using INHERITED = GrMeshDrawOp;
2429 };
2430
2431 ///////////////////////////////////////////////////////////////////////////////
2432
2433 // We have three possible cases for geometry for a roundrect.
2434 //
2435 // In the case of a normal fill or a stroke, we draw the roundrect as a 9-patch:
2436 // ____________
2437 // |_|________|_|
2438 // | | | |
2439 // | | | |
2440 // | | | |
2441 // |_|________|_|
2442 // |_|________|_|
2443 //
2444 // For strokes, we don't draw the center quad.
2445 //
2446 // For circular roundrects, in the case where the stroke width is greater than twice
2447 // the corner radius (overstroke), we add additional geometry to mark out the rectangle
2448 // in the center. The shared vertices are duplicated so we can set a different outer radius
2449 // for the fill calculation.
2450 // ____________
2451 // |_|________|_|
2452 // | |\ ____ /| |
2453 // | | | | | |
2454 // | | |____| | |
2455 // |_|/______\|_|
2456 // |_|________|_|
2457 //
2458 // We don't draw the center quad from the fill rect in this case.
2459 //
2460 // For filled rrects that need to provide a distance vector we resuse the overstroke
2461 // geometry but make the inner rect degenerate (either a point or a horizontal or
2462 // vertical line).
2463
2464 static const uint16_t gOverstrokeRRectIndices[] = {
2465 // clang-format off
2466 // overstroke quads
2467 // we place this at the beginning so that we can skip these indices when rendering normally
2468 16, 17, 19, 16, 19, 18,
2469 19, 17, 23, 19, 23, 21,
2470 21, 23, 22, 21, 22, 20,
2471 22, 16, 18, 22, 18, 20,
2472
2473 // corners
2474 0, 1, 5, 0, 5, 4,
2475 2, 3, 7, 2, 7, 6,
2476 8, 9, 13, 8, 13, 12,
2477 10, 11, 15, 10, 15, 14,
2478
2479 // edges
2480 1, 2, 6, 1, 6, 5,
2481 4, 5, 9, 4, 9, 8,
2482 6, 7, 11, 6, 11, 10,
2483 9, 10, 14, 9, 14, 13,
2484
2485 // center
2486 // we place this at the end so that we can ignore these indices when not rendering as filled
2487 5, 6, 10, 5, 10, 9,
2488 // clang-format on
2489 };
2490
2491 // fill and standard stroke indices skip the overstroke "ring"
2492 static const uint16_t* gStandardRRectIndices = gOverstrokeRRectIndices + 6 * 4;
2493
2494 // overstroke count is arraysize minus the center indices
2495 static const int kIndicesPerOverstrokeRRect = std::size(gOverstrokeRRectIndices) - 6;
2496 // fill count skips overstroke indices and includes center
2497 static const int kIndicesPerFillRRect = kIndicesPerOverstrokeRRect - 6 * 4 + 6;
2498 // stroke count is fill count minus center indices
2499 static const int kIndicesPerStrokeRRect = kIndicesPerFillRRect - 6;
2500 static const int kVertsPerStandardRRect = 16;
2501 static const int kVertsPerOverstrokeRRect = 24;
2502
2503 enum RRectType {
2504 kFill_RRectType,
2505 kStroke_RRectType,
2506 kOverstroke_RRectType,
2507 };
2508
2509 static int rrect_type_to_vert_count(RRectType type) {
2510 switch (type) {
2511 case kFill_RRectType:
2512 case kStroke_RRectType:
2513 return kVertsPerStandardRRect;
2514 case kOverstroke_RRectType:
2515 return kVertsPerOverstrokeRRect;
2516 }
2517 SK_ABORT("Invalid type");
2518 }
2519
2520 static int rrect_type_to_index_count(RRectType type) {
2521 switch (type) {
2522 case kFill_RRectType:
2523 return kIndicesPerFillRRect;
2524 case kStroke_RRectType:
2525 return kIndicesPerStrokeRRect;
2526 case kOverstroke_RRectType:
2527 return kIndicesPerOverstrokeRRect;
2528 }
2529 SK_ABORT("Invalid type");
2530 }
2531
2532 static const uint16_t* rrect_type_to_indices(RRectType type) {
2533 switch (type) {
2534 case kFill_RRectType:
2535 case kStroke_RRectType:
2536 return gStandardRRectIndices;
2537 case kOverstroke_RRectType:
2538 return gOverstrokeRRectIndices;
2539 }
2540 SK_ABORT("Invalid type");
2541 }
2542
2543 ///////////////////////////////////////////////////////////////////////////////////////////////////
2544
2545 // For distance computations in the interior of filled rrects we:
2546 //
2547 // add a interior degenerate (point or line) rect
2548 // each vertex of that rect gets -outerRad as its radius
2549 // this makes the computation of the distance to the outer edge be negative
2550 // negative values are caught and then handled differently in the GP's onEmitCode
2551 // each vertex is also given the normalized x & y distance from the interior rect's edge
2552 // the GP takes the min of those depths +1 to get the normalized distance to the outer edge
2553
2554 class CircularRRectOp final : public GrMeshDrawOp {
2555 private:
2556 using Helper = GrSimpleMeshDrawOpHelper;
2557
2558 public:
2559 DEFINE_OP_CLASS_ID
2560
2561 // A devStrokeWidth <= 0 indicates a fill only. If devStrokeWidth > 0 then strokeOnly indicates
2562 // whether the rrect is only stroked or stroked and filled.
2563 static GrOp::Owner Make(GrRecordingContext* context,
2564 GrPaint&& paint,
2565 const SkMatrix& viewMatrix,
2566 const SkRect& devRect,
2567 float devRadius,
2568 float devStrokeWidth,
2569 bool strokeOnly) {
2570 return Helper::FactoryHelper<CircularRRectOp>(context, std::move(paint), viewMatrix,
2571 devRect, devRadius,
2572 devStrokeWidth, strokeOnly);
2573 }
2574 CircularRRectOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
2575 const SkMatrix& viewMatrix, const SkRect& devRect, float devRadius,
2576 float devStrokeWidth, bool strokeOnly)
2577 : INHERITED(ClassID())
2578 , fViewMatrixIfUsingLocalCoords(viewMatrix)
2579 , fHelper(processorSet, GrAAType::kCoverage) {
2580 SkRect bounds = devRect;
2581 SkASSERT(!(devStrokeWidth <= 0 && strokeOnly));
2582 SkScalar innerRadius = 0.0f;
2583 SkScalar outerRadius = devRadius;
2584 SkScalar halfWidth = 0;
2585 RRectType type = kFill_RRectType;
2586 if (devStrokeWidth > 0) {
2587 if (SkScalarNearlyZero(devStrokeWidth)) {
2588 halfWidth = SK_ScalarHalf;
2589 } else {
2590 halfWidth = SkScalarHalf(devStrokeWidth);
2591 }
2592
2593 if (strokeOnly) {
2594 // Outset stroke by 1/4 pixel
2595 devStrokeWidth += 0.25f;
2596 // If stroke is greater than width or height, this is still a fill
2597 // Otherwise we compute stroke params
2598 if (devStrokeWidth <= devRect.width() && devStrokeWidth <= devRect.height()) {
2599 innerRadius = devRadius - halfWidth;
2600 type = (innerRadius >= 0) ? kStroke_RRectType : kOverstroke_RRectType;
2601 }
2602 }
2603 outerRadius += halfWidth;
2604 bounds.outset(halfWidth, halfWidth);
2605 }
2606
2607 // The radii are outset for two reasons. First, it allows the shader to simply perform
2608 // simpler computation because the computed alpha is zero, rather than 50%, at the radius.
2609 // Second, the outer radius is used to compute the verts of the bounding box that is
2610 // rendered and the outset ensures the box will cover all partially covered by the rrect
2611 // corners.
2612 outerRadius += SK_ScalarHalf;
2613 innerRadius -= SK_ScalarHalf;
2614
2615 this->setBounds(bounds, HasAABloat::kYes, IsHairline::kNo);
2616
2617 // Expand the rect for aa to generate correct vertices.
2618 bounds.outset(SK_ScalarHalf, SK_ScalarHalf);
2619
2620 fRRects.emplace_back(RRect{color, innerRadius, outerRadius, bounds, type});
2621 fVertCount = rrect_type_to_vert_count(type);
2622 fIndexCount = rrect_type_to_index_count(type);
2623 fAllFill = (kFill_RRectType == type);
2624 }
2625
2626 const char* name() const override { return "CircularRRectOp"; }
2627
2628 void visitProxies(const GrVisitProxyFunc& func) const override {
2629 if (fProgramInfo) {
2630 fProgramInfo->visitFPProxies(func);
2631 } else {
2632 fHelper.visitProxies(func);
2633 }
2634 }
2635
2636 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
2637 GrClampType clampType) override {
2638 SkPMColor4f* color = &fRRects.front().fColor;
2639 return fHelper.finalizeProcessors(caps, clip, clampType,
2640 GrProcessorAnalysisCoverage::kSingleChannel, color,
2641 &fWideColor);
2642 }
2643
2644 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
2645
2646 private:
2647 static void FillInOverstrokeVerts(VertexWriter& verts, const SkRect& bounds, SkScalar smInset,
2648 SkScalar bigInset, SkScalar xOffset, SkScalar outerRadius,
2649 SkScalar innerRadius, const VertexColor& color) {
2650 SkASSERT(smInset < bigInset);
2651
2652 // TL
2653 verts << (bounds.fLeft + smInset) << (bounds.fTop + smInset)
2654 << color
2655 << xOffset << 0.0f
2656 << outerRadius << innerRadius;
2657
2658 // TR
2659 verts << (bounds.fRight - smInset) << (bounds.fTop + smInset)
2660 << color
2661 << xOffset << 0.0f
2662 << outerRadius << innerRadius;
2663
2664 verts << (bounds.fLeft + bigInset) << (bounds.fTop + bigInset)
2665 << color
2666 << 0.0f << 0.0f
2667 << outerRadius << innerRadius;
2668
2669 verts << (bounds.fRight - bigInset) << (bounds.fTop + bigInset)
2670 << color
2671 << 0.0f << 0.0f
2672 << outerRadius << innerRadius;
2673
2674 verts << (bounds.fLeft + bigInset) << (bounds.fBottom - bigInset)
2675 << color
2676 << 0.0f << 0.0f
2677 << outerRadius << innerRadius;
2678
2679 verts << (bounds.fRight - bigInset) << (bounds.fBottom - bigInset)
2680 << color
2681 << 0.0f << 0.0f
2682 << outerRadius << innerRadius;
2683
2684 // BL
2685 verts << (bounds.fLeft + smInset) << (bounds.fBottom - smInset)
2686 << color
2687 << xOffset << 0.0f
2688 << outerRadius << innerRadius;
2689
2690 // BR
2691 verts << (bounds.fRight - smInset) << (bounds.fBottom - smInset)
2692 << color
2693 << xOffset << 0.0f
2694 << outerRadius << innerRadius;
2695 }
2696
2697 GrProgramInfo* programInfo() override { return fProgramInfo; }
2698
2699 void onCreateProgramInfo(const GrCaps* caps,
2700 SkArenaAlloc* arena,
2701 const GrSurfaceProxyView& writeView,
2702 bool usesMSAASurface,
2703 GrAppliedClip&& appliedClip,
2704 const GrDstProxyView& dstProxyView,
2705 GrXferBarrierFlags renderPassXferBarriers,
2706 GrLoadOp colorLoadOp) override {
2707 SkASSERT(!usesMSAASurface);
2708
2709 // Invert the view matrix as a local matrix (if any other processors require coords).
2710 SkMatrix localMatrix;
2711 if (!fViewMatrixIfUsingLocalCoords.invert(&localMatrix)) {
2712 return;
2713 }
2714
2715 GrGeometryProcessor* gp = CircleGeometryProcessor::Make(arena, !fAllFill,
2716 false, false, false, false,
2717 fWideColor, localMatrix);
2718
2719 fProgramInfo = fHelper.createProgramInfo(caps, arena, writeView, usesMSAASurface,
2720 std::move(appliedClip), dstProxyView, gp,
2721 GrPrimitiveType::kTriangles,
2722 renderPassXferBarriers, colorLoadOp);
2723 }
2724
2725 void onPrepareDraws(GrMeshDrawTarget* target) override {
2726 if (!fProgramInfo) {
2727 this->createProgramInfo(target);
2728 if (!fProgramInfo) {
2729 return;
2730 }
2731 }
2732
2733 sk_sp<const GrBuffer> vertexBuffer;
2734 int firstVertex;
2735
2736 VertexWriter verts = target->makeVertexWriter(fProgramInfo->geomProc().vertexStride(),
2737 fVertCount, &vertexBuffer, &firstVertex);
2738 if (!verts) SK_UNLIKELY {
2739 SkDebugf("Could not allocate vertices\n");
2740 return;
2741 }
2742
2743 sk_sp<const GrBuffer> indexBuffer;
2744 int firstIndex = 0;
2745 uint16_t* indices = target->makeIndexSpace(fIndexCount, &indexBuffer, &firstIndex);
2746 if (!indices) SK_UNLIKELY {
2747 SkDebugf("Could not allocate indices\n");
2748 return;
2749 }
2750
2751 int currStartVertex = 0;
2752 for (const auto& rrect : fRRects) {
2753 VertexColor color(rrect.fColor, fWideColor);
2754 SkScalar outerRadius = rrect.fOuterRadius;
2755 const SkRect& bounds = rrect.fDevBounds;
2756
2757 SkScalar yCoords[4] = {bounds.fTop, bounds.fTop + outerRadius,
2758 bounds.fBottom - outerRadius, bounds.fBottom};
2759
2760 SkScalar yOuterRadii[4] = {-1, 0, 0, 1};
2761 // The inner radius in the vertex data must be specified in normalized space.
2762 // For fills, specifying -1/outerRadius guarantees an alpha of 1.0 at the inner radius.
2763 SkScalar innerRadius = rrect.fType != kFill_RRectType
2764 ? rrect.fInnerRadius / rrect.fOuterRadius
2765 : -1.0f / rrect.fOuterRadius;
2766 for (int i = 0; i < 4; ++i) {
2767 verts << bounds.fLeft << yCoords[i]
2768 << color
2769 << -1.0f << yOuterRadii[i]
2770 << outerRadius << innerRadius;
2771
2772 verts << (bounds.fLeft + outerRadius) << yCoords[i]
2773 << color
2774 << 0.0f << yOuterRadii[i]
2775 << outerRadius << innerRadius;
2776
2777 verts << (bounds.fRight - outerRadius) << yCoords[i]
2778 << color
2779 << 0.0f << yOuterRadii[i]
2780 << outerRadius << innerRadius;
2781
2782 verts << bounds.fRight << yCoords[i]
2783 << color
2784 << 1.0f << yOuterRadii[i]
2785 << outerRadius << innerRadius;
2786 }
2787 // Add the additional vertices for overstroked rrects.
2788 // Effectively this is an additional stroked rrect, with its
2789 // outer radius = outerRadius - innerRadius, and inner radius = 0.
2790 // This will give us correct AA in the center and the correct
2791 // distance to the outer edge.
2792 //
2793 // Also, the outer offset is a constant vector pointing to the right, which
2794 // guarantees that the distance value along the outer rectangle is constant.
2795 if (kOverstroke_RRectType == rrect.fType) {
2796 SkASSERT(rrect.fInnerRadius <= 0.0f);
2797
2798 SkScalar overstrokeOuterRadius = outerRadius - rrect.fInnerRadius;
2799 // this is the normalized distance from the outer rectangle of this
2800 // geometry to the outer edge
2801 SkScalar maxOffset = -rrect.fInnerRadius / overstrokeOuterRadius;
2802
2803 FillInOverstrokeVerts(verts, bounds, outerRadius, overstrokeOuterRadius, maxOffset,
2804 overstrokeOuterRadius, 0.0f, color);
2805 }
2806
2807 const uint16_t* primIndices = rrect_type_to_indices(rrect.fType);
2808 const int primIndexCount = rrect_type_to_index_count(rrect.fType);
2809 for (int i = 0; i < primIndexCount; ++i) {
2810 *indices++ = primIndices[i] + currStartVertex;
2811 }
2812
2813 currStartVertex += rrect_type_to_vert_count(rrect.fType);
2814 }
2815
2816 fMesh = target->allocMesh();
2817 fMesh->setIndexed(std::move(indexBuffer), fIndexCount, firstIndex, 0, fVertCount - 1,
2818 GrPrimitiveRestart::kNo, std::move(vertexBuffer), firstVertex);
2819 }
2820
2821 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
2822 if (!fProgramInfo || !fMesh) {
2823 return;
2824 }
2825
2826 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
2827 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
2828 flushState->drawMesh(*fMesh);
2829 }
2830
2831 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
2832 CircularRRectOp* that = t->cast<CircularRRectOp>();
2833
2834 // Cannot combine if the net number of indices would overflow int32, or if the net number
2835 // of vertices would overflow uint16 (since the index values are 16-bit that point into
2836 // the vertex buffer).
2837 if ((fIndexCount > INT32_MAX - that->fIndexCount) ||
2838 (fVertCount > SkToInt(UINT16_MAX) - that->fVertCount)) {
2839 return CombineResult::kCannotCombine;
2840 }
2841
2842 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
2843 return CombineResult::kCannotCombine;
2844 }
2845
2846 if (fHelper.usesLocalCoords() &&
2847 !SkMatrixPriv::CheapEqual(fViewMatrixIfUsingLocalCoords,
2848 that->fViewMatrixIfUsingLocalCoords)) {
2849 return CombineResult::kCannotCombine;
2850 }
2851
2852 fRRects.push_back_n(that->fRRects.size(), that->fRRects.begin());
2853 fVertCount += that->fVertCount;
2854 fIndexCount += that->fIndexCount;
2855 fAllFill = fAllFill && that->fAllFill;
2856 fWideColor = fWideColor || that->fWideColor;
2857 return CombineResult::kMerged;
2858 }
2859
2860 #if defined(GPU_TEST_UTILS)
2861 SkString onDumpInfo() const override {
2862 SkString string;
2863 for (int i = 0; i < fRRects.size(); ++i) {
2864 string.appendf(
2865 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f],"
2866 "InnerRad: %.2f, OuterRad: %.2f\n",
2867 fRRects[i].fColor.toBytes_RGBA(), fRRects[i].fDevBounds.fLeft,
2868 fRRects[i].fDevBounds.fTop, fRRects[i].fDevBounds.fRight,
2869 fRRects[i].fDevBounds.fBottom, fRRects[i].fInnerRadius,
2870 fRRects[i].fOuterRadius);
2871 }
2872 string += fHelper.dumpInfo();
2873 return string;
2874 }
2875 #endif
2876
2877 struct RRect {
2878 SkPMColor4f fColor;
2879 SkScalar fInnerRadius;
2880 SkScalar fOuterRadius;
2881 SkRect fDevBounds;
2882 RRectType fType;
2883 };
2884
2885 SkMatrix fViewMatrixIfUsingLocalCoords;
2886 Helper fHelper;
2887 int fVertCount;
2888 int fIndexCount;
2889 bool fAllFill;
2890 bool fWideColor;
2891 STArray<1, RRect, true> fRRects;
2892
2893 GrSimpleMesh* fMesh = nullptr;
2894 GrProgramInfo* fProgramInfo = nullptr;
2895
2896 using INHERITED = GrMeshDrawOp;
2897 };
2898
2899 static const int kNumRRectsInIndexBuffer = 256;
2900
2901 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gStrokeRRectOnlyIndexBufferKey);
2902 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gRRectOnlyIndexBufferKey);
2903 static sk_sp<const GrBuffer> get_rrect_index_buffer(RRectType type,
2904 GrResourceProvider* resourceProvider) {
2905 SKGPU_DEFINE_STATIC_UNIQUE_KEY(gStrokeRRectOnlyIndexBufferKey);
2906 SKGPU_DEFINE_STATIC_UNIQUE_KEY(gRRectOnlyIndexBufferKey);
2907 switch (type) {
2908 case kFill_RRectType:
2909 return resourceProvider->findOrCreatePatternedIndexBuffer(
2910 gStandardRRectIndices, kIndicesPerFillRRect, kNumRRectsInIndexBuffer,
2911 kVertsPerStandardRRect, gRRectOnlyIndexBufferKey);
2912 case kStroke_RRectType:
2913 return resourceProvider->findOrCreatePatternedIndexBuffer(
2914 gStandardRRectIndices, kIndicesPerStrokeRRect, kNumRRectsInIndexBuffer,
2915 kVertsPerStandardRRect, gStrokeRRectOnlyIndexBufferKey);
2916 default:
2917 SkASSERT(false);
2918 return nullptr;
2919 }
2920 }
2921
2922 class EllipticalRRectOp final : public GrMeshDrawOp {
2923 private:
2924 using Helper = GrSimpleMeshDrawOpHelper;
2925
2926 public:
2927 DEFINE_OP_CLASS_ID
2928
2929 // If devStrokeWidths values are <= 0 indicates then fill only. Otherwise, strokeOnly indicates
2930 // whether the rrect is only stroked or stroked and filled.
2931 static GrOp::Owner Make(GrRecordingContext* context,
2932 GrPaint&& paint,
2933 const SkMatrix& viewMatrix,
2934 const SkRect& devRect,
2935 float devXRadius,
2936 float devYRadius,
2937 SkVector devStrokeWidths,
2938 bool strokeOnly) {
2939 SkASSERT(devXRadius >= 0.5 || strokeOnly);
2940 SkASSERT(devYRadius >= 0.5 || strokeOnly);
2941 SkASSERT((devStrokeWidths.fX > 0) == (devStrokeWidths.fY > 0));
2942 SkASSERT(!(strokeOnly && devStrokeWidths.fX <= 0));
2943 if (devStrokeWidths.fX > 0) {
2944 if (SkScalarNearlyZero(devStrokeWidths.length())) {
2945 devStrokeWidths.set(SK_ScalarHalf, SK_ScalarHalf);
2946 } else {
2947 devStrokeWidths.scale(SK_ScalarHalf);
2948 }
2949
2950 // we only handle thick strokes for near-circular ellipses
2951 if (devStrokeWidths.length() > SK_ScalarHalf &&
2952 (SK_ScalarHalf * devXRadius > devYRadius ||
2953 SK_ScalarHalf * devYRadius > devXRadius)) {
2954 return nullptr;
2955 }
2956
2957 // we don't handle it if curvature of the stroke is less than curvature of the ellipse
2958 if (devStrokeWidths.fX * (devYRadius * devYRadius) <
2959 (devStrokeWidths.fY * devStrokeWidths.fY) * devXRadius) {
2960 return nullptr;
2961 }
2962 if (devStrokeWidths.fY * (devXRadius * devXRadius) <
2963 (devStrokeWidths.fX * devStrokeWidths.fX) * devYRadius) {
2964 return nullptr;
2965 }
2966 }
2967 return Helper::FactoryHelper<EllipticalRRectOp>(context, std::move(paint),
2968 viewMatrix, devRect,
2969 devXRadius, devYRadius, devStrokeWidths,
2970 strokeOnly);
2971 }
2972
2973 EllipticalRRectOp(GrProcessorSet* processorSet, const SkPMColor4f& color,
2974 const SkMatrix& viewMatrix, const SkRect& devRect, float devXRadius,
2975 float devYRadius, SkVector devStrokeHalfWidths, bool strokeOnly)
2976 : INHERITED(ClassID())
2977 , fHelper(processorSet, GrAAType::kCoverage)
2978 , fUseScale(false) {
2979 SkScalar innerXRadius = 0.0f;
2980 SkScalar innerYRadius = 0.0f;
2981 SkRect bounds = devRect;
2982 bool stroked = false;
2983 if (devStrokeHalfWidths.fX > 0) {
2984 // this is legit only if scale & translation (which should be the case at the moment)
2985 if (strokeOnly) {
2986 innerXRadius = devXRadius - devStrokeHalfWidths.fX;
2987 innerYRadius = devYRadius - devStrokeHalfWidths.fY;
2988 stroked = (innerXRadius >= 0 && innerYRadius >= 0);
2989 }
2990
2991 devXRadius += devStrokeHalfWidths.fX;
2992 devYRadius += devStrokeHalfWidths.fY;
2993 bounds.outset(devStrokeHalfWidths.fX, devStrokeHalfWidths.fY);
2994 }
2995
2996 fStroked = stroked;
2997 fViewMatrixIfUsingLocalCoords = viewMatrix;
2998 this->setBounds(bounds, HasAABloat::kYes, IsHairline::kNo);
2999 fRRects.emplace_back(
3000 RRect{color, devXRadius, devYRadius, innerXRadius, innerYRadius, bounds});
3001 }
3002
3003 const char* name() const override { return "EllipticalRRectOp"; }
3004
3005 void visitProxies(const GrVisitProxyFunc& func) const override {
3006 if (fProgramInfo) {
3007 fProgramInfo->visitFPProxies(func);
3008 } else {
3009 fHelper.visitProxies(func);
3010 }
3011 }
3012
3013 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
3014 GrClampType clampType) override {
3015 fUseScale = !caps.shaderCaps()->fFloatIs32Bits;
3016 SkPMColor4f* color = &fRRects.front().fColor;
3017 return fHelper.finalizeProcessors(caps, clip, clampType,
3018 GrProcessorAnalysisCoverage::kSingleChannel, color,
3019 &fWideColor);
3020 }
3021
3022 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
3023
3024 private:
3025 GrProgramInfo* programInfo() override { return fProgramInfo; }
3026
3027 void onCreateProgramInfo(const GrCaps* caps,
3028 SkArenaAlloc* arena,
3029 const GrSurfaceProxyView& writeView,
3030 bool usesMSAASurface,
3031 GrAppliedClip&& appliedClip,
3032 const GrDstProxyView& dstProxyView,
3033 GrXferBarrierFlags renderPassXferBarriers,
3034 GrLoadOp colorLoadOp) override {
3035 SkMatrix localMatrix;
3036 if (!fViewMatrixIfUsingLocalCoords.invert(&localMatrix)) {
3037 return;
3038 }
3039
3040 GrGeometryProcessor* gp = EllipseGeometryProcessor::Make(arena, fStroked, fWideColor,
3041 fUseScale, localMatrix);
3042
3043 fProgramInfo = fHelper.createProgramInfo(caps, arena, writeView, usesMSAASurface,
3044 std::move(appliedClip), dstProxyView, gp,
3045 GrPrimitiveType::kTriangles,
3046 renderPassXferBarriers, colorLoadOp);
3047 }
3048
3049 void onPrepareDraws(GrMeshDrawTarget* target) override {
3050 if (!fProgramInfo) {
3051 this->createProgramInfo(target);
3052 if (!fProgramInfo) {
3053 return;
3054 }
3055 }
3056
3057 // drop out the middle quad if we're stroked
3058 int indicesPerInstance = fStroked ? kIndicesPerStrokeRRect : kIndicesPerFillRRect;
3059 sk_sp<const GrBuffer> indexBuffer = get_rrect_index_buffer(
3060 fStroked ? kStroke_RRectType : kFill_RRectType, target->resourceProvider());
3061
3062 if (!indexBuffer) {
3063 SkDebugf("Could not allocate indices\n");
3064 return;
3065 }
3066 PatternHelper helper(target, GrPrimitiveType::kTriangles,
3067 fProgramInfo->geomProc().vertexStride(),
3068 std::move(indexBuffer), kVertsPerStandardRRect, indicesPerInstance,
3069 fRRects.size(), kNumRRectsInIndexBuffer);
3070 VertexWriter verts{helper.vertices()};
3071 if (!verts) {
3072 SkDebugf("Could not allocate vertices\n");
3073 return;
3074 }
3075
3076 for (const auto& rrect : fRRects) {
3077 VertexColor color(rrect.fColor, fWideColor);
3078 // Compute the reciprocals of the radii here to save time in the shader
3079 float reciprocalRadii[4] = {
3080 SkScalarInvert(rrect.fXRadius),
3081 SkScalarInvert(rrect.fYRadius),
3082 // Pinned below, so divide by zero is acceptable
3083 sk_ieee_float_divide(1.0f, rrect.fInnerXRadius),
3084 sk_ieee_float_divide(1.0f, rrect.fInnerYRadius)
3085 };
3086
3087 // If the stroke width is exactly double the radius, the inner radii will be zero.
3088 // Pin to a large value, to avoid infinities in the shader. crbug.com/1139750
3089 reciprocalRadii[2] = std::min(reciprocalRadii[2], 1e6f);
3090 reciprocalRadii[3] = std::min(reciprocalRadii[3], 1e6f);
3091
3092 // On MSAA, bloat enough to guarantee any pixel that might be touched by the rrect has
3093 // full sample coverage.
3094 float aaBloat = target->usesMSAASurface() ? SK_ScalarSqrt2 : .5f;
3095
3096 // Extend out the radii to antialias.
3097 SkScalar xOuterRadius = rrect.fXRadius + aaBloat;
3098 SkScalar yOuterRadius = rrect.fYRadius + aaBloat;
3099
3100 SkScalar xMaxOffset = xOuterRadius;
3101 SkScalar yMaxOffset = yOuterRadius;
3102 if (!fStroked) {
3103 // For filled rrects we map a unit circle in the vertex attributes rather than
3104 // computing an ellipse and modifying that distance, so we normalize to 1.
3105 xMaxOffset /= rrect.fXRadius;
3106 yMaxOffset /= rrect.fYRadius;
3107 }
3108
3109 const SkRect& bounds = rrect.fDevBounds.makeOutset(aaBloat, aaBloat);
3110
3111 SkScalar yCoords[4] = {bounds.fTop, bounds.fTop + yOuterRadius,
3112 bounds.fBottom - yOuterRadius, bounds.fBottom};
3113 SkScalar yOuterOffsets[4] = {yMaxOffset,
3114 SK_ScalarNearlyZero, // we're using inversesqrt() in
3115 // shader, so can't be exactly 0
3116 SK_ScalarNearlyZero, yMaxOffset};
3117
3118 auto maybeScale = VertexWriter::If(fUseScale, std::max(rrect.fXRadius, rrect.fYRadius));
3119 for (int i = 0; i < 4; ++i) {
3120 verts << bounds.fLeft << yCoords[i]
3121 << color
3122 << xMaxOffset << yOuterOffsets[i]
3123 << maybeScale
3124 << reciprocalRadii;
3125
3126 verts << (bounds.fLeft + xOuterRadius) << yCoords[i]
3127 << color
3128 << SK_ScalarNearlyZero << yOuterOffsets[i]
3129 << maybeScale
3130 << reciprocalRadii;
3131
3132 verts << (bounds.fRight - xOuterRadius) << yCoords[i]
3133 << color
3134 << SK_ScalarNearlyZero << yOuterOffsets[i]
3135 << maybeScale
3136 << reciprocalRadii;
3137
3138 verts << bounds.fRight << yCoords[i]
3139 << color
3140 << xMaxOffset << yOuterOffsets[i]
3141 << maybeScale
3142 << reciprocalRadii;
3143 }
3144 }
3145 fMesh = helper.mesh();
3146 }
3147
3148 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
3149 if (!fProgramInfo || !fMesh) {
3150 return;
3151 }
3152
3153 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
3154 flushState->bindTextures(fProgramInfo->geomProc(), nullptr, fProgramInfo->pipeline());
3155 flushState->drawMesh(*fMesh);
3156 }
3157
3158 CombineResult onCombineIfPossible(GrOp* t, SkArenaAlloc*, const GrCaps& caps) override {
3159 EllipticalRRectOp* that = t->cast<EllipticalRRectOp>();
3160
3161 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
3162 return CombineResult::kCannotCombine;
3163 }
3164
3165 if (fStroked != that->fStroked) {
3166 return CombineResult::kCannotCombine;
3167 }
3168
3169 if (fHelper.usesLocalCoords() &&
3170 !SkMatrixPriv::CheapEqual(fViewMatrixIfUsingLocalCoords,
3171 that->fViewMatrixIfUsingLocalCoords)) {
3172 return CombineResult::kCannotCombine;
3173 }
3174
3175 fRRects.push_back_n(that->fRRects.size(), that->fRRects.begin());
3176 fWideColor = fWideColor || that->fWideColor;
3177 return CombineResult::kMerged;
3178 }
3179
3180 #if defined(GPU_TEST_UTILS)
3181 SkString onDumpInfo() const override {
3182 SkString string = SkStringPrintf("Stroked: %d\n", fStroked);
3183 for (const auto& geo : fRRects) {
3184 string.appendf(
3185 "Color: 0x%08x Rect [L: %.2f, T: %.2f, R: %.2f, B: %.2f], "
3186 "XRad: %.2f, YRad: %.2f, InnerXRad: %.2f, InnerYRad: %.2f\n",
3187 geo.fColor.toBytes_RGBA(), geo.fDevBounds.fLeft, geo.fDevBounds.fTop,
3188 geo.fDevBounds.fRight, geo.fDevBounds.fBottom, geo.fXRadius, geo.fYRadius,
3189 geo.fInnerXRadius, geo.fInnerYRadius);
3190 }
3191 string += fHelper.dumpInfo();
3192 return string;
3193 }
3194 #endif
3195
3196 struct RRect {
3197 SkPMColor4f fColor;
3198 SkScalar fXRadius;
3199 SkScalar fYRadius;
3200 SkScalar fInnerXRadius;
3201 SkScalar fInnerYRadius;
3202 SkRect fDevBounds;
3203 };
3204
3205 SkMatrix fViewMatrixIfUsingLocalCoords;
3206 Helper fHelper;
3207 bool fStroked;
3208 bool fWideColor;
3209 bool fUseScale;
3210 STArray<1, RRect, true> fRRects;
3211
3212 GrSimpleMesh* fMesh = nullptr;
3213 GrProgramInfo* fProgramInfo = nullptr;
3214
3215 using INHERITED = GrMeshDrawOp;
3216 };
3217
3218 GrOp::Owner GrOvalOpFactory::MakeCircularRRectOp(GrRecordingContext* context,
3219 GrPaint&& paint,
3220 const SkMatrix& viewMatrix,
3221 const SkRRect& rrect,
3222 const SkStrokeRec& stroke,
3223 const GrShaderCaps* shaderCaps) {
3224 SkASSERT(viewMatrix.rectStaysRect());
3225 SkASSERT(viewMatrix.isSimilarity());
3226 SkASSERT(rrect.isSimple());
3227 SkASSERT(!rrect.isOval());
3228 SkASSERT(SkRRectPriv::GetSimpleRadii(rrect).fX == SkRRectPriv::GetSimpleRadii(rrect).fY);
3229
3230 // RRect ops only handle simple, but not too simple, rrects.
3231 // Do any matrix crunching before we reset the draw state for device coords.
3232 const SkRect& rrectBounds = rrect.getBounds();
3233 SkRect bounds;
3234 viewMatrix.mapRect(&bounds, rrectBounds);
3235
3236 SkScalar radius = SkRRectPriv::GetSimpleRadii(rrect).fX;
3237 SkScalar scaledRadius = SkScalarAbs(radius * (viewMatrix[SkMatrix::kMScaleX] +
3238 viewMatrix[SkMatrix::kMSkewY]));
3239
3240 // Do mapping of stroke. Use -1 to indicate fill-only draws.
3241 SkScalar scaledStroke = -1;
3242 SkScalar strokeWidth = stroke.getWidth();
3243 SkStrokeRec::Style style = stroke.getStyle();
3244
3245 bool isStrokeOnly =
3246 SkStrokeRec::kStroke_Style == style || SkStrokeRec::kHairline_Style == style;
3247 bool hasStroke = isStrokeOnly || SkStrokeRec::kStrokeAndFill_Style == style;
3248
3249 if (hasStroke) {
3250 if (SkStrokeRec::kHairline_Style == style) {
3251 scaledStroke = SK_Scalar1;
3252 } else {
3253 scaledStroke = SkScalarAbs(strokeWidth * (viewMatrix[SkMatrix::kMScaleX] +
3254 viewMatrix[SkMatrix::kMSkewY]));
3255 }
3256 }
3257
3258 // The way the effect interpolates the offset-to-ellipse/circle-center attribute only works on
3259 // the interior of the rrect if the radii are >= 0.5. Otherwise, the inner rect of the nine-
3260 // patch will have fractional coverage. This only matters when the interior is actually filled.
3261 // We could consider falling back to rect rendering here, since a tiny radius is
3262 // indistinguishable from a square corner.
3263 if (!isStrokeOnly && SK_ScalarHalf > scaledRadius) {
3264 return nullptr;
3265 }
3266
3267 return CircularRRectOp::Make(context, std::move(paint), viewMatrix, bounds, scaledRadius,
3268 scaledStroke, isStrokeOnly);
3269 }
3270
3271 GrOp::Owner make_rrect_op(GrRecordingContext* context,
3272 GrPaint&& paint,
3273 const SkMatrix& viewMatrix,
3274 const SkRRect& rrect,
3275 const SkStrokeRec& stroke) {
3276 SkASSERT(viewMatrix.rectStaysRect());
3277 SkASSERT(rrect.isSimple());
3278 SkASSERT(!rrect.isOval());
3279
3280 // RRect ops only handle simple, but not too simple, rrects.
3281 // Do any matrix crunching before we reset the draw state for device coords.
3282 const SkRect& rrectBounds = rrect.getBounds();
3283 SkRect bounds;
3284 viewMatrix.mapRect(&bounds, rrectBounds);
3285
3286 SkVector radii = SkRRectPriv::GetSimpleRadii(rrect);
3287 SkScalar xRadius = SkScalarAbs(viewMatrix[SkMatrix::kMScaleX] * radii.fX +
3288 viewMatrix[SkMatrix::kMSkewY] * radii.fY);
3289 SkScalar yRadius = SkScalarAbs(viewMatrix[SkMatrix::kMSkewX] * radii.fX +
3290 viewMatrix[SkMatrix::kMScaleY] * radii.fY);
3291
3292 SkStrokeRec::Style style = stroke.getStyle();
3293
3294 // Do (potentially) anisotropic mapping of stroke. Use -1s to indicate fill-only draws.
3295 SkVector scaledStroke = {-1, -1};
3296 SkScalar strokeWidth = stroke.getWidth();
3297
3298 bool isStrokeOnly =
3299 SkStrokeRec::kStroke_Style == style || SkStrokeRec::kHairline_Style == style;
3300 bool hasStroke = isStrokeOnly || SkStrokeRec::kStrokeAndFill_Style == style;
3301
3302 if (hasStroke) {
3303 if (SkStrokeRec::kHairline_Style == style) {
3304 scaledStroke.set(1, 1);
3305 } else {
3306 scaledStroke.fX = SkScalarAbs(
3307 strokeWidth * (viewMatrix[SkMatrix::kMScaleX] + viewMatrix[SkMatrix::kMSkewY]));
3308 scaledStroke.fY = SkScalarAbs(
3309 strokeWidth * (viewMatrix[SkMatrix::kMSkewX] + viewMatrix[SkMatrix::kMScaleY]));
3310 }
3311
3312 // if half of strokewidth is greater than radius, we don't handle that right now
3313 if ((SK_ScalarHalf * scaledStroke.fX > xRadius ||
3314 SK_ScalarHalf * scaledStroke.fY > yRadius)) {
3315 return nullptr;
3316 }
3317 }
3318
3319 // The matrix may have a rotation by an odd multiple of 90 degrees.
3320 if (viewMatrix.getScaleX() == 0) {
3321 std::swap(xRadius, yRadius);
3322 std::swap(scaledStroke.fX, scaledStroke.fY);
3323 }
3324
3325 // The way the effect interpolates the offset-to-ellipse/circle-center attribute only works on
3326 // the interior of the rrect if the radii are >= 0.5. Otherwise, the inner rect of the nine-
3327 // patch will have fractional coverage. This only matters when the interior is actually filled.
3328 // We could consider falling back to rect rendering here, since a tiny radius is
3329 // indistinguishable from a square corner.
3330 if (!isStrokeOnly && (SK_ScalarHalf > xRadius || SK_ScalarHalf > yRadius)) {
3331 return nullptr;
3332 }
3333
3334 // if the corners are circles, use the circle renderer
3335 return EllipticalRRectOp::Make(context, std::move(paint), viewMatrix, bounds,
3336 xRadius, yRadius, scaledStroke, isStrokeOnly);
3337 }
3338
3339 GrOp::Owner GrOvalOpFactory::MakeRRectOp(GrRecordingContext* context,
3340 GrPaint&& paint,
3341 const SkMatrix& viewMatrix,
3342 const SkRRect& rrect,
3343 const SkStrokeRec& stroke,
3344 const GrShaderCaps* shaderCaps) {
3345 if (rrect.isOval()) {
3346 return MakeOvalOp(context, std::move(paint), viewMatrix, rrect.getBounds(),
3347 GrStyle(stroke, nullptr), shaderCaps);
3348 }
3349
3350 if (!viewMatrix.rectStaysRect() || !rrect.isSimple()) {
3351 return nullptr;
3352 }
3353
3354 return make_rrect_op(context, std::move(paint), viewMatrix, rrect, stroke);
3355 }
3356
3357 ///////////////////////////////////////////////////////////////////////////////
3358
3359 GrOp::Owner GrOvalOpFactory::MakeCircleOp(GrRecordingContext* context,
3360 GrPaint&& paint,
3361 const SkMatrix& viewMatrix,
3362 const SkRect& oval,
3363 const GrStyle& style,
3364 const GrShaderCaps* shaderCaps) {
3365 SkScalar width = oval.width();
3366 SkASSERT(width > SK_ScalarNearlyZero && SkScalarNearlyEqual(width, oval.height()) &&
3367 circle_stays_circle(viewMatrix));
3368
3369 auto r = width / 2.f;
3370 SkPoint center = { oval.centerX(), oval.centerY() };
3371 if (style.hasNonDashPathEffect()) {
3372 return nullptr;
3373 } else if (style.isDashed()) {
3374 if (style.strokeRec().getCap() != SkPaint::kButt_Cap ||
3375 style.dashIntervalCnt() != 2 || style.strokeRec().getWidth() >= width) {
3376 return nullptr;
3377 }
3378 auto onInterval = style.dashIntervals()[0];
3379 auto offInterval = style.dashIntervals()[1];
3380 if (offInterval == 0) {
3381 GrStyle strokeStyle(style.strokeRec(), nullptr);
3382 return MakeOvalOp(context, std::move(paint), viewMatrix, oval,
3383 strokeStyle, shaderCaps);
3384 } else if (onInterval == 0) {
3385 // There is nothing to draw but we have no way to indicate that here.
3386 return nullptr;
3387 }
3388 auto angularOnInterval = onInterval / r;
3389 auto angularOffInterval = offInterval / r;
3390 auto phaseAngle = style.dashPhase() / r;
3391 // Currently this function doesn't accept ovals with different start angles, though
3392 // it could.
3393 static const SkScalar kStartAngle = 0.f;
3394 return ButtCapDashedCircleOp::Make(context, std::move(paint), viewMatrix, center, r,
3395 style.strokeRec().getWidth(), kStartAngle,
3396 angularOnInterval, angularOffInterval, phaseAngle);
3397 }
3398 return CircleOp::Make(context, std::move(paint), viewMatrix, center, r, style);
3399 }
3400
3401 GrOp::Owner GrOvalOpFactory::MakeOvalOp(GrRecordingContext* context,
3402 GrPaint&& paint,
3403 const SkMatrix& viewMatrix,
3404 const SkRect& oval,
3405 const GrStyle& style,
3406 const GrShaderCaps* shaderCaps) {
3407 if (style.pathEffect()) {
3408 return nullptr;
3409 }
3410
3411 // prefer the device space ellipse op for batchability
3412 if (viewMatrix.rectStaysRect()) {
3413 return EllipseOp::Make(context, std::move(paint), viewMatrix, oval, style.strokeRec());
3414 }
3415
3416 // Otherwise, if we have shader derivative support, render as device-independent
3417 if (shaderCaps->fShaderDerivativeSupport) {
3418 SkScalar a = viewMatrix[SkMatrix::kMScaleX];
3419 SkScalar b = viewMatrix[SkMatrix::kMSkewX];
3420 SkScalar c = viewMatrix[SkMatrix::kMSkewY];
3421 SkScalar d = viewMatrix[SkMatrix::kMScaleY];
3422 // Check for near-degenerate matrix
3423 if (a*a + c*c > SK_ScalarNearlyZero && b*b + d*d > SK_ScalarNearlyZero) {
3424 return DIEllipseOp::Make(context, std::move(paint), viewMatrix, oval,
3425 style.strokeRec());
3426 }
3427 }
3428
3429 return nullptr;
3430 }
3431
3432 ///////////////////////////////////////////////////////////////////////////////
3433
3434 GrOp::Owner GrOvalOpFactory::MakeArcOp(GrRecordingContext* context,
3435 GrPaint&& paint,
3436 const SkMatrix& viewMatrix,
3437 const SkRect& oval, SkScalar startAngle,
3438 SkScalar sweepAngle, bool useCenter,
3439 const GrStyle& style,
3440 const GrShaderCaps* shaderCaps) {
3441 SkASSERT(!oval.isEmpty());
3442 SkASSERT(sweepAngle);
3443 SkScalar width = oval.width();
3444 if (SkScalarAbs(sweepAngle) >= 360.f) {
3445 return nullptr;
3446 }
3447 if (!SkScalarNearlyEqual(width, oval.height()) || !circle_stays_circle(viewMatrix)) {
3448 return nullptr;
3449 }
3450 SkPoint center = {oval.centerX(), oval.centerY()};
3451 CircleOp::ArcParams arcParams = {SkDegreesToRadians(startAngle), SkDegreesToRadians(sweepAngle),
3452 useCenter};
3453 return CircleOp::Make(context, std::move(paint), viewMatrix,
3454 center, width / 2.f, style, &arcParams);
3455 }
3456
3457 ///////////////////////////////////////////////////////////////////////////////
3458
3459 #if defined(GPU_TEST_UTILS)
3460
3461 GR_DRAW_OP_TEST_DEFINE(CircleOp) {
3462 if (numSamples > 1) {
3463 return nullptr;
3464 }
3465
3466 do {
3467 SkScalar rotate = random->nextSScalar1() * 360.f;
3468 SkScalar translateX = random->nextSScalar1() * 1000.f;
3469 SkScalar translateY = random->nextSScalar1() * 1000.f;
3470 SkScalar scale;
3471 do {
3472 scale = random->nextSScalar1() * 100.f;
3473 } while (scale == 0);
3474 SkMatrix viewMatrix;
3475 viewMatrix.setRotate(rotate);
3476 viewMatrix.postTranslate(translateX, translateY);
3477 viewMatrix.postScale(scale, scale);
3478 SkRect circle = GrTest::TestSquare(random);
3479 SkPoint center = {circle.centerX(), circle.centerY()};
3480 SkScalar radius = circle.width() / 2.f;
3481 SkStrokeRec stroke = GrTest::TestStrokeRec(random);
3482 CircleOp::ArcParams arcParamsTmp;
3483 const CircleOp::ArcParams* arcParams = nullptr;
3484 if (random->nextBool()) {
3485 arcParamsTmp.fStartAngleRadians = random->nextSScalar1() * SK_ScalarPI * 2;
3486 arcParamsTmp.fSweepAngleRadians = random->nextSScalar1() * SK_ScalarPI * 2 - .01f;
3487 arcParamsTmp.fUseCenter = random->nextBool();
3488 arcParams = &arcParamsTmp;
3489 }
3490 GrOp::Owner op = CircleOp::Make(context, std::move(paint), viewMatrix,
3491 center, radius,
3492 GrStyle(stroke, nullptr), arcParams);
3493 if (op) {
3494 return op;
3495 }
3496 assert_alive(paint);
3497 } while (true);
3498 }
3499
3500 GR_DRAW_OP_TEST_DEFINE(ButtCapDashedCircleOp) {
3501 if (numSamples > 1) {
3502 return nullptr;
3503 }
3504
3505 SkScalar rotate = random->nextSScalar1() * 360.f;
3506 SkScalar translateX = random->nextSScalar1() * 1000.f;
3507 SkScalar translateY = random->nextSScalar1() * 1000.f;
3508 SkScalar scale;
3509 do {
3510 scale = random->nextSScalar1() * 100.f;
3511 } while (scale == 0);
3512 SkMatrix viewMatrix;
3513 viewMatrix.setRotate(rotate);
3514 viewMatrix.postTranslate(translateX, translateY);
3515 viewMatrix.postScale(scale, scale);
3516 SkRect circle = GrTest::TestSquare(random);
3517 SkPoint center = {circle.centerX(), circle.centerY()};
3518 SkScalar radius = circle.width() / 2.f;
3519 SkScalar strokeWidth = random->nextRangeScalar(0.001f * radius, 1.8f * radius);
3520 SkScalar onAngle = random->nextRangeScalar(0.01f, 1000.f);
3521 SkScalar offAngle = random->nextRangeScalar(0.01f, 1000.f);
3522 SkScalar startAngle = random->nextRangeScalar(-1000.f, 1000.f);
3523 SkScalar phase = random->nextRangeScalar(-1000.f, 1000.f);
3524 return ButtCapDashedCircleOp::Make(context, std::move(paint), viewMatrix,
3525 center, radius, strokeWidth,
3526 startAngle, onAngle, offAngle, phase);
3527 }
3528
3529 GR_DRAW_OP_TEST_DEFINE(EllipseOp) {
3530 SkMatrix viewMatrix = GrTest::TestMatrixRectStaysRect(random);
3531 SkRect ellipse = GrTest::TestSquare(random);
3532 return EllipseOp::Make(context, std::move(paint), viewMatrix, ellipse,
3533 GrTest::TestStrokeRec(random));
3534 }
3535
3536 GR_DRAW_OP_TEST_DEFINE(DIEllipseOp) {
3537 SkMatrix viewMatrix = GrTest::TestMatrix(random);
3538 SkRect ellipse = GrTest::TestSquare(random);
3539 return DIEllipseOp::Make(context, std::move(paint), viewMatrix, ellipse,
3540 GrTest::TestStrokeRec(random));
3541 }
3542
3543 GR_DRAW_OP_TEST_DEFINE(CircularRRectOp) {
3544 do {
3545 SkScalar rotate = random->nextSScalar1() * 360.f;
3546 SkScalar translateX = random->nextSScalar1() * 1000.f;
3547 SkScalar translateY = random->nextSScalar1() * 1000.f;
3548 SkScalar scale;
3549 do {
3550 scale = random->nextSScalar1() * 100.f;
3551 } while (scale == 0);
3552 SkMatrix viewMatrix;
3553 viewMatrix.setRotate(rotate);
3554 viewMatrix.postTranslate(translateX, translateY);
3555 viewMatrix.postScale(scale, scale);
3556 SkRect rect = GrTest::TestRect(random);
3557 SkScalar radius = random->nextRangeF(0.1f, 10.f);
3558 SkRRect rrect = SkRRect::MakeRectXY(rect, radius, radius);
3559 if (rrect.isOval()) {
3560 continue;
3561 }
3562 GrOp::Owner op =
3563 GrOvalOpFactory::MakeCircularRRectOp(context, std::move(paint), viewMatrix, rrect,
3564 GrTest::TestStrokeRec(random), nullptr);
3565 if (op) {
3566 return op;
3567 }
3568 assert_alive(paint);
3569 } while (true);
3570 }
3571
3572 GR_DRAW_OP_TEST_DEFINE(RRectOp) {
3573 SkMatrix viewMatrix = GrTest::TestMatrixRectStaysRect(random);
3574 const SkRRect& rrect = GrTest::TestRRectSimple(random);
3575 return make_rrect_op(context, std::move(paint), viewMatrix, rrect,
3576 GrTest::TestStrokeRec(random));
3577 }
3578
3579 #endif
3580
3581 #endif // SK_ENABLE_OPTIMIZE_SIZE