blob: e80ec51f6268a9c00cf9ea4e06c0b92e7cf6ad6a [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"
Greg Daniel6f5441a2020-01-28 17:02:49 -050011#include "src/gpu/GrBitmapTextureMaker.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050012#include "src/gpu/GrClip.h"
13#include "src/gpu/GrContextPriv.h"
Greg Daniel456f9b52020-03-05 19:14:18 +000014#include "src/gpu/GrGpuResource.h"
Brian Salomonf2ebdd92019-09-30 12:15:30 -040015#include "src/gpu/GrImageInfo.h"
Mike Kleinc0bd9f92019-04-23 12:05:21 -050016#include "src/gpu/GrMemoryPool.h"
17#include "src/gpu/GrProxyProvider.h"
18#include "src/gpu/GrRenderTargetContext.h"
19#include "src/gpu/GrRenderTargetContextPriv.h"
20#include "src/gpu/GrResourceProvider.h"
21#include "src/gpu/glsl/GrGLSLFragmentProcessor.h"
22#include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
23#include "src/gpu/ops/GrFillRectOp.h"
24#include "src/gpu/ops/GrMeshDrawOp.h"
25#include "tests/TestUtils.h"
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
Robert Phillips7c525e62018-06-12 10:11:12 -040033 static std::unique_ptr<GrDrawOp> Make(GrContext* context,
34 std::unique_ptr<GrFragmentProcessor> fp) {
Robert Phillips9da87e02019-02-04 13:26:26 -050035 GrOpMemoryPool* pool = context->priv().opMemoryPool();
Robert Phillipsc994a932018-06-19 13:09:54 -040036
37 return pool->allocate<TestOp>(std::move(fp));
Brian Salomon82ddc942017-07-14 12:00:13 -040038 }
39
Robert Phillips5f567c72017-09-14 08:27:37 -040040 const char* name() const override { return "TestOp"; }
41
Chris Dalton1706cbf2019-05-21 19:35:29 -060042 void visitProxies(const VisitProxyFunc& func) const override {
Robert Phillips5f567c72017-09-14 08:27:37 -040043 fProcessors.visitProxies(func);
44 }
45
Brian Salomon82ddc942017-07-14 12:00:13 -040046 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
47
Chris Dalton6ce447a2019-06-23 18:07:38 -060048 GrProcessorSet::Analysis finalize(
49 const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
50 GrClampType clampType) override {
Brian Salomon82ddc942017-07-14 12:00:13 -040051 static constexpr GrProcessorAnalysisColor kUnknownColor;
Brian Osmancf860852018-10-31 14:04:39 -040052 SkPMColor4f overrideColor;
Chris Daltonb8fff0d2019-03-05 10:11:58 -070053 return fProcessors.finalize(
54 kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip,
Chris Dalton6ce447a2019-06-23 18:07:38 -060055 &GrUserStencilSettings::kUnused, hasMixedSampledCoverage, caps, clampType,
56 &overrideColor);
Brian Salomon649a3412017-03-09 13:50:43 -050057 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050058
59private:
Robert Phillips7c525e62018-06-12 10:11:12 -040060 friend class ::GrOpMemoryPool; // for ctor
61
Brian Salomonaff329b2017-08-11 09:40:37 -040062 TestOp(std::unique_ptr<GrFragmentProcessor> fp)
63 : INHERITED(ClassID()), fProcessors(std::move(fp)) {
Greg Daniel5faf4742019-10-01 15:14:44 -040064 this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
Brian Salomon82ddc942017-07-14 12:00:13 -040065 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050066
Robert Phillips2669a7b2020-03-12 12:07:19 -040067 GrProgramInfo* programInfo() override { return nullptr; }
Robert Phillips4133dc42020-03-11 15:55:55 -040068 void onCreateProgramInfo(const GrCaps*,
69 SkArenaAlloc*,
Brian Salomon8afde5f2020-04-01 16:22:00 -040070 const GrSurfaceProxyView* writeView,
Robert Phillips4133dc42020-03-11 15:55:55 -040071 GrAppliedClip&&,
72 const GrXferProcessor::DstProxyView&) override { return; }
Robert Phillips2669a7b2020-03-12 12:07:19 -040073 void onPrePrepareDraws(GrRecordingContext*,
Brian Salomon8afde5f2020-04-01 16:22:00 -040074 const GrSurfaceProxyView* writeView,
Robert Phillips2669a7b2020-03-12 12:07:19 -040075 GrAppliedClip*,
76 const GrXferProcessor::DstProxyView&) override { return; }
Brian Salomon91326c32017-08-09 16:02:19 -040077 void onPrepareDraws(Target* target) override { return; }
Chris Dalton07cdcfc92019-02-26 11:13:22 -070078 void onExecute(GrOpFlushState*, const SkRect&) override { return; }
Brian Salomonbc6b99d2017-01-11 10:32:34 -050079
Brian Salomon82ddc942017-07-14 12:00:13 -040080 GrProcessorSet fProcessors;
81
82 typedef GrMeshDrawOp INHERITED;
Brian Salomonbc6b99d2017-01-11 10:32:34 -050083};
84
85/**
Robert Phillips3d4cac52019-06-11 08:08:08 -040086 * 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 -050087 * of resources owned by child FPs.
88 */
89class TestFP : public GrFragmentProcessor {
90public:
Brian Salomonaff329b2017-08-11 09:40:37 -040091 static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) {
92 return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child)));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050093 }
Brian Salomon92b9ccf2020-06-17 14:19:19 -040094 static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<GrSurfaceProxyView>& views) {
95 return std::unique_ptr<GrFragmentProcessor>(new TestFP(views));
Brian Salomonbc6b99d2017-01-11 10:32:34 -050096 }
97
98 const char* name() const override { return "test"; }
99
100 void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
Mike Klein0ec1c572018-12-04 11:52:51 -0500101 static std::atomic<int32_t> nextKey{0};
102 b->add32(nextKey++);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500103 }
104
Brian Salomonaff329b2017-08-11 09:40:37 -0400105 std::unique_ptr<GrFragmentProcessor> clone() const override {
106 return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this));
Brian Salomonb17e6392017-07-28 13:41:51 -0400107 }
108
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500109private:
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400110 TestFP(const SkTArray<GrSurfaceProxyView>& views)
111 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
John Stilesfe7aed62020-07-20 13:48:02 -0400112 for (const GrSurfaceProxyView& view : views) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400113 this->registerChild(GrTextureEffect::Make(view, kUnknown_SkAlphaType));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500114 }
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500115 }
116
Brian Salomonaff329b2017-08-11 09:40:37 -0400117 TestFP(std::unique_ptr<GrFragmentProcessor> child)
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400118 : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
Michael Ludwig9aba6252020-06-22 14:46:36 -0400119 this->registerChild(std::move(child));
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500120 }
121
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400122 explicit TestFP(const TestFP& that) : INHERITED(kTestFP_ClassID, that.optimizationFlags()) {
123 this->cloneAndRegisterAllChildProcessors(that);
Brian Salomonb17e6392017-07-28 13:41:51 -0400124 }
125
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500126 virtual GrGLSLFragmentProcessor* onCreateGLSLInstance() const override {
127 class TestGLSLFP : public GrGLSLFragmentProcessor {
128 public:
129 TestGLSLFP() {}
130 void emitCode(EmitArgs& args) override {
131 GrGLSLFPFragmentBuilder* fragBuilder = args.fFragBuilder;
132 fragBuilder->codeAppendf("%s = %s;", args.fOutputColor, args.fInputColor);
133 }
134
135 private:
136 };
137 return new TestGLSLFP();
138 }
139
140 bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
141
Brian Salomon587e08f2017-01-27 10:59:27 -0500142 typedef GrFragmentProcessor INHERITED;
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500143};
144}
145
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500146DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
Robert Phillips6d344c32020-07-06 10:56:46 -0400147 auto context = ctxInfo.directContext();
Robert Phillips9da87e02019-02-04 13:26:26 -0500148 GrProxyProvider* proxyProvider = context->priv().proxyProvider();
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500149
Brian Salomona56a7462020-02-07 14:17:25 -0500150 static constexpr SkISize kDims = {10, 10};
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500151
Greg Daniel4065d452018-11-16 15:43:41 -0500152 const GrBackendFormat format =
Robert Phillips0a15cc62019-07-30 12:49:10 -0400153 context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
154 GrRenderable::kNo);
Greg Daniel47c20e82020-01-21 14:29:57 -0500155 GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
Greg Daniel4065d452018-11-16 15:43:41 -0500156
Brian Salomonb17e6392017-07-28 13:41:51 -0400157 for (bool makeClone : {false, true}) {
158 for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
Greg Daniele20fcad2020-01-08 11:52:34 -0500159 auto renderTargetContext = GrRenderTargetContext::Make(
160 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1});
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500161 {
Robert Phillips3d4cac52019-06-11 08:08:08 -0400162 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
Brian Salomondf1bd6d2020-03-26 20:37:01 -0400163 format, kDims, GrRenderable::kNo, 1, GrMipMapped::kNo, SkBackingFit::kExact,
164 SkBudgeted::kYes, GrProtected::kNo);
Robert Phillips3d4cac52019-06-11 08:08:08 -0400165
Brian Salomonb17e6392017-07-28 13:41:51 -0400166 {
Greg Daniel026a60c2020-02-12 10:53:51 -0500167 SkTArray<GrSurfaceProxyView> views;
Greg Daniel026a60c2020-02-12 10:53:51 -0500168 views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
Brian Salomon92b9ccf2020-06-17 14:19:19 -0400169 auto fp = TestFP::Make(std::move(views));
Brian Salomonb17e6392017-07-28 13:41:51 -0400170 for (int i = 0; i < parentCnt; ++i) {
171 fp = TestFP::Make(std::move(fp));
172 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400173 std::unique_ptr<GrFragmentProcessor> clone;
Brian Salomonb17e6392017-07-28 13:41:51 -0400174 if (makeClone) {
175 clone = fp->clone();
176 }
Robert Phillips7c525e62018-06-12 10:11:12 -0400177 std::unique_ptr<GrDrawOp> op(TestOp::Make(context, std::move(fp)));
Brian Salomonb17e6392017-07-28 13:41:51 -0400178 renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));
179 if (clone) {
Robert Phillips7c525e62018-06-12 10:11:12 -0400180 op = TestOp::Make(context, std::move(clone));
Brian Salomonb17e6392017-07-28 13:41:51 -0400181 renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));
182 }
183 }
Brian Salomonb17e6392017-07-28 13:41:51 -0400184
Robert Phillips3d4cac52019-06-11 08:08:08 -0400185 // If the fp is cloned the number of refs should increase by one (for the clone)
186 int expectedProxyRefs = makeClone ? 3 : 2;
187
Brian Salomon28a8f282019-10-24 20:07:39 -0400188 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
Brian Salomonb17e6392017-07-28 13:41:51 -0400189
Greg Daniel0a2464f2020-05-14 15:45:44 -0400190 context->flushAndSubmit();
Brian Salomonb17e6392017-07-28 13:41:51 -0400191
Brian Salomon557e8122019-10-24 10:37:08 -0400192 // just one from the 'proxy' sk_sp
Brian Salomon28a8f282019-10-24 20:07:39 -0400193 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
Brian Salomonbc6b99d2017-01-11 10:32:34 -0500194 }
195 }
196 }
197}
Brian Salomon587e08f2017-01-27 10:59:27 -0500198
Mike Kleinc0bd9f92019-04-23 12:05:21 -0500199#include "tools/flags/CommandLineFlags.h"
Mike Klein84836b72019-03-21 11:31:36 -0500200static DEFINE_bool(randomProcessorTest, false,
201 "Use non-deterministic seed for random processor tests?");
Mike Klein5b3f3432019-03-21 11:42:21 -0500202static DEFINE_int(processorSeed, 0,
203 "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
Brian Salomon0e05a822017-07-25 09:43:22 -0400204
205#if GR_TEST_UTILS
206
Michael Ludwig7034f152018-10-08 16:43:58 -0400207static GrColor input_texel_color(int i, int j, SkScalar delta) {
208 // Delta must be less than 0.5 to prevent over/underflow issues with the input color
209 SkASSERT(delta <= 0.5);
Brian Salomon587e08f2017-01-27 10:59:27 -0500210
Brian Osman50ea3c02019-02-04 10:01:53 -0500211 SkColor color = SkColorSetARGB((uint8_t)(i & 0xFF),
212 (uint8_t)(j & 0xFF),
213 (uint8_t)((i + j) & 0xFF),
214 (uint8_t)((2 * j - i) & 0xFF));
Brian Osmancb3d0872018-10-16 15:19:28 -0400215 SkColor4f color4f = SkColor4f::FromColor(color);
Brian Salomonbc73eb42019-12-18 14:57:45 -0500216 // We only apply delta to the r,g, and b channels. This is because we're using this
217 // to test the canTweakAlphaForCoverage() optimization. A processor is allowed
218 // to use the input color's alpha in its calculation and report this optimization.
219 for (int i = 0; i < 3; i++) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400220 if (color4f[i] > 0.5) {
221 color4f[i] -= delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400222 } else {
Brian Osmancb3d0872018-10-16 15:19:28 -0400223 color4f[i] += delta;
Michael Ludwig7034f152018-10-08 16:43:58 -0400224 }
225 }
Brian Osmancb3d0872018-10-16 15:19:28 -0400226 return color4f.premul().toBytes_RGBA();
Brian Salomon0e05a822017-07-25 09:43:22 -0400227}
Brian Salomon587e08f2017-01-27 10:59:27 -0500228
John Stiles0dee9b02020-07-20 11:45:58 -0400229void test_draw_op(GrContext* context, GrRenderTargetContext* rtc,
230 std::unique_ptr<GrFragmentProcessor> fp) {
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500231 GrPaint paint;
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500232 paint.addColorFragmentProcessor(std::move(fp));
233 paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
Brian Salomonac70f842017-05-08 10:43:33 -0400234
Michael Ludwigaa1b6b32019-05-29 14:43:13 -0400235 auto op = GrFillRectOp::MakeNonAARect(context, std::move(paint), SkMatrix::I(),
236 SkRect::MakeWH(rtc->width(), rtc->height()));
Brian Salomonfc118442019-11-22 19:09:27 -0500237 rtc->priv().testingOnly_addDrawOp(std::move(op));
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500238}
239
John Stiles0dee9b02020-07-20 11:45:58 -0400240// The output buffer must be the same size as the render-target context.
241void render_fp(GrContext* context, GrRenderTargetContext* rtc,
Brian Salomon3f4de782020-06-18 14:16:00 -0400242 std::unique_ptr<GrFragmentProcessor> fp,
John Stiles0dee9b02020-07-20 11:45:58 -0400243 GrColor* outBuffer) {
244 test_draw_op(context, rtc, std::move(fp));
245 std::fill_n(outBuffer, rtc->width() * rtc->height(), 0);
246 rtc->readPixels(SkImageInfo::Make(rtc->width(), rtc->height(), kRGBA_8888_SkColorType,
Brian Salomon9f2b86c2019-10-22 10:37:46 -0400247 kPremul_SkAlphaType),
John Stiles0dee9b02020-07-20 11:45:58 -0400248 outBuffer, /*rowBytes=*/0, /*srcPt=*/{0, 0});
Michael Ludwig7034f152018-10-08 16:43:58 -0400249}
250
John Stilesaf110302020-07-20 09:45:51 -0400251// This class is responsible for reproducibly generating a random fragment processor.
252// An identical randomly-designed FP can be generated as many times as needed.
253class TestFPGenerator {
254 public:
255 TestFPGenerator() = delete;
256 TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
257 : fContext(context)
258 , fResourceProvider(resourceProvider)
259 , fInitialSeed(synthesizeInitialSeed())
260 , fRandomSeed(fInitialSeed) {}
Brian Osmanc35a2d42017-03-17 10:58:53 -0400261
John Stilesaf110302020-07-20 09:45:51 -0400262 uint32_t initialSeed() { return fInitialSeed; }
263
264 bool init() {
265 // Initializes the two test texture proxies that are available to the FP test factories.
266 SkRandom random{fRandomSeed};
267 static constexpr int kTestTextureSize = 256;
268
269 {
270 // Put premul data into the RGBA texture that the test FPs can optionally use.
271 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
272 for (int y = 0; y < kTestTextureSize; ++y) {
273 for (int x = 0; x < kTestTextureSize; ++x) {
274 rgbaData[kTestTextureSize * y + x] = input_texel_color(
275 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
276 }
277 }
278
279 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
280 kRGBA_8888_SkColorType, kPremul_SkAlphaType);
281 SkBitmap bitmap;
282 bitmap.installPixels(
283 ii, rgbaData, ii.minRowBytes(),
284 [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
285 bitmap.setImmutable();
286 GrBitmapTextureMaker maker(fContext, bitmap,
287 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
288 GrSurfaceProxyView view = maker.view(GrMipMapped::kNo);
289 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
290 SkDebugf("Unable to instantiate RGBA8888 test texture.");
291 return false;
292 }
293 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
294 kPremul_SkAlphaType};
295 }
296
297 {
298 // Put random values into the alpha texture that the test FPs can optionally use.
299 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
300 for (int y = 0; y < kTestTextureSize; ++y) {
301 for (int x = 0; x < kTestTextureSize; ++x) {
302 alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
303 }
304 }
305
306 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
307 kAlpha_8_SkColorType, kPremul_SkAlphaType);
308 SkBitmap bitmap;
309 bitmap.installPixels(
310 ii, alphaData, ii.minRowBytes(),
311 [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
312 bitmap.setImmutable();
313 GrBitmapTextureMaker maker(fContext, bitmap,
314 GrImageTexGenPolicy::kNew_Uncached_Budgeted);
315 GrSurfaceProxyView view = maker.view(GrMipMapped::kNo);
316 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
317 SkDebugf("Unable to instantiate A8 test texture.");
318 return false;
319 }
320 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
321 kPremul_SkAlphaType};
322 }
323
324 return true;
325 }
326
327 void reroll() {
328 // Feed our current random seed into SkRandom to generate a new seed.
329 SkRandom random{fRandomSeed};
330 fRandomSeed = random.nextU();
331 }
332
John Stiles0dee9b02020-07-20 11:45:58 -0400333 std::unique_ptr<GrFragmentProcessor> make(int type,
334 std::unique_ptr<GrFragmentProcessor> inputFP) {
John Stilesaf110302020-07-20 09:45:51 -0400335 // This will generate the exact same randomized FP (of each requested type) each time
336 // it's called. Call `reroll` to get a different FP.
337 SkRandom random{fRandomSeed};
John Stiles0dee9b02020-07-20 11:45:58 -0400338 GrProcessorTestData testData{&random, fContext, SK_ARRAY_COUNT(fTestViews), fTestViews,
339 std::move(inputFP)};
John Stilesaf110302020-07-20 09:45:51 -0400340 return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
341 }
342
John Stiles0dee9b02020-07-20 11:45:58 -0400343 std::unique_ptr<GrFragmentProcessor> make(int type, GrSurfaceProxyView view,
344 SkAlphaType alpha = kPremul_SkAlphaType) {
345 return make(type, GrTextureEffect::Make(view, alpha));
346 }
347
John Stilesaf110302020-07-20 09:45:51 -0400348 private:
349 static uint32_t synthesizeInitialSeed() {
350 if (FLAGS_randomProcessorTest) {
351 std::random_device rd;
352 return rd();
353 } else {
354 return FLAGS_processorSeed;
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500355 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400356 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400357
John Stilesaf110302020-07-20 09:45:51 -0400358 GrDirectContext* fContext; // owned by caller
359 GrResourceProvider* fResourceProvider; // owned by caller
360 const uint32_t fInitialSeed;
361 uint32_t fRandomSeed;
362 GrProcessorTestData::ViewInfo fTestViews[2];
363};
Brian Salomon0e05a822017-07-25 09:43:22 -0400364
365// Creates a texture of premul colors used as the output of the fragment processor that precedes
366// the fragment processor under test. Color values are those provided by input_texel_color().
Greg Daniel124486b2020-02-11 11:54:55 -0500367GrSurfaceProxyView make_input_texture(GrRecordingContext* context, int width, int height,
368 SkScalar delta) {
Greg Daniel6f5441a2020-01-28 17:02:49 -0500369 GrColor* data = new GrColor[width * height];
Brian Salomon0e05a822017-07-25 09:43:22 -0400370 for (int y = 0; y < width; ++y) {
371 for (int x = 0; x < height; ++x) {
Greg Daniel6f5441a2020-01-28 17:02:49 -0500372 data[width * y + x] = input_texel_color(x, y, delta);
Brian Salomon0e05a822017-07-25 09:43:22 -0400373 }
374 }
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500375
Brian Osman2700abc2018-09-12 10:19:41 -0400376 SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
Greg Daniel6f5441a2020-01-28 17:02:49 -0500377 SkBitmap bitmap;
378 bitmap.installPixels(ii, data, ii.minRowBytes(),
379 [](void* addr, void* context) { delete[] (GrColor*)addr; }, nullptr);
380 bitmap.setImmutable();
Brian Salomonbc074a62020-03-18 10:06:13 -0400381 GrBitmapTextureMaker maker(context, bitmap, GrImageTexGenPolicy::kNew_Uncached_Budgeted);
Brian Salomonecbb0fb2020-02-28 18:07:32 -0500382 return maker.view(GrMipMapped::kNo);
Brian Salomon0e05a822017-07-25 09:43:22 -0400383}
Robert Phillips0bd24dc2018-01-16 08:06:32 -0500384
John Stilesaf110302020-07-20 09:45:51 -0400385// We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400386// actually contains unpremul data. Also, even though we made the result data by rendering into
387// a "unpremul" GrRenderTargetContext, our input texture is unpremul and outside of the random
388// effect configuration, we didn't do anything to ensure the output is actually premul. We just
389// don't currently allow kUnpremul GrRenderTargetContexts.
390static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
Michael Ludwige8e10752018-10-01 12:42:53 -0400391
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400392bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
John Stilesaf110302020-07-20 09:45:51 -0400393 SkImageInfo info =
394 SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400395 SkBitmap bmp;
396 bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
Brian Salomon28a8f282019-10-24 20:07:39 -0400397 return BipmapToBase64DataURI(bmp, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400398}
399
Greg Daniel124486b2020-02-11 11:54:55 -0500400bool log_texture_view(GrContext* context, GrSurfaceProxyView src, SkString* dst) {
401 SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
402 kLogAlphaType);
Greg Daniel3912a4b2020-01-14 09:56:04 -0500403
Greg Daniel124486b2020-02-11 11:54:55 -0500404 auto sContext = GrSurfaceContext::Make(context, std::move(src), GrColorType::kRGBA_8888,
Greg Daniel3912a4b2020-01-14 09:56:04 -0500405 kLogAlphaType, nullptr);
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400406 SkBitmap bm;
407 SkAssertResult(bm.tryAllocPixels(ii));
408 SkAssertResult(sContext->readPixels(ii, bm.getPixels(), bm.rowBytes(), {0, 0}));
Brian Salomon28a8f282019-10-24 20:07:39 -0400409 return BipmapToBase64DataURI(bm, dst);
Michael Ludwige8e10752018-10-01 12:42:53 -0400410}
411
Michael Ludwig7034f152018-10-08 16:43:58 -0400412bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
413 // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
Brian Salomon682ba432019-12-17 20:20:23 +0000414 // 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 -0400415 // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
416 // too unforgiving).
Brian Salomon682ba432019-12-17 20:20:23 +0000417 static constexpr SkScalar kTolerance = 0.01f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400418 for (int i = 0; i < 4; i++) {
419 if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
420 return false;
421 }
422 }
423 return true;
424}
425
Brian Salomonbc73eb42019-12-18 14:57:45 -0500426// Given three input colors (color preceding the FP being tested) provided to the FP at the same
427// local coord and the three corresponding FP outputs, this ensures that either:
428// out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
429// where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
430// change), OR:
431// out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
432// (per-channel modulation instead of modulation by just the alpha channel)
433// It does this by estimating the pre-modulated fp color from one of the input/output pairs and
434// confirms the conditions hold for the other two pairs.
435// It is required that the three input colors have the same alpha as fp is allowed to be a function
436// of the input alpha (but not r, g, or b).
437bool legal_modulation(const GrColor in[3], const GrColor out[3]) {
Michael Ludwig7034f152018-10-08 16:43:58 -0400438 // Convert to floating point, which is the number space the FP operates in (more or less)
Brian Salomonbc73eb42019-12-18 14:57:45 -0500439 SkPMColor4f inf[3], outf[3];
440 for (int i = 0; i < 3; ++i) {
441 inf[i] = SkPMColor4f::FromBytes_RGBA(in[i]);
442 outf[i] = SkPMColor4f::FromBytes_RGBA(out[i]);
443 }
444 // This test is only valid if all the input alphas are the same.
445 SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
Michael Ludwig7034f152018-10-08 16:43:58 -0400446
447 // Reconstruct the output of the FP before the shader modulated its color with the input value.
448 // When the original input is very small, it may cause the final output color to round
449 // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
450 // will then have a guaranteed larger channel value (since the offset will be added to it).
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500451 SkPMColor4f fpPreColorModulation = {0,0,0,0};
452 SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
Michael Ludwig7034f152018-10-08 16:43:58 -0400453 for (int i = 0; i < 4; i++) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500454 // Use the most stepped up frame
455 int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
456 maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
John Stilesfe7aed62020-07-20 13:48:02 -0400457 const SkPMColor4f& in = inf[maxInIdx];
458 const SkPMColor4f& out = outf[maxInIdx];
Brian Salomon0a7ca7a2019-12-27 12:18:19 -0500459 if (in[i] > 0) {
460 fpPreColorModulation[i] = out[i] / in[i];
461 }
462 if (in[3] > 0) {
463 fpPreAlphaModulation[i] = out[i] / in[3];
464 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400465 }
466
467 // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
468 // of the transformed input colors.
Brian Salomonbc73eb42019-12-18 14:57:45 -0500469 SkPMColor4f expectedForAlphaModulation[3];
470 SkPMColor4f expectedForColorModulation[3];
471 for (int i = 0; i < 3; ++i) {
472 expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
473 expectedForColorModulation[i] = fpPreColorModulation * inf[i];
474 // If the input alpha is 0 then the other channels should also be zero
475 // since the color is assumed to be premul. Modulating zeros by anything
476 // should produce zeros.
477 if (inf[i].fA == 0) {
478 SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
479 expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
480 }
481 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400482
Brian Salomonbc73eb42019-12-18 14:57:45 -0500483 bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
484 fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
485 fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
486
487 bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
488 fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
489 fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
490
491 // This can be enabled to print the values that caused this check to fail.
492 if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
493 SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
494 fpPreColorModulation[0],
495 fpPreColorModulation[1],
496 fpPreColorModulation[2],
497 fpPreColorModulation[3]);
498 for (int i = 0; i < 3; ++i) {
499 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
500 "(%.03f, %.03f, %.03f, %.03f) | "
501 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
502 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
503 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
504 expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
505 expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
506 fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
507 }
508 SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
509 fpPreAlphaModulation[0],
510 fpPreAlphaModulation[1],
511 fpPreAlphaModulation[2],
512 fpPreAlphaModulation[3]);
513 for (int i = 0; i < 3; ++i) {
514 SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
515 "(%.03f, %.03f, %.03f, %.03f) | "
516 "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
517 inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
518 outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
519 expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
520 expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
521 fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
522 }
523 }
524 return isLegalColorModulation || isLegalAlphaModulation;
Michael Ludwig7034f152018-10-08 16:43:58 -0400525}
526
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500527DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400528 GrDirectContext* context = ctxInfo.directContext();
529 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon1c053642017-07-24 10:16:19 -0400530 using FPFactory = GrFragmentProcessorTestFactory;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400531
John Stilesaf110302020-07-20 09:45:51 -0400532 TestFPGenerator fpGenerator{context, resourceProvider};
533 if (!fpGenerator.init()) {
534 ERRORF(reporter, "Could not initialize TestFPGenerator");
535 return;
Brian Osmanc35a2d42017-03-17 10:58:53 -0400536 }
Brian Osmanc35a2d42017-03-17 10:58:53 -0400537
Brian Salomon0e05a822017-07-25 09:43:22 -0400538 // Make the destination context for the test.
539 static constexpr int kRenderSize = 256;
Greg Daniele20fcad2020-01-08 11:52:34 -0500540 auto rtc = GrRenderTargetContext::Make(
541 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
542 {kRenderSize, kRenderSize});
Brian Salomond1a8bdf2017-02-10 12:39:26 -0500543
Michael Ludwig7034f152018-10-08 16:43:58 -0400544 // Coverage optimization uses three frames with a linearly transformed input texture. The first
545 // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
546 // difference between the frame outputs if the FP is properly following the modulation
547 // requirements of the coverage optimization.
548 static constexpr SkScalar kInputDelta = 0.2f;
John Stiles0dee9b02020-07-20 11:45:58 -0400549 GrSurfaceProxyView inputTexture1 = make_input_texture(context, kRenderSize, kRenderSize, 0.0f);
550 GrSurfaceProxyView inputTexture2 = make_input_texture(context, kRenderSize, kRenderSize,
551 kInputDelta);
552 GrSurfaceProxyView inputTexture3 = make_input_texture(context, kRenderSize, kRenderSize,
553 2 * kInputDelta);
Robert Phillips30f9bc62017-02-22 15:28:38 -0500554
Michael Ludwige8e10752018-10-01 12:42:53 -0400555 // Encoded images are very verbose and this tests many potential images, so only export the
556 // first failure (subsequent failures have a reasonable chance of being related).
557 bool loggedFirstFailure = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400558 bool loggedFirstWarning = false;
Michael Ludwig7034f152018-10-08 16:43:58 -0400559
John Stilesaf110302020-07-20 09:45:51 -0400560 // Storage for the three frames required for coverage compatibility optimization testing.
561 // Each frame uses the correspondingly numbered inputTextureX.
562 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
563 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
564 std::vector<GrColor> readData3(kRenderSize * kRenderSize);
Michael Ludwig7034f152018-10-08 16:43:58 -0400565
Brian Salomon0e05a822017-07-25 09:43:22 -0400566 // Because processor factories configure themselves in random ways, this is not exhaustive.
Brian Salomon587e08f2017-01-27 10:59:27 -0500567 for (int i = 0; i < FPFactory::Count(); ++i) {
John Stilesfe7aed62020-07-20 13:48:02 -0400568 int optimizedForOpaqueInput = 0;
569 int optimizedForCoverageAsAlpha = 0;
570 int optimizedForConstantOutputForInput = 0;
John Stilesaf110302020-07-20 09:45:51 -0400571
John Stilesfe7aed62020-07-20 13:48:02 -0400572#ifdef __MSVC_RUNTIME_CHECKS
Brian Osman50ea3c02019-02-04 10:01:53 -0500573 // This test is infuriatingly slow with MSVC runtime checks enabled
John Stilesfe7aed62020-07-20 13:48:02 -0400574 static constexpr int kMinimumTrials = 1;
575 static constexpr int kMaximumTrials = 1;
576 static constexpr int kExpectedSuccesses = 1;
577#else
578 // We start by testing each fragment-processor 100 times, watching the optimization bits
579 // that appear. If we see an optimization bit appear in those first 100 trials, we keep
580 // running tests until we see at least five successful trials that have this optimization
581 // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
582 // that this FP doesn't support that optimization at all.
583 static constexpr int kMinimumTrials = 100;
584 static constexpr int kMaximumTrials = 2000;
585 static constexpr int kExpectedSuccesses = 5;
Brian Osman50ea3c02019-02-04 10:01:53 -0500586#endif
Robert Phillipsa91e0b72017-05-01 13:12:20 -0400587
John Stilesfe7aed62020-07-20 13:48:02 -0400588 for (int trial = 0;; ++trial) {
John Stilesaf110302020-07-20 09:45:51 -0400589 // Create a randomly-configured FP.
590 fpGenerator.reroll();
John Stilesfe7aed62020-07-20 13:48:02 -0400591 std::unique_ptr<GrFragmentProcessor> fp = fpGenerator.make(i, inputTexture1);
John Stilesaf110302020-07-20 09:45:51 -0400592
John Stilesfe7aed62020-07-20 13:48:02 -0400593 // If we have iterated enough times and seen a sufficient number of successes on each
594 // optimization bit that can be returned, stop running trials.
595 if (trial >= kMinimumTrials) {
596 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
597 optimizedForOpaqueInput < kExpectedSuccesses) ||
598 (optimizedForCoverageAsAlpha > 0 &&
599 optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
600 (optimizedForConstantOutputForInput > 0 &&
601 optimizedForConstantOutputForInput < kExpectedSuccesses);
602 if (!moreTrialsNeeded) break;
603
604 if (trial >= kMaximumTrials) {
605 SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
606 "Seed: 0x%08x, processor: %s.",
607 kMaximumTrials, fpGenerator.initialSeed(), fp->name());
608 break;
609 }
610 }
611
612 // Skip further testing if this trial has no optimization bits enabled.
Brian Salomon587e08f2017-01-27 10:59:27 -0500613 if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
Brian Salomonf3b995b2017-02-15 10:22:23 -0500614 !fp->compatibleWithCoverageAsAlpha()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500615 continue;
616 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400617
John Stilesaf110302020-07-20 09:45:51 -0400618 // We can make identical copies of the test FP in order to test coverage-as-alpha.
Michael Ludwig7034f152018-10-08 16:43:58 -0400619 if (fp->compatibleWithCoverageAsAlpha()) {
John Stiles0dee9b02020-07-20 11:45:58 -0400620 // Create and render two identical versions of this FP, but using different input
621 // textures, to check coverage optimization. We don't need to do this step for
622 // constant-output or preserving-opacity tests.
623 render_fp(context, rtc.get(), fpGenerator.make(i, inputTexture2), readData2.data());
624 render_fp(context, rtc.get(), fpGenerator.make(i, inputTexture3), 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.
638 render_fp(context, rtc.get(), fpGenerator.make(i, inputTexture1), readData1.data());
Brian Salomonaff329b2017-08-11 09:40:37 -0400639
Michael Ludwig314d3772018-10-03 16:04:38 -0400640 // This test has a history of being flaky on a number of devices. If an FP is logically
641 // violating the optimizations, it's reasonable to expect it to violate requirements on
642 // a large number of pixels in the image. Sporadic pixel violations are more indicative
643 // of device errors and represents a separate problem.
Michael Ludwig72ab3462018-12-10 12:43:36 -0500644#if defined(SK_BUILD_FOR_SKQP)
Michael Ludwig314d3772018-10-03 16:04:38 -0400645 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
646#else
647 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
648#endif
649
Michael Ludwig314d3772018-10-03 16:04:38 -0400650 // Collect first optimization failure message, to be output later as a warning or an
651 // error depending on whether the rendering "passed" or failed.
John Stilesaf110302020-07-20 09:45:51 -0400652 int failedPixelCount = 0;
Michael Ludwig314d3772018-10-03 16:04:38 -0400653 SkString coverageMessage;
654 SkString opaqueMessage;
655 SkString constMessage;
656 for (int y = 0; y < kRenderSize; ++y) {
657 for (int x = 0; x < kRenderSize; ++x) {
658 bool passing = true;
Michael Ludwig7034f152018-10-08 16:43:58 -0400659 GrColor input = input_texel_color(x, y, 0.0f);
John Stilesaf110302020-07-20 09:45:51 -0400660 GrColor output = readData1[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400661
662 if (fp->compatibleWithCoverageAsAlpha()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500663 GrColor ins[3];
664 ins[0] = input;
665 ins[1] = input_texel_color(x, y, kInputDelta);
666 ins[2] = input_texel_color(x, y, 2 * kInputDelta);
Michael Ludwig7034f152018-10-08 16:43:58 -0400667
Brian Salomonbc73eb42019-12-18 14:57:45 -0500668 GrColor outs[3];
669 outs[0] = output;
John Stilesaf110302020-07-20 09:45:51 -0400670 outs[1] = readData2[y * kRenderSize + x];
671 outs[2] = readData3[y * kRenderSize + x];
Michael Ludwig7034f152018-10-08 16:43:58 -0400672
Brian Salomonbc73eb42019-12-18 14:57:45 -0500673 if (!legal_modulation(ins, outs)) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500674 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400675 if (coverageMessage.isEmpty()) {
Brian Salomonbc73eb42019-12-18 14:57:45 -0500676 coverageMessage.printf(
677 "\"Modulating\" processor %s did not match "
Michael Ludwig7034f152018-10-08 16:43:58 -0400678 "alpha-modulation nor color-modulation rules. "
679 "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
680 fp->name(), input, output, x, y);
Michael Ludwig314d3772018-10-03 16:04:38 -0400681 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500682 }
683 }
Michael Ludwig7034f152018-10-08 16:43:58 -0400684
Brian Osmancb3d0872018-10-16 15:19:28 -0400685 SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
686 SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
Brian Osman1d5b5982018-10-01 13:41:39 -0400687 SkPMColor4f expected4f;
Michael Ludwig7034f152018-10-08 16:43:58 -0400688 if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
Brian Osmancb3d0872018-10-16 15:19:28 -0400689 float rDiff = fabsf(output4f.fR - expected4f.fR);
690 float gDiff = fabsf(output4f.fG - expected4f.fG);
691 float bDiff = fabsf(output4f.fB - expected4f.fB);
692 float aDiff = fabsf(output4f.fA - expected4f.fA);
Brian Salomon5d4cd9e2017-02-09 11:16:46 -0500693 static constexpr float kTol = 4 / 255.f;
Brian Salomon587e08f2017-01-27 10:59:27 -0500694 if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400695 if (constMessage.isEmpty()) {
696 passing = false;
697
698 constMessage.printf("Processor %s claimed output for const input "
699 "doesn't match actual output. Error: %f, Tolerance: %f, "
700 "input: (%f, %f, %f, %f), actual: (%f, %f, %f, %f), "
Michael Ludwig7034f152018-10-08 16:43:58 -0400701 "expected(%f, %f, %f, %f)", fp->name(),
Brian Osman788b9162020-02-07 10:36:46 -0500702 std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))), kTol,
Michael Ludwig314d3772018-10-03 16:04:38 -0400703 input4f.fR, input4f.fG, input4f.fB, input4f.fA,
Brian Osmancb3d0872018-10-16 15:19:28 -0400704 output4f.fR, output4f.fG, output4f.fB, output4f.fA,
705 expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
Michael Ludwig314d3772018-10-03 16:04:38 -0400706 }
Brian Salomon587e08f2017-01-27 10:59:27 -0500707 }
708 }
Brian Osman00b29392018-11-05 15:42:43 -0500709 if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
Brian Salomon587e08f2017-01-27 10:59:27 -0500710 passing = false;
Michael Ludwig314d3772018-10-03 16:04:38 -0400711
712 if (opaqueMessage.isEmpty()) {
713 opaqueMessage.printf("Processor %s claimed opaqueness is preserved but "
714 "it is not. Input: 0x%08x, Output: 0x%08x.",
Michael Ludwig7034f152018-10-08 16:43:58 -0400715 fp->name(), input, output);
Michael Ludwige8e10752018-10-01 12:42:53 -0400716 }
Brian Osmanbd1f76f2017-03-15 11:33:12 -0400717 }
Michael Ludwig314d3772018-10-03 16:04:38 -0400718
719 if (!passing) {
720 // Regardless of how many optimizations the pixel violates, count it as a
721 // single bad pixel.
722 failedPixelCount++;
723 }
724 }
725 }
726
727 // Finished analyzing the entire image, see if the number of pixel failures meets the
728 // threshold for an FP violating the optimization requirements.
729 if (failedPixelCount > kMaxAcceptableFailedPixels) {
Michael Ludwig4504a6522018-10-03 16:47:55 -0400730 ERRORF(reporter, "Processor violated %d of %d pixels, seed: 0x%08x, processor: %s"
Michael Ludwig314d3772018-10-03 16:04:38 -0400731 ", first failing pixel details are below:",
John Stilesaf110302020-07-20 09:45:51 -0400732 failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
Michael Ludwig7034f152018-10-08 16:43:58 -0400733 fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400734
735 // Print first failing pixel's details.
736 if (!coverageMessage.isEmpty()) {
737 ERRORF(reporter, coverageMessage.c_str());
738 }
739 if (!constMessage.isEmpty()) {
740 ERRORF(reporter, constMessage.c_str());
741 }
742 if (!opaqueMessage.isEmpty()) {
743 ERRORF(reporter, opaqueMessage.c_str());
744 }
745
746 if (!loggedFirstFailure) {
747 // Print with ERRORF to make sure the encoded image is output
748 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500749 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400750 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400751 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400752 ERRORF(reporter, "Input image: %s\n\n"
753 "===========================================================\n\n"
754 "Output image: %s\n", input.c_str(), output.c_str());
755 loggedFirstFailure = true;
756 }
John Stilesaf110302020-07-20 09:45:51 -0400757 } else if (failedPixelCount > 0) {
Michael Ludwig314d3772018-10-03 16:04:38 -0400758 // Don't trigger an error, but don't just hide the failures either.
759 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
760 "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
John Stilesaf110302020-07-20 09:45:51 -0400761 fpGenerator.initialSeed(), fp->dumpInfo().c_str());
Michael Ludwig314d3772018-10-03 16:04:38 -0400762 if (!coverageMessage.isEmpty()) {
763 INFOF(reporter, coverageMessage.c_str());
764 }
765 if (!constMessage.isEmpty()) {
766 INFOF(reporter, constMessage.c_str());
767 }
768 if (!opaqueMessage.isEmpty()) {
769 INFOF(reporter, opaqueMessage.c_str());
770 }
771 if (!loggedFirstWarning) {
772 SkString input;
Greg Daniel124486b2020-02-11 11:54:55 -0500773 log_texture_view(context, inputTexture1, &input);
Michael Ludwig314d3772018-10-03 16:04:38 -0400774 SkString output;
John Stilesaf110302020-07-20 09:45:51 -0400775 log_pixels(readData1.data(), kRenderSize, &output);
Michael Ludwig314d3772018-10-03 16:04:38 -0400776 INFOF(reporter, "Input image: %s\n\n"
777 "===========================================================\n\n"
778 "Output image: %s\n", input.c_str(), output.c_str());
779 loggedFirstWarning = true;
Brian Salomon587e08f2017-01-27 10:59:27 -0500780 }
781 }
782 }
783 }
784}
Robert Phillips18166ee2017-06-01 12:55:44 -0400785
John Stiles8c71f3e2020-06-15 15:07:19 -0400786static void describe_fp_children(const GrFragmentProcessor& fp,
787 std::string indent,
788 SkString* text) {
789 for (int index = 0; index < fp.numChildProcessors(); ++index) {
Brian Osman12c5d292020-07-13 16:11:35 -0400790 const GrFragmentProcessor* childFP = fp.childProcessor(index);
791 text->appendf("\n%s(#%d) -> %s", indent.c_str(), index, childFP ? childFP->name() : "null");
792 if (childFP) {
793 describe_fp_children(*childFP, indent + "\t", text);
794 }
John Stiles8c71f3e2020-06-15 15:07:19 -0400795 }
796}
797
798static SkString describe_fp(const GrFragmentProcessor& fp) {
799 SkString text;
800 text.printf("\n%s", fp.name());
801 describe_fp_children(fp, "\t", &text);
802 return text;
803}
804
Brian Salomon3f4de782020-06-18 14:16:00 -0400805// Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
806// progenitor.
Brian Salomon0e05a822017-07-25 09:43:22 -0400807DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
John Stilesaf110302020-07-20 09:45:51 -0400808 GrDirectContext* context = ctxInfo.directContext();
809 GrResourceProvider* resourceProvider = context->priv().resourceProvider();
Brian Salomon0e05a822017-07-25 09:43:22 -0400810
John Stilesaf110302020-07-20 09:45:51 -0400811 TestFPGenerator fpGenerator{context, resourceProvider};
812 if (!fpGenerator.init()) {
813 ERRORF(reporter, "Could not initialize TestFPGenerator");
814 return;
815 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400816
817 // Make the destination context for the test.
818 static constexpr int kRenderSize = 1024;
Greg Daniele20fcad2020-01-08 11:52:34 -0500819 auto rtc = GrRenderTargetContext::Make(
820 context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
821 {kRenderSize, kRenderSize});
Brian Salomon0e05a822017-07-25 09:43:22 -0400822
John Stiles0dee9b02020-07-20 11:45:58 -0400823 GrSurfaceProxyView inputTexture = make_input_texture(context, kRenderSize, kRenderSize, 0.0f);
John Stilesaf110302020-07-20 09:45:51 -0400824
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400825 // On failure we write out images, but just write the first failing set as the print is very
826 // large.
827 bool loggedFirstFailure = false;
828
John Stilesaf110302020-07-20 09:45:51 -0400829 // Storage for the original frame's readback and the readback of its clone.
830 std::vector<GrColor> readData1(kRenderSize * kRenderSize);
831 std::vector<GrColor> readData2(kRenderSize * kRenderSize);
832
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400833 // This test has a history of being flaky on a number of devices. If an FP clone is logically
John Stilesaf110302020-07-20 09:45:51 -0400834 // wrong, it's reasonable to expect it produce a large number of pixel differences in the image.
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400835 // Sporadic pixel violations are more indicative device errors and represents a separate
836 // problem.
837#if defined(SK_BUILD_FOR_SKQP)
838 static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
839#else
840 static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
841#endif
Brian Salomon0e05a822017-07-25 09:43:22 -0400842
843 // Because processor factories configure themselves in random ways, this is not exhaustive.
844 for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
845 static constexpr int kTimesToInvokeFactory = 10;
846 for (int j = 0; j < kTimesToInvokeFactory; ++j) {
John Stilesaf110302020-07-20 09:45:51 -0400847 fpGenerator.reroll();
John Stiles0dee9b02020-07-20 11:45:58 -0400848 std::unique_ptr<GrFragmentProcessor> fp = fpGenerator.make(i, /*inputFP=*/nullptr);
John Stiles8c71f3e2020-06-15 15:07:19 -0400849 std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
Brian Salomon0e05a822017-07-25 09:43:22 -0400850 if (!clone) {
Brian Salomon96271cd2017-07-31 16:27:23 -0400851 ERRORF(reporter, "Clone of processor %s failed.", fp->name());
Brian Salomon0e05a822017-07-25 09:43:22 -0400852 continue;
853 }
Brian Salomonaff329b2017-08-11 09:40:37 -0400854 const char* name = fp->name();
John Stiles8c71f3e2020-06-15 15:07:19 -0400855 REPORTER_ASSERT(reporter, !strcmp(fp->name(), clone->name()),
856 "%s\n", describe_fp(*fp).c_str());
Brian Salomonce06e262017-08-01 16:23:40 -0400857 REPORTER_ASSERT(reporter, fp->compatibleWithCoverageAsAlpha() ==
John Stiles8c71f3e2020-06-15 15:07:19 -0400858 clone->compatibleWithCoverageAsAlpha(),
859 "%s\n", describe_fp(*fp).c_str());
860 REPORTER_ASSERT(reporter, fp->isEqual(*clone),
861 "%s\n", describe_fp(*fp).c_str());
862 REPORTER_ASSERT(reporter, fp->preservesOpaqueInput() == clone->preservesOpaqueInput(),
863 "%s\n", describe_fp(*fp).c_str());
Brian Salomonce06e262017-08-01 16:23:40 -0400864 REPORTER_ASSERT(reporter, fp->hasConstantOutputForConstantInput() ==
John Stiles8c71f3e2020-06-15 15:07:19 -0400865 clone->hasConstantOutputForConstantInput(),
866 "%s\n", describe_fp(*fp).c_str());
867 REPORTER_ASSERT(reporter, fp->numChildProcessors() == clone->numChildProcessors(),
868 "%s\n", describe_fp(*fp).c_str());
Brian Osman9cf98dc2020-07-01 17:21:27 -0400869 REPORTER_ASSERT(reporter, fp->usesVaryingCoords() == clone->usesVaryingCoords(),
Michael Ludwige88320b2020-06-24 09:04:56 -0400870 "%s\n", describe_fp(*fp).c_str());
871 REPORTER_ASSERT(reporter, fp->referencesSampleCoords() ==
872 clone->referencesSampleCoords(),
John Stiles8c71f3e2020-06-15 15:07:19 -0400873 "%s\n", describe_fp(*fp).c_str());
Brian Salomon0e05a822017-07-25 09:43:22 -0400874 // Draw with original and read back the results.
John Stiles0dee9b02020-07-20 11:45:58 -0400875 render_fp(context, rtc.get(), std::move(fp), readData1.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400876
877 // Draw with clone and read back the results.
John Stiles0dee9b02020-07-20 11:45:58 -0400878 render_fp(context, rtc.get(), std::move(clone), readData2.data());
Brian Salomon0e05a822017-07-25 09:43:22 -0400879
880 // Check that the results are the same.
881 bool passing = true;
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400882 int failedPixelCount = 0;
883 int firstWrongX = 0;
884 int firstWrongY = 0;
Brian Salomon0e05a822017-07-25 09:43:22 -0400885 for (int y = 0; y < kRenderSize && passing; ++y) {
886 for (int x = 0; x < kRenderSize && passing; ++x) {
887 int idx = y * kRenderSize + x;
888 if (readData1[idx] != readData2[idx]) {
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400889 if (!failedPixelCount) {
890 firstWrongX = x;
891 firstWrongY = y;
892 }
893 ++failedPixelCount;
894 }
895 if (failedPixelCount > kMaxAcceptableFailedPixels) {
Brian Salomon0e05a822017-07-25 09:43:22 -0400896 passing = false;
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400897 idx = firstWrongY * kRenderSize + firstWrongX;
898 ERRORF(reporter,
899 "Processor %s made clone produced different output at (%d, %d). "
900 "Input color: 0x%08x, Original Output Color: 0x%08x, "
901 "Clone Output Color: 0x%08x.",
902 name, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
903 readData1[idx], readData2[idx]);
904 if (!loggedFirstFailure) {
905 // Write the images out as data urls for inspection.
906 // We mark the data as unpremul to avoid conversion when encoding as
907 // PNG. Also, even though we made the data by rendering into
908 // a "unpremul" GrRenderTargetContext, our input texture is unpremul and
909 // outside of the random effect configuration, we didn't do anything to
910 // ensure the output is actually premul.
911 auto info = SkImageInfo::Make(kRenderSize, kRenderSize,
912 kRGBA_8888_SkColorType,
913 kUnpremul_SkAlphaType);
Brian Salomon3f4de782020-06-18 14:16:00 -0400914 SkString inputURL, origURL, cloneURL;
915 if (log_texture_view(context, inputTexture, &inputURL) &&
John Stilesaf110302020-07-20 09:45:51 -0400916 log_pixels(readData1.data(), kRenderSize, &origURL) &&
917 log_pixels(readData2.data(), kRenderSize, &cloneURL)) {
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400918 ERRORF(reporter,
919 "\nInput image:\n%s\n\n"
920 "==========================================================="
921 "\n\n"
922 "Orig output image:\n%s\n"
923 "==========================================================="
924 "\n\n"
925 "Clone output image:\n%s\n",
Brian Salomon3f4de782020-06-18 14:16:00 -0400926 inputURL.c_str(), origURL.c_str(), cloneURL.c_str());
Brian Salomoncd8b6d52019-08-13 12:40:04 -0400927 loggedFirstFailure = true;
928 }
929 }
Brian Salomon0e05a822017-07-25 09:43:22 -0400930 }
931 }
932 }
933 }
934 }
935}
936
Hal Canary6f6961e2017-01-31 13:50:44 -0500937#endif // GR_TEST_UTILS