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