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