1 /*
2 * Copyright 2019 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 "gm/gm.h"
9 #include "include/core/SkBlendMode.h"
10 #include "include/core/SkCanvas.h"
11 #include "include/core/SkColorSpace.h"
12 #include "include/core/SkMatrix.h"
13 #include "include/core/SkRect.h"
14 #include "include/core/SkRefCnt.h"
15 #include "include/core/SkSize.h"
16 #include "include/core/SkString.h"
17 #include "include/core/SkTypes.h"
18 #include "include/gpu/GrContext.h"
19 #include "include/gpu/GrTypes.h"
20 #include "include/private/GrRecordingContext.h"
21 #include "include/private/GrTypesPriv.h"
22 #include "include/private/SkColorData.h"
23 #include "src/gpu/GrBuffer.h"
24 #include "src/gpu/GrCaps.h"
25 #include "src/gpu/GrClip.h"
26 #include "src/gpu/GrColorSpaceXform.h"
27 #include "src/gpu/GrContextPriv.h"
28 #include "src/gpu/GrGeometryProcessor.h"
29 #include "src/gpu/GrMemoryPool.h"
30 #include "src/gpu/GrOpFlushState.h"
31 #include "src/gpu/GrOpsRenderPass.h"
32 #include "src/gpu/GrPaint.h"
33 #include "src/gpu/GrPipeline.h"
34 #include "src/gpu/GrPrimitiveProcessor.h"
35 #include "src/gpu/GrProcessor.h"
36 #include "src/gpu/GrProcessorSet.h"
37 #include "src/gpu/GrRecordingContextPriv.h"
38 #include "src/gpu/GrRenderTargetContext.h"
39 #include "src/gpu/GrRenderTargetContextPriv.h"
40 #include "src/gpu/GrSamplerState.h"
41 #include "src/gpu/GrShaderCaps.h"
42 #include "src/gpu/GrShaderVar.h"
43 #include "src/gpu/GrSurfaceProxy.h"
44 #include "src/gpu/GrTextureProxy.h"
45 #include "src/gpu/GrUserStencilSettings.h"
46 #include "src/gpu/effects/GrPorterDuffXferProcessor.h"
47 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
48 #include "src/gpu/glsl/GrGLSLGeometryProcessor.h"
49 #include "src/gpu/glsl/GrGLSLPrimitiveProcessor.h"
50 #include "src/gpu/glsl/GrGLSLProgramBuilder.h"
51 #include "src/gpu/glsl/GrGLSLVarying.h"
52 #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
53 #include "src/gpu/ops/GrDrawOp.h"
54 #include "src/gpu/ops/GrOp.h"
55 #include "tools/gpu/ProxyUtils.h"
56
57 #include <memory>
58 #include <utility>
59
60 class GrAppliedClip;
61 class GrGLSLProgramDataManager;
62
63 namespace skiagm {
64
65 enum class GradType : bool {
66 kHW,
67 kSW
68 };
69
70 /**
71 * This test ensures that the shaderBuilder's sample offsets and sample mask are correlated with
72 * actual HW sample locations. It does so by drawing pseudo-random subpixel boxes, and only turning
73 * off the samples whose locations fall inside the boxes.
74 */
75 class SampleLocationsGM : public GpuGM {
76 public:
SampleLocationsGM(GradType gradType,GrSurfaceOrigin origin)77 SampleLocationsGM(GradType gradType, GrSurfaceOrigin origin)
78 : fGradType(gradType)
79 , fOrigin(origin) {}
80
81 private:
onShortName()82 SkString onShortName() override {
83 return SkStringPrintf("samplelocations%s%s",
84 (GradType::kHW == fGradType) ? "_hwgrad" : "_swgrad",
85 (kTopLeft_GrSurfaceOrigin == fOrigin) ? "_topleft" : "_botleft");
86 }
87
onISize()88 SkISize onISize() override { return SkISize::Make(200, 200); }
89 DrawResult onDraw(GrContext*, GrRenderTargetContext*, SkCanvas*, SkString* errorMsg) override;
90
91 const GradType fGradType;
92 const GrSurfaceOrigin fOrigin;
93 };
94
95 ////////////////////////////////////////////////////////////////////////////////////////////////////
96 // SkSL code.
97
98 class SampleLocationsTestProcessor : public GrGeometryProcessor {
99 public:
Make(SkArenaAlloc * arena,GradType gradType)100 static GrGeometryProcessor* Make(SkArenaAlloc* arena, GradType gradType) {
101 return arena->make<SampleLocationsTestProcessor>(gradType);
102 }
103
name() const104 const char* name() const override { return "SampleLocationsTestProcessor"; }
105
getGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder * b) const106 void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const final {
107 b->add32((uint32_t)fGradType);
108 }
109
110 GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const final;
111
112 private:
113 friend class ::SkArenaAlloc; // for access to ctor
114
SampleLocationsTestProcessor(GradType gradType)115 SampleLocationsTestProcessor(GradType gradType)
116 : GrGeometryProcessor(kSampleLocationsTestProcessor_ClassID)
117 , fGradType(gradType) {
118 this->setWillUseCustomFeature(CustomFeatures::kSampleLocations);
119 }
120
121 const GradType fGradType;
122
123 class Impl;
124
125 typedef GrGeometryProcessor INHERITED;
126 };
127
128 class SampleLocationsTestProcessor::Impl : public GrGLSLGeometryProcessor {
onEmitCode(EmitArgs & args,GrGPArgs * gpArgs)129 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) override {
130 const auto& proc = args.fGP.cast<SampleLocationsTestProcessor>();
131 auto* v = args.fVertBuilder;
132 auto* f = args.fFragBuilder;
133
134 GrGLSLVarying coord(kFloat2_GrSLType);
135 GrGLSLVarying grad(kFloat2_GrSLType);
136 args.fVaryingHandler->addVarying("coord", &coord);
137 if (GradType::kSW == proc.fGradType) {
138 args.fVaryingHandler->addVarying("grad", &grad);
139 }
140
141 // Pixel grid.
142 v->codeAppendf("int x = sk_InstanceID %% 200;");
143 v->codeAppendf("int y = sk_InstanceID / 200;");
144
145 // Create pseudo-random rectangles inside a 16x16 subpixel grid. This works out nicely
146 // because there are 17 positions on the grid (including both edges), and 17 is a great
147 // prime number for generating pseudo-random numbers.
148 v->codeAppendf("int ileft = (sk_InstanceID*929) %% 17;");
149 v->codeAppendf("int iright = ileft + 1 + ((sk_InstanceID*1637) %% (17 - ileft));");
150 v->codeAppendf("int itop = (sk_InstanceID*313) %% 17;");
151 v->codeAppendf("int ibot = itop + 1 + ((sk_InstanceID*1901) %% (17 - itop));");
152
153 // Outset (or inset) the rectangle, for the very likely scenario that samples fall on exact
154 // 16ths of a pixel. GL_SUBPIXEL_BITS is allowed to be as low as 4, so try not to let the
155 // outset value to get too small.
156 v->codeAppendf("float outset = 1/32.0;");
157 v->codeAppendf("outset = (0 == (x + y) %% 2) ? -outset : +outset;");
158 v->codeAppendf("float l = ileft/16.0 - outset;");
159 v->codeAppendf("float r = iright/16.0 + outset;");
160 v->codeAppendf("float t = itop/16.0 - outset;");
161 v->codeAppendf("float b = ibot/16.0 + outset;");
162
163 v->codeAppendf("float2 vertexpos;");
164 v->codeAppendf("vertexpos.x = float(x) + ((0 == (sk_VertexID %% 2)) ? l : r);");
165 v->codeAppendf("vertexpos.y = float(y) + ((0 == (sk_VertexID / 2)) ? t : b);");
166 gpArgs->fPositionVar.set(kFloat2_GrSLType, "vertexpos");
167
168 v->codeAppendf("%s.x = (0 == (sk_VertexID %% 2)) ? -1 : +1;", coord.vsOut());
169 v->codeAppendf("%s.y = (0 == (sk_VertexID / 2)) ? -1 : +1;", coord.vsOut());
170 if (GradType::kSW == proc.fGradType) {
171 v->codeAppendf("%s = 2/float2(r - l, b - t);", grad.vsOut());
172 }
173
174 // Fragment shader: Output RED.
175 f->codeAppendf("%s = half4(1,0,0,1);", args.fOutputColor);
176 f->codeAppendf("%s = half4(1);", args.fOutputCoverage);
177
178 // Now turn off all the samples inside our sub-rectangle. As long as the shaderBuilder's
179 // sample offsets and sample mask are correlated with actual HW sample locations, no red
180 // will bleed through.
181 f->codeAppendf("for (int i = 0; i < %i; ++i) {",
182 f->getProgramBuilder()->effectiveSampleCnt());
183 if (GradType::kHW == proc.fGradType) {
184 f->codeAppendf("float2x2 grad = float2x2(dFdx(%s), dFdy(%s));",
185 coord.fsIn(), coord.fsIn());
186 } else {
187 f->codeAppendf("float2x2 grad = float2x2(%s.x, 0, 0, %s.y);", grad.fsIn(), grad.fsIn());
188 }
189 f->codeAppendf( "float2 samplecoord = %s[i] * grad + %s;",
190 f->sampleOffsets(), coord.fsIn());
191 f->codeAppendf( "if (all(lessThanEqual(abs(samplecoord), float2(1)))) {");
192 f->maskOffMultisampleCoverage(
193 "~(1 << i)", GrGLSLFPFragmentBuilder::ScopeFlags::kInsideLoop);
194 f->codeAppendf( "}");
195 f->codeAppendf("}");
196 }
197
setData(const GrGLSLProgramDataManager &,const GrPrimitiveProcessor &,const CoordTransformRange &)198 void setData(const GrGLSLProgramDataManager&, const GrPrimitiveProcessor&,
199 const CoordTransformRange&) override {}
200 };
201
createGLSLInstance(const GrShaderCaps &) const202 GrGLSLPrimitiveProcessor* SampleLocationsTestProcessor::createGLSLInstance(
203 const GrShaderCaps&) const {
204 return new Impl();
205 }
206
207 ////////////////////////////////////////////////////////////////////////////////////////////////////
208 // Draw Op.
209
210 static constexpr GrUserStencilSettings gStencilWrite(
211 GrUserStencilSettings::StaticInit<
212 0x0001,
213 GrUserStencilTest::kAlways,
214 0xffff,
215 GrUserStencilOp::kReplace,
216 GrUserStencilOp::kKeep,
217 0xffff>()
218 );
219
220 class SampleLocationsTestOp : public GrDrawOp {
221 public:
222 DEFINE_OP_CLASS_ID
223
Make(GrRecordingContext * ctx,const SkMatrix & viewMatrix,GradType gradType)224 static std::unique_ptr<GrDrawOp> Make(
225 GrRecordingContext* ctx, const SkMatrix& viewMatrix, GradType gradType) {
226 GrOpMemoryPool* pool = ctx->priv().opMemoryPool();
227 return pool->allocate<SampleLocationsTestOp>(gradType);
228 }
229
230 private:
SampleLocationsTestOp(GradType gradType)231 SampleLocationsTestOp(GradType gradType) : GrDrawOp(ClassID()), fGradType(gradType) {
232 this->setBounds(SkRect::MakeIWH(200, 200), HasAABloat::kNo, IsHairline::kNo);
233 }
234
name() const235 const char* name() const override { return "SampleLocationsTestOp"; }
fixedFunctionFlags() const236 FixedFunctionFlags fixedFunctionFlags() const override {
237 return FixedFunctionFlags::kUsesHWAA | FixedFunctionFlags::kUsesStencil;
238 }
finalize(const GrCaps &,const GrAppliedClip *,bool hasMixedSampledCoverage,GrClampType)239 GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*,
240 bool hasMixedSampledCoverage, GrClampType) override {
241 return GrProcessorSet::EmptySetAnalysis();
242 }
243
244
createProgramInfo(const GrCaps * caps,SkArenaAlloc * arena,const GrSurfaceProxyView * outputView,GrAppliedClip && appliedClip,const GrXferProcessor::DstProxyView & dstProxyView) const245 GrProgramInfo* createProgramInfo(const GrCaps* caps,
246 SkArenaAlloc* arena,
247 const GrSurfaceProxyView* outputView,
248 GrAppliedClip&& appliedClip,
249 const GrXferProcessor::DstProxyView& dstProxyView) const {
250 GrGeometryProcessor* geomProc = SampleLocationsTestProcessor::Make(arena, fGradType);
251
252 GrPipeline::InputFlags flags = GrPipeline::InputFlags::kHWAntialias;
253
254 return sk_gpu_test::CreateProgramInfo(caps, arena, outputView,
255 std::move(appliedClip), dstProxyView,
256 geomProc, SkBlendMode::kSrcOver,
257 GrPrimitiveType::kTriangleStrip,
258 flags, &gStencilWrite);
259 }
260
createProgramInfo(GrOpFlushState * flushState) const261 GrProgramInfo* createProgramInfo(GrOpFlushState* flushState) const {
262 return this->createProgramInfo(&flushState->caps(),
263 flushState->allocator(),
264 flushState->outputView(),
265 flushState->detachAppliedClip(),
266 flushState->dstProxyView());
267 }
268
onPrePrepare(GrRecordingContext * context,const GrSurfaceProxyView * outputView,GrAppliedClip * clip,const GrXferProcessor::DstProxyView & dstProxyView)269 void onPrePrepare(GrRecordingContext* context,
270 const GrSurfaceProxyView* outputView,
271 GrAppliedClip* clip,
272 const GrXferProcessor::DstProxyView& dstProxyView) final {
273 // We're going to create the GrProgramInfo (and the GrPipeline and geometry processor
274 // it relies on) in the DDL-record-time arena.
275 SkArenaAlloc* arena = context->priv().recordTimeAllocator();
276
277 // This is equivalent to a GrOpFlushState::detachAppliedClip
278 GrAppliedClip appliedClip = clip ? std::move(*clip) : GrAppliedClip();
279
280 fProgramInfo = this->createProgramInfo(context->priv().caps(), arena, outputView,
281 std::move(appliedClip), dstProxyView);
282
283 context->priv().recordProgramInfo(fProgramInfo);
284 }
285
onPrepare(GrOpFlushState *)286 void onPrepare(GrOpFlushState*) final {}
287
onExecute(GrOpFlushState * flushState,const SkRect & chainBounds)288 void onExecute(GrOpFlushState* flushState, const SkRect& chainBounds) final {
289 if (!fProgramInfo) {
290 fProgramInfo = this->createProgramInfo(flushState);
291 }
292
293 flushState->bindPipelineAndScissorClip(*fProgramInfo, SkRect::MakeIWH(200, 200));
294 flushState->bindBuffers(nullptr, nullptr, nullptr);
295 flushState->drawInstanced(200*200, 0, 4, 0);
296 }
297
298 const GradType fGradType;
299
300 // The program info (and both the GrPipeline and GrPrimitiveProcessor it relies on), when
301 // allocated, are allocated in either the ddl-record-time or flush-time arena. It is the
302 // arena's job to free up their memory so we just have a bare programInfo pointer here. We
303 // don't even store the GrPipeline and GrPrimitiveProcessor pointers here bc they are
304 // guaranteed to have the same lifetime as the program info.
305 GrProgramInfo* fProgramInfo = nullptr;
306
307 friend class ::GrOpMemoryPool; // for ctor
308
309 typedef GrDrawOp INHERITED;
310 };
311
312 ////////////////////////////////////////////////////////////////////////////////////////////////////
313 // Test.
314
onDraw(GrContext * ctx,GrRenderTargetContext * rtc,SkCanvas * canvas,SkString * errorMsg)315 DrawResult SampleLocationsGM::onDraw(
316 GrContext* ctx, GrRenderTargetContext* rtc, SkCanvas* canvas, SkString* errorMsg) {
317 if (!ctx->priv().caps()->sampleLocationsSupport()) {
318 *errorMsg = "Requires support for sample locations.";
319 return DrawResult::kSkip;
320 }
321 if (!ctx->priv().caps()->shaderCaps()->sampleMaskSupport()) {
322 *errorMsg = "Requires support for sample mask.";
323 return DrawResult::kSkip;
324 }
325 if (rtc->numSamples() <= 1 && !ctx->priv().caps()->mixedSamplesSupport()) {
326 *errorMsg = "MSAA and mixed samples only.";
327 return DrawResult::kSkip;
328 }
329
330 auto offscreenRTC = GrRenderTargetContext::Make(
331 ctx, rtc->colorInfo().colorType(), nullptr, SkBackingFit::kExact, {200, 200},
332 rtc->numSamples(), GrMipMapped::kNo, GrProtected::kNo, fOrigin);
333 if (!offscreenRTC) {
334 *errorMsg = "Failed to create offscreen render target.";
335 return DrawResult::kFail;
336 }
337 if (offscreenRTC->numSamples() <= 1 &&
338 !offscreenRTC->asRenderTargetProxy()->canUseMixedSamples(*ctx->priv().caps())) {
339 *errorMsg = "MSAA and mixed samples only.";
340 return DrawResult::kSkip;
341 }
342
343 static constexpr GrUserStencilSettings kStencilCover(
344 GrUserStencilSettings::StaticInit<
345 0x0000,
346 GrUserStencilTest::kNotEqual,
347 0xffff,
348 GrUserStencilOp::kZero,
349 GrUserStencilOp::kKeep,
350 0xffff>()
351 );
352
353 offscreenRTC->clear(nullptr, {0,1,0,1}, GrRenderTargetContext::CanClearFullscreen::kYes);
354
355 // Stencil.
356 offscreenRTC->priv().testingOnly_addDrawOp(
357 SampleLocationsTestOp::Make(ctx, canvas->getTotalMatrix(), fGradType));
358
359 // Cover.
360 GrPaint coverPaint;
361 coverPaint.setColor4f({1,0,0,1});
362 coverPaint.setXPFactory(GrPorterDuffXPFactory::Get(SkBlendMode::kSrcOver));
363 rtc->priv().stencilRect(GrNoClip(), &kStencilCover, std::move(coverPaint), GrAA::kNo,
364 SkMatrix::I(), SkRect::MakeWH(200, 200));
365
366 // Copy offscreen texture to canvas.
367 rtc->drawTexture(GrNoClip(), offscreenRTC->readSurfaceView(),
368 offscreenRTC->colorInfo().alphaType(),
369 GrSamplerState::Filter::kNearest, SkBlendMode::kSrc, SK_PMColor4fWHITE,
370 {0,0,200,200}, {0,0,200,200}, GrAA::kNo, GrQuadAAFlags::kNone,
371 SkCanvas::SrcRectConstraint::kStrict_SrcRectConstraint, SkMatrix::I(),
372 nullptr);
373
374 return skiagm::DrawResult::kOk;
375 }
376
377 DEF_GM( return new SampleLocationsGM(GradType::kHW, kTopLeft_GrSurfaceOrigin); )
378 DEF_GM( return new SampleLocationsGM(GradType::kHW, kBottomLeft_GrSurfaceOrigin); )
379 DEF_GM( return new SampleLocationsGM(GradType::kSW, kTopLeft_GrSurfaceOrigin); )
380 DEF_GM( return new SampleLocationsGM(GradType::kSW, kBottomLeft_GrSurfaceOrigin); )
381
382 }
383