blob: 809bee1e595d8e6b4288b1f829f18d89155edd03 [file] [log] [blame]
Brian Salomonbc6b99d2017-01-11 10:32:34 -05001/*
2 * Copyright 2016 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
Mike Kleinc0bd9f92019-04-23 12:05:21 -05008#include "tests/Test.h"
Brian Salomonbc6b99d2017-01-11 10:32:34 -05009
Robert Phillips6d344c32020-07-06 10:56:46 -040010#include "include/gpu/GrDirectContext.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050011#include "src/gpu/GrClip.h"
Adlai Hollera0693042020-10-14 11:23:11 -040012#include "src/gpu/GrDirectContextPriv.h"
Greg Daniel456f9b52020-03-05 19:14:18 +000013#include "src/gpu/GrGpuResource.h"
Brian Salomonf2ebdd92019-09-30 12:15:30 -040014#include "src/gpu/GrImageInfo.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050015#include "src/gpu/GrMemoryPool.h"
16#include "src/gpu/GrProxyProvider.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050017#include "src/gpu/GrResourceProvider.h"
Brian Salomon27c42022021-04-28 12:39:21 -040018#include "src/gpu/SkGr.h"
Robert Phillips550de7f2021-07-06 16:28:52 -040019#include "src/gpu/effects/GrTextureEffect.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050020#include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
21#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050022#include "src/gpu/ops/GrMeshDrawOp.h"
Robert Phillips4dca8312021-07-28 15:13:20 -040023#include "src/gpu/v1/SurfaceDrawContext_v1.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050024#include "tests/TestUtils.h"
Brian Salomoneebe7352020-12-09 16:37:04 -050025
Mike Klein0ec1c572018-12-04 11:52:51 -050026#include <atomic>
Hal Canary8a001442018-09-19 11:31:27 -040027#include <random>
28
Brian Salomonbc6b99d2017-01-11 10:32:34 -050029namespace {
Brian Salomon82ddc942017-07-14 12:00:13 -040030class TestOp : public GrMeshDrawOp {
Brian Salomonbc6b99d2017-01-11 10:32:34 -050031public:
32 DEFINE_OP_CLASS_ID
Herb Derbyc76d4092020-10-07 16:46:15 -040033 static GrOp::Owner Make(GrRecordingContext* rContext,
34 std::unique_ptr<GrFragmentProcessor> fp) {
35 return GrOp::Make<TestOp>(rContext, std::move(fp));
Brian Salomon82ddc942017-07-14 12:00:13 -040036 }
37
Robert Phillips5f567c72017-09-14 08:27:37 -040038 const char* name() const override { return "TestOp"; }
39
Robert Phillips294723d2021-06-17 09:23:58 -040040 void visitProxies(const GrVisitProxyFunc& func) const override {
Robert Phillips5f567c72017-09-14 08:27:37 -040041 fProcessors.visitProxies(func);
42 }
43
Brian Salomon82ddc942017-07-14 12:00:13 -040044 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
45
Chris Dalton57ab06c2021-04-22 12:57:28 -060046 GrProcessorSet::Analysis finalize(const GrCaps& caps, const GrAppliedClip* clip,
47 GrClampType clampType) override {
Brian Salomon82ddc942017-07-14 12:00:13 -040048 static constexpr GrProcessorAnalysisColor kUnknownColor;
Brian Osmancf860852018-10-31 14:04:39 -040049 SkPMColor4f overrideColor;
Chris Daltonb8fff0d2019-03-05 10:11:58 -070050 return fProcessors.finalize(
51 kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip,
Chris Dalton57ab06c2021-04-22 12:57:28 -060052 &GrUserStencilSettings::kUnused, caps, clampType, &overrideColor);
Brian Salomon649a3412017-03-09 13:50:43 -050053 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050054
55private:
Herb Derbyc76d4092020-10-07 16:46:15 -040056 friend class ::GrOp; // for ctor
Robert Phillips7c525e62018-06-12 10:11:12 -040057
Brian Salomonaff329b2017-08-11 09:40:37 -040058 TestOp(std::unique_ptr<GrFragmentProcessor> fp)
59 : INHERITED(ClassID()), fProcessors(std::move(fp)) {
Greg Daniel5faf4742019-10-01 15:14:44 -040060 this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
Brian Salomon82ddc942017-07-14 12:00:13 -040061 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050062
Robert Phillips2669a7b2020-03-12 12:07:19 -040063 GrProgramInfo* programInfo() override { return nullptr; }
Robert Phillips4133dc42020-03-11 15:55:55 -040064 void onCreateProgramInfo(const GrCaps*,
65 SkArenaAlloc*,
Adlai Hollere2296f72020-11-19 13:41:26 -050066 const GrSurfaceProxyView& writeView,
Chris Dalton6aaf00f2021-07-13 13:26:39 -060067 bool usesMSAASurface,
Robert Phillips4133dc42020-03-11 15:55:55 -040068 GrAppliedClip&&,
John Stiles52cb1d02021-06-02 11:58:05 -040069 const GrDstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050070 GrXferBarrierFlags renderPassXferBarriers,
71 GrLoadOp colorLoadOp) override {}
Robert Phillips2669a7b2020-03-12 12:07:19 -040072 void onPrePrepareDraws(GrRecordingContext*,
Adlai Hollere2296f72020-11-19 13:41:26 -050073 const GrSurfaceProxyView& writeView,
Robert Phillips2669a7b2020-03-12 12:07:19 -040074 GrAppliedClip*,
John Stiles52cb1d02021-06-02 11:58:05 -040075 const GrDstProxyView&,
Greg Daniel42dbca52020-11-20 10:22:43 -050076 GrXferBarrierFlags renderPassXferBarriers,
77 GrLoadOp colorLoadOp) override {}
Robert Phillips71143952021-06-17 14:55:07 -040078 void onPrepareDraws(GrMeshDrawTarget*) override { return; }
Chris Dalton07cdcfc92019-02-26 11:13:22 -070079 void onExecute(GrOpFlushState*, const SkRect&) override { return; }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050080
Brian Salomon82ddc942017-07-14 12:00:13 -040081 GrProcessorSet fProcessors;
82
John Stiles7571f9e2020-09-02 22:42:33 -040083 using INHERITED = GrMeshDrawOp;
Brian Salomonbc6b99d2017-01-11 10:32:34 -050084};
85
86/**
Robert Phillips3d4cac52019-06-11 08:08:08 -040087 * FP used to test ref counts on owned GrGpuResources. Can also be a parent FP to test counts
Brian Salomonbc6b99d2017-01-11 10:32:34 -050088 * of resources owned by child FPs.
89 */
90class TestFP : public GrFragmentProcessor {
91public:
Brian Salomonaff329b2017-08-11 09:40:37 -040092 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) {
93 return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child)));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050094 }
Brian Salomon92b9ccf2020-06-17 14:19:19 -040095 static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<GrSurfaceProxyView>& views) {
96 return std::unique_ptr<GrFragmentProcessor>(new TestFP(views));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050097 }
98
99 const char* name() const override { return "test"; }
100
Brian Salomon13b28732021-08-06 15:33:58 -0400101 void onAddToKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
Mike Klein0ec1c572018-12-04 11:52:51 -0500102 static std::atomic<int32_t> nextKey{0};
103 b->add32(nextKey++);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500104 }
105
Brian Salomonaff329b2017-08-11 09:40:37 -0400106 std::unique_ptr<GrFragmentProcessor> clone() const override {
107 return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this));
Brian Salomonb17e6392017-07-28 13:41:51 -0400108 }
109
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500110private:
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400111 TestFP(const SkTArray<GrSurfaceProxyView>& views)
112 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
John Stilesfe7aed62020-07-20 13:48:02 -0400113 for (const GrSurfaceProxyView& view : views) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400114 this->registerChild(GrTextureEffect::Make(view, kUnknown_SkAlphaType));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500115 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500116 }
117
Brian Salomonaff329b2017-08-11 09:40:37 -0400118 TestFP(std::unique_ptr<GrFragmentProcessor> child)
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400119 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400120 this->registerChild(std::move(child));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500121 }
122
John Stiles307f8f52021-08-09 15:36:59 -0400123 explicit TestFP(const TestFP& that) : INHERITED(that) {}
Brian Salomonb17e6392017-07-28 13:41:51 -0400124
Brian Salomon3176e862021-08-09 11:23:04 -0400125 std::unique_ptr<ProgramImpl> onMakeProgramImpl() const override {
126 class TestGLSLFP : public ProgramImpl {
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500127 public:
128 TestGLSLFP() {}
129 void emitCode(EmitArgs& args) override {
John Stilesd1eab8b2020-12-15 09:47:26 -0500130 args.fFragBuilder->codeAppendf("return half4(1);");
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500131 }
132
133 private:
134 };
Brian Salomon18ab2032021-02-23 10:07:05 -0500135 return std::make_unique<TestGLSLFP>();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500136 }
137
138 bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
139
John Stiles7571f9e2020-09-02 22:42:33 -0400140 using INHERITED = GrFragmentProcessor;
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500141};
John Stilesa6841be2020-08-06 14:11:56 -0400142} // namespace
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500143
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500144DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400145 auto dContext = ctxInfo.directContext();
146 GrProxyProvider* proxyProvider = dContext->priv().proxyProvider();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500147
Brian Salomona56a7462020-02-07 14:17:25 -0500148 static constexpr SkISize kDims = {10, 10};
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500149
Greg Daniel4065d452018-11-16 15:43:41 -0500150 const GrBackendFormat format =
Robert Phillips4dca8312021-07-28 15:13:20 -0400151 dContext->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
152 GrRenderable::kNo);
153 GrSwizzle swizzle = dContext->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
Greg Daniel4065d452018-11-16 15:43:41 -0500154
Brian Salomonb17e6392017-07-28 13:41:51 -0400155 for (bool makeClone : {false, true}) {
156 for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400157 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
158 dContext, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1},
Chris Daltonf5b87f92021-04-19 17:27:09 -0600159 SkSurfaceProps());
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500160 {
Robert Phillips3d4cac52019-06-11 08:08:08 -0400161 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
Brian Salomon7e67dca2020-07-21 09:27:25 -0400162 format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kExact,
Brian Salomondf1bd6d2020-03-26 20:37:01 -0400163 SkBudgeted::kYes, GrProtected::kNo);
Robert Phillips3d4cac52019-06-11 08:08:08 -0400164
Brian Salomonb17e6392017-07-28 13:41:51 -0400165 {
Greg Daniel026a60c2020-02-12 10:53:51 -0500166 SkTArray<GrSurfaceProxyView> views;
Greg Daniel026a60c2020-02-12 10:53:51 -0500167 views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400168 auto fp = TestFP::Make(std::move(views));
Brian Salomonb17e6392017-07-28 13:41:51 -0400169 for (int i = 0; i < parentCnt; ++i) {
170 fp = TestFP::Make(std::move(fp));
171 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400172 std::unique_ptr<GrFragmentProcessor> clone;
Brian Salomonb17e6392017-07-28 13:41:51 -0400173 if (makeClone) {
174 clone = fp->clone();
175 }
Robert Phillips4dca8312021-07-28 15:13:20 -0400176 GrOp::Owner op = TestOp::Make(dContext, std::move(fp));
177 sdc->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400178 if (clone) {
Robert Phillips4dca8312021-07-28 15:13:20 -0400179 op = TestOp::Make(dContext, std::move(clone));
180 sdc->addDrawOp(std::move(op));
Brian Salomonb17e6392017-07-28 13:41:51 -0400181 }
182 }
Brian Salomonb17e6392017-07-28 13:41:51 -0400183
Robert Phillips3d4cac52019-06-11 08:08:08 -0400184 // If the fp is cloned the number of refs should increase by one (for the clone)
185 int expectedProxyRefs = makeClone ? 3 : 2;
186
Brian Salomon28a8f282019-10-24 20:07:39 -0400187 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
Brian Salomonb17e6392017-07-28 13:41:51 -0400188
Robert Phillips4dca8312021-07-28 15:13:20 -0400189 dContext->flushAndSubmit();
Brian Salomonb17e6392017-07-28 13:41:51 -0400190
Brian Salomon557e8122019-10-24 10:37:08 -0400191 // just one from the 'proxy' sk_sp
Brian Salomon28a8f282019-10-24 20:07:39 -0400192 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500193 }
194 }
195 }
196}
Brian Salomon587e08f2017-01-27 10:59:27 -0500197
Mike Kleinc0bd9f92019-04-23 12:05:21 -0500198#include "tools/flags/CommandLineFlags.h"
Mike Klein84836b72019-03-21 11:31:36 -0500199static DEFINE_bool(randomProcessorTest, false,
200 "Use non-deterministic seed for random processor tests?");
Mike Klein5b3f3432019-03-21 11:42:21 -0500201static DEFINE_int(processorSeed, 0,
202 "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
Brian Salomon0e05a822017-07-25 09:43:22 -0400203
204#if GR_TEST_UTILS
205
Michael Ludwig7034f152018-10-08 16:43:58 -0400206static GrColor input_texel_color(int i, int j, SkScalar delta) {
207 // Delta must be less than 0.5 to prevent over/underflow issues with the input color
208 SkASSERT(delta <= 0.5);
Brian Salomon587e08f2017-01-27 10:59:27 -0500209
Brian Osman50ea3c02019-02-04 10:01:53 -0500210 SkColor color = SkColorSetARGB((uint8_t)(i & 0xFF),
211 (uint8_t)(j & 0xFF),
212 (uint8_t)((i + j) & 0xFF),
213 (uint8_t)((2 * j - i) & 0xFF));
Brian Osmancb3d0872018-10-16 15:19:28 -0400214 SkColor4f color4f = SkColor4f::FromColor(color);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500215 // We only apply delta to the r,g, and b channels. This is because we're using this
216 // to test the canTweakAlphaForCoverage() optimization. A processor is allowed
217 // to use the input color's alpha in its calculation and report this optimization.
218 for (int i = 0; i < 3; i++) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400219 if (color4f[i] > 0.5) {
220 color4f[i] -= delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400221 } else {
Brian Osmancb3d0872018-10-16 15:19:28 -0400222 color4f[i] += delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400223 }
224 }
Brian Osmancb3d0872018-10-16 15:19:28 -0400225 return color4f.premul().toBytes_RGBA();
Brian Salomon0e05a822017-07-25 09:43:22 -0400226}
Brian Salomon587e08f2017-01-27 10:59:27 -0500227
John Stiles0dee9b02020-07-20 11:45:58 -0400228// The output buffer must be the same size as the render-target context.
Adlai Hollerc95b5892020-08-11 12:02:22 -0400229void render_fp(GrDirectContext* dContext,
Robert Phillips4dca8312021-07-28 15:13:20 -0400230 skgpu::v1::SurfaceDrawContext* sdc,
Brian Salomon3f4de782020-06-18 14:16:00 -0400231 std::unique_ptr<GrFragmentProcessor> fp,
John Stiles0dee9b02020-07-20 11:45:58 -0400232 GrColor* outBuffer) {
Robert Phillipsba701382021-07-07 14:15:12 -0400233 sdc->fillWithFP(std::move(fp));
234 std::fill_n(outBuffer, sdc->width() * sdc->height(), 0);
235 auto ii = SkImageInfo::Make(sdc->dimensions(), kRGBA_8888_SkColorType, kPremul_SkAlphaType);
236 GrPixmap resultPM(ii, outBuffer, sdc->width()*sizeof(uint32_t));
237 sdc->readPixels(dContext, resultPM, {0, 0});
Michael Ludwig7034f152018-10-08 16:43:58 -0400238}
239
John Stilesaf110302020-07-20 09:45:51 -0400240// This class is responsible for reproducibly generating a random fragment processor.
241// An identical randomly-designed FP can be generated as many times as needed.
242class TestFPGenerator {
243 public:
244 TestFPGenerator() = delete;
245 TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
246 : fContext(context)
247 , fResourceProvider(resourceProvider)
248 , fInitialSeed(synthesizeInitialSeed())
249 , fRandomSeed(fInitialSeed) {}
Brian Osmanc35a2d42017-03-17 10:58:53 -0400250
John Stilesaf110302020-07-20 09:45:51 -0400251 uint32_t initialSeed() { return fInitialSeed; }
252
253 bool init() {
254 // Initializes the two test texture proxies that are available to the FP test factories.
255 SkRandom random{fRandomSeed};
256 static constexpr int kTestTextureSize = 256;
257
258 {
259 // Put premul data into the RGBA texture that the test FPs can optionally use.
260 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
261 for (int y = 0; y < kTestTextureSize; ++y) {
262 for (int x = 0; x < kTestTextureSize; ++x) {
263 rgbaData[kTestTextureSize * y + x] = input_texel_color(
264 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
265 }
266 }
267
268 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
269 kRGBA_8888_SkColorType, kPremul_SkAlphaType);
270 SkBitmap bitmap;
271 bitmap.installPixels(
272 ii, rgbaData, ii.minRowBytes(),
273 [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
274 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400275 auto view = std::get<0>(GrMakeUncachedBitmapProxyView(fContext, bitmap));
276 if (!view || !view.proxy()->instantiate(fResourceProvider)) {
John Stilesaf110302020-07-20 09:45:51 -0400277 SkDebugf("Unable to instantiate RGBA8888 test texture.");
278 return false;
279 }
280 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
281 kPremul_SkAlphaType};
282 }
283
284 {
285 // Put random values into the alpha texture that the test FPs can optionally use.
286 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
287 for (int y = 0; y < kTestTextureSize; ++y) {
288 for (int x = 0; x < kTestTextureSize; ++x) {
289 alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
290 }
291 }
292
293 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
294 kAlpha_8_SkColorType, kPremul_SkAlphaType);
295 SkBitmap bitmap;
296 bitmap.installPixels(
297 ii, alphaData, ii.minRowBytes(),
298 [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
299 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400300 auto view = std::get<0>(GrMakeUncachedBitmapProxyView(fContext, bitmap));
301 if (!view || !view.proxy()->instantiate(fResourceProvider)) {
John Stilesaf110302020-07-20 09:45:51 -0400302 SkDebugf("Unable to instantiate A8 test texture.");
303 return false;
304 }
305 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
306 kPremul_SkAlphaType};
307 }
308
309 return true;
310 }
311
312 void reroll() {
313 // Feed our current random seed into SkRandom to generate a new seed.
314 SkRandom random{fRandomSeed};
315 fRandomSeed = random.nextU();
316 }
317
John Stiles87d0a2f2020-08-10 13:12:41 -0400318 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
John Stiles0dee9b02020-07-20 11:45:58 -0400319 std::unique_ptr<GrFragmentProcessor> inputFP) {
John Stilesaf110302020-07-20 09:45:51 -0400320 // This will generate the exact same randomized FP (of each requested type) each time
321 // it's called. Call `reroll` to get a different FP.
322 SkRandom random{fRandomSeed};
John Stiles87d0a2f2020-08-10 13:12:41 -0400323 GrProcessorTestData testData{&random, fContext, randomTreeDepth,
324 SK_ARRAY_COUNT(fTestViews), fTestViews,
John Stiles0dee9b02020-07-20 11:45:58 -0400325 std::move(inputFP)};
John Stilesaf110302020-07-20 09:45:51 -0400326 return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
327 }
328
John Stiles87d0a2f2020-08-10 13:12:41 -0400329 std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
330 GrSurfaceProxyView view,
John Stiles0dee9b02020-07-20 11:45:58 -0400331 SkAlphaType alpha = kPremul_SkAlphaType) {
John Stiles87d0a2f2020-08-10 13:12:41 -0400332 return make(type, randomTreeDepth, GrTextureEffect::Make(view, alpha));
John Stiles0dee9b02020-07-20 11:45:58 -0400333 }
334
John Stilesaf110302020-07-20 09:45:51 -0400335 private:
336 static uint32_t synthesizeInitialSeed() {
337 if (FLAGS_randomProcessorTest) {
338 std::random_device rd;
339 return rd();
340 } else {
341 return FLAGS_processorSeed;
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500342 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400343 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400344
John Stilesaf110302020-07-20 09:45:51 -0400345 GrDirectContext* fContext; // owned by caller
346 GrResourceProvider* fResourceProvider; // owned by caller
347 const uint32_t fInitialSeed;
348 uint32_t fRandomSeed;
349 GrProcessorTestData::ViewInfo fTestViews[2];
350};
Brian Salomon0e05a822017-07-25 09:43:22 -0400351
John Stiles4ed69472020-08-11 16:04:31 -0400352// Creates an array of color values from input_texel_color(), to be used as an input texture.
353std::vector<GrColor> make_input_pixels(int width, int height, SkScalar delta) {
354 std::vector<GrColor> pixel(width * height);
Brian Salomon0e05a822017-07-25 09:43:22 -0400355 for (int y = 0; y < width; ++y) {
356 for (int x = 0; x < height; ++x) {
John Stiles4ed69472020-08-11 16:04:31 -0400357 pixel[width * y + x] = input_texel_color(x, y, delta);
Brian Salomon0e05a822017-07-25 09:43:22 -0400358 }
359 }
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500360
John Stiles4ed69472020-08-11 16:04:31 -0400361 return pixel;
362}
363
364// Creates a texture of premul colors used as the output of the fragment processor that precedes
365// the fragment processor under test. An array of W*H colors are passed in as the texture data.
366GrSurfaceProxyView make_input_texture(GrRecordingContext* context,
367 int width, int height, GrColor* pixel) {
Brian Osman2700abc2018-09-12 10:19:41 -0400368 SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
Greg Daniel6f5441a2020-01-28 17:02:49 -0500369 SkBitmap bitmap;
John Stiles4ed69472020-08-11 16:04:31 -0400370 bitmap.installPixels(ii, pixel, ii.minRowBytes());
Greg Daniel6f5441a2020-01-28 17:02:49 -0500371 bitmap.setImmutable();
Brian Salomon27c42022021-04-28 12:39:21 -0400372 return std::get<0>(GrMakeUncachedBitmapProxyView(context, bitmap));
Brian Salomon0e05a822017-07-25 09:43:22 -0400373}
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500374
John Stilesaf110302020-07-20 09:45:51 -0400375// We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400376// actually contains unpremul data. Also, even though we made the result data by rendering into
Robert Phillips4dca8312021-07-28 15:13:20 -0400377// a "unpremul" SurfaceDrawContext, our input texture is unpremul and outside of the random
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400378// effect configuration, we didn't do anything to ensure the output is actually premul. We just
Brian Salomoneebe7352020-12-09 16:37:04 -0500379// don't currently allow kUnpremul GrSurfaceDrawContexts.
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400380static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
Michael Ludwige8e10752018-10-01 12:42:53 -0400381
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400382bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
John Stilesaf110302020-07-20 09:45:51 -0400383 SkImageInfo info =
384 SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400385 SkBitmap bmp;
386 bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
Brian Salomon28a8f282019-10-24 20:07:39 -0400387 return BipmapToBase64DataURI(bmp, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400388}
389
Adlai Hollerc95b5892020-08-11 12:02:22 -0400390bool log_texture_view(GrDirectContext* dContext, GrSurfaceProxyView src, SkString* dst) {
Greg Daniel124486b2020-02-11 11:54:55 -0500391 SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
392 kLogAlphaType);
Greg Daniel3912a4b2020-01-14 09:56:04 -0500393
Robert Phillips33bf2b52021-08-02 11:14:38 -0400394 auto sContext = dContext->priv().makeSC(std::move(src), ii.colorInfo());
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400395 SkBitmap bm;
396 SkAssertResult(bm.tryAllocPixels(ii));
Brian Salomondd4087d2020-12-23 20:36:44 -0500397 SkAssertResult(sContext->readPixels(dContext, bm.pixmap(), {0, 0}));
Brian Salomon28a8f282019-10-24 20:07:39 -0400398 return BipmapToBase64DataURI(bm, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400399}
400
Michael Ludwig7034f152018-10-08 16:43:58 -0400401bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
402 // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
Brian Salomon682ba432019-12-17 20:20:23 +0000403 // from that, it is not uncommon for a valid output to differ from estimate by up to 0.01
Michael Ludwig7034f152018-10-08 16:43:58 -0400404 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
405 // too unforgiving).
Brian Salomon682ba432019-12-17 20:20:23 +0000406 static constexpr SkScalar kTolerance = 0.01f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400407 for (int i = 0; i < 4; i++) {
408 if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
409 return false;
410 }
411 }
412 return true;
413}
414
Brian Salomonbc73eb42019-12-18 14:57:45 -0500415// Given three input colors (color preceding the FP being tested) provided to the FP at the same
416// local coord and the three corresponding FP outputs, this ensures that either:
417// out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
418// where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
419// change), OR:
420// out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
421// (per-channel modulation instead of modulation by just the alpha channel)
422// It does this by estimating the pre-modulated fp color from one of the input/output pairs and
423// confirms the conditions hold for the other two pairs.
424// It is required that the three input colors have the same alpha as fp is allowed to be a function
425// of the input alpha (but not r, g, or b).
426bool legal_modulation(const GrColor in[3], const GrColor out[3]) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400427 // Convert to floating point, which is the number space the FP operates in (more or less)
Brian Salomonbc73eb42019-12-18 14:57:45 -0500428 SkPMColor4f inf[3], outf[3];
429 for (int i = 0; i < 3; ++i) {
430 inf[i] = SkPMColor4f::FromBytes_RGBA(in[i]);
431 outf[i] = SkPMColor4f::FromBytes_RGBA(out[i]);
432 }
433 // This test is only valid if all the input alphas are the same.
434 SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
Michael Ludwig7034f152018-10-08 16:43:58 -0400435
436 // Reconstruct the output of the FP before the shader modulated its color with the input value.
437 // When the original input is very small, it may cause the final output color to round
438 // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
439 // will then have a guaranteed larger channel value (since the offset will be added to it).
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500440 SkPMColor4f fpPreColorModulation = {0,0,0,0};
441 SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
Michael Ludwig7034f152018-10-08 16:43:58 -0400442 for (int i = 0; i < 4; i++) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500443 // Use the most stepped up frame
444 int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
445 maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
John Stilesfe7aed62020-07-20 13:48:02 -0400446 const SkPMColor4f& in = inf[maxInIdx];
447 const SkPMColor4f& out = outf[maxInIdx];
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500448 if (in[i] > 0) {
449 fpPreColorModulation[i] = out[i] / in[i];
450 }
451 if (in[3] > 0) {
452 fpPreAlphaModulation[i] = out[i] / in[3];
453 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400454 }
455
456 // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
457 // of the transformed input colors.
Brian Salomonbc73eb42019-12-18 14:57:45 -0500458 SkPMColor4f expectedForAlphaModulation[3];
459 SkPMColor4f expectedForColorModulation[3];
460 for (int i = 0; i < 3; ++i) {
461 expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
462 expectedForColorModulation[i] = fpPreColorModulation * inf[i];
463 // If the input alpha is 0 then the other channels should also be zero
464 // since the color is assumed to be premul. Modulating zeros by anything
465 // should produce zeros.
466 if (inf[i].fA == 0) {
467 SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
468 expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
469 }
470 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400471
Brian Salomonbc73eb42019-12-18 14:57:45 -0500472 bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
473 fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
474 fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
475
476 bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
477 fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
478 fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
479
480 // This can be enabled to print the values that caused this check to fail.
481 if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
482 SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
483 fpPreColorModulation[0],
484 fpPreColorModulation[1],
485 fpPreColorModulation[2],
486 fpPreColorModulation[3]);
487 for (int i = 0; i < 3; ++i) {
488 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
489 "(%.03f, %.03f, %.03f, %.03f) | "
490 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
491 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
492 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
493 expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
494 expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
495 fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
496 }
497 SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
498 fpPreAlphaModulation[0],
499 fpPreAlphaModulation[1],
500 fpPreAlphaModulation[2],
501 fpPreAlphaModulation[3]);
502 for (int i = 0; i < 3; ++i) {
503 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
504 "(%.03f, %.03f, %.03f, %.03f) | "
505 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
506 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
507 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
508 expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
509 expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
510 fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
511 }
512 }
513 return isLegalColorModulation || isLegalAlphaModulation;
Michael Ludwig7034f152018-10-08 16:43:58 -0400514}
515
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500516DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400517 GrDirectContext* context = ctxInfo.directContext();
518 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon1c053642017-07-24 10:16:19 -0400519 using FPFactory = GrFragmentProcessorTestFactory;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400520
John Stilesaf110302020-07-20 09:45:51 -0400521 TestFPGenerator fpGenerator{context, resourceProvider};
522 if (!fpGenerator.init()) {
523 ERRORF(reporter, "Could not initialize TestFPGenerator");
524 return;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400525 }
Brian Osmanc35a2d42017-03-17 10:58:53 -0400526
Brian Salomon0e05a822017-07-25 09:43:22 -0400527 // Make the destination context for the test.
528 static constexpr int kRenderSize = 256;
Robert Phillips4dca8312021-07-28 15:13:20 -0400529 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500530 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
Chris Daltonf5b87f92021-04-19 17:27:09 -0600531 {kRenderSize, kRenderSize}, SkSurfaceProps());
Brian Salomond1a8bdf2017-02-10 12:39:26 -0500532
Michael Ludwig7034f152018-10-08 16:43:58 -0400533 // Coverage optimization uses three frames with a linearly transformed input texture. The first
534 // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
535 // difference between the frame outputs if the FP is properly following the modulation
536 // requirements of the coverage optimization.
537 static constexpr SkScalar kInputDelta = 0.2f;
John Stiles4ed69472020-08-11 16:04:31 -0400538 std::vector<GrColor> inputPixels1 = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
539 std::vector<GrColor> inputPixels2 =
540 make_input_pixels(kRenderSize, kRenderSize, 1 * kInputDelta);
541 std::vector<GrColor> inputPixels3 =
542 make_input_pixels(kRenderSize, kRenderSize, 2 * kInputDelta);
543 GrSurfaceProxyView inputTexture1 =
544 make_input_texture(context, kRenderSize, kRenderSize, inputPixels1.data());
545 GrSurfaceProxyView inputTexture2 =
546 make_input_texture(context, kRenderSize, kRenderSize, inputPixels2.data());
547 GrSurfaceProxyView inputTexture3 =
548 make_input_texture(context, kRenderSize, kRenderSize, inputPixels3.data());
Robert Phillips30f9bc62017-02-22 15:28:38 -0500549
Michael Ludwige8e10752018-10-01 12:42:53 -0400550 // Encoded images are very verbose and this tests many potential images, so only export the
551 // first failure (subsequent failures have a reasonable chance of being related).
552 bool loggedFirstFailure = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400553 bool loggedFirstWarning = false;
Michael Ludwig7034f152018-10-08 16:43:58 -0400554
John Stilesaf110302020-07-20 09:45:51 -0400555 // Storage for the three frames required for coverage compatibility optimization testing.
556 // Each frame uses the correspondingly numbered inputTextureX.
557 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
558 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
559 std::vector<GrColor> readData3(kRenderSize * kRenderSize);
Michael Ludwig7034f152018-10-08 16:43:58 -0400560
Brian Salomon0e05a822017-07-25 09:43:22 -0400561 // Because processor factories configure themselves in random ways, this is not exhaustive.
Brian Salomon587e08f2017-01-27 10:59:27 -0500562 for (int i = 0; i < FPFactory::Count(); ++i) {
John Stilesfe7aed62020-07-20 13:48:02 -0400563 int optimizedForOpaqueInput = 0;
564 int optimizedForCoverageAsAlpha = 0;
565 int optimizedForConstantOutputForInput = 0;
John Stilesaf110302020-07-20 09:45:51 -0400566
John Stilesfe7aed62020-07-20 13:48:02 -0400567#ifdef __MSVC_RUNTIME_CHECKS
Brian Osman50ea3c02019-02-04 10:01:53 -0500568 // This test is infuriatingly slow with MSVC runtime checks enabled
John Stilesfe7aed62020-07-20 13:48:02 -0400569 static constexpr int kMinimumTrials = 1;
570 static constexpr int kMaximumTrials = 1;
571 static constexpr int kExpectedSuccesses = 1;
572#else
573 // We start by testing each fragment-processor 100 times, watching the optimization bits
574 // that appear. If we see an optimization bit appear in those first 100 trials, we keep
575 // running tests until we see at least five successful trials that have this optimization
576 // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
577 // that this FP doesn't support that optimization at all.
578 static constexpr int kMinimumTrials = 100;
579 static constexpr int kMaximumTrials = 2000;
580 static constexpr int kExpectedSuccesses = 5;
Brian Osman50ea3c02019-02-04 10:01:53 -0500581#endif
Robert Phillipsa91e0b72017-05-01 13:12:20 -0400582
John Stilesfe7aed62020-07-20 13:48:02 -0400583 for (int trial = 0;; ++trial) {
John Stilesaf110302020-07-20 09:45:51 -0400584 // Create a randomly-configured FP.
585 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400586 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400587 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1);
John Stilesaf110302020-07-20 09:45:51 -0400588
John Stilesfe7aed62020-07-20 13:48:02 -0400589 // If we have iterated enough times and seen a sufficient number of successes on each
590 // optimization bit that can be returned, stop running trials.
591 if (trial >= kMinimumTrials) {
592 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
593 optimizedForOpaqueInput < kExpectedSuccesses) ||
594 (optimizedForCoverageAsAlpha > 0 &&
595 optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
596 (optimizedForConstantOutputForInput > 0 &&
597 optimizedForConstantOutputForInput < kExpectedSuccesses);
598 if (!moreTrialsNeeded) break;
599
600 if (trial >= kMaximumTrials) {
601 SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
John Stilesba1879d2020-08-11 13:58:32 -0400602 "Seed: 0x%08x, processor:\n%s",
603 kMaximumTrials, fpGenerator.initialSeed(), fp->dumpTreeInfo().c_str());
John Stilesfe7aed62020-07-20 13:48:02 -0400604 break;
605 }
606 }
607
608 // Skip further testing if this trial has no optimization bits enabled.
Brian Salomon587e08f2017-01-27 10:59:27 -0500609 if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
Brian Salomonf3b995b2017-02-15 10:22:23 -0500610 !fp->compatibleWithCoverageAsAlpha()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500611 continue;
612 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400613
John Stilesaf110302020-07-20 09:45:51 -0400614 // We can make identical copies of the test FP in order to test coverage-as-alpha.
Michael Ludwig7034f152018-10-08 16:43:58 -0400615 if (fp->compatibleWithCoverageAsAlpha()) {
John Stiles0dee9b02020-07-20 11:45:58 -0400616 // Create and render two identical versions of this FP, but using different input
617 // textures, to check coverage optimization. We don't need to do this step for
618 // constant-output or preserving-opacity tests.
Robert Phillips4dca8312021-07-28 15:13:20 -0400619 render_fp(context, sdc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400620 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture2),
John Stiles87d0a2f2020-08-10 13:12:41 -0400621 readData2.data());
Robert Phillips4dca8312021-07-28 15:13:20 -0400622 render_fp(context, sdc.get(),
John Stiles9fbe9e92020-08-10 16:35:01 -0400623 fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture3),
John Stiles87d0a2f2020-08-10 13:12:41 -0400624 readData3.data());
John Stilesfe7aed62020-07-20 13:48:02 -0400625 ++optimizedForCoverageAsAlpha;
626 }
627
628 if (fp->hasConstantOutputForConstantInput()) {
629 ++optimizedForConstantOutputForInput;
630 }
631
632 if (fp->preservesOpaqueInput()) {
633 ++optimizedForOpaqueInput;
Michael Ludwig7034f152018-10-08 16:43:58 -0400634 }
Brian Salomon3f4de782020-06-18 14:16:00 -0400635
John Stiles0dee9b02020-07-20 11:45:58 -0400636 // Draw base frame last so that rtc holds the original FP behavior if we need to dump
637 // the image to the log.
Robert Phillips4dca8312021-07-28 15:13:20 -0400638 render_fp(context, sdc.get(), fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1),
John Stiles87d0a2f2020-08-10 13:12:41 -0400639 readData1.data());
Brian Salomonaff329b2017-08-11 09:40:37 -0400640
Michael Ludwig314d3772018-10-03 16:04:38 -0400641 // This test has a history of being flaky on a number of devices. If an FP is logically
642 // violating the optimizations, it's reasonable to expect it to violate requirements on
643 // a large number of pixels in the image. Sporadic pixel violations are more indicative
644 // of device errors and represents a separate problem.
Michael Ludwig72ab3462018-12-10 12:43:36 -0500645#if defined(SK_BUILD_FOR_SKQP)
Michael Ludwig314d3772018-10-03 16:04:38 -0400646 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
647#else
648 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
649#endif
650
Michael Ludwig314d3772018-10-03 16:04:38 -0400651 // Collect first optimization failure message, to be output later as a warning or an
652 // error depending on whether the rendering "passed" or failed.
John Stilesaf110302020-07-20 09:45:51 -0400653 int failedPixelCount = 0;
Michael Ludwig314d3772018-10-03 16:04:38 -0400654 SkString coverageMessage;
655 SkString opaqueMessage;
656 SkString constMessage;
657 for (int y = 0; y < kRenderSize; ++y) {
658 for (int x = 0; x < kRenderSize; ++x) {
659 bool passing = true;
John Stiles4ed69472020-08-11 16:04:31 -0400660 GrColor input = inputPixels1[y * kRenderSize + x];
John Stilesaf110302020-07-20 09:45:51 -0400661 GrColor output = readData1[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400662
663 if (fp->compatibleWithCoverageAsAlpha()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500664 GrColor ins[3];
665 ins[0] = input;
John Stiles4ed69472020-08-11 16:04:31 -0400666 ins[1] = inputPixels2[y * kRenderSize + x];
667 ins[2] = inputPixels3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400668
Brian Salomonbc73eb42019-12-18 14:57:45 -0500669 GrColor outs[3];
670 outs[0] = output;
John Stilesaf110302020-07-20 09:45:51 -0400671 outs[1] = readData2[y * kRenderSize + x];
672 outs[2] = readData3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400673
Brian Salomonbc73eb42019-12-18 14:57:45 -0500674 if (!legal_modulation(ins, outs)) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500675 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400676 if (coverageMessage.isEmpty()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500677 coverageMessage.printf(
John Stilesba1879d2020-08-11 13:58:32 -0400678 "\"Modulating\" processor did not match alpha-modulation "
679 "nor color-modulation rules.\n"
Michael Ludwig7034f152018-10-08 16:43:58 -0400680 "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
John Stilesba1879d2020-08-11 13:58:32 -0400681 input, output, x, y);
Michael Ludwig314d3772018-10-03 16:04:38 -0400682 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500683 }
684 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400685
Brian Osmancb3d0872018-10-16 15:19:28 -0400686 SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
687 SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
Brian Osman1d5b5982018-10-01 13:41:39 -0400688 SkPMColor4f expected4f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400689 if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400690 float rDiff = fabsf(output4f.fR - expected4f.fR);
691 float gDiff = fabsf(output4f.fG - expected4f.fG);
692 float bDiff = fabsf(output4f.fB - expected4f.fB);
693 float aDiff = fabsf(output4f.fA - expected4f.fA);
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500694 static constexpr float kTol = 4 / 255.f;
Brian Salomon587e08f2017-01-27 10:59:27 -0500695 if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400696 if (constMessage.isEmpty()) {
697 passing = false;
698
John Stilesba1879d2020-08-11 13:58:32 -0400699 constMessage.printf(
700 "Processor claimed output for const input doesn't match "
701 "actual output.\n"
702 "Error: %f, Tolerance: %f, input: (%f, %f, %f, %f), "
703 "actual: (%f, %f, %f, %f), expected(%f, %f, %f, %f).",
704 std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))),
705 kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA,
Brian Osmancb3d0872018-10-16 15:19:28 -0400706 output4f.fR, output4f.fG, output4f.fB, output4f.fA,
707 expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
Michael Ludwig314d3772018-10-03 16:04:38 -0400708 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500709 }
710 }
Brian Osman00b29392018-11-05 15:42:43 -0500711 if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500712 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400713
714 if (opaqueMessage.isEmpty()) {
John Stilesba1879d2020-08-11 13:58:32 -0400715 opaqueMessage.printf(
716 "Processor claimed opaqueness is preserved but "
Michael Ludwig314d3772018-10-03 16:04:38 -0400717 "it is not. Input: 0x%08x, Output: 0x%08x.",
John Stilesba1879d2020-08-11 13:58:32 -0400718 input, output);
Michael Ludwige8e10752018-10-01 12:42:53 -0400719 }
Brian Osmanbd1f76f2017-03-15 11:33:12 -0400720 }
Michael Ludwig314d3772018-10-03 16:04:38 -0400721
722 if (!passing) {
723 // Regardless of how many optimizations the pixel violates, count it as a
724 // single bad pixel.
725 failedPixelCount++;
726 }
727 }
728 }
729
730 // Finished analyzing the entire image, see if the number of pixel failures meets the
731 // threshold for an FP violating the optimization requirements.
732 if (failedPixelCount > kMaxAcceptableFailedPixels) {
John Stilesba1879d2020-08-11 13:58:32 -0400733 ERRORF(reporter,
734 "Processor violated %d of %d pixels, seed: 0x%08x.\n"
735 "Processor:\n%s\nFirst failing pixel details are below:",
John Stilesaf110302020-07-20 09:45:51 -0400736 failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
John Stilesba1879d2020-08-11 13:58:32 -0400737 fp->dumpTreeInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400738
739 // Print first failing pixel's details.
740 if (!coverageMessage.isEmpty()) {
741 ERRORF(reporter, coverageMessage.c_str());
742 }
743 if (!constMessage.isEmpty()) {
744 ERRORF(reporter, constMessage.c_str());
745 }
746 if (!opaqueMessage.isEmpty()) {
747 ERRORF(reporter, opaqueMessage.c_str());
748 }
749
750 if (!loggedFirstFailure) {
751 // Print with ERRORF to make sure the encoded image is output
752 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500753 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400754 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400755 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400756 ERRORF(reporter, "Input image: %s\n\n"
757 "===========================================================\n\n"
758 "Output image: %s\n", input.c_str(), output.c_str());
759 loggedFirstFailure = true;
760 }
John Stilesaf110302020-07-20 09:45:51 -0400761 } else if (failedPixelCount > 0) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400762 // Don't trigger an error, but don't just hide the failures either.
763 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
764 "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
John Stilesaf110302020-07-20 09:45:51 -0400765 fpGenerator.initialSeed(), fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400766 if (!coverageMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400767 INFOF(reporter, "%s", coverageMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400768 }
769 if (!constMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400770 INFOF(reporter, "%s", constMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400771 }
772 if (!opaqueMessage.isEmpty()) {
John Stiles7bf79992021-06-25 11:05:20 -0400773 INFOF(reporter, "%s", opaqueMessage.c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400774 }
775 if (!loggedFirstWarning) {
776 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500777 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400778 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400779 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400780 INFOF(reporter, "Input image: %s\n\n"
781 "===========================================================\n\n"
782 "Output image: %s\n", input.c_str(), output.c_str());
783 loggedFirstWarning = true;
Brian Salomon587e08f2017-01-27 10:59:27 -0500784 }
785 }
786 }
787 }
788}
Robert Phillips18166ee2017-06-01 12:55:44 -0400789
John Stilesea8be212020-08-10 11:38:41 -0400790static void assert_processor_equality(skiatest::Reporter* reporter,
791 const GrFragmentProcessor& fp,
792 const GrFragmentProcessor& clone) {
793 REPORTER_ASSERT(reporter, !strcmp(fp.name(), clone.name()),
John Stilesba1879d2020-08-11 13:58:32 -0400794 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400795 REPORTER_ASSERT(reporter, fp.compatibleWithCoverageAsAlpha() ==
796 clone.compatibleWithCoverageAsAlpha(),
John Stilesba1879d2020-08-11 13:58:32 -0400797 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400798 REPORTER_ASSERT(reporter, fp.isEqual(clone),
John Stilesba1879d2020-08-11 13:58:32 -0400799 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400800 REPORTER_ASSERT(reporter, fp.preservesOpaqueInput() == clone.preservesOpaqueInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400801 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400802 REPORTER_ASSERT(reporter, fp.hasConstantOutputForConstantInput() ==
803 clone.hasConstantOutputForConstantInput(),
John Stilesba1879d2020-08-11 13:58:32 -0400804 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400805 REPORTER_ASSERT(reporter, fp.numChildProcessors() == clone.numChildProcessors(),
John Stilesba1879d2020-08-11 13:58:32 -0400806 "\n%s", fp.dumpTreeInfo().c_str());
Brian Salomon66b500a2021-08-02 12:37:14 -0400807 REPORTER_ASSERT(reporter, fp.sampleUsage() == clone.sampleUsage(),
John Stilesba1879d2020-08-11 13:58:32 -0400808 "\n%s", fp.dumpTreeInfo().c_str());
Brian Salomon66b500a2021-08-02 12:37:14 -0400809 REPORTER_ASSERT(reporter, fp.usesSampleCoords() == clone.usesSampleCoords(),
John Stilesba1879d2020-08-11 13:58:32 -0400810 "\n%s", fp.dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400811}
812
813static bool verify_identical_render(skiatest::Reporter* reporter, int renderSize,
814 const char* processorType,
815 const GrColor readData1[], const GrColor readData2[]) {
816 // The ProcessorClone test has a history of being flaky on a number of devices. If an FP clone
817 // is logically wrong, it's reasonable to expect it produce a large number of pixel differences
818 // in the image. Sporadic pixel violations are more indicative device errors and represents a
819 // separate problem.
820#if defined(SK_BUILD_FOR_SKQP)
821 const int maxAcceptableFailedPixels = 0; // Strict when running as SKQP
822#else
823 const int maxAcceptableFailedPixels = 2 * renderSize; // ~0.002% of the pixels (size 1024*1024)
824#endif
825
826 int failedPixelCount = 0;
827 int firstWrongX = 0;
828 int firstWrongY = 0;
829 int idx = 0;
830 for (int y = 0; y < renderSize; ++y) {
831 for (int x = 0; x < renderSize; ++x, ++idx) {
832 if (readData1[idx] != readData2[idx]) {
833 if (!failedPixelCount) {
834 firstWrongX = x;
835 firstWrongY = y;
836 }
837 ++failedPixelCount;
838 }
839 if (failedPixelCount > maxAcceptableFailedPixels) {
840 idx = firstWrongY * renderSize + firstWrongX;
841 ERRORF(reporter,
842 "%s produced different output at (%d, %d). "
843 "Input color: 0x%08x, Original Output Color: 0x%08x, "
844 "Clone Output Color: 0x%08x.",
845 processorType, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
846 readData1[idx], readData2[idx]);
847
848 return false;
849 }
850 }
851 }
852
853 return true;
854}
855
856static void log_clone_failure(skiatest::Reporter* reporter, int renderSize,
857 GrDirectContext* context, const GrSurfaceProxyView& inputTexture,
858 GrColor pixelsFP[], GrColor pixelsClone[], GrColor pixelsRegen[]) {
859 // Write the images out as data URLs for inspection.
860 SkString inputURL, origURL, cloneURL, regenURL;
861 if (log_texture_view(context, inputTexture, &inputURL) &&
862 log_pixels(pixelsFP, renderSize, &origURL) &&
863 log_pixels(pixelsClone, renderSize, &cloneURL) &&
864 log_pixels(pixelsRegen, renderSize, &regenURL)) {
865 ERRORF(reporter,
866 "\nInput image:\n%s\n\n"
867 "==========================================================="
868 "\n\n"
869 "Orig output image:\n%s\n"
870 "==========================================================="
871 "\n\n"
872 "Clone output image:\n%s\n"
873 "==========================================================="
874 "\n\n"
875 "Regen output image:\n%s\n",
876 inputURL.c_str(), origURL.c_str(), cloneURL.c_str(), regenURL.c_str());
877 }
878}
879
Brian Salomon3f4de782020-06-18 14:16:00 -0400880// Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
881// progenitor.
Brian Salomon0e05a822017-07-25 09:43:22 -0400882DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400883 GrDirectContext* context = ctxInfo.directContext();
884 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon0e05a822017-07-25 09:43:22 -0400885
John Stilesaf110302020-07-20 09:45:51 -0400886 TestFPGenerator fpGenerator{context, resourceProvider};
887 if (!fpGenerator.init()) {
888 ERRORF(reporter, "Could not initialize TestFPGenerator");
889 return;
890 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400891
892 // Make the destination context for the test.
893 static constexpr int kRenderSize = 1024;
Robert Phillips4dca8312021-07-28 15:13:20 -0400894 auto sdc = skgpu::v1::SurfaceDrawContext::Make(
Greg Daniele20fcad2020-01-08 11:52:34 -0500895 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
Chris Daltonf5b87f92021-04-19 17:27:09 -0600896 {kRenderSize, kRenderSize}, SkSurfaceProps());
Brian Salomon0e05a822017-07-25 09:43:22 -0400897
John Stiles4ed69472020-08-11 16:04:31 -0400898 std::vector<GrColor> inputPixels = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
899 GrSurfaceProxyView inputTexture =
900 make_input_texture(context, kRenderSize, kRenderSize, inputPixels.data());
John Stilesaf110302020-07-20 09:45:51 -0400901
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400902 // On failure we write out images, but just write the first failing set as the print is very
903 // large.
904 bool loggedFirstFailure = false;
905
John Stilesaf110302020-07-20 09:45:51 -0400906 // Storage for the original frame's readback and the readback of its clone.
John Stilesea8be212020-08-10 11:38:41 -0400907 std::vector<GrColor> readDataFP(kRenderSize * kRenderSize);
908 std::vector<GrColor> readDataClone(kRenderSize * kRenderSize);
909 std::vector<GrColor> readDataRegen(kRenderSize * kRenderSize);
Brian Salomon0e05a822017-07-25 09:43:22 -0400910
911 // Because processor factories configure themselves in random ways, this is not exhaustive.
912 for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
913 static constexpr int kTimesToInvokeFactory = 10;
914 for (int j = 0; j < kTimesToInvokeFactory; ++j) {
John Stilesaf110302020-07-20 09:45:51 -0400915 fpGenerator.reroll();
John Stiles87d0a2f2020-08-10 13:12:41 -0400916 std::unique_ptr<GrFragmentProcessor> fp =
John Stiles9fbe9e92020-08-10 16:35:01 -0400917 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles87d0a2f2020-08-10 13:12:41 -0400918 std::unique_ptr<GrFragmentProcessor> regen =
John Stiles9fbe9e92020-08-10 16:35:01 -0400919 fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
John Stiles8c71f3e2020-06-15 15:07:19 -0400920 std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
Brian Salomon0e05a822017-07-25 09:43:22 -0400921 if (!clone) {
John Stilesba1879d2020-08-11 13:58:32 -0400922 ERRORF(reporter, "Clone of processor %s failed.", fp->dumpTreeInfo().c_str());
Brian Salomon0e05a822017-07-25 09:43:22 -0400923 continue;
924 }
John Stilesea8be212020-08-10 11:38:41 -0400925 assert_processor_equality(reporter, *fp, *clone);
926
Brian Salomon0e05a822017-07-25 09:43:22 -0400927 // Draw with original and read back the results.
Robert Phillips4dca8312021-07-28 15:13:20 -0400928 render_fp(context, sdc.get(), std::move(fp), readDataFP.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400929
930 // Draw with clone and read back the results.
Robert Phillips4dca8312021-07-28 15:13:20 -0400931 render_fp(context, sdc.get(), std::move(clone), readDataClone.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400932
933 // Check that the results are the same.
John Stilesea8be212020-08-10 11:38:41 -0400934 if (!verify_identical_render(reporter, kRenderSize, "Processor clone",
935 readDataFP.data(), readDataClone.data())) {
936 // Dump a description from the regenerated processor (since the original FP has
937 // already been consumed).
John Stilesba1879d2020-08-11 13:58:32 -0400938 ERRORF(reporter, "FP hierarchy:\n%s", regen->dumpTreeInfo().c_str());
John Stilesea8be212020-08-10 11:38:41 -0400939
940 // Render and readback output from the regenerated FP. If this also mismatches, the
941 // FP itself doesn't generate consistent output. This could happen if:
942 // - the FP's TestCreate() does not always generate the same FP from a given seed
943 // - the FP's Make() does not always generate the same FP when given the same inputs
944 // - the FP itself generates inconsistent pixels (shader UB?)
945 // - the driver has a bug
Robert Phillips4dca8312021-07-28 15:13:20 -0400946 render_fp(context, sdc.get(), std::move(regen), readDataRegen.data());
John Stilesea8be212020-08-10 11:38:41 -0400947
948 if (!verify_identical_render(reporter, kRenderSize, "Regenerated processor",
949 readDataFP.data(), readDataRegen.data())) {
950 ERRORF(reporter, "Output from regen did not match original!\n");
951 } else {
952 ERRORF(reporter, "Regenerated processor output matches original results.\n");
953 }
954
955 // If this is the first time we've encountered a cloning failure, log the generated
956 // images to the reporter as data URLs.
957 if (!loggedFirstFailure) {
958 log_clone_failure(reporter, kRenderSize, context, inputTexture,
959 readDataFP.data(), readDataClone.data(),
960 readDataRegen.data());
961 loggedFirstFailure = true;
Brian Salomon0e05a822017-07-25 09:43:22 -0400962 }
963 }
964 }
965 }
966}
967
Hal Canary6f6961e2017-01-31 13:50:44 -0500968#endif // GR_TEST_UTILS