• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017 Google Inc.
3  *
4  * Use of this source code is governed by a BSD-style license that can be
5  * found in the LICENSE file.
6  */
7 
8 #include "tests/Test.h"
9 
10 #include <array>
11 #include <memory>
12 #include <vector>
13 #include "include/core/SkBitmap.h"
14 #include "include/gpu/GrDirectContext.h"
15 #include "src/gpu/GrCaps.h"
16 #include "src/gpu/GrDirectContextPriv.h"
17 #include "src/gpu/GrGeometryProcessor.h"
18 #include "src/gpu/GrImageInfo.h"
19 #include "src/gpu/GrMemoryPool.h"
20 #include "src/gpu/GrOpFlushState.h"
21 #include "src/gpu/GrOpsRenderPass.h"
22 #include "src/gpu/GrProgramInfo.h"
23 #include "src/gpu/GrResourceProvider.h"
24 #include "src/gpu/KeyBuilder.h"
25 #include "src/gpu/ResourceKey.h"
26 #include "src/gpu/glsl/GrGLSLFragmentShaderBuilder.h"
27 #include "src/gpu/glsl/GrGLSLVarying.h"
28 #include "src/gpu/glsl/GrGLSLVertexGeoBuilder.h"
29 #include "src/gpu/ops/GrSimpleMeshDrawOpHelper.h"
30 #include "src/gpu/v1/SurfaceDrawContext_v1.h"
31 
32 #if 0
33 #include "tools/ToolUtils.h"
34 #define WRITE_PNG_CONTEXT_TYPE kANGLE_D3D11_ES3_ContextType
35 #endif
36 
37 SKGPU_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
38 
39 static constexpr int kBoxSize = 2;
40 static constexpr int kBoxCountY = 8;
41 static constexpr int kBoxCountX = 8;
42 static constexpr int kBoxCount = kBoxCountY * kBoxCountX;
43 
44 static constexpr int kImageWidth = kBoxCountY * kBoxSize;
45 static constexpr int kImageHeight = kBoxCountX * kBoxSize;
46 
47 static constexpr int kIndexPatternRepeatCount = 3;
48 constexpr uint16_t kIndexPattern[6] = {0, 1, 2, 1, 2, 3};
49 
50 
51 class DrawMeshHelper {
52 public:
DrawMeshHelper(GrOpFlushState * state)53     DrawMeshHelper(GrOpFlushState* state) : fState(state) {}
54 
55     sk_sp<const GrBuffer> getIndexBuffer();
56 
57     sk_sp<const GrBuffer> makeIndexBuffer(const uint16_t[], int count);
58 
makeVertexBuffer(const SkTArray<T> & data)59     template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const SkTArray<T>& data) {
60         return this->makeVertexBuffer(data.begin(), data.count());
61     }
makeVertexBuffer(const std::vector<T> & data)62     template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const std::vector<T>& data) {
63         return this->makeVertexBuffer(data.data(), data.size());
64     }
65     template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const T* data, int count);
66 
target()67     GrMeshDrawTarget* target() { return fState; }
68 
69     sk_sp<const GrBuffer> fIndexBuffer;
70     sk_sp<const GrBuffer> fIndexBuffer2;
71     sk_sp<const GrBuffer> fInstBuffer;
72     sk_sp<const GrBuffer> fVertBuffer;
73     sk_sp<const GrBuffer> fVertBuffer2;
74     sk_sp<const GrBuffer> fDrawIndirectBuffer;
75     size_t fDrawIndirectBufferOffset;
76 
77     GrOpsRenderPass* bindPipeline(GrPrimitiveType, bool isInstanced, bool hasVertexBuffer);
78 
79 private:
80     GrOpFlushState* fState;
81 };
82 
83 struct Box {
84     float fX, fY;
85     GrColor fColor;
86 };
87 
88 ////////////////////////////////////////////////////////////////////////////////////////////////////
89 
90 /**
91  * This is a GPU-backend specific test. It tries to test all possible usecases of
92  * GrOpsRenderPass::draw*. The test works by drawing checkerboards of colored boxes, reading back
93  * the pixels, and comparing with expected results. The boxes are drawn on integer boundaries and
94  * the (opaque) colors are chosen from the set (r,g,b) = (0,255)^3, so the GPU renderings ought to
95  * produce exact matches.
96  */
97 
98 static void run_test(GrDirectContext*, const char* testName, skiatest::Reporter*,
99                      const std::unique_ptr<skgpu::v1::SurfaceDrawContext>&, const SkBitmap& gold,
100                      std::function<void(DrawMeshHelper*)> prepareFn,
101                      std::function<void(DrawMeshHelper*)> executeFn);
102 
103 #ifdef WRITE_PNG_CONTEXT_TYPE
IsContextTypeForOutputPNGs(skiatest::GrContextFactoryContextType type)104 static bool IsContextTypeForOutputPNGs(skiatest::GrContextFactoryContextType type) {
105     return type == skiatest::GrContextFactoryContextType::WRITE_PNG_CONTEXT_TYPE;
106 }
DEF_GPUTEST_FOR_CONTEXTS(GrMeshTest,IsContextTypeForOutputPNGs,reporter,ctxInfo,nullptr)107 DEF_GPUTEST_FOR_CONTEXTS(GrMeshTest, IsContextTypeForOutputPNGs, reporter, ctxInfo, nullptr) {
108 #else
109 DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrMeshTest, reporter, ctxInfo) {
110 #endif
111     auto dContext = ctxInfo.directContext();
112 
113     auto sdc = skgpu::v1::SurfaceDrawContext::Make(
114             dContext, GrColorType::kRGBA_8888, nullptr, SkBackingFit::kExact,
115             {kImageWidth, kImageHeight}, SkSurfaceProps());
116     if (!sdc) {
117         ERRORF(reporter, "could not create render target context.");
118         return;
119     }
120 
121     SkTArray<Box> boxes;
122     SkTArray<std::array<Box, 4>> vertexData;
123     SkBitmap gold;
124 
125     // ---- setup ----------
126 
127     SkPaint paint;
128     paint.setBlendMode(SkBlendMode::kSrc);
129     gold.allocN32Pixels(kImageWidth, kImageHeight);
130 
131     SkCanvas goldCanvas(gold);
132 
133     for (int y = 0; y < kBoxCountY; ++y) {
134         for (int x = 0; x < kBoxCountX; ++x) {
135             int c = y + x;
136             int rgb[3] = {-(c & 1) & 0xff, -((c >> 1) & 1) & 0xff, -((c >> 2) & 1) & 0xff};
137 
138             const Box box = boxes.push_back() = {
139                     float(x * kBoxSize),
140                     float(y * kBoxSize),
141                     GrColorPackRGBA(rgb[0], rgb[1], rgb[2], 255)
142             };
143 
144             std::array<Box, 4>& boxVertices = vertexData.push_back();
145             for (int i = 0; i < 4; ++i) {
146                 boxVertices[i] = {
147                         box.fX + (i / 2) * kBoxSize,
148                         box.fY + (i % 2) * kBoxSize,
149                         box.fColor
150                 };
151             }
152 
153             paint.setARGB(255, rgb[0], rgb[1], rgb[2]);
154             goldCanvas.drawRect(SkRect::MakeXYWH(box.fX, box.fY, kBoxSize, kBoxSize), paint);
155         }
156     }
157 
158     // ---- tests ----------
159 
160 #define VALIDATE(buff)                           \
161     do {                                         \
162         if (!buff) {                             \
163             ERRORF(reporter, #buff " is null."); \
164             return;                              \
165         }                                        \
166     } while (0)
167 
168     run_test(dContext, "draw", reporter, sdc, gold,
169              [&](DrawMeshHelper* helper) {
170                  SkTArray<Box> expandedVertexData;
171                  for (int i = 0; i < kBoxCount; ++i) {
172                      for (int j = 0; j < 6; ++j) {
173                          expandedVertexData.push_back(vertexData[i][kIndexPattern[j]]);
174                      }
175                  }
176 
177                  // Draw boxes one line at a time to exercise base vertex.
178                  helper->fVertBuffer = helper->makeVertexBuffer(expandedVertexData);
179                  VALIDATE(helper->fVertBuffer);
180              },
181              [&](DrawMeshHelper* helper) {
182                  for (int y = 0; y < kBoxCountY; ++y) {
183                      auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
184                      pass->bindBuffers(nullptr, nullptr, helper->fVertBuffer);
185                      pass->draw(kBoxCountX * 6, y * kBoxCountX * 6);
186                  }
187              });
188 
189     run_test(dContext, "drawIndexed", reporter, sdc, gold,
190              [&](DrawMeshHelper* helper) {
191                 helper->fIndexBuffer = helper->getIndexBuffer();
192                 VALIDATE(helper->fIndexBuffer);
193                 helper->fVertBuffer = helper->makeVertexBuffer(vertexData);
194                 VALIDATE(helper->fVertBuffer);
195              },
196              [&](DrawMeshHelper* helper) {
197                 int baseRepetition = 0;
198                 int i = 0;
199                 // Start at various repetitions within the patterned index buffer to exercise base
200                 // index.
201                 while (i < kBoxCount) {
202                     static_assert(kIndexPatternRepeatCount >= 3);
203                     int repetitionCount = std::min(3 - baseRepetition, kBoxCount - i);
204 
205                     auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
206                     pass->bindBuffers(helper->fIndexBuffer, nullptr, helper->fVertBuffer);
207                     pass->drawIndexed(repetitionCount * 6, baseRepetition * 6, baseRepetition * 4,
208                                       (baseRepetition + repetitionCount) * 4 - 1,
209                                       (i - baseRepetition) * 4);
210 
211                     baseRepetition = (baseRepetition + 1) % 3;
212                     i += repetitionCount;
213                 }
214             });
215 
216     run_test(dContext, "drawIndexPattern", reporter, sdc, gold,
217              [&](DrawMeshHelper* helper) {
218                  helper->fIndexBuffer = helper->getIndexBuffer();
219                  VALIDATE(helper->fIndexBuffer);
220                  helper->fVertBuffer = helper->makeVertexBuffer(vertexData);
221                  VALIDATE(helper->fVertBuffer);
222              },
223              [&](DrawMeshHelper* helper) {
224                 // Draw boxes one line at a time to exercise base vertex. drawIndexPattern does
225                 // not support a base index.
226                 for (int y = 0; y < kBoxCountY; ++y) {
227                     auto pass = helper->bindPipeline(GrPrimitiveType::kTriangles, false, true);
228                     pass->bindBuffers(helper->fIndexBuffer, nullptr, helper->fVertBuffer);
229                     pass->drawIndexPattern(6, kBoxCountX, kIndexPatternRepeatCount, 4,
230                                            y * kBoxCountX * 4);
231 
232                 }
233              });
234 
235     for (bool indexed : {false, true}) {
236         if (!dContext->priv().caps()->drawInstancedSupport()) {
237             break;
238         }
239 
240         run_test(dContext, indexed ? "drawIndexedInstanced" : "drawInstanced",
241                  reporter, sdc, gold,
242                  [&](DrawMeshHelper* helper) {
243                      helper->fIndexBuffer = indexed ? helper->getIndexBuffer() : nullptr;
244                      SkTArray<uint16_t> baseIndexData;
245                      baseIndexData.push_back(kBoxCountX/2 * 6); // for testing base index.
246                      for (int i = 0; i < 6; ++i) {
247                          baseIndexData.push_back(kIndexPattern[i]);
248                      }
249                      helper->fIndexBuffer2 = helper->makeIndexBuffer(baseIndexData.begin(),
250                                                                      baseIndexData.count());
251                      helper->fInstBuffer = helper->makeVertexBuffer(boxes);
252                      VALIDATE(helper->fInstBuffer);
253                      helper->fVertBuffer =
254                              helper->makeVertexBuffer(std::vector<float>{0,0, 0,1, 1,0, 1,1});
255                      VALIDATE(helper->fVertBuffer);
256                      helper->fVertBuffer2 = helper->makeVertexBuffer( // for testing base vertex.
257                          std::vector<float>{-1,-1, -1,-1, 0,0, 0,1, 1,0, 1,1});
258                      VALIDATE(helper->fVertBuffer2);
259                  },
260                  [&](DrawMeshHelper* helper) {
261                      // Draw boxes one line at a time to exercise base instance, base vertex, and
262                      // null vertex buffer.
263                      for (int y = 0; y < kBoxCountY; ++y) {
264                          sk_sp<const GrBuffer> vertexBuffer;
265                          int baseVertex = 0;
266                          switch (y % 3) {
267                              case 0:
268                                  if (dContext->priv().caps()->shaderCaps()->vertexIDSupport()) {
269                                      break;
270                                  }
271                                  [[fallthrough]];
272                              case 1:
273                                  vertexBuffer = helper->fVertBuffer;
274                                  break;
275                              case 2:
276                                  vertexBuffer = helper->fVertBuffer2;
277                                  baseVertex = 2;
278                                  break;
279                          }
280 
281                          GrPrimitiveType primitiveType = indexed ? GrPrimitiveType::kTriangles
282                                                                  : GrPrimitiveType::kTriangleStrip;
283                          auto pass = helper->bindPipeline(primitiveType, true,
284                                                           SkToBool(vertexBuffer));
285                          if (indexed) {
286                              sk_sp<const GrBuffer> indexBuffer = (y % 2) ?
287                                      helper->fIndexBuffer2 : helper->fIndexBuffer;
288                              VALIDATE(indexBuffer);
289                              int baseIndex = (y % 2);
290                              pass->bindBuffers(std::move(indexBuffer), helper->fInstBuffer,
291                                                std::move(vertexBuffer));
292                              pass->drawIndexedInstanced(6, baseIndex, kBoxCountX, y * kBoxCountX,
293                                                         baseVertex);
294                          } else {
295                              pass->bindBuffers(nullptr, helper->fInstBuffer,
296                                                std::move(vertexBuffer));
297                              pass->drawInstanced(kBoxCountX, y * kBoxCountY, 4, baseVertex);
298                          }
299                      }
300                  });
301     }
302 
303     for (bool indexed : {false, true}) {
304         if (!dContext->priv().caps()->drawInstancedSupport()) {
305             break;
306         }
307 
308         run_test(dContext, (indexed) ? "drawIndexedIndirect" : "drawIndirect",
309                  reporter, sdc, gold,
310                  [&](DrawMeshHelper* helper) {
311                      SkTArray<uint16_t> baseIndexData;
312                      baseIndexData.push_back(kBoxCountX/2 * 6); // for testing base index.
313                      for (int j = 0; j < kBoxCountY; ++j) {
314                          for (int i = 0; i < 6; ++i) {
315                              baseIndexData.push_back(kIndexPattern[i]);
316                          }
317                      }
318                      helper->fIndexBuffer2 = helper->makeIndexBuffer(baseIndexData.begin(),
319                                                                      baseIndexData.count());
320                      VALIDATE(helper->fIndexBuffer2);
321                      helper->fInstBuffer = helper->makeVertexBuffer(boxes);
322                      VALIDATE(helper->fInstBuffer);
323                      helper->fVertBuffer = helper->makeVertexBuffer(std::vector<float>{
324                              -1,-1, 0,0, 0,1, 1,0, 1,1, -1,-1, 0,0, 1,0, 0,1, 1,1});
325                      VALIDATE(helper->fVertBuffer);
326 
327                      GrDrawIndirectWriter indirectWriter;
328                      GrDrawIndexedIndirectWriter indexedIndirectWriter;
329                      if (indexed) {
330                          // Make helper->fDrawIndirectBufferOffset nonzero.
331                          sk_sp<const GrBuffer> ignoredBuff;
332                          size_t ignoredOffset;
333                          // Make a superfluous call to makeDrawIndirectSpace in order to test
334                          // "offsetInBytes!=0" for the actual call to makeDrawIndexedIndirectSpace.
335                          helper->target()->makeDrawIndirectSpace(29, &ignoredBuff, &ignoredOffset);
336                          indexedIndirectWriter = helper->target()->makeDrawIndexedIndirectSpace(
337                                  kBoxCountY, &helper->fDrawIndirectBuffer,
338                                  &helper->fDrawIndirectBufferOffset);
339                      } else {
340                          // Make helper->fDrawIndirectBufferOffset nonzero.
341                          sk_sp<const GrBuffer> ignoredBuff;
342                          size_t ignoredOffset;
343                          // Make a superfluous call to makeDrawIndexedIndirectSpace in order to test
344                          // "offsetInBytes!=0" for the actual call to makeDrawIndirectSpace.
345                          helper->target()->makeDrawIndexedIndirectSpace(7, &ignoredBuff,
346                                                                         &ignoredOffset);
347                          indirectWriter = helper->target()->makeDrawIndirectSpace(
348                                  kBoxCountY, &helper->fDrawIndirectBuffer,
349                                  &helper->fDrawIndirectBufferOffset);
350                      }
351 
352                      // Draw boxes one line at a time to exercise multiple draws.
353                      for (int y = 0; y < kBoxCountY; ++y) {
354                          int baseVertex = (y % 2) ? 1 : 6;
355                          if (indexed) {
356                              int baseIndex = 1 + y * 6;
357                              indexedIndirectWriter.writeIndexed(6, baseIndex, kBoxCountX,
358                                                                 y * kBoxCountX, baseVertex);
359                          } else {
360                              indirectWriter.write(kBoxCountX, y * kBoxCountX, 4, baseVertex);
361                          }
362                      }
363                  },
364                  [&](DrawMeshHelper* helper) {
365                      GrOpsRenderPass* pass;
366                      if (indexed) {
367                          pass = helper->bindPipeline(GrPrimitiveType::kTriangles, true, true);
368                          pass->bindBuffers(helper->fIndexBuffer2, helper->fInstBuffer,
369                                            helper->fVertBuffer);
370                          for (int i = 0; i < 3; ++i) {
371                              int start = kBoxCountY * i / 3;
372                              int end = kBoxCountY * (i + 1) / 3;
373                              size_t offset = helper->fDrawIndirectBufferOffset + start *
374                                              sizeof(GrDrawIndexedIndirectCommand);
375                              pass->drawIndexedIndirect(helper->fDrawIndirectBuffer.get(), offset,
376                                                        end - start);
377                          }
378                      } else {
379                          pass = helper->bindPipeline(GrPrimitiveType::kTriangleStrip, true, true);
380                          pass->bindBuffers(nullptr, helper->fInstBuffer, helper->fVertBuffer);
381                          for (int i = 0; i < 2; ++i) {
382                              int start = kBoxCountY * i / 2;
383                              int end = kBoxCountY * (i + 1) / 2;
384                              size_t offset = helper->fDrawIndirectBufferOffset + start *
385                                              sizeof(GrDrawIndirectCommand);
386                              pass->drawIndirect(helper->fDrawIndirectBuffer.get(), offset,
387                                                 end - start);
388                          }
389                      }
390                  });
391     }
392 }
393 
394 ////////////////////////////////////////////////////////////////////////////////////////////////////
395 
396 namespace {
397 class MeshTestOp : public GrDrawOp {
398 public:
399     DEFINE_OP_CLASS_ID
400 
401     static GrOp::Owner Make(GrRecordingContext* rContext,
402                             std::function<void(DrawMeshHelper*)> prepareFn,
403                             std::function<void(DrawMeshHelper*)> executeFn) {
404         return GrOp::Make<MeshTestOp>(rContext, prepareFn, executeFn);
405     }
406 
407 private:
408     friend class GrOp;  // for ctor
409 
410     MeshTestOp(std::function<void(DrawMeshHelper*)> prepareFn,
411                std::function<void(DrawMeshHelper*)> executeFn)
412             : INHERITED(ClassID()), fPrepareFn(prepareFn), fExecuteFn(executeFn) {
413         this->setBounds(
414                 SkRect::MakeIWH(kImageWidth, kImageHeight), HasAABloat::kNo, IsHairline::kNo);
415     }
416 
417     const char* name() const override { return "GrMeshTestOp"; }
418     FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
419     GrProcessorSet::Analysis finalize(const GrCaps&, const GrAppliedClip*, GrClampType) override {
420         return GrProcessorSet::EmptySetAnalysis();
421     }
422 
423     void onPrePrepare(GrRecordingContext*,
424                       const GrSurfaceProxyView& writeView,
425                       GrAppliedClip*,
426                       const GrDstProxyView&,
427                       GrXferBarrierFlags renderPassXferBarriers,
428                       GrLoadOp colorLoadOp) override {}
429     void onPrepare(GrOpFlushState* state) override {
430         fHelper = std::make_unique<DrawMeshHelper>(state);
431         fPrepareFn(fHelper.get());
432     }
433     void onExecute(GrOpFlushState* state, const SkRect& chainBounds) override {
434         fExecuteFn(fHelper.get());
435     }
436 
437     std::unique_ptr<DrawMeshHelper> fHelper;
438     std::function<void(DrawMeshHelper*)> fPrepareFn;
439     std::function<void(DrawMeshHelper*)> fExecuteFn;
440 
441     using INHERITED = GrDrawOp;
442 };
443 
444 class MeshTestProcessor : public GrGeometryProcessor {
445 public:
446     static GrGeometryProcessor* Make(SkArenaAlloc* arena, bool instanced, bool hasVertexBuffer) {
447         return arena->make([&](void* ptr) {
448             return new (ptr) MeshTestProcessor(instanced, hasVertexBuffer);
449         });
450     }
451 
452     const char* name() const override { return "GrMeshTestProcessor"; }
453 
454     void addToKey(const GrShaderCaps&, skgpu::KeyBuilder* b) const final {
455         b->add32(fInstanceLocation.isInitialized());
456         b->add32(fVertexPosition.isInitialized());
457     }
458 
459     std::unique_ptr<ProgramImpl> makeProgramImpl(const GrShaderCaps&) const final;
460 
461 private:
462     class Impl;
463 
464     const Attribute& inColor() const {
465         return fVertexColor.isInitialized() ? fVertexColor : fInstanceColor;
466     }
467 
468     MeshTestProcessor(bool instanced, bool hasVertexBuffer)
469             : INHERITED(kGrMeshTestProcessor_ClassID) {
470         if (instanced) {
471             fInstanceLocation = {"location", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
472             fInstanceColor = {"color", kUByte4_norm_GrVertexAttribType, SkSLType::kHalf4};
473             this->setInstanceAttributesWithImplicitOffsets(&fInstanceLocation, 2);
474             if (hasVertexBuffer) {
475                 fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
476                 this->setVertexAttributesWithImplicitOffsets(&fVertexPosition, 1);
477             }
478         } else {
479             fVertexPosition = {"vertex", kFloat2_GrVertexAttribType, SkSLType::kHalf2};
480             fVertexColor = {"color", kUByte4_norm_GrVertexAttribType, SkSLType::kHalf4};
481             this->setVertexAttributesWithImplicitOffsets(&fVertexPosition, 2);
482         }
483     }
484 
485     Attribute fVertexPosition;
486     Attribute fVertexColor;
487 
488     Attribute fInstanceLocation;
489     Attribute fInstanceColor;
490 
491     using INHERITED = GrGeometryProcessor;
492 };
493 }  // anonymous namespace
494 
495 std::unique_ptr<GrGeometryProcessor::ProgramImpl> MeshTestProcessor::makeProgramImpl(
496         const GrShaderCaps&) const {
497     class Impl : public ProgramImpl {
498     public:
499         void setData(const GrGLSLProgramDataManager&,
500                      const GrShaderCaps&,
501                      const GrGeometryProcessor&) final {}
502 
503     private:
504         void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
505             const MeshTestProcessor& mp = args.fGeomProc.cast<MeshTestProcessor>();
506             GrGLSLVertexBuilder* v = args.fVertBuilder;
507             GrGLSLFPFragmentBuilder* f = args.fFragBuilder;
508 
509             GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
510             varyingHandler->emitAttributes(mp);
511             f->codeAppendf("half4 %s;", args.fOutputColor);
512             varyingHandler->addPassThroughAttribute(mp.inColor().asShaderVar(), args.fOutputColor);
513 
514             if (!mp.fInstanceLocation.isInitialized()) {
515                 v->codeAppendf("float2 vertex = %s;", mp.fVertexPosition.name());
516             } else {
517                 if (mp.fVertexPosition.isInitialized()) {
518                     v->codeAppendf("float2 offset = %s;", mp.fVertexPosition.name());
519                 } else {
520                     v->codeAppend("float2 offset = float2(sk_VertexID / 2, sk_VertexID % 2);");
521                 }
522                 v->codeAppendf("float2 vertex = %s + offset * %i;", mp.fInstanceLocation.name(),
523                                kBoxSize);
524             }
525             gpArgs->fPositionVar.set(SkSLType::kFloat2, "vertex");
526 
527             f->codeAppendf("const half4 %s = half4(1);", args.fOutputCoverage);
528         }
529     };
530 
531     return std::make_unique<Impl>();
532 }
533 
534 ////////////////////////////////////////////////////////////////////////////////////////////////////
535 
536 sk_sp<const GrBuffer> DrawMeshHelper::makeIndexBuffer(const uint16_t indices[], int count) {
537     return sk_sp<const GrBuffer>(fState->resourceProvider()->createBuffer(
538             count * sizeof(uint16_t), GrGpuBufferType::kIndex, kDynamic_GrAccessPattern, indices));
539 }
540 
541 template<typename T>
542 sk_sp<const GrBuffer> DrawMeshHelper::makeVertexBuffer(const T* data, int count) {
543     return sk_sp<const GrBuffer>(fState->resourceProvider()->createBuffer(
544             count * sizeof(T), GrGpuBufferType::kVertex, kDynamic_GrAccessPattern, data));
545 }
546 
547 sk_sp<const GrBuffer> DrawMeshHelper::getIndexBuffer() {
548     SKGPU_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
549     return fState->resourceProvider()->findOrCreatePatternedIndexBuffer(
550             kIndexPattern, 6, kIndexPatternRepeatCount, 4, gIndexBufferKey);
551 }
552 
553 GrOpsRenderPass* DrawMeshHelper::bindPipeline(GrPrimitiveType primitiveType, bool isInstanced,
554                                               bool hasVertexBuffer) {
555     GrProcessorSet processorSet(SkBlendMode::kSrc);
556 
557     // TODO: add a GrProcessorSet testing helper to make this easier
558     SkPMColor4f overrideColor;
559     processorSet.finalize(GrProcessorAnalysisColor(),
560                           GrProcessorAnalysisCoverage::kNone,
561                           fState->appliedClip(),
562                           nullptr,
563                           fState->caps(),
564                           GrClampType::kAuto,
565                           &overrideColor);
566 
567     auto pipeline = GrSimpleMeshDrawOpHelper::CreatePipeline(fState,
568                                                              std::move(processorSet),
569                                                              GrPipeline::InputFlags::kNone);
570 
571     GrGeometryProcessor* mtp = MeshTestProcessor::Make(fState->allocator(), isInstanced,
572                                                        hasVertexBuffer);
573 
574     GrProgramInfo programInfo(fState->caps(), fState->writeView(), fState->usesMSAASurface(),
575                               pipeline, &GrUserStencilSettings::kUnused, mtp, primitiveType, 0,
576                               fState->renderPassBarriers(), fState->colorLoadOp());
577 
578     fState->opsRenderPass()->bindPipeline(programInfo, SkRect::MakeIWH(kImageWidth, kImageHeight));
579     return fState->opsRenderPass();
580 }
581 
582 static void run_test(GrDirectContext* dContext,
583                      const char* testName,
584                      skiatest::Reporter* reporter,
585                      const std::unique_ptr<skgpu::v1::SurfaceDrawContext>& sdc,
586                      const SkBitmap& gold,
587                      std::function<void(DrawMeshHelper*)> prepareFn,
588                      std::function<void(DrawMeshHelper*)> executeFn) {
589     const int w = gold.width(), h = gold.height();
590     const uint32_t* goldPx = reinterpret_cast<const uint32_t*>(gold.getPixels());
591     if (h != sdc->height() || w != sdc->width()) {
592         ERRORF(reporter, "[%s] expectation and rtc not compatible (?).", testName);
593         return;
594     }
595     if (sizeof(uint32_t) * kImageWidth != gold.rowBytes()) {
596         ERRORF(reporter, "[%s] unexpected row bytes in gold image", testName);
597         return;
598     }
599 
600     GrPixmap resultPM = GrPixmap::Allocate(gold.info());
601     sdc->clear(SkPMColor4f::FromBytes_RGBA(0xbaaaaaad));
602     sdc->addDrawOp(MeshTestOp::Make(dContext, prepareFn, executeFn));
603 
604     sdc->readPixels(dContext, resultPM, {0, 0});
605 
606 #ifdef WRITE_PNG_CONTEXT_TYPE
607 #define STRINGIFY(X) #X
608 #define TOSTRING(X) STRINGIFY(X)
609     SkString filename;
610     filename.printf("GrMeshTest_%s_%s.png", TOSTRING(WRITE_PNG_CONTEXT_TYPE), testName);
611     SkDebugf("writing %s...\n", filename.c_str());
612     ToolUtils::EncodeImageToFile(filename.c_str(), resultPM, SkEncodedImageFormat::kPNG, 100);
613 #endif
614 
615     for (int y = 0; y < h; ++y) {
616         for (int x = 0; x < w; ++x) {
617             uint32_t expected = goldPx[y * kImageWidth + x];
618             uint32_t actual = static_cast<uint32_t*>(resultPM.addr())[y * kImageWidth + x];
619             if (expected != actual) {
620                 ERRORF(reporter, "[%s] pixel (%i,%i): got 0x%x expected 0x%x",
621                        testName, x, y, actual, expected);
622                 return;
623             }
624         }
625     }
626 }
627