blob: 3a2be784a5000d7494d0e7144cfa14d94febb627 [file] [log] [blame]
Chris Dalton114a3c02017-05-26 15:17:19 -06001/*
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 "SkTypes.h"
9#include "Test.h"
10
11#if SK_SUPPORT_GPU
12
13#include "GrContext.h"
14#include "GrGeometryProcessor.h"
15#include "GrOpFlushState.h"
16#include "GrRenderTargetContext.h"
17#include "GrRenderTargetContextPriv.h"
18#include "GrResourceProvider.h"
19#include "GrResourceKey.h"
20#include "SkMakeUnique.h"
21#include "glsl/GrGLSLVertexShaderBuilder.h"
22#include "glsl/GrGLSLFragmentShaderBuilder.h"
23#include "glsl/GrGLSLGeometryProcessor.h"
24#include "glsl/GrGLSLVarying.h"
25#include <array>
Chris Dalton1d616352017-05-31 12:51:23 -060026#include <vector>
Chris Dalton114a3c02017-05-26 15:17:19 -060027
28
29GR_DECLARE_STATIC_UNIQUE_KEY(gIndexBufferKey);
30
31static constexpr int kBoxSize = 2;
32static constexpr int kBoxCountY = 8;
33static constexpr int kBoxCountX = 8;
34static constexpr int kBoxCount = kBoxCountY * kBoxCountX;
35
36static constexpr int kImageWidth = kBoxCountY * kBoxSize;
37static constexpr int kImageHeight = kBoxCountX * kBoxSize;
38
39static constexpr int kIndexPatternRepeatCount = 3;
40constexpr uint16_t kIndexPattern[6] = {0, 1, 2, 1, 2, 3};
41
42
43class DrawMeshHelper {
44public:
45 DrawMeshHelper(GrOpFlushState* state) : fState(state) {}
46
47 sk_sp<const GrBuffer> getIndexBuffer();
48
49 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const SkTArray<T>& data) {
50 return this->makeVertexBuffer(data.begin(), data.count());
51 }
Chris Dalton1d616352017-05-31 12:51:23 -060052 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const std::vector<T>& data) {
53 return this->makeVertexBuffer(data.data(), data.size());
54 }
Chris Dalton114a3c02017-05-26 15:17:19 -060055 template<typename T> sk_sp<const GrBuffer> makeVertexBuffer(const T* data, int count);
56
57 void drawMesh(const GrMesh& mesh);
58
59private:
60 GrOpFlushState* fState;
61};
62
63struct Box {
64 float fX, fY;
65 GrColor fColor;
66};
67
68////////////////////////////////////////////////////////////////////////////////////////////////////
69
70/**
71 * This is a GPU-backend specific test. It tries to test all possible usecases of GrMesh. The test
72 * works by drawing checkerboards of colored boxes, reading back the pixels, and comparing with
73 * expected results. The boxes are drawn on integer boundaries and the (opaque) colors are chosen
74 * from the set (r,g,b) = (0,255)^3, so the GPU renderings ought to produce exact matches.
75 */
76
77static void run_test(const char* testName, skiatest::Reporter*, const sk_sp<GrRenderTargetContext>&,
78 const SkBitmap& gold, std::function<void(DrawMeshHelper*)> testFn);
79
80DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrMeshTest, reporter, ctxInfo) {
81 GrContext* const context = ctxInfo.grContext();
82
83 sk_sp<GrRenderTargetContext> rtc(
84 context->makeDeferredRenderTargetContext(SkBackingFit::kExact, kImageWidth, kImageHeight,
85 kRGBA_8888_GrPixelConfig, nullptr));
86 if (!rtc) {
87 ERRORF(reporter, "could not create render target context.");
88 return;
89 }
90
91 SkTArray<Box> boxes;
92 SkTArray<std::array<Box, 4>> vertexData;
93 SkBitmap gold;
94
95 // ---- setup ----------
96
97 SkPaint paint;
98 paint.setBlendMode(SkBlendMode::kSrc);
99 gold.allocN32Pixels(kImageWidth, kImageHeight);
100
101 SkCanvas goldCanvas(gold);
102
103 for (int y = 0; y < kBoxCountY; ++y) {
104 for (int x = 0; x < kBoxCountX; ++x) {
105 int c = y + x;
106 int rgb[3] = {-(c & 1) & 0xff, -((c >> 1) & 1) & 0xff, -((c >> 2) & 1) & 0xff};
107
108 const Box box = boxes.push_back() = {
109 float(x * kBoxSize),
110 float(y * kBoxSize),
111 GrColorPackRGBA(rgb[0], rgb[1], rgb[2], 255)
112 };
113
114 std::array<Box, 4>& boxVertices = vertexData.push_back();
115 for (int i = 0; i < 4; ++i) {
116 boxVertices[i] = {
117 box.fX + (i/2) * kBoxSize,
118 box.fY + (i%2) * kBoxSize,
119 box.fColor
120 };
121 }
122
123 paint.setARGB(255, rgb[0], rgb[1], rgb[2]);
124 goldCanvas.drawRect(SkRect::MakeXYWH(box.fX, box.fY, kBoxSize, kBoxSize), paint);
125 }
126 }
127
128 goldCanvas.flush();
129
130 // ---- tests ----------
131
132#define VALIDATE(buff) \
133 if (!buff) { \
134 ERRORF(reporter, #buff " is null."); \
135 return; \
136 }
137
138 run_test("setNonIndexedNonInstanced", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
139 SkTArray<Box> expandedVertexData;
140 for (int i = 0; i < kBoxCount; ++i) {
141 for (int j = 0; j < 6; ++j) {
142 expandedVertexData.push_back(vertexData[i][kIndexPattern[j]]);
143 }
144 }
145
146 // Draw boxes one line at a time to exercise base vertex.
147 auto vbuff = helper->makeVertexBuffer(expandedVertexData);
148 VALIDATE(vbuff);
149 for (int y = 0; y < kBoxCountY; ++y) {
150 GrMesh mesh(kTriangles_GrPrimitiveType);
Chris Dalton1d616352017-05-31 12:51:23 -0600151 mesh.setNonIndexedNonInstanced(kBoxCountX * 6);
Chris Dalton114a3c02017-05-26 15:17:19 -0600152 mesh.setVertexData(vbuff.get(), y * kBoxCountX * 6);
153 helper->drawMesh(mesh);
154 }
155 });
156
157 run_test("setIndexed", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
158 auto ibuff = helper->getIndexBuffer();
159 VALIDATE(ibuff);
160 auto vbuff = helper->makeVertexBuffer(vertexData);
161 VALIDATE(vbuff);
162 int baseRepetition = 0;
163 int i = 0;
164
165 // Start at various repetitions within the patterned index buffer to exercise base index.
166 while (i < kBoxCount) {
167 GR_STATIC_ASSERT(kIndexPatternRepeatCount >= 3);
168 int repetitionCount = SkTMin(3 - baseRepetition, kBoxCount - i);
169
170 GrMesh mesh(kTriangles_GrPrimitiveType);
171 mesh.setIndexed(ibuff.get(), repetitionCount * 6, baseRepetition * 6,
172 baseRepetition * 4, (baseRepetition + repetitionCount) * 4 - 1);
173 mesh.setVertexData(vbuff.get(), (i - baseRepetition) * 4);
174 helper->drawMesh(mesh);
175
176 baseRepetition = (baseRepetition + 1) % 3;
177 i += repetitionCount;
178 }
179 });
180
181 run_test("setIndexedPatterned", reporter, rtc, gold, [&](DrawMeshHelper* helper) {
182 auto ibuff = helper->getIndexBuffer();
183 VALIDATE(ibuff);
184 auto vbuff = helper->makeVertexBuffer(vertexData);
185 VALIDATE(vbuff);
186
187 // Draw boxes one line at a time to exercise base vertex. setIndexedPatterned does not
188 // support a base index.
189 for (int y = 0; y < kBoxCountY; ++y) {
190 GrMesh mesh(kTriangles_GrPrimitiveType);
191 mesh.setIndexedPatterned(ibuff.get(), 6, 4, kBoxCountX, kIndexPatternRepeatCount);
192 mesh.setVertexData(vbuff.get(), y * kBoxCountX * 4);
193 helper->drawMesh(mesh);
194 }
195 });
Chris Dalton1d616352017-05-31 12:51:23 -0600196
197 for (bool indexed : {false, true}) {
198 if (!context->caps()->instanceAttribSupport()) {
199 break;
200 }
201
202 run_test(indexed ? "setIndexedInstanced" : "setInstanced",
203 reporter, rtc, gold, [&](DrawMeshHelper* helper) {
204 auto idxbuff = indexed ? helper->getIndexBuffer() : nullptr;
205 auto instbuff = helper->makeVertexBuffer(boxes);
206 VALIDATE(instbuff);
207 auto vbuff = helper->makeVertexBuffer(std::vector<float>{0,0, 0,1, 1,0, 1,1});
208 VALIDATE(vbuff);
209 auto vbuff2 = helper->makeVertexBuffer( // for testing base vertex.
210 std::vector<float>{-1,-1, -1,-1, 0,0, 0,1, 1,0, 1,1});
211 VALIDATE(vbuff2);
212
213 // Draw boxes one line at a time to exercise base instance, base vertex, and null vertex
214 // buffer. setIndexedInstanced intentionally does not support a base index.
215 for (int y = 0; y < kBoxCountY; ++y) {
216 GrMesh mesh(indexed ? kTriangles_GrPrimitiveType : kTriangleStrip_GrPrimitiveType);
217 if (indexed) {
218 VALIDATE(idxbuff);
219 mesh.setIndexedInstanced(idxbuff.get(), 6,
220 instbuff.get(), kBoxCountX, y * kBoxCountX);
221 } else {
222 mesh.setInstanced(instbuff.get(), kBoxCountX, y * kBoxCountX, 4);
223 }
224 switch (y % 3) {
225 case 0:
226 if (context->caps()->shaderCaps()->vertexIDSupport()) {
227 if (y % 2) {
228 // We don't need this call because it's the initial state of GrMesh.
229 mesh.setVertexData(nullptr);
230 }
231 break;
232 }
233 // Fallthru.
234 case 1:
235 mesh.setVertexData(vbuff.get());
236 break;
237 case 2:
238 mesh.setVertexData(vbuff2.get(), 2);
239 break;
240 }
241 helper->drawMesh(mesh);
242 }
243 });
244 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600245}
246
247////////////////////////////////////////////////////////////////////////////////////////////////////
248
249class GrMeshTestOp : public GrDrawOp {
250public:
251 DEFINE_OP_CLASS_ID
252
253 GrMeshTestOp(std::function<void(DrawMeshHelper*)> testFn)
254 : INHERITED(ClassID())
255 , fTestFn(testFn) {
256 this->setBounds(SkRect::MakeIWH(kImageWidth, kImageHeight),
257 HasAABloat::kNo, IsZeroArea::kNo);
258 }
259
260private:
261 const char* name() const override { return "GrMeshTestOp"; }
262 FixedFunctionFlags fixedFunctionFlags() const override { return FixedFunctionFlags::kNone; }
263 bool xpRequiresDstTexture(const GrCaps&, const GrAppliedClip*) override { return false; }
264 bool onCombineIfPossible(GrOp* other, const GrCaps& caps) override { return false; }
265 void onPrepare(GrOpFlushState*) override {}
266 void onExecute(GrOpFlushState* state) override {
267 DrawMeshHelper helper(state);
268 fTestFn(&helper);
269 }
270
271 std::function<void(DrawMeshHelper*)> fTestFn;
272
273 typedef GrDrawOp INHERITED;
274};
275
276class GrMeshTestProcessor : public GrGeometryProcessor {
277public:
Chris Dalton1d616352017-05-31 12:51:23 -0600278 GrMeshTestProcessor(bool instanced, bool hasVertexBuffer)
279 : fInstanceLocation(nullptr)
280 , fVertex(nullptr)
281 , fColor(nullptr) {
282 if (instanced) {
283 fInstanceLocation = &this->addInstanceAttrib("location", kVec2f_GrVertexAttribType);
284 if (hasVertexBuffer) {
285 fVertex = &this->addVertexAttrib("vertex", kVec2f_GrVertexAttribType);
286 }
287 fColor = &this->addInstanceAttrib("color", kVec4ub_GrVertexAttribType);
288 } else {
289 fVertex = &this->addVertexAttrib("vertex", kVec2f_GrVertexAttribType);
290 fColor = &this->addVertexAttrib("color", kVec4ub_GrVertexAttribType);
291 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600292 this->initClassID<GrMeshTestProcessor>();
293 }
294
295 const char* name() const override { return "GrMeshTest Processor"; }
296
Chris Dalton1d616352017-05-31 12:51:23 -0600297 void getGLSLProcessorKey(const GrShaderCaps&, GrProcessorKeyBuilder* b) const final {
298 b->add32(SkToBool(fInstanceLocation));
299 b->add32(SkToBool(fVertex));
300 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600301
302 GrGLSLPrimitiveProcessor* createGLSLInstance(const GrShaderCaps&) const final;
303
304protected:
Chris Dalton1d616352017-05-31 12:51:23 -0600305 const Attribute* fInstanceLocation;
306 const Attribute* fVertex;
307 const Attribute* fColor;
Chris Dalton114a3c02017-05-26 15:17:19 -0600308
309 friend class GLSLMeshTestProcessor;
310 typedef GrGeometryProcessor INHERITED;
311};
312
313class GLSLMeshTestProcessor : public GrGLSLGeometryProcessor {
314 void setData(const GrGLSLProgramDataManager& pdman, const GrPrimitiveProcessor&,
315 FPCoordTransformIter&& transformIter) final {}
316
317 void onEmitCode(EmitArgs& args, GrGPArgs* gpArgs) final {
318 const GrMeshTestProcessor& mp = args.fGP.cast<GrMeshTestProcessor>();
319
320 GrGLSLVaryingHandler* varyingHandler = args.fVaryingHandler;
321 varyingHandler->emitAttributes(mp);
Chris Dalton1d616352017-05-31 12:51:23 -0600322 varyingHandler->addPassThroughAttribute(mp.fColor, args.fOutputColor);
Chris Dalton114a3c02017-05-26 15:17:19 -0600323
324 GrGLSLVertexBuilder* v = args.fVertBuilder;
Chris Dalton1d616352017-05-31 12:51:23 -0600325 if (!mp.fInstanceLocation) {
326 v->codeAppendf("vec2 vertex = %s;", mp.fVertex->fName);
327 } else {
328 if (mp.fVertex) {
329 v->codeAppendf("vec2 offset = %s;", mp.fVertex->fName);
330 } else {
331 v->codeAppend ("vec2 offset = vec2(sk_VertexID / 2, sk_VertexID % 2);");
332 }
333 v->codeAppendf("vec2 vertex = %s + offset * %i;",
334 mp.fInstanceLocation->fName, kBoxSize);
335 }
Chris Dalton114a3c02017-05-26 15:17:19 -0600336 gpArgs->fPositionVar.set(kVec2f_GrSLType, "vertex");
337
338 GrGLSLPPFragmentBuilder* f = args.fFragBuilder;
339 f->codeAppendf("%s = vec4(1);", args.fOutputCoverage);
340 }
341};
342
343GrGLSLPrimitiveProcessor* GrMeshTestProcessor::createGLSLInstance(const GrShaderCaps&) const {
344 return new GLSLMeshTestProcessor;
345}
346
347////////////////////////////////////////////////////////////////////////////////////////////////////
348
349template<typename T>
350sk_sp<const GrBuffer> DrawMeshHelper::makeVertexBuffer(const T* data, int count) {
351 return sk_sp<const GrBuffer>(
352 fState->resourceProvider()->createBuffer(
353 count * sizeof(T), kVertex_GrBufferType, kDynamic_GrAccessPattern,
354 GrResourceProvider::kNoPendingIO_Flag |
355 GrResourceProvider::kRequireGpuMemory_Flag, data));
356}
357
358sk_sp<const GrBuffer> DrawMeshHelper::getIndexBuffer() {
359 GR_DEFINE_STATIC_UNIQUE_KEY(gIndexBufferKey);
360 return sk_sp<const GrBuffer>(
361 fState->resourceProvider()->findOrCreatePatternedIndexBuffer(
362 kIndexPattern, 6, kIndexPatternRepeatCount, 4, gIndexBufferKey));
363}
364
365void DrawMeshHelper::drawMesh(const GrMesh& mesh) {
366 GrRenderTarget* rt = fState->drawOpArgs().fRenderTarget;
367 GrPipeline pipeline(rt, SkBlendMode::kSrc);
Chris Dalton1d616352017-05-31 12:51:23 -0600368 GrMeshTestProcessor mtp(mesh.isInstanced(), mesh.hasVertexData());
369 fState->commandBuffer()->draw(pipeline, mtp, &mesh, 1,
Chris Dalton114a3c02017-05-26 15:17:19 -0600370 SkRect::MakeIWH(kImageWidth, kImageHeight));
371}
372
373static void run_test(const char* testName, skiatest::Reporter* reporter,
374 const sk_sp<GrRenderTargetContext>& rtc, const SkBitmap& gold,
375 std::function<void(DrawMeshHelper*)> testFn) {
376 const int w = gold.width(), h = gold.height(), rowBytes = gold.rowBytes();
377 const uint32_t* goldPx = reinterpret_cast<const uint32_t*>(gold.getPixels());
378 if (h != rtc->height() || w != rtc->width()) {
379 ERRORF(reporter, "[%s] expectation and rtc not compatible (?).", testName);
380 return;
381 }
382 if (sizeof(uint32_t) * kImageWidth != gold.rowBytes()) {
383 ERRORF(reporter, "unexpected row bytes in gold image.", testName);
384 return;
385 }
386
387 SkAutoSTMalloc<kImageHeight * kImageWidth, uint32_t> resultPx(h * rowBytes);
388 rtc->clear(nullptr, 0xbaaaaaad, true);
389 rtc->priv().testingOnly_addDrawOp(skstd::make_unique<GrMeshTestOp>(testFn));
390 rtc->readPixels(gold.info(), resultPx, rowBytes, 0, 0, 0);
391 for (int y = 0; y < h; ++y) {
392 for (int x = 0; x < w; ++x) {
393 uint32_t expected = goldPx[y * kImageWidth + x];
394 uint32_t actual = resultPx[y * kImageWidth + x];
395 if (expected != actual) {
396 ERRORF(reporter, "[%s] pixel (%i,%i): got 0x%x expected 0x%x",
397 testName, x, y, actual, expected);
398 return;
399 }
400 }
401 }
402}
403
404#endif