1 /*
2 * Copyright 2015 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #include "include/core/SkString.h"
9 #include "src/core/SkGeometry.h"
10 #include "src/core/SkPathPriv.h"
11 #include "src/core/SkTraceEvent.h"
12 #include "src/gpu/GrAuditTrail.h"
13 #include "src/gpu/GrCaps.h"
14 #include "src/gpu/GrDefaultGeoProcFactory.h"
15 #include "src/gpu/GrDrawOpTest.h"
16 #include "src/gpu/GrGeometryProcessor.h"
17 #include "src/gpu/GrOpFlushState.h"
18 #include "src/gpu/GrProcessor.h"
19 #include "src/gpu/GrProgramInfo.h"
20 #include "src/gpu/GrRenderTargetContext.h"
21 #include "src/gpu/GrStyle.h"
22 #include "src/gpu/GrVertexWriter.h"
23 #include "src/gpu/geometry/GrPathUtils.h"
24 #include "src/gpu/geometry/GrShape.h"
25 #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
26 #include "src/gpu/ops/GrAAConvexTessellator.h"
27 #include "src/gpu/ops/GrAALinearizingConvexPathRenderer.h"
28 #include "src/gpu/ops/GrMeshDrawOp.h"
29 #include "src/gpu/ops/GrSimpleMeshDrawOpHelperWithStencil.h"
30
31 static const int DEFAULT_BUFFER_SIZE = 100;
32
33 // The thicker the stroke, the harder it is to produce high-quality results using tessellation. For
34 // the time being, we simply drop back to software rendering above this stroke width.
35 static const SkScalar kMaxStrokeWidth = 20.0;
36
GrAALinearizingConvexPathRenderer()37 GrAALinearizingConvexPathRenderer::GrAALinearizingConvexPathRenderer() {
38 }
39
40 ///////////////////////////////////////////////////////////////////////////////
41
42 GrPathRenderer::CanDrawPath
onCanDrawPath(const CanDrawPathArgs & args) const43 GrAALinearizingConvexPathRenderer::onCanDrawPath(const CanDrawPathArgs& args) const {
44 if (GrAAType::kCoverage != args.fAAType) {
45 return CanDrawPath::kNo;
46 }
47 if (!args.fShape->knownToBeConvex()) {
48 return CanDrawPath::kNo;
49 }
50 if (args.fShape->style().pathEffect()) {
51 return CanDrawPath::kNo;
52 }
53 if (args.fShape->inverseFilled()) {
54 return CanDrawPath::kNo;
55 }
56 if (args.fShape->bounds().width() <= 0 && args.fShape->bounds().height() <= 0) {
57 // Stroked zero length lines should draw, but this PR doesn't handle that case
58 return CanDrawPath::kNo;
59 }
60 const SkStrokeRec& stroke = args.fShape->style().strokeRec();
61
62 if (stroke.getStyle() == SkStrokeRec::kStroke_Style ||
63 stroke.getStyle() == SkStrokeRec::kStrokeAndFill_Style) {
64 if (!args.fViewMatrix->isSimilarity()) {
65 return CanDrawPath::kNo;
66 }
67 SkScalar strokeWidth = args.fViewMatrix->getMaxScale() * stroke.getWidth();
68 if (strokeWidth < 1.0f && stroke.getStyle() == SkStrokeRec::kStroke_Style) {
69 return CanDrawPath::kNo;
70 }
71 if (strokeWidth > kMaxStrokeWidth ||
72 !args.fShape->knownToBeClosed() ||
73 stroke.getJoin() == SkPaint::Join::kRound_Join) {
74 return CanDrawPath::kNo;
75 }
76 return CanDrawPath::kYes;
77 }
78 if (stroke.getStyle() != SkStrokeRec::kFill_Style) {
79 return CanDrawPath::kNo;
80 }
81 return CanDrawPath::kYes;
82 }
83
84 // extract the result vertices and indices from the GrAAConvexTessellator
extract_verts(const GrAAConvexTessellator & tess,void * vertData,const GrVertexColor & color,uint16_t firstIndex,uint16_t * idxs)85 static void extract_verts(const GrAAConvexTessellator& tess,
86 void* vertData,
87 const GrVertexColor& color,
88 uint16_t firstIndex,
89 uint16_t* idxs) {
90 GrVertexWriter verts{vertData};
91 for (int i = 0; i < tess.numPts(); ++i) {
92 verts.write(tess.point(i), color, tess.coverage(i));
93 }
94
95 for (int i = 0; i < tess.numIndices(); ++i) {
96 idxs[i] = tess.index(i) + firstIndex;
97 }
98 }
99
create_lines_only_gp(SkArenaAlloc * arena,bool tweakAlphaForCoverage,const SkMatrix & viewMatrix,bool usesLocalCoords,bool wideColor)100 static GrGeometryProcessor* create_lines_only_gp(SkArenaAlloc* arena,
101 bool tweakAlphaForCoverage,
102 const SkMatrix& viewMatrix,
103 bool usesLocalCoords,
104 bool wideColor) {
105 using namespace GrDefaultGeoProcFactory;
106
107 Coverage::Type coverageType =
108 tweakAlphaForCoverage ? Coverage::kAttributeTweakAlpha_Type : Coverage::kAttribute_Type;
109 LocalCoords::Type localCoordsType =
110 usesLocalCoords ? LocalCoords::kUsePosition_Type : LocalCoords::kUnused_Type;
111 Color::Type colorType =
112 wideColor ? Color::kPremulWideColorAttribute_Type : Color::kPremulGrColorAttribute_Type;
113
114 return MakeForDeviceSpace(arena, colorType, coverageType, localCoordsType, viewMatrix);
115 }
116
117 namespace {
118
119 class AAFlatteningConvexPathOp final : public GrMeshDrawOp {
120 private:
121 using Helper = GrSimpleMeshDrawOpHelperWithStencil;
122
123 public:
124 DEFINE_OP_CLASS_ID
Make(GrRecordingContext * context,GrPaint && paint,const SkMatrix & viewMatrix,const SkPath & path,SkScalar strokeWidth,SkStrokeRec::Style style,SkPaint::Join join,SkScalar miterLimit,const GrUserStencilSettings * stencilSettings)125 static std::unique_ptr<GrDrawOp> Make(GrRecordingContext* context,
126 GrPaint&& paint,
127 const SkMatrix& viewMatrix,
128 const SkPath& path,
129 SkScalar strokeWidth,
130 SkStrokeRec::Style style,
131 SkPaint::Join join,
132 SkScalar miterLimit,
133 const GrUserStencilSettings* stencilSettings) {
134 return Helper::FactoryHelper<AAFlatteningConvexPathOp>(context, std::move(paint),
135 viewMatrix, path,
136 strokeWidth, style, join, miterLimit,
137 stencilSettings);
138 }
139
AAFlatteningConvexPathOp(const Helper::MakeArgs & helperArgs,const SkPMColor4f & color,const SkMatrix & viewMatrix,const SkPath & path,SkScalar strokeWidth,SkStrokeRec::Style style,SkPaint::Join join,SkScalar miterLimit,const GrUserStencilSettings * stencilSettings)140 AAFlatteningConvexPathOp(const Helper::MakeArgs& helperArgs,
141 const SkPMColor4f& color,
142 const SkMatrix& viewMatrix,
143 const SkPath& path,
144 SkScalar strokeWidth,
145 SkStrokeRec::Style style,
146 SkPaint::Join join,
147 SkScalar miterLimit,
148 const GrUserStencilSettings* stencilSettings)
149 : INHERITED(ClassID())
150 , fHelper(helperArgs, GrAAType::kCoverage, stencilSettings)
151 , fViewMatrix(viewMatrix) {
152 fPaths.emplace_back(PathData{color, path, strokeWidth, style, join, miterLimit});
153
154 // compute bounds
155 SkRect bounds = path.getBounds();
156 SkScalar w = strokeWidth;
157 if (w > 0) {
158 w /= 2;
159 SkScalar maxScale = viewMatrix.getMaxScale();
160 // We should not have a perspective matrix, thus we should have a valid scale.
161 SkASSERT(maxScale != -1);
162 if (SkPaint::kMiter_Join == join && w * maxScale > 1.f) {
163 w *= miterLimit;
164 }
165 bounds.outset(w, w);
166 }
167 this->setTransformedBounds(bounds, viewMatrix, HasAABloat::kYes, IsHairline::kNo);
168 }
169
name() const170 const char* name() const override { return "AAFlatteningConvexPathOp"; }
171
visitProxies(const VisitProxyFunc & func) const172 void visitProxies(const VisitProxyFunc& func) const override {
173 if (fProgramInfo) {
174 fProgramInfo->visitFPProxies(func);
175 } else {
176 fHelper.visitProxies(func);
177 }
178 }
179
180 #ifdef SK_DEBUG
dumpInfo() const181 SkString dumpInfo() const override {
182 SkString string;
183 for (const auto& path : fPaths) {
184 string.appendf(
185 "Color: 0x%08x, StrokeWidth: %.2f, Style: %d, Join: %d, "
186 "MiterLimit: %.2f\n",
187 path.fColor.toBytes_RGBA(), path.fStrokeWidth, path.fStyle, path.fJoin,
188 path.fMiterLimit);
189 }
190 string += fHelper.dumpInfo();
191 string += INHERITED::dumpInfo();
192 return string;
193 }
194 #endif
195
fixedFunctionFlags() const196 FixedFunctionFlags fixedFunctionFlags() const override { return fHelper.fixedFunctionFlags(); }
197
finalize(const GrCaps & caps,const GrAppliedClip * clip,bool hasMixedSampledCoverage,GrClampType clampType)198 GrProcessorSet::Analysis finalize(
199 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
200 GrClampType clampType) override {
201 return fHelper.finalizeProcessors(
202 caps, clip, hasMixedSampledCoverage, clampType,
203 GrProcessorAnalysisCoverage::kSingleChannel, &fPaths.back().fColor, &fWideColor);
204 }
205
206 private:
programInfo()207 GrProgramInfo* programInfo() override { return fProgramInfo; }
208
onCreateProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView * outputView,GrAppliedClip && appliedClip,const GrXferProcessor::DstProxyView & dstProxyView)209 void onCreateProgramInfo(const GrCaps* caps,
210 SkArenaAlloc* arena,
211 const GrSurfaceProxyView* outputView,
212 GrAppliedClip&& appliedClip,
213 const GrXferProcessor::DstProxyView& dstProxyView) override {
214 GrGeometryProcessor* gp = create_lines_only_gp(arena,
215 fHelper.compatibleWithCoverageAsAlpha(),
216 fViewMatrix,
217 fHelper.usesLocalCoords(),
218 fWideColor);
219 if (!gp) {
220 SkDebugf("Couldn't create a GrGeometryProcessor\n");
221 return;
222 }
223
224 fProgramInfo = fHelper.createProgramInfoWithStencil(caps, arena, outputView,
225 std::move(appliedClip), dstProxyView,
226 gp, GrPrimitiveType::kTriangles);
227 }
228
recordDraw(Target * target,int vertexCount,size_t vertexStride,void * vertices,int indexCount,uint16_t * indices)229 void recordDraw(Target* target,
230 int vertexCount, size_t vertexStride, void* vertices,
231 int indexCount, uint16_t* indices) {
232 if (vertexCount == 0 || indexCount == 0) {
233 return;
234 }
235 sk_sp<const GrBuffer> vertexBuffer;
236 int firstVertex;
237 void* verts = target->makeVertexSpace(vertexStride, vertexCount, &vertexBuffer,
238 &firstVertex);
239 if (!verts) {
240 SkDebugf("Could not allocate vertices\n");
241 return;
242 }
243 memcpy(verts, vertices, vertexCount * vertexStride);
244
245 sk_sp<const GrBuffer> indexBuffer;
246 int firstIndex;
247 uint16_t* idxs = target->makeIndexSpace(indexCount, &indexBuffer, &firstIndex);
248 if (!idxs) {
249 SkDebugf("Could not allocate indices\n");
250 return;
251 }
252 memcpy(idxs, indices, indexCount * sizeof(uint16_t));
253 GrSimpleMesh* mesh = target->allocMesh();
254 mesh->setIndexed(std::move(indexBuffer), indexCount, firstIndex, 0, vertexCount - 1,
255 GrPrimitiveRestart::kNo, std::move(vertexBuffer), firstVertex);
256 fMeshes.push_back(mesh);
257 }
258
onPrepareDraws(Target * target)259 void onPrepareDraws(Target* target) override {
260 if (!fProgramInfo) {
261 this->createProgramInfo(target);
262 if (!fProgramInfo) {
263 return;
264 }
265 }
266
267 size_t vertexStride = fProgramInfo->primProc().vertexStride();
268 int instanceCount = fPaths.count();
269
270 int64_t vertexCount = 0;
271 int64_t indexCount = 0;
272 int64_t maxVertices = DEFAULT_BUFFER_SIZE;
273 int64_t maxIndices = DEFAULT_BUFFER_SIZE;
274 uint8_t* vertices = (uint8_t*) sk_malloc_throw(maxVertices * vertexStride);
275 uint16_t* indices = (uint16_t*) sk_malloc_throw(maxIndices * sizeof(uint16_t));
276 for (int i = 0; i < instanceCount; i++) {
277 const PathData& args = fPaths[i];
278 GrAAConvexTessellator tess(args.fStyle, args.fStrokeWidth,
279 args.fJoin, args.fMiterLimit);
280
281 if (!tess.tessellate(fViewMatrix, args.fPath)) {
282 continue;
283 }
284
285 int currentVertices = tess.numPts();
286 if (vertexCount + currentVertices > static_cast<int>(UINT16_MAX)) {
287 // if we added the current instance, we would overflow the indices we can store in a
288 // uint16_t. Draw what we've got so far and reset.
289 this->recordDraw(target, vertexCount, vertexStride, vertices, indexCount, indices);
290 vertexCount = 0;
291 indexCount = 0;
292 }
293 if (vertexCount + currentVertices > maxVertices) {
294 maxVertices = std::max(vertexCount + currentVertices, maxVertices * 2);
295 if (maxVertices * vertexStride > SK_MaxS32) {
296 sk_free(vertices);
297 sk_free(indices);
298 return;
299 }
300 vertices = (uint8_t*) sk_realloc_throw(vertices, maxVertices * vertexStride);
301 }
302 int currentIndices = tess.numIndices();
303 if (indexCount + currentIndices > maxIndices) {
304 maxIndices = std::max(indexCount + currentIndices, maxIndices * 2);
305 if (maxIndices * sizeof(uint16_t) > SK_MaxS32) {
306 sk_free(vertices);
307 sk_free(indices);
308 return;
309 }
310 indices = (uint16_t*) sk_realloc_throw(indices, maxIndices * sizeof(uint16_t));
311 }
312
313 extract_verts(tess, vertices + vertexStride * vertexCount,
314 GrVertexColor(args.fColor, fWideColor), vertexCount,
315 indices + indexCount);
316 vertexCount += currentVertices;
317 indexCount += currentIndices;
318 }
319 if (vertexCount <= SK_MaxS32 && indexCount <= SK_MaxS32) {
320 this->recordDraw(target, vertexCount, vertexStride, vertices, indexCount, indices);
321 }
322 sk_free(vertices);
323 sk_free(indices);
324 }
325
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)326 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) override {
327 if (!fProgramInfo || fMeshes.isEmpty()) {
328 return;
329 }
330
331 flushState->bindPipelineAndScissorClip(*fProgramInfo, chainBounds);
332 flushState->bindTextures(fProgramInfo->primProc(), nullptr, fProgramInfo->pipeline());
333 for (int i = 0; i < fMeshes.count(); ++i) {
334 flushState->drawMesh(*fMeshes[i]);
335 }
336 }
337
onCombineIfPossible(GrOp * t,GrRecordingContext::Arenas *,const GrCaps & caps)338 CombineResult onCombineIfPossible(GrOp* t, GrRecordingContext::Arenas*,
339 const GrCaps& caps) override {
340 AAFlatteningConvexPathOp* that = t->cast<AAFlatteningConvexPathOp>();
341 if (!fHelper.isCompatible(that->fHelper, caps, this->bounds(), that->bounds())) {
342 return CombineResult::kCannotCombine;
343 }
344 if (fViewMatrix != that->fViewMatrix) {
345 return CombineResult::kCannotCombine;
346 }
347
348 fPaths.push_back_n(that->fPaths.count(), that->fPaths.begin());
349 fWideColor |= that->fWideColor;
350 return CombineResult::kMerged;
351 }
352
353
354 struct PathData {
355 SkPMColor4f fColor;
356 SkPath fPath;
357 SkScalar fStrokeWidth;
358 SkStrokeRec::Style fStyle;
359 SkPaint::Join fJoin;
360 SkScalar fMiterLimit;
361 };
362
363 SkSTArray<1, PathData, true> fPaths;
364 Helper fHelper;
365 SkMatrix fViewMatrix;
366 bool fWideColor;
367
368 SkTDArray<GrSimpleMesh*> fMeshes;
369 GrProgramInfo* fProgramInfo = nullptr;
370
371 typedef GrMeshDrawOp INHERITED;
372 };
373
374 } // anonymous namespace
375
onDrawPath(const DrawPathArgs & args)376 bool GrAALinearizingConvexPathRenderer::onDrawPath(const DrawPathArgs& args) {
377 GR_AUDIT_TRAIL_AUTO_FRAME(args.fRenderTargetContext->auditTrail(),
378 "GrAALinearizingConvexPathRenderer::onDrawPath");
379 SkASSERT(args.fRenderTargetContext->numSamples() <= 1);
380 SkASSERT(!args.fShape->isEmpty());
381 SkASSERT(!args.fShape->style().pathEffect());
382
383 SkPath path;
384 args.fShape->asPath(&path);
385 bool fill = args.fShape->style().isSimpleFill();
386 const SkStrokeRec& stroke = args.fShape->style().strokeRec();
387 SkScalar strokeWidth = fill ? -1.0f : stroke.getWidth();
388 SkPaint::Join join = fill ? SkPaint::Join::kMiter_Join : stroke.getJoin();
389 SkScalar miterLimit = stroke.getMiter();
390
391 std::unique_ptr<GrDrawOp> op = AAFlatteningConvexPathOp::Make(
392 args.fContext, std::move(args.fPaint), *args.fViewMatrix, path, strokeWidth,
393 stroke.getStyle(), join, miterLimit, args.fUserStencilSettings);
394 args.fRenderTargetContext->addDrawOp(*args.fClip, std::move(op));
395 return true;
396 }
397
398 ///////////////////////////////////////////////////////////////////////////////////////////////////
399
400 #if GR_TEST_UTILS
401
GR_DRAW_OP_TEST_DEFINE(AAFlatteningConvexPathOp)402 GR_DRAW_OP_TEST_DEFINE(AAFlatteningConvexPathOp) {
403 SkMatrix viewMatrix = GrTest::TestMatrixPreservesRightAngles(random);
404 SkPath path = GrTest::TestPathConvex(random);
405
406 SkStrokeRec::Style styles[3] = { SkStrokeRec::kFill_Style,
407 SkStrokeRec::kStroke_Style,
408 SkStrokeRec::kStrokeAndFill_Style };
409
410 SkStrokeRec::Style style = styles[random->nextU() % 3];
411
412 SkScalar strokeWidth = -1.f;
413 SkPaint::Join join = SkPaint::kMiter_Join;
414 SkScalar miterLimit = 0.5f;
415
416 if (SkStrokeRec::kFill_Style != style) {
417 strokeWidth = random->nextRangeF(1.0f, 10.0f);
418 if (random->nextBool()) {
419 join = SkPaint::kMiter_Join;
420 } else {
421 join = SkPaint::kBevel_Join;
422 }
423 miterLimit = random->nextRangeF(0.5f, 2.0f);
424 }
425 const GrUserStencilSettings* stencilSettings = GrGetRandomStencil(random, context);
426 return AAFlatteningConvexPathOp::Make(context, std::move(paint), viewMatrix, path, strokeWidth,
427 style, join, miterLimit, stencilSettings);
428 }
429
430 #endif
431