1 /*
2 * Copyright 2017 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/SkTypes.h"
9
10 #if SK_SUPPORT_GPU
11
12 #include "include/core/SkCanvas.h"
13 #include "include/core/SkPaint.h"
14 #include "include/core/SkPath.h"
15 #include "samplecode/Sample.h"
16 #include "src/core/SkRectPriv.h"
17 #include "src/gpu/GrClip.h"
18 #include "src/gpu/GrContextPriv.h"
19 #include "src/gpu/GrGpu.h"
20 #include "src/gpu/GrMemoryPool.h"
21 #include "src/gpu/GrRenderTargetContext.h"
22 #include "src/gpu/GrRenderTargetContextPriv.h"
23 #include "src/gpu/GrResourceProvider.h"
24 #include "src/gpu/ccpr/GrCCCoverageProcessor.h"
25 #include "src/gpu/ccpr/GrCCFillGeometry.h"
26 #include "src/gpu/ccpr/GrCCStroker.h"
27 #include "src/gpu/ccpr/GrGSCoverageProcessor.h"
28 #include "src/gpu/ccpr/GrVSCoverageProcessor.h"
29 #include "src/gpu/geometry/GrPathUtils.h"
30 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
31 #include "src/gpu/ops/GrDrawOp.h"
32
33 #ifdef SK_GL
34 #include "src/gpu/gl/GrGLGpu.h"
35 #endif
36
37 using TriPointInstance = GrCCCoverageProcessor::TriPointInstance;
38 using QuadPointInstance = GrCCCoverageProcessor::QuadPointInstance;
39 using PrimitiveType = GrCCCoverageProcessor::PrimitiveType;
40
41 static constexpr float kDebugBloat = 40;
42
43 /**
44 * This sample visualizes the AA bloat geometry generated by the ccpr geometry shaders. It
45 * increases the AA bloat by 50x and outputs color instead of coverage (coverage=+1 -> green,
46 * coverage=0 -> black, coverage=-1 -> red). Use the keys 1-7 to cycle through the different
47 * geometry processors.
48 */
49 class CCPRGeometryView : public Sample {
onOnceBeforeDraw()50 void onOnceBeforeDraw() override { this->updateGpuData(); }
51 void onDrawContent(SkCanvas*) override;
52
53 Sample::Click* onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey) override;
54 bool onClick(Sample::Click*) override;
55 bool onChar(SkUnichar) override;
name()56 SkString name() override { return SkString("CCPRGeometry"); }
57
58 class Click;
59 class DrawCoverageCountOp;
60 class VisualizeCoverageCountFP;
61
updateAndInval()62 void updateAndInval() { this->updateGpuData(); }
63
64 void updateGpuData();
65
66 PrimitiveType fPrimitiveType = PrimitiveType::kTriangles;
67 SkCubicType fCubicType;
68 SkMatrix fCubicKLM;
69
70 SkPoint fPoints[4] = {
71 {100.05f, 100.05f}, {400.75f, 100.05f}, {400.75f, 300.95f}, {100.05f, 300.95f}};
72
73 float fConicWeight = .5;
74 float fStrokeWidth = 40;
75 bool fDoStroke = false;
76
77 SkTArray<TriPointInstance> fTriPointInstances;
78 SkTArray<QuadPointInstance> fQuadPointInstances;
79 SkPath fPath;
80 };
81
82 class CCPRGeometryView::DrawCoverageCountOp : public GrDrawOp {
83 DEFINE_OP_CLASS_ID
84
85 public:
DrawCoverageCountOp(CCPRGeometryView * view)86 DrawCoverageCountOp(CCPRGeometryView* view) : INHERITED(ClassID()), fView(view) {
87 this->setBounds(SkRect::MakeIWH(fView->width(), fView->height()), GrOp::HasAABloat::kNo,
88 GrOp::IsHairline::kNo);
89 }
90
name() const91 const char* name() const override {
92 return "[Testing/Sample code] CCPRGeometryView::DrawCoverageCountOp";
93 }
94
95 private:
fixedFunctionFlags() const96 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
finalize(const GrCaps &,const GrAppliedClip *,bool hasMixedSampledCoverage,GrClampType)97 GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*,
98 bool hasMixedSampledCoverage, GrClampType) override {
99 return GrProcessorSet::EmptySetAnalysis();
100 }
onPrePrepare(GrRecordingContext *,const GrSurfaceProxyView * outputView,GrAppliedClip *,const GrXferProcessor::DstProxyView &)101 void onPrePrepare(GrRecordingContext*,
102 const GrSurfaceProxyView* outputView,
103 GrAppliedClip*,
104 const GrXferProcessor::DstProxyView&) override {}
onPrepare(GrOpFlushState *)105 void onPrepare(GrOpFlushState*) override {}
106 void onExecute(GrOpFlushState*, const SkRect& chainBounds) override;
107
108 CCPRGeometryView* fView;
109
110 typedef GrDrawOp INHERITED;
111 };
112
113 class CCPRGeometryView::VisualizeCoverageCountFP : public GrFragmentProcessor {
114 public:
VisualizeCoverageCountFP()115 VisualizeCoverageCountFP() : GrFragmentProcessor(kTestFP_ClassID, kNone_OptimizationFlags) {}
116
117 private:
name() const118 const char* name() const override {
119 return "[Testing/Sample code] CCPRGeometryView::VisualizeCoverageCountFP";
120 }
clone() const121 std::unique_ptr<GrFragmentProcessor> clone() const override {
122 return std::make_unique<VisualizeCoverageCountFP>();
123 }
onGetGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder *) const124 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder*) const override {}
onIsEqual(const GrFragmentProcessor &) const125 bool onIsEqual(const GrFragmentProcessor&) const override { return true; }
126
127 class Impl : public GrGLSLFragmentProcessor {
emitCode(EmitArgs & args)128 void emitCode(EmitArgs& args) override {
129 GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
130 f->codeAppendf("half count = %s.a;", args.fInputColor);
131 f->codeAppendf("%s = half4(clamp(-count, 0, 1), clamp(+count, 0, 1), 0, abs(count));",
132 args.fOutputColor);
133 }
134 };
135
onCreateGLSLInstance() const136 GrGLSLFragmentProcessor* onCreateGLSLInstance() const override { return new Impl; }
137 };
138
draw_klm_line(int w,int h,SkCanvas * canvas,const SkScalar line[3],SkColor color)139 static void draw_klm_line(int w, int h, SkCanvas* canvas, const SkScalar line[3], SkColor color) {
140 SkPoint p1, p2;
141 if (SkScalarAbs(line[1]) > SkScalarAbs(line[0])) {
142 // Draw from vertical edge to vertical edge.
143 p1 = {0, -line[2] / line[1]};
144 p2 = {(SkScalar)w, (-line[2] - w * line[0]) / line[1]};
145 } else {
146 // Draw from horizontal edge to horizontal edge.
147 p1 = {-line[2] / line[0], 0};
148 p2 = {(-line[2] - h * line[1]) / line[0], (SkScalar)h};
149 }
150
151 SkPaint linePaint;
152 linePaint.setColor(color);
153 linePaint.setAlpha(128);
154 linePaint.setStyle(SkPaint::kStroke_Style);
155 linePaint.setStrokeWidth(0);
156 linePaint.setAntiAlias(true);
157 canvas->drawLine(p1, p2, linePaint);
158 }
159
onDrawContent(SkCanvas * canvas)160 void CCPRGeometryView::onDrawContent(SkCanvas* canvas) {
161 canvas->clear(SK_ColorBLACK);
162
163 if (!fDoStroke) {
164 SkPaint outlinePaint;
165 outlinePaint.setColor(0x80ffffff);
166 outlinePaint.setStyle(SkPaint::kStroke_Style);
167 outlinePaint.setStrokeWidth(0);
168 outlinePaint.setAntiAlias(true);
169 canvas->drawPath(fPath, outlinePaint);
170 }
171
172 #if 0
173 SkPaint gridPaint;
174 gridPaint.setColor(0x10000000);
175 gridPaint.setStyle(SkPaint::kStroke_Style);
176 gridPaint.setStrokeWidth(0);
177 gridPaint.setAntiAlias(true);
178 for (int y = 0; y < this->height(); y += kDebugBloat) {
179 canvas->drawLine(0, y, this->width(), y, gridPaint);
180 }
181 for (int x = 0; x < this->width(); x += kDebugBloat) {
182 canvas->drawLine(x, 0, x, this->height(), outlinePaint);
183 }
184 #endif
185
186 SkString caption;
187 if (GrRenderTargetContext* rtc = canvas->internal_private_accessTopLayerRenderTargetContext()) {
188 // Render coverage count.
189 GrContext* ctx = canvas->getGrContext();
190 SkASSERT(ctx);
191
192 GrOpMemoryPool* pool = ctx->priv().opMemoryPool();
193
194 int width = this->width();
195 int height = this->height();
196 auto ccbuff = GrRenderTargetContext::Make(
197 ctx, GrColorType::kAlpha_F16, nullptr, SkBackingFit::kApprox, {width, height});
198 SkASSERT(ccbuff);
199 ccbuff->clear(nullptr, SK_PMColor4fTRANSPARENT,
200 GrRenderTargetContext::CanClearFullscreen::kYes);
201 ccbuff->priv().testingOnly_addDrawOp(pool->allocate<DrawCoverageCountOp>(this));
202
203 // Visualize coverage count in main canvas.
204 GrPaint paint;
205 paint.addColorFragmentProcessor(
206 GrTextureEffect::Make(ccbuff->readSurfaceView(), ccbuff->colorInfo().alphaType()));
207 paint.addColorFragmentProcessor(
208 std::make_unique<VisualizeCoverageCountFP>());
209 paint.setPorterDuffXPFactory(SkBlendMode::kSrcOver);
210 rtc->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(),
211 SkRect::MakeIWH(this->width(), this->height()));
212
213 // Add label.
214 caption.appendf("PrimitiveType_%s",
215 GrCCCoverageProcessor::PrimitiveTypeName(fPrimitiveType));
216 if (PrimitiveType::kCubics == fPrimitiveType) {
217 caption.appendf(" (%s)", SkCubicTypeName(fCubicType));
218 } else if (PrimitiveType::kConics == fPrimitiveType) {
219 caption.appendf(" (w=%f)", fConicWeight);
220 }
221 if (fDoStroke) {
222 caption.appendf(" (stroke_width=%f)", fStrokeWidth);
223 }
224 } else {
225 caption = "Use GPU backend to visualize geometry.";
226 }
227
228 SkPaint pointsPaint;
229 pointsPaint.setColor(SK_ColorBLUE);
230 pointsPaint.setStrokeWidth(8);
231 pointsPaint.setAntiAlias(true);
232
233 if (PrimitiveType::kCubics == fPrimitiveType) {
234 canvas->drawPoints(SkCanvas::kPoints_PointMode, 4, fPoints, pointsPaint);
235 if (!fDoStroke) {
236 int w = this->width(), h = this->height();
237 draw_klm_line(w, h, canvas, &fCubicKLM[0], SK_ColorYELLOW);
238 draw_klm_line(w, h, canvas, &fCubicKLM[3], SK_ColorBLUE);
239 draw_klm_line(w, h, canvas, &fCubicKLM[6], SK_ColorRED);
240 }
241 } else {
242 canvas->drawPoints(SkCanvas::kPoints_PointMode, 2, fPoints, pointsPaint);
243 canvas->drawPoints(SkCanvas::kPoints_PointMode, 1, fPoints + 3, pointsPaint);
244 }
245
246 SkFont font(nullptr, 20);
247 SkPaint captionPaint;
248 captionPaint.setColor(SK_ColorWHITE);
249 canvas->drawString(caption, 10, 30, font, captionPaint);
250 }
251
updateGpuData()252 void CCPRGeometryView::updateGpuData() {
253 using Verb = GrCCFillGeometry::Verb;
254 fTriPointInstances.reset();
255 fQuadPointInstances.reset();
256
257 fPath.reset();
258 fPath.moveTo(fPoints[0]);
259
260 if (PrimitiveType::kCubics == fPrimitiveType) {
261 double t[2], s[2];
262 fCubicType = GrPathUtils::getCubicKLM(fPoints, &fCubicKLM, t, s);
263 GrCCFillGeometry geometry;
264 geometry.beginContour(fPoints[0]);
265 geometry.cubicTo(fPoints, kDebugBloat / 2, kDebugBloat / 2);
266 geometry.endContour();
267 int ptsIdx = 0;
268 for (Verb verb : geometry.verbs()) {
269 switch (verb) {
270 case Verb::kLineTo:
271 ++ptsIdx;
272 continue;
273 case Verb::kMonotonicQuadraticTo:
274 ptsIdx += 2;
275 continue;
276 case Verb::kMonotonicCubicTo:
277 fQuadPointInstances.push_back().set(&geometry.points()[ptsIdx], 0, 0);
278 ptsIdx += 3;
279 continue;
280 default:
281 continue;
282 }
283 }
284 fPath.cubicTo(fPoints[1], fPoints[2], fPoints[3]);
285 } else if (PrimitiveType::kTriangles != fPrimitiveType) {
286 SkPoint P3[3] = {fPoints[0], fPoints[1], fPoints[3]};
287 GrCCFillGeometry geometry;
288 geometry.beginContour(P3[0]);
289 if (PrimitiveType::kQuadratics == fPrimitiveType) {
290 geometry.quadraticTo(P3);
291 fPath.quadTo(fPoints[1], fPoints[3]);
292 } else {
293 SkASSERT(PrimitiveType::kConics == fPrimitiveType);
294 geometry.conicTo(P3, fConicWeight);
295 fPath.conicTo(fPoints[1], fPoints[3], fConicWeight);
296 }
297 geometry.endContour();
298 int ptsIdx = 0, conicWeightIdx = 0;
299 for (Verb verb : geometry.verbs()) {
300 if (Verb::kBeginContour == verb ||
301 Verb::kEndOpenContour == verb ||
302 Verb::kEndClosedContour == verb) {
303 continue;
304 }
305 if (Verb::kLineTo == verb) {
306 ++ptsIdx;
307 continue;
308 }
309 SkASSERT(Verb::kMonotonicQuadraticTo == verb || Verb::kMonotonicConicTo == verb);
310 if (PrimitiveType::kQuadratics == fPrimitiveType &&
311 Verb::kMonotonicQuadraticTo == verb) {
312 fTriPointInstances.push_back().set(
313 &geometry.points()[ptsIdx], Sk2f(0, 0),
314 TriPointInstance::Ordering::kXYTransposed);
315 } else if (PrimitiveType::kConics == fPrimitiveType &&
316 Verb::kMonotonicConicTo == verb) {
317 fQuadPointInstances.push_back().setW(&geometry.points()[ptsIdx], Sk2f(0, 0),
318 geometry.getConicWeight(conicWeightIdx++));
319 }
320 ptsIdx += 2;
321 }
322 } else {
323 fTriPointInstances.push_back().set(
324 fPoints[0], fPoints[1], fPoints[3], Sk2f(0, 0),
325 TriPointInstance::Ordering::kXYTransposed);
326 fPath.lineTo(fPoints[1]);
327 fPath.lineTo(fPoints[3]);
328 fPath.close();
329 }
330 }
331
onExecute(GrOpFlushState * state,const SkRect & chainBounds)332 void CCPRGeometryView::DrawCoverageCountOp::onExecute(GrOpFlushState* state,
333 const SkRect& chainBounds) {
334 GrResourceProvider* rp = state->resourceProvider();
335 GrContext* context = state->gpu()->getContext();
336 #ifdef SK_GL
337 GrGLGpu* glGpu = GrBackendApi::kOpenGL == context->backend()
338 ? static_cast<GrGLGpu*>(state->gpu())
339 : nullptr;
340 if (glGpu) {
341 glGpu->handleDirtyContext();
342 // GR_GL_CALL(glGpu->glInterface(), PolygonMode(GR_GL_FRONT_AND_BACK, GR_GL_LINE));
343 GR_GL_CALL(glGpu->glInterface(), Enable(GR_GL_LINE_SMOOTH));
344 }
345 #endif
346
347 GrPipeline pipeline(GrScissorTest::kDisabled, SkBlendMode::kPlus,
348 state->drawOpArgs().writeSwizzle());
349
350 std::unique_ptr<GrCCCoverageProcessor> proc;
351 if (state->caps().shaderCaps()->geometryShaderSupport()) {
352 proc = std::make_unique<GrGSCoverageProcessor>();
353 } else {
354 proc = std::make_unique<GrVSCoverageProcessor>();
355 }
356 SkDEBUGCODE(proc->enableDebugBloat(kDebugBloat));
357
358 GrOpsRenderPass* renderPass = state->opsRenderPass();
359
360 if (!fView->fDoStroke) {
361 for (int i = 0; i < proc->numSubpasses(); ++i) {
362 proc->reset(fView->fPrimitiveType, i, rp);
363 proc->bindPipeline(state, pipeline, this->bounds());
364
365 if (PrimitiveType::kCubics == fView->fPrimitiveType ||
366 PrimitiveType::kConics == fView->fPrimitiveType) {
367 sk_sp<GrGpuBuffer> instBuff(rp->createBuffer(
368 fView->fQuadPointInstances.count() * sizeof(QuadPointInstance),
369 GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
370 fView->fQuadPointInstances.begin()));
371 if (!fView->fQuadPointInstances.empty() && instBuff) {
372 proc->bindBuffers(renderPass, instBuff.get());
373 proc->drawInstances(renderPass, fView->fQuadPointInstances.count(), 0);
374 }
375 } else {
376 sk_sp<GrGpuBuffer> instBuff(rp->createBuffer(
377 fView->fTriPointInstances.count() * sizeof(TriPointInstance),
378 GrGpuBufferType::kVertex, kDynamic_GrAccessPattern,
379 fView->fTriPointInstances.begin()));
380 if (!fView->fTriPointInstances.empty() && instBuff) {
381 proc->bindBuffers(renderPass, instBuff.get());
382 proc->drawInstances(renderPass, fView->fTriPointInstances.count(), 0);
383 }
384 }
385 }
386 } else if (PrimitiveType::kConics != fView->fPrimitiveType) { // No conic stroke support yet.
387 GrCCStroker stroker(0,0,0);
388
389 SkPaint p;
390 p.setStyle(SkPaint::kStroke_Style);
391 p.setStrokeWidth(fView->fStrokeWidth);
392 p.setStrokeJoin(SkPaint::kMiter_Join);
393 p.setStrokeMiter(4);
394 // p.setStrokeCap(SkPaint::kRound_Cap);
395 stroker.parseDeviceSpaceStroke(fView->fPath, SkPathPriv::PointData(fView->fPath),
396 SkStrokeRec(p), p.getStrokeWidth(), GrScissorTest::kDisabled,
397 SkIRect::MakeWH(fView->width(), fView->height()), {0, 0});
398 GrCCStroker::BatchID batchID = stroker.closeCurrentBatch();
399
400 GrOnFlushResourceProvider onFlushRP(context->priv().drawingManager());
401 stroker.prepareToDraw(&onFlushRP);
402
403 SkIRect ibounds;
404 this->bounds().roundOut(&ibounds);
405 stroker.drawStrokes(state, proc.get(), batchID, ibounds);
406 }
407
408 #ifdef SK_GL
409 if (glGpu) {
410 context->resetContext(kMisc_GrGLBackendState);
411 }
412 #endif
413 }
414
415 class CCPRGeometryView::Click : public Sample::Click {
416 public:
Click(int ptIdx)417 Click(int ptIdx) : fPtIdx(ptIdx) {}
418
doClick(SkPoint points[])419 void doClick(SkPoint points[]) {
420 if (fPtIdx >= 0) {
421 points[fPtIdx] += fCurr - fPrev;
422 } else {
423 for (int i = 0; i < 4; ++i) {
424 points[i] += fCurr - fPrev;
425 }
426 }
427 }
428
429 private:
430 int fPtIdx;
431 };
432
onFindClickHandler(SkScalar x,SkScalar y,skui::ModifierKey)433 Sample::Click* CCPRGeometryView::onFindClickHandler(SkScalar x, SkScalar y, skui::ModifierKey) {
434 for (int i = 0; i < 4; ++i) {
435 if (PrimitiveType::kCubics != fPrimitiveType && 2 == i) {
436 continue;
437 }
438 if (fabs(x - fPoints[i].x()) < 20 && fabsf(y - fPoints[i].y()) < 20) {
439 return new Click(i);
440 }
441 }
442 return new Click(-1);
443 }
444
onClick(Sample::Click * click)445 bool CCPRGeometryView::onClick(Sample::Click* click) {
446 Click* myClick = (Click*)click;
447 myClick->doClick(fPoints);
448 this->updateAndInval();
449 return true;
450 }
451
onChar(SkUnichar unichar)452 bool CCPRGeometryView::onChar(SkUnichar unichar) {
453 if (unichar >= '1' && unichar <= '4') {
454 fPrimitiveType = PrimitiveType(unichar - '1');
455 if (fPrimitiveType >= PrimitiveType::kWeightedTriangles) {
456 fPrimitiveType = (PrimitiveType) ((int)fPrimitiveType + 1);
457 }
458 this->updateAndInval();
459 return true;
460 }
461 float* valueToScale = nullptr;
462 if (fDoStroke) {
463 valueToScale = &fStrokeWidth;
464 } else if (PrimitiveType::kConics == fPrimitiveType) {
465 valueToScale = &fConicWeight;
466 }
467 if (valueToScale) {
468 if (unichar == '+') {
469 *valueToScale *= 2;
470 this->updateAndInval();
471 return true;
472 }
473 if (unichar == '+' || unichar == '=') {
474 *valueToScale *= 5/4.f;
475 this->updateAndInval();
476 return true;
477 }
478 if (unichar == '-') {
479 *valueToScale *= 4/5.f;
480 this->updateAndInval();
481 return true;
482 }
483 if (unichar == '_') {
484 *valueToScale *= .5f;
485 this->updateAndInval();
486 return true;
487 }
488 }
489 if (unichar == 'D') {
490 SkDebugf(" SkPoint fPoints[4] = {\n");
491 SkDebugf(" {%ff, %ff},\n", fPoints[0].x(), fPoints[0].y());
492 SkDebugf(" {%ff, %ff},\n", fPoints[1].x(), fPoints[1].y());
493 SkDebugf(" {%ff, %ff},\n", fPoints[2].x(), fPoints[2].y());
494 SkDebugf(" {%ff, %ff}\n", fPoints[3].x(), fPoints[3].y());
495 SkDebugf(" };\n");
496 return true;
497 }
498 if (unichar == 'S') {
499 fDoStroke = !fDoStroke;
500 this->updateAndInval();
501 }
502 return false;
503 }
504
505 DEF_SAMPLE(return new CCPRGeometryView;)
506
507 #endif // SK_SUPPORT_GPU
508