1 /*
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 
8 #include "tests/Test.h"
9 
10 #include "include/gpu/GrDirectContext.h"
11 #include "src/gpu/GrBitmapTextureMaker.h"
12 #include "src/gpu/GrClip.h"
13 #include "src/gpu/GrDirectContextPriv.h"
14 #include "src/gpu/GrGpuResource.h"
15 #include "src/gpu/GrImageInfo.h"
16 #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"
26 #include <atomic>
27 #include <random>
28 
29 namespace {
30 class TestOp : public GrMeshDrawOp {
31 public:
32     DEFINE_OP_CLASS_ID
Make(GrRecordingContext * rContext,std::unique_ptr<GrFragmentProcessor> fp)33     static GrOp::Owner Make(GrRecordingContext* rContext,
34                             std::unique_ptr<GrFragmentProcessor> fp) {
35         return GrOp::Make<TestOp>(rContext, std::move(fp));
36     }
37 
name() const38     const char* name() const override { return "TestOp"; }
39 
visitProxies(const VisitProxyFunc & func) const40     void visitProxies(const VisitProxyFunc& func) const override {
41         fProcessors.visitProxies(func);
42     }
43 
fixedFunctionFlags() const44     FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
45 
finalize(const GrCaps & caps,const GrAppliedClip * clip,bool hasMixedSampledCoverage,GrClampType clampType)46     GrProcessorSet::Analysis finalize(
47             const GrCaps& caps, const GrAppliedClip* clip, bool hasMixedSampledCoverage,
48             GrClampType clampType) override {
49         static constexpr GrProcessorAnalysisColor kUnknownColor;
50         SkPMColor4f overrideColor;
51         return fProcessors.finalize(
52                 kUnknownColor, GrProcessorAnalysisCoverage::kNone, clip,
53                 &GrUserStencilSettings::kUnused, hasMixedSampledCoverage, caps, clampType,
54                 &overrideColor);
55     }
56 
57 private:
58     friend class ::GrOp; // for ctor
59 
TestOp(std::unique_ptr<GrFragmentProcessor> fp)60     TestOp(std::unique_ptr<GrFragmentProcessor> fp)
61             : INHERITED(ClassID()), fProcessors(std::move(fp)) {
62         this->setBounds(SkRect::MakeWH(100, 100), HasAABloat::kNo, IsHairline::kNo);
63     }
64 
programInfo()65     GrProgramInfo* programInfo() override { return nullptr; }
onCreateProgramInfo(const GrCaps *,SkArenaAlloc *,const GrSurfaceProxyView * writeView,GrAppliedClip &&,const GrXferProcessor::DstProxyView &,GrXferBarrierFlags renderPassXferBarriers)66     void onCreateProgramInfo(const GrCaps*,
67                              SkArenaAlloc*,
68                              const GrSurfaceProxyView* writeView,
69                              GrAppliedClip&&,
70                              const GrXferProcessor::DstProxyView&,
71                              GrXferBarrierFlags renderPassXferBarriers) override {}
onPrePrepareDraws(GrRecordingContext *,const GrSurfaceProxyView * writeView,GrAppliedClip *,const GrXferProcessor::DstProxyView &,GrXferBarrierFlags renderPassXferBarriers)72     void onPrePrepareDraws(GrRecordingContext*,
73                            const GrSurfaceProxyView* writeView,
74                            GrAppliedClip*,
75                            const GrXferProcessor::DstProxyView&,
76                            GrXferBarrierFlags renderPassXferBarriers) override {}
onPrepareDraws(Target * target)77     void onPrepareDraws(Target* target) override { return; }
onExecute(GrOpFlushState *,const SkRect &)78     void onExecute(GrOpFlushState*, const SkRect&) override { return; }
79 
80     GrProcessorSet fProcessors;
81 
82     using INHERITED = GrMeshDrawOp;
83 };
84 
85 /**
86  * FP used to test ref counts on owned GrGpuResources. Can also be a parent FP to test counts
87  * of resources owned by child FPs.
88  */
89 class TestFP : public GrFragmentProcessor {
90 public:
Make(std::unique_ptr<GrFragmentProcessor> child)91     static std::unique_ptr<GrFragmentProcessor> Make(std::unique_ptr<GrFragmentProcessor> child) {
92         return std::unique_ptr<GrFragmentProcessor>(new TestFP(std::move(child)));
93     }
Make(const SkTArray<GrSurfaceProxyView> & views)94     static std::unique_ptr<GrFragmentProcessor> Make(const SkTArray<GrSurfaceProxyView>& views) {
95         return std::unique_ptr<GrFragmentProcessor>(new TestFP(views));
96     }
97 
name() const98     const char* name() const override { return "test"; }
99 
onGetGLSLProcessorKey(const GrShaderCaps &,GrProcessorKeyBuilder * b) const100     void onGetGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const override {
101         static std::atomic<int32_t> nextKey{0};
102         b->add32(nextKey++);
103     }
104 
clone() const105     std::unique_ptr<GrFragmentProcessor> clone() const override {
106         return std::unique_ptr<GrFragmentProcessor>(new TestFP(*this));
107     }
108 
109 private:
TestFP(const SkTArray<GrSurfaceProxyView> & views)110     TestFP(const SkTArray<GrSurfaceProxyView>& views)
111             : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
112         for (const GrSurfaceProxyView& view : views) {
113             this->registerChild(GrTextureEffect::Make(view, kUnknown_SkAlphaType));
114         }
115     }
116 
TestFP(std::unique_ptr<GrFragmentProcessor> child)117     TestFP(std::unique_ptr<GrFragmentProcessor> child)
118             : INHERITED(kTestFP_ClassID, kNone_OptimizationFlags) {
119         this->registerChild(std::move(child));
120     }
121 
TestFP(const TestFP & that)122     explicit TestFP(const TestFP& that) : INHERITED(kTestFP_ClassID, that.optimizationFlags()) {
123         this->cloneAndRegisterAllChildProcessors(that);
124     }
125 
onCreateGLSLInstance() const126     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 
onIsEqual(const GrFragmentProcessor &) const140     bool onIsEqual(const GrFragmentProcessor&) const override { return false; }
141 
142     using INHERITED = GrFragmentProcessor;
143 };
144 }  // namespace
145 
DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest,reporter,ctxInfo)146 DEF_GPUTEST_FOR_ALL_CONTEXTS(ProcessorRefTest, reporter, ctxInfo) {
147     auto context = ctxInfo.directContext();
148     GrProxyProvider* proxyProvider = context->priv().proxyProvider();
149 
150     static constexpr SkISize kDims = {10, 10};
151 
152     const GrBackendFormat format =
153         context->priv().caps()->getDefaultBackendFormat(GrColorType::kRGBA_8888,
154                                                         GrRenderable::kNo);
155     GrSwizzle swizzle = context->priv().caps()->getReadSwizzle(format, GrColorType::kRGBA_8888);
156 
157     for (bool makeClone : {false, true}) {
158         for (int parentCnt = 0; parentCnt < 2; parentCnt++) {
159             auto renderTargetContext = GrRenderTargetContext::Make(
160                     context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kApprox, {1, 1});
161             {
162                 sk_sp<GrTextureProxy> proxy = proxyProvider->createProxy(
163                         format, kDims, GrRenderable::kNo, 1, GrMipmapped::kNo, SkBackingFit::kExact,
164                         SkBudgeted::kYes, GrProtected::kNo);
165 
166                 {
167                     SkTArray<GrSurfaceProxyView> views;
168                     views.push_back({proxy, kTopLeft_GrSurfaceOrigin, swizzle});
169                     auto fp = TestFP::Make(std::move(views));
170                     for (int i = 0; i < parentCnt; ++i) {
171                         fp = TestFP::Make(std::move(fp));
172                     }
173                     std::unique_ptr<GrFragmentProcessor> clone;
174                     if (makeClone) {
175                         clone = fp->clone();
176                     }
177                     GrOp::Owner op = TestOp::Make(context, std::move(fp));
178                     renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));
179                     if (clone) {
180                         op = TestOp::Make(context, std::move(clone));
181                         renderTargetContext->priv().testingOnly_addDrawOp(std::move(op));
182                     }
183                 }
184 
185                 // If the fp is cloned the number of refs should increase by one (for the clone)
186                 int expectedProxyRefs = makeClone ? 3 : 2;
187 
188                 CheckSingleThreadedProxyRefs(reporter, proxy.get(), expectedProxyRefs, -1);
189 
190                 context->flushAndSubmit();
191 
192                 // just one from the 'proxy' sk_sp
193                 CheckSingleThreadedProxyRefs(reporter, proxy.get(), 1, 1);
194             }
195         }
196     }
197 }
198 
199 #include "tools/flags/CommandLineFlags.h"
200 static DEFINE_bool(randomProcessorTest, false,
201                    "Use non-deterministic seed for random processor tests?");
202 static DEFINE_int(processorSeed, 0,
203                   "Use specific seed for processor tests. Overridden by --randomProcessorTest.");
204 
205 #if GR_TEST_UTILS
206 
input_texel_color(int i,int j,SkScalar delta)207 static 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);
210 
211     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));
215     SkColor4f color4f = SkColor4f::FromColor(color);
216     // 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++) {
220         if (color4f[i] > 0.5) {
221             color4f[i] -= delta;
222         } else {
223             color4f[i] += delta;
224         }
225     }
226     return color4f.premul().toBytes_RGBA();
227 }
228 
test_draw_op(GrRecordingContext * rContext,GrRenderTargetContext * rtc,std::unique_ptr<GrFragmentProcessor> fp)229 void test_draw_op(GrRecordingContext* rContext,
230                   GrRenderTargetContext* rtc,
231                   std::unique_ptr<GrFragmentProcessor> fp) {
232     GrPaint paint;
233     paint.setColorFragmentProcessor(std::move(fp));
234     paint.setPorterDuffXPFactory(SkBlendMode::kSrc);
235 
236     auto op = GrFillRectOp::MakeNonAARect(rContext, std::move(paint), SkMatrix::I(),
237                                           SkRect::MakeWH(rtc->width(), rtc->height()));
238     rtc->priv().testingOnly_addDrawOp(std::move(op));
239 }
240 
241 // The output buffer must be the same size as the render-target context.
render_fp(GrDirectContext * dContext,GrRenderTargetContext * rtc,std::unique_ptr<GrFragmentProcessor> fp,GrColor * outBuffer)242 void render_fp(GrDirectContext* dContext,
243                GrRenderTargetContext* rtc,
244                std::unique_ptr<GrFragmentProcessor> fp,
245                GrColor* outBuffer) {
246     test_draw_op(dContext, rtc, std::move(fp));
247     std::fill_n(outBuffer, rtc->width() * rtc->height(), 0);
248     rtc->readPixels(dContext, SkImageInfo::Make(rtc->width(), rtc->height(), kRGBA_8888_SkColorType,
249                                       kPremul_SkAlphaType),
250                     outBuffer, /*rowBytes=*/0, /*srcPt=*/{0, 0});
251 }
252 
253 // This class is responsible for reproducibly generating a random fragment processor.
254 // An identical randomly-designed FP can be generated as many times as needed.
255 class TestFPGenerator {
256     public:
257         TestFPGenerator() = delete;
TestFPGenerator(GrDirectContext * context,GrResourceProvider * resourceProvider)258         TestFPGenerator(GrDirectContext* context, GrResourceProvider* resourceProvider)
259                 : fContext(context)
260                 , fResourceProvider(resourceProvider)
261                 , fInitialSeed(synthesizeInitialSeed())
262                 , fRandomSeed(fInitialSeed) {}
263 
initialSeed()264         uint32_t initialSeed() { return fInitialSeed; }
265 
init()266         bool init() {
267             // Initializes the two test texture proxies that are available to the FP test factories.
268             SkRandom random{fRandomSeed};
269             static constexpr int kTestTextureSize = 256;
270 
271             {
272                 // Put premul data into the RGBA texture that the test FPs can optionally use.
273                 GrColor* rgbaData = new GrColor[kTestTextureSize * kTestTextureSize];
274                 for (int y = 0; y < kTestTextureSize; ++y) {
275                     for (int x = 0; x < kTestTextureSize; ++x) {
276                         rgbaData[kTestTextureSize * y + x] = input_texel_color(
277                                 random.nextULessThan(256), random.nextULessThan(256), 0.0f);
278                     }
279                 }
280 
281                 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
282                                                    kRGBA_8888_SkColorType, kPremul_SkAlphaType);
283                 SkBitmap bitmap;
284                 bitmap.installPixels(
285                         ii, rgbaData, ii.minRowBytes(),
286                         [](void* addr, void* context) { delete[](GrColor*) addr; }, nullptr);
287                 bitmap.setImmutable();
288                 GrBitmapTextureMaker maker(fContext, bitmap,
289                                            GrImageTexGenPolicy::kNew_Uncached_Budgeted);
290                 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
291                 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
292                     SkDebugf("Unable to instantiate RGBA8888 test texture.");
293                     return false;
294                 }
295                 fTestViews[0] = GrProcessorTestData::ViewInfo{view, GrColorType::kRGBA_8888,
296                                                               kPremul_SkAlphaType};
297             }
298 
299             {
300                 // Put random values into the alpha texture that the test FPs can optionally use.
301                 uint8_t* alphaData = new uint8_t[kTestTextureSize * kTestTextureSize];
302                 for (int y = 0; y < kTestTextureSize; ++y) {
303                     for (int x = 0; x < kTestTextureSize; ++x) {
304                         alphaData[kTestTextureSize * y + x] = random.nextULessThan(256);
305                     }
306                 }
307 
308                 SkImageInfo ii = SkImageInfo::Make(kTestTextureSize, kTestTextureSize,
309                                                    kAlpha_8_SkColorType, kPremul_SkAlphaType);
310                 SkBitmap bitmap;
311                 bitmap.installPixels(
312                         ii, alphaData, ii.minRowBytes(),
313                         [](void* addr, void* context) { delete[](uint8_t*) addr; }, nullptr);
314                 bitmap.setImmutable();
315                 GrBitmapTextureMaker maker(fContext, bitmap,
316                                            GrImageTexGenPolicy::kNew_Uncached_Budgeted);
317                 GrSurfaceProxyView view = maker.view(GrMipmapped::kNo);
318                 if (!view.proxy() || !view.proxy()->instantiate(fResourceProvider)) {
319                     SkDebugf("Unable to instantiate A8 test texture.");
320                     return false;
321                 }
322                 fTestViews[1] = GrProcessorTestData::ViewInfo{view, GrColorType::kAlpha_8,
323                                                               kPremul_SkAlphaType};
324             }
325 
326             return true;
327         }
328 
reroll()329         void reroll() {
330             // Feed our current random seed into SkRandom to generate a new seed.
331             SkRandom random{fRandomSeed};
332             fRandomSeed = random.nextU();
333         }
334 
make(int type,int randomTreeDepth,std::unique_ptr<GrFragmentProcessor> inputFP)335         std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
336                                                   std::unique_ptr<GrFragmentProcessor> inputFP) {
337             // This will generate the exact same randomized FP (of each requested type) each time
338             // it's called. Call `reroll` to get a different FP.
339             SkRandom random{fRandomSeed};
340             GrProcessorTestData testData{&random, fContext, randomTreeDepth,
341                                          SK_ARRAY_COUNT(fTestViews), fTestViews,
342                                          std::move(inputFP)};
343             return GrFragmentProcessorTestFactory::MakeIdx(type, &testData);
344         }
345 
make(int type,int randomTreeDepth,GrSurfaceProxyView view,SkAlphaType alpha=kPremul_SkAlphaType)346         std::unique_ptr<GrFragmentProcessor> make(int type, int randomTreeDepth,
347                                                   GrSurfaceProxyView view,
348                                                   SkAlphaType alpha = kPremul_SkAlphaType) {
349             return make(type, randomTreeDepth, GrTextureEffect::Make(view, alpha));
350         }
351 
352     private:
synthesizeInitialSeed()353         static uint32_t synthesizeInitialSeed() {
354             if (FLAGS_randomProcessorTest) {
355                 std::random_device rd;
356                 return rd();
357             } else {
358                 return FLAGS_processorSeed;
359             }
360         }
361 
362         GrDirectContext* fContext;              // owned by caller
363         GrResourceProvider* fResourceProvider;  // owned by caller
364         const uint32_t fInitialSeed;
365         uint32_t fRandomSeed;
366         GrProcessorTestData::ViewInfo fTestViews[2];
367 };
368 
369 // Creates an array of color values from input_texel_color(), to be used as an input texture.
make_input_pixels(int width,int height,SkScalar delta)370 std::vector<GrColor> make_input_pixels(int width, int height, SkScalar delta) {
371     std::vector<GrColor> pixel(width * height);
372     for (int y = 0; y < width; ++y) {
373         for (int x = 0; x < height; ++x) {
374             pixel[width * y + x] = input_texel_color(x, y, delta);
375         }
376     }
377 
378     return pixel;
379 }
380 
381 // Creates a texture of premul colors used as the output of the fragment processor that precedes
382 // the fragment processor under test. An array of W*H colors are passed in as the texture data.
make_input_texture(GrRecordingContext * context,int width,int height,GrColor * pixel)383 GrSurfaceProxyView make_input_texture(GrRecordingContext* context,
384                                       int width, int height, GrColor* pixel) {
385     SkImageInfo ii = SkImageInfo::Make(width, height, kRGBA_8888_SkColorType, kPremul_SkAlphaType);
386     SkBitmap bitmap;
387     bitmap.installPixels(ii, pixel, ii.minRowBytes());
388     bitmap.setImmutable();
389     GrBitmapTextureMaker maker(context, bitmap, GrImageTexGenPolicy::kNew_Uncached_Budgeted);
390     return maker.view(GrMipmapped::kNo);
391 }
392 
393 // We tag logged data as unpremul to avoid conversion when encoding as PNG. The input texture
394 // actually contains unpremul data. Also, even though we made the result data by rendering into
395 // a "unpremul" GrRenderTargetContext, our input texture is unpremul and outside of the random
396 // effect configuration, we didn't do anything to ensure the output is actually premul. We just
397 // don't currently allow kUnpremul GrRenderTargetContexts.
398 static constexpr auto kLogAlphaType = kUnpremul_SkAlphaType;
399 
log_pixels(GrColor * pixels,int widthHeight,SkString * dst)400 bool log_pixels(GrColor* pixels, int widthHeight, SkString* dst) {
401     SkImageInfo info =
402             SkImageInfo::Make(widthHeight, widthHeight, kRGBA_8888_SkColorType, kLogAlphaType);
403     SkBitmap bmp;
404     bmp.installPixels(info, pixels, widthHeight * sizeof(GrColor));
405     return BipmapToBase64DataURI(bmp, dst);
406 }
407 
log_texture_view(GrDirectContext * dContext,GrSurfaceProxyView src,SkString * dst)408 bool log_texture_view(GrDirectContext* dContext, GrSurfaceProxyView src, SkString* dst) {
409     SkImageInfo ii = SkImageInfo::Make(src.proxy()->dimensions(), kRGBA_8888_SkColorType,
410                                        kLogAlphaType);
411 
412     auto sContext = GrSurfaceContext::Make(dContext, std::move(src), GrColorType::kRGBA_8888,
413                                            kLogAlphaType, nullptr);
414     SkBitmap bm;
415     SkAssertResult(bm.tryAllocPixels(ii));
416     SkAssertResult(sContext->readPixels(dContext, ii, bm.getPixels(), bm.rowBytes(), {0, 0}));
417     return BipmapToBase64DataURI(bm, dst);
418 }
419 
fuzzy_color_equals(const SkPMColor4f & c1,const SkPMColor4f & c2)420 bool fuzzy_color_equals(const SkPMColor4f& c1, const SkPMColor4f& c2) {
421     // With the loss of precision of rendering into 32-bit color, then estimating the FP's output
422     // from that, it is not uncommon for a valid output to differ from estimate by up to 0.01
423     // (really 1/128 ~ .0078, but frequently floating point issues make that tolerance a little
424     // too unforgiving).
425     static constexpr SkScalar kTolerance = 0.01f;
426     for (int i = 0; i < 4; i++) {
427         if (!SkScalarNearlyEqual(c1[i], c2[i], kTolerance)) {
428             return false;
429         }
430     }
431     return true;
432 }
433 
434 // Given three input colors (color preceding the FP being tested) provided to the FP at the same
435 // local coord and the three corresponding FP outputs, this ensures that either:
436 //   out[0] = fp * in[0].a, out[1] = fp * in[1].a, and out[2] = fp * in[2].a
437 // where fp is the pre-modulated color that should not be changing across frames (FP's state doesn't
438 // change), OR:
439 //   out[0] = fp * in[0], out[1] = fp * in[1], and out[2] = fp * in[2]
440 // (per-channel modulation instead of modulation by just the alpha channel)
441 // It does this by estimating the pre-modulated fp color from one of the input/output pairs and
442 // confirms the conditions hold for the other two pairs.
443 // It is required that the three input colors have the same alpha as fp is allowed to be a function
444 // of the input alpha (but not r, g, or b).
legal_modulation(const GrColor in[3],const GrColor out[3])445 bool legal_modulation(const GrColor in[3], const GrColor out[3]) {
446     // Convert to floating point, which is the number space the FP operates in (more or less)
447     SkPMColor4f inf[3], outf[3];
448     for (int i = 0; i < 3; ++i) {
449         inf[i]  = SkPMColor4f::FromBytes_RGBA(in[i]);
450         outf[i] = SkPMColor4f::FromBytes_RGBA(out[i]);
451     }
452     // This test is only valid if all the input alphas are the same.
453     SkASSERT(inf[0].fA == inf[1].fA && inf[1].fA == inf[2].fA);
454 
455     // Reconstruct the output of the FP before the shader modulated its color with the input value.
456     // When the original input is very small, it may cause the final output color to round
457     // to 0, in which case we estimate the pre-modulated color using one of the stepped frames that
458     // will then have a guaranteed larger channel value (since the offset will be added to it).
459     SkPMColor4f fpPreColorModulation = {0,0,0,0};
460     SkPMColor4f fpPreAlphaModulation = {0,0,0,0};
461     for (int i = 0; i < 4; i++) {
462         // Use the most stepped up frame
463         int maxInIdx = inf[0][i] > inf[1][i] ? 0 : 1;
464         maxInIdx = inf[maxInIdx][i] > inf[2][i] ? maxInIdx : 2;
465         const SkPMColor4f& in = inf[maxInIdx];
466         const SkPMColor4f& out = outf[maxInIdx];
467         if (in[i] > 0) {
468             fpPreColorModulation[i] = out[i] / in[i];
469         }
470         if (in[3] > 0) {
471             fpPreAlphaModulation[i] = out[i] / in[3];
472         }
473     }
474 
475     // With reconstructed pre-modulated FP output, derive the expected value of fp * input for each
476     // of the transformed input colors.
477     SkPMColor4f expectedForAlphaModulation[3];
478     SkPMColor4f expectedForColorModulation[3];
479     for (int i = 0; i < 3; ++i) {
480         expectedForAlphaModulation[i] = fpPreAlphaModulation * inf[i].fA;
481         expectedForColorModulation[i] = fpPreColorModulation * inf[i];
482         // If the input alpha is 0 then the other channels should also be zero
483         // since the color is assumed to be premul. Modulating zeros by anything
484         // should produce zeros.
485         if (inf[i].fA == 0) {
486             SkASSERT(inf[i].fR == 0 && inf[i].fG == 0 && inf[i].fB == 0);
487             expectedForColorModulation[i] = expectedForAlphaModulation[i] = {0, 0, 0, 0};
488         }
489     }
490 
491     bool isLegalColorModulation = fuzzy_color_equals(outf[0], expectedForColorModulation[0]) &&
492                                   fuzzy_color_equals(outf[1], expectedForColorModulation[1]) &&
493                                   fuzzy_color_equals(outf[2], expectedForColorModulation[2]);
494 
495     bool isLegalAlphaModulation = fuzzy_color_equals(outf[0], expectedForAlphaModulation[0]) &&
496                                   fuzzy_color_equals(outf[1], expectedForAlphaModulation[1]) &&
497                                   fuzzy_color_equals(outf[2], expectedForAlphaModulation[2]);
498 
499     // This can be enabled to print the values that caused this check to fail.
500     if (0 && !isLegalColorModulation && !isLegalAlphaModulation) {
501         SkDebugf("Color modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
502                  fpPreColorModulation[0],
503                  fpPreColorModulation[1],
504                  fpPreColorModulation[2],
505                  fpPreColorModulation[3]);
506         for (int i = 0; i < 3; ++i) {
507             SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
508                      "(%.03f, %.03f, %.03f, %.03f) | "
509                      "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
510                      inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
511                      outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
512                      expectedForColorModulation[i].fR, expectedForColorModulation[i].fG,
513                      expectedForColorModulation[i].fB, expectedForColorModulation[i].fA,
514                      fuzzy_color_equals(outf[i], expectedForColorModulation[i]));
515         }
516         SkDebugf("Alpha modulation test\n\timplied mod color: (%.03f, %.03f, %.03f, %.03f)\n",
517                  fpPreAlphaModulation[0],
518                  fpPreAlphaModulation[1],
519                  fpPreAlphaModulation[2],
520                  fpPreAlphaModulation[3]);
521         for (int i = 0; i < 3; ++i) {
522             SkDebugf("\t(%.03f, %.03f, %.03f, %.03f) -> "
523                      "(%.03f, %.03f, %.03f, %.03f) | "
524                      "(%.03f, %.03f, %.03f, %.03f), ok: %d\n",
525                      inf[i].fR, inf[i].fG, inf[i].fB, inf[i].fA,
526                      outf[i].fR, outf[i].fG, outf[i].fB, outf[i].fA,
527                      expectedForAlphaModulation[i].fR, expectedForAlphaModulation[i].fG,
528                      expectedForAlphaModulation[i].fB, expectedForAlphaModulation[i].fA,
529                      fuzzy_color_equals(outf[i], expectedForAlphaModulation[i]));
530         }
531     }
532     return isLegalColorModulation || isLegalAlphaModulation;
533 }
534 
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest,reporter,ctxInfo)535 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorOptimizationValidationTest, reporter, ctxInfo) {
536     GrDirectContext* context = ctxInfo.directContext();
537     GrResourceProvider* resourceProvider = context->priv().resourceProvider();
538     using FPFactory = GrFragmentProcessorTestFactory;
539 
540     TestFPGenerator fpGenerator{context, resourceProvider};
541     if (!fpGenerator.init()) {
542         ERRORF(reporter, "Could not initialize TestFPGenerator");
543         return;
544     }
545 
546     // Make the destination context for the test.
547     static constexpr int kRenderSize = 256;
548     auto rtc = GrRenderTargetContext::Make(
549             context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
550             {kRenderSize, kRenderSize});
551 
552     // Coverage optimization uses three frames with a linearly transformed input texture.  The first
553     // frame has no offset, second frames add .2 and .4, which should then be present as a fixed
554     // difference between the frame outputs if the FP is properly following the modulation
555     // requirements of the coverage optimization.
556     static constexpr SkScalar kInputDelta = 0.2f;
557     std::vector<GrColor> inputPixels1 = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
558     std::vector<GrColor> inputPixels2 =
559             make_input_pixels(kRenderSize, kRenderSize, 1 * kInputDelta);
560     std::vector<GrColor> inputPixels3 =
561             make_input_pixels(kRenderSize, kRenderSize, 2 * kInputDelta);
562     GrSurfaceProxyView inputTexture1 =
563             make_input_texture(context, kRenderSize, kRenderSize, inputPixels1.data());
564     GrSurfaceProxyView inputTexture2 =
565             make_input_texture(context, kRenderSize, kRenderSize, inputPixels2.data());
566     GrSurfaceProxyView inputTexture3 =
567             make_input_texture(context, kRenderSize, kRenderSize, inputPixels3.data());
568 
569     // Encoded images are very verbose and this tests many potential images, so only export the
570     // first failure (subsequent failures have a reasonable chance of being related).
571     bool loggedFirstFailure = false;
572     bool loggedFirstWarning = false;
573 
574     // Storage for the three frames required for coverage compatibility optimization testing.
575     // Each frame uses the correspondingly numbered inputTextureX.
576     std::vector<GrColor> readData1(kRenderSize * kRenderSize);
577     std::vector<GrColor> readData2(kRenderSize * kRenderSize);
578     std::vector<GrColor> readData3(kRenderSize * kRenderSize);
579 
580     // Because processor factories configure themselves in random ways, this is not exhaustive.
581     for (int i = 0; i < FPFactory::Count(); ++i) {
582         int optimizedForOpaqueInput = 0;
583         int optimizedForCoverageAsAlpha = 0;
584         int optimizedForConstantOutputForInput = 0;
585 
586 #ifdef __MSVC_RUNTIME_CHECKS
587         // This test is infuriatingly slow with MSVC runtime checks enabled
588         static constexpr int kMinimumTrials = 1;
589         static constexpr int kMaximumTrials = 1;
590         static constexpr int kExpectedSuccesses = 1;
591 #else
592         // We start by testing each fragment-processor 100 times, watching the optimization bits
593         // that appear. If we see an optimization bit appear in those first 100 trials, we keep
594         // running tests until we see at least five successful trials that have this optimization
595         // bit enabled. If we never see a particular optimization bit after 100 trials, we assume
596         // that this FP doesn't support that optimization at all.
597         static constexpr int kMinimumTrials = 100;
598         static constexpr int kMaximumTrials = 2000;
599         static constexpr int kExpectedSuccesses = 5;
600 #endif
601 
602         for (int trial = 0;; ++trial) {
603             // Create a randomly-configured FP.
604             fpGenerator.reroll();
605             std::unique_ptr<GrFragmentProcessor> fp =
606                     fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1);
607 
608             // If we have iterated enough times and seen a sufficient number of successes on each
609             // optimization bit that can be returned, stop running trials.
610             if (trial >= kMinimumTrials) {
611                 bool moreTrialsNeeded = (optimizedForOpaqueInput > 0 &&
612                                          optimizedForOpaqueInput < kExpectedSuccesses) ||
613                                         (optimizedForCoverageAsAlpha > 0 &&
614                                          optimizedForCoverageAsAlpha < kExpectedSuccesses) ||
615                                         (optimizedForConstantOutputForInput > 0 &&
616                                          optimizedForConstantOutputForInput < kExpectedSuccesses);
617                 if (!moreTrialsNeeded) break;
618 
619                 if (trial >= kMaximumTrials) {
620                     SkDebugf("Abandoning ProcessorOptimizationValidationTest after %d trials. "
621                              "Seed: 0x%08x, processor:\n%s",
622                              kMaximumTrials, fpGenerator.initialSeed(), fp->dumpTreeInfo().c_str());
623                     break;
624                 }
625             }
626 
627             // Skip further testing if this trial has no optimization bits enabled.
628             if (!fp->hasConstantOutputForConstantInput() && !fp->preservesOpaqueInput() &&
629                 !fp->compatibleWithCoverageAsAlpha()) {
630                 continue;
631             }
632 
633             // We can make identical copies of the test FP in order to test coverage-as-alpha.
634             if (fp->compatibleWithCoverageAsAlpha()) {
635                 // Create and render two identical versions of this FP, but using different input
636                 // textures, to check coverage optimization. We don't need to do this step for
637                 // constant-output or preserving-opacity tests.
638                 render_fp(context, rtc.get(),
639                           fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture2),
640                           readData2.data());
641                 render_fp(context, rtc.get(),
642                           fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture3),
643                           readData3.data());
644                 ++optimizedForCoverageAsAlpha;
645             }
646 
647             if (fp->hasConstantOutputForConstantInput()) {
648                 ++optimizedForConstantOutputForInput;
649             }
650 
651             if (fp->preservesOpaqueInput()) {
652                 ++optimizedForOpaqueInput;
653             }
654 
655             // Draw base frame last so that rtc holds the original FP behavior if we need to dump
656             // the image to the log.
657             render_fp(context, rtc.get(), fpGenerator.make(i, /*randomTreeDepth=*/1, inputTexture1),
658                       readData1.data());
659 
660             // This test has a history of being flaky on a number of devices. If an FP is logically
661             // violating the optimizations, it's reasonable to expect it to violate requirements on
662             // a large number of pixels in the image. Sporadic pixel violations are more indicative
663             // of device errors and represents a separate problem.
664 #if defined(SK_BUILD_FOR_SKQP)
665             static constexpr int kMaxAcceptableFailedPixels = 0; // Strict when running as SKQP
666 #else
667             static constexpr int kMaxAcceptableFailedPixels = 2 * kRenderSize; // ~0.7% of the image
668 #endif
669 
670             // Collect first optimization failure message, to be output later as a warning or an
671             // error depending on whether the rendering "passed" or failed.
672             int failedPixelCount = 0;
673             SkString coverageMessage;
674             SkString opaqueMessage;
675             SkString constMessage;
676             for (int y = 0; y < kRenderSize; ++y) {
677                 for (int x = 0; x < kRenderSize; ++x) {
678                     bool passing = true;
679                     GrColor input = inputPixels1[y * kRenderSize + x];
680                     GrColor output = readData1[y * kRenderSize + x];
681 
682                     if (fp->compatibleWithCoverageAsAlpha()) {
683                         GrColor ins[3];
684                         ins[0] = input;
685                         ins[1] = inputPixels2[y * kRenderSize + x];
686                         ins[2] = inputPixels3[y * kRenderSize + x];
687 
688                         GrColor outs[3];
689                         outs[0] = output;
690                         outs[1] = readData2[y * kRenderSize + x];
691                         outs[2] = readData3[y * kRenderSize + x];
692 
693                         if (!legal_modulation(ins, outs)) {
694                             passing = false;
695                             if (coverageMessage.isEmpty()) {
696                                 coverageMessage.printf(
697                                         "\"Modulating\" processor did not match alpha-modulation "
698                                         "nor color-modulation rules.\n"
699                                         "Input: 0x%08x, Output: 0x%08x, pixel (%d, %d).",
700                                         input, output, x, y);
701                             }
702                         }
703                     }
704 
705                     SkPMColor4f input4f = SkPMColor4f::FromBytes_RGBA(input);
706                     SkPMColor4f output4f = SkPMColor4f::FromBytes_RGBA(output);
707                     SkPMColor4f expected4f;
708                     if (fp->hasConstantOutputForConstantInput(input4f, &expected4f)) {
709                         float rDiff = fabsf(output4f.fR - expected4f.fR);
710                         float gDiff = fabsf(output4f.fG - expected4f.fG);
711                         float bDiff = fabsf(output4f.fB - expected4f.fB);
712                         float aDiff = fabsf(output4f.fA - expected4f.fA);
713                         static constexpr float kTol = 4 / 255.f;
714                         if (rDiff > kTol || gDiff > kTol || bDiff > kTol || aDiff > kTol) {
715                             if (constMessage.isEmpty()) {
716                                 passing = false;
717 
718                                 constMessage.printf(
719                                         "Processor claimed output for const input doesn't match "
720                                         "actual output.\n"
721                                         "Error: %f, Tolerance: %f, input: (%f, %f, %f, %f), "
722                                         "actual: (%f, %f, %f, %f), expected(%f, %f, %f, %f).",
723                                         std::max(rDiff, std::max(gDiff, std::max(bDiff, aDiff))),
724                                         kTol, input4f.fR, input4f.fG, input4f.fB, input4f.fA,
725                                         output4f.fR, output4f.fG, output4f.fB, output4f.fA,
726                                         expected4f.fR, expected4f.fG, expected4f.fB, expected4f.fA);
727                             }
728                         }
729                     }
730                     if (input4f.isOpaque() && fp->preservesOpaqueInput() && !output4f.isOpaque()) {
731                         passing = false;
732 
733                         if (opaqueMessage.isEmpty()) {
734                             opaqueMessage.printf(
735                                     "Processor claimed opaqueness is preserved but "
736                                     "it is not. Input: 0x%08x, Output: 0x%08x.",
737                                     input, output);
738                         }
739                     }
740 
741                     if (!passing) {
742                         // Regardless of how many optimizations the pixel violates, count it as a
743                         // single bad pixel.
744                         failedPixelCount++;
745                     }
746                 }
747             }
748 
749             // Finished analyzing the entire image, see if the number of pixel failures meets the
750             // threshold for an FP violating the optimization requirements.
751             if (failedPixelCount > kMaxAcceptableFailedPixels) {
752                 ERRORF(reporter,
753                        "Processor violated %d of %d pixels, seed: 0x%08x.\n"
754                        "Processor:\n%s\nFirst failing pixel details are below:",
755                        failedPixelCount, kRenderSize * kRenderSize, fpGenerator.initialSeed(),
756                        fp->dumpTreeInfo().c_str());
757 
758                 // Print first failing pixel's details.
759                 if (!coverageMessage.isEmpty()) {
760                     ERRORF(reporter, coverageMessage.c_str());
761                 }
762                 if (!constMessage.isEmpty()) {
763                     ERRORF(reporter, constMessage.c_str());
764                 }
765                 if (!opaqueMessage.isEmpty()) {
766                     ERRORF(reporter, opaqueMessage.c_str());
767                 }
768 
769                 if (!loggedFirstFailure) {
770                     // Print with ERRORF to make sure the encoded image is output
771                     SkString input;
772                     log_texture_view(context, inputTexture1, &input);
773                     SkString output;
774                     log_pixels(readData1.data(), kRenderSize, &output);
775                     ERRORF(reporter, "Input image: %s\n\n"
776                            "===========================================================\n\n"
777                            "Output image: %s\n", input.c_str(), output.c_str());
778                     loggedFirstFailure = true;
779                 }
780             } else if (failedPixelCount > 0) {
781                 // Don't trigger an error, but don't just hide the failures either.
782                 INFOF(reporter, "Processor violated %d of %d pixels (below error threshold), seed: "
783                       "0x%08x, processor: %s", failedPixelCount, kRenderSize * kRenderSize,
784                       fpGenerator.initialSeed(), fp->dumpInfo().c_str());
785                 if (!coverageMessage.isEmpty()) {
786                     INFOF(reporter, coverageMessage.c_str());
787                 }
788                 if (!constMessage.isEmpty()) {
789                     INFOF(reporter, constMessage.c_str());
790                 }
791                 if (!opaqueMessage.isEmpty()) {
792                     INFOF(reporter, opaqueMessage.c_str());
793                 }
794                 if (!loggedFirstWarning) {
795                     SkString input;
796                     log_texture_view(context, inputTexture1, &input);
797                     SkString output;
798                     log_pixels(readData1.data(), kRenderSize, &output);
799                     INFOF(reporter, "Input image: %s\n\n"
800                           "===========================================================\n\n"
801                           "Output image: %s\n", input.c_str(), output.c_str());
802                     loggedFirstWarning = true;
803                 }
804             }
805         }
806     }
807 }
808 
assert_processor_equality(skiatest::Reporter * reporter,const GrFragmentProcessor & fp,const GrFragmentProcessor & clone)809 static void assert_processor_equality(skiatest::Reporter* reporter,
810                                       const GrFragmentProcessor& fp,
811                                       const GrFragmentProcessor& clone) {
812     REPORTER_ASSERT(reporter, !strcmp(fp.name(), clone.name()),
813                               "\n%s", fp.dumpTreeInfo().c_str());
814     REPORTER_ASSERT(reporter, fp.compatibleWithCoverageAsAlpha() ==
815                               clone.compatibleWithCoverageAsAlpha(),
816                               "\n%s", fp.dumpTreeInfo().c_str());
817     REPORTER_ASSERT(reporter, fp.isEqual(clone),
818                               "\n%s", fp.dumpTreeInfo().c_str());
819     REPORTER_ASSERT(reporter, fp.preservesOpaqueInput() == clone.preservesOpaqueInput(),
820                               "\n%s", fp.dumpTreeInfo().c_str());
821     REPORTER_ASSERT(reporter, fp.hasConstantOutputForConstantInput() ==
822                               clone.hasConstantOutputForConstantInput(),
823                               "\n%s", fp.dumpTreeInfo().c_str());
824     REPORTER_ASSERT(reporter, fp.numChildProcessors() == clone.numChildProcessors(),
825                               "\n%s", fp.dumpTreeInfo().c_str());
826     REPORTER_ASSERT(reporter, fp.usesVaryingCoords() == clone.usesVaryingCoords(),
827                               "\n%s", fp.dumpTreeInfo().c_str());
828     REPORTER_ASSERT(reporter, fp.referencesSampleCoords() == clone.referencesSampleCoords(),
829                               "\n%s", fp.dumpTreeInfo().c_str());
830 }
831 
verify_identical_render(skiatest::Reporter * reporter,int renderSize,const char * processorType,const GrColor readData1[],const GrColor readData2[])832 static bool verify_identical_render(skiatest::Reporter* reporter, int renderSize,
833                                     const char* processorType,
834                                     const GrColor readData1[], const GrColor readData2[]) {
835     // The ProcessorClone test has a history of being flaky on a number of devices. If an FP clone
836     // is logically wrong, it's reasonable to expect it produce a large number of pixel differences
837     // in the image. Sporadic pixel violations are more indicative device errors and represents a
838     // separate problem.
839 #if defined(SK_BUILD_FOR_SKQP)
840     const int maxAcceptableFailedPixels = 0;  // Strict when running as SKQP
841 #else
842     const int maxAcceptableFailedPixels = 2 * renderSize;  // ~0.002% of the pixels (size 1024*1024)
843 #endif
844 
845     int failedPixelCount = 0;
846     int firstWrongX = 0;
847     int firstWrongY = 0;
848     int idx = 0;
849     for (int y = 0; y < renderSize; ++y) {
850         for (int x = 0; x < renderSize; ++x, ++idx) {
851             if (readData1[idx] != readData2[idx]) {
852                 if (!failedPixelCount) {
853                     firstWrongX = x;
854                     firstWrongY = y;
855                 }
856                 ++failedPixelCount;
857             }
858             if (failedPixelCount > maxAcceptableFailedPixels) {
859                 idx = firstWrongY * renderSize + firstWrongX;
860                 ERRORF(reporter,
861                        "%s produced different output at (%d, %d). "
862                        "Input color: 0x%08x, Original Output Color: 0x%08x, "
863                        "Clone Output Color: 0x%08x.",
864                        processorType, firstWrongX, firstWrongY, input_texel_color(x, y, 0.0f),
865                        readData1[idx], readData2[idx]);
866 
867                 return false;
868             }
869         }
870     }
871 
872     return true;
873 }
874 
log_clone_failure(skiatest::Reporter * reporter,int renderSize,GrDirectContext * context,const GrSurfaceProxyView & inputTexture,GrColor pixelsFP[],GrColor pixelsClone[],GrColor pixelsRegen[])875 static void log_clone_failure(skiatest::Reporter* reporter, int renderSize,
876                               GrDirectContext* context, const GrSurfaceProxyView& inputTexture,
877                               GrColor pixelsFP[], GrColor pixelsClone[], GrColor pixelsRegen[]) {
878     // Write the images out as data URLs for inspection.
879     SkString inputURL, origURL, cloneURL, regenURL;
880     if (log_texture_view(context, inputTexture, &inputURL) &&
881         log_pixels(pixelsFP, renderSize, &origURL) &&
882         log_pixels(pixelsClone, renderSize, &cloneURL) &&
883         log_pixels(pixelsRegen, renderSize, &regenURL)) {
884         ERRORF(reporter,
885                "\nInput image:\n%s\n\n"
886                "==========================================================="
887                "\n\n"
888                "Orig output image:\n%s\n"
889                "==========================================================="
890                "\n\n"
891                "Clone output image:\n%s\n"
892                "==========================================================="
893                "\n\n"
894                "Regen output image:\n%s\n",
895                inputURL.c_str(), origURL.c_str(), cloneURL.c_str(), regenURL.c_str());
896     }
897 }
898 
899 // Tests that a fragment processor returned by GrFragmentProcessor::clone() is equivalent to its
900 // progenitor.
DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest,reporter,ctxInfo)901 DEF_GPUTEST_FOR_GL_RENDERING_CONTEXTS(ProcessorCloneTest, reporter, ctxInfo) {
902     GrDirectContext* context = ctxInfo.directContext();
903     GrResourceProvider* resourceProvider = context->priv().resourceProvider();
904 
905     TestFPGenerator fpGenerator{context, resourceProvider};
906     if (!fpGenerator.init()) {
907         ERRORF(reporter, "Could not initialize TestFPGenerator");
908         return;
909     }
910 
911     // Make the destination context for the test.
912     static constexpr int kRenderSize = 1024;
913     auto rtc = GrRenderTargetContext::Make(
914             context, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
915             {kRenderSize, kRenderSize});
916 
917     std::vector<GrColor> inputPixels = make_input_pixels(kRenderSize, kRenderSize, 0.0f);
918     GrSurfaceProxyView inputTexture =
919             make_input_texture(context, kRenderSize, kRenderSize, inputPixels.data());
920 
921     // On failure we write out images, but just write the first failing set as the print is very
922     // large.
923     bool loggedFirstFailure = false;
924 
925     // Storage for the original frame's readback and the readback of its clone.
926     std::vector<GrColor> readDataFP(kRenderSize * kRenderSize);
927     std::vector<GrColor> readDataClone(kRenderSize * kRenderSize);
928     std::vector<GrColor> readDataRegen(kRenderSize * kRenderSize);
929 
930     // Because processor factories configure themselves in random ways, this is not exhaustive.
931     for (int i = 0; i < GrFragmentProcessorTestFactory::Count(); ++i) {
932         static constexpr int kTimesToInvokeFactory = 10;
933         for (int j = 0; j < kTimesToInvokeFactory; ++j) {
934             fpGenerator.reroll();
935             std::unique_ptr<GrFragmentProcessor> fp =
936                     fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
937             std::unique_ptr<GrFragmentProcessor> regen =
938                     fpGenerator.make(i, /*randomTreeDepth=*/1, /*inputFP=*/nullptr);
939             std::unique_ptr<GrFragmentProcessor> clone = fp->clone();
940             if (!clone) {
941                 ERRORF(reporter, "Clone of processor %s failed.", fp->dumpTreeInfo().c_str());
942                 continue;
943             }
944             assert_processor_equality(reporter, *fp, *clone);
945 
946             // Draw with original and read back the results.
947             render_fp(context, rtc.get(), std::move(fp), readDataFP.data());
948 
949             // Draw with clone and read back the results.
950             render_fp(context, rtc.get(), std::move(clone), readDataClone.data());
951 
952             // Check that the results are the same.
953             if (!verify_identical_render(reporter, kRenderSize, "Processor clone",
954                                          readDataFP.data(), readDataClone.data())) {
955                 // Dump a description from the regenerated processor (since the original FP has
956                 // already been consumed).
957                 ERRORF(reporter, "FP hierarchy:\n%s", regen->dumpTreeInfo().c_str());
958 
959                 // Render and readback output from the regenerated FP. If this also mismatches, the
960                 // FP itself doesn't generate consistent output. This could happen if:
961                 // - the FP's TestCreate() does not always generate the same FP from a given seed
962                 // - the FP's Make() does not always generate the same FP when given the same inputs
963                 // - the FP itself generates inconsistent pixels (shader UB?)
964                 // - the driver has a bug
965                 render_fp(context, rtc.get(), std::move(regen), readDataRegen.data());
966 
967                 if (!verify_identical_render(reporter, kRenderSize, "Regenerated processor",
968                                              readDataFP.data(), readDataRegen.data())) {
969                     ERRORF(reporter, "Output from regen did not match original!\n");
970                 } else {
971                     ERRORF(reporter, "Regenerated processor output matches original results.\n");
972                 }
973 
974                 // If this is the first time we've encountered a cloning failure, log the generated
975                 // images to the reporter as data URLs.
976                 if (!loggedFirstFailure) {
977                     log_clone_failure(reporter, kRenderSize, context, inputTexture,
978                                       readDataFP.data(), readDataClone.data(),
979                                       readDataRegen.data());
980                     loggedFirstFailure = true;
981                 }
982             }
983         }
984     }
985 }
986 
987 #endif  // GR_TEST_UTILS
988