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