Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / third_party / skia / tests / GLProgramsTest.cpp
1
2 /*
3  * Copyright 2011 Google Inc.
4  *
5  * Use of this source code is governed by a BSD-style license that can be
6  * found in the LICENSE file.
7  */
8
9 // This is a GPU-backend specific test. It relies on static intializers to work
10
11 #include "SkTypes.h"
12
13 #if SK_SUPPORT_GPU && SK_ALLOW_STATIC_GLOBAL_INITIALIZERS
14
15 #include "GrTBackendProcessorFactory.h"
16 #include "GrContextFactory.h"
17 #include "GrOptDrawState.h"
18 #include "effects/GrConfigConversionEffect.h"
19 #include "gl/builders/GrGLProgramBuilder.h"
20 #include "gl/GrGLPathRendering.h"
21 #include "gl/GrGpuGL.h"
22 #include "SkChecksum.h"
23 #include "SkRandom.h"
24 #include "Test.h"
25
26 /*
27  * A dummy processor which just tries to insert a massive key and verify that it can retrieve the
28  * whole thing correctly
29  */
30 static const uint32_t kMaxKeySize = 1024;
31
32 class GLBigKeyProcessor;
33
34 class BigKeyProcessor : public GrFragmentProcessor {
35 public:
36     static GrFragmentProcessor* Create() {
37         GR_CREATE_STATIC_PROCESSOR(gBigKeyProcessor, BigKeyProcessor, ())
38         return SkRef(gBigKeyProcessor);
39     }
40
41     static const char* Name() { return "Big ol' Key"; }
42
43     virtual const GrBackendFragmentProcessorFactory& getFactory() const SK_OVERRIDE {
44         return GrTBackendFragmentProcessorFactory<BigKeyProcessor>::getInstance();
45     }
46
47     typedef GLBigKeyProcessor GLProcessor;
48
49 private:
50     BigKeyProcessor() { }
51     virtual bool onIsEqual(const GrFragmentProcessor&) const SK_OVERRIDE { return true; }
52     virtual void onComputeInvariantOutput(InvariantOutput* inout) const SK_OVERRIDE { }
53
54     GR_DECLARE_FRAGMENT_PROCESSOR_TEST;
55
56     typedef GrFragmentProcessor INHERITED;
57 };
58
59 GR_DEFINE_FRAGMENT_PROCESSOR_TEST(BigKeyProcessor);
60
61 GrFragmentProcessor* BigKeyProcessor::TestCreate(SkRandom*,
62                                                  GrContext*,
63                                                  const GrDrawTargetCaps&,
64                                                  GrTexture*[]) {
65     return BigKeyProcessor::Create();
66 }
67
68 class GLBigKeyProcessor : public GrGLFragmentProcessor {
69 public:
70     GLBigKeyProcessor(const GrBackendProcessorFactory& factory, const GrProcessor&)
71         : INHERITED(factory) {}
72
73     virtual void emitCode(GrGLFPBuilder* builder,
74                           const GrFragmentProcessor& fp,
75                           const GrProcessorKey& key,
76                           const char* outputColor,
77                           const char* inputColor,
78                           const TransformedCoordsArray&,
79                           const TextureSamplerArray&) {
80         for (uint32_t i = 0; i < kMaxKeySize; i++) {
81             SkASSERT(key.get32(i) == i);
82         }
83     }
84
85     static void GenKey(const GrProcessor& processor, const GrGLCaps&, GrProcessorKeyBuilder* b) {
86         for (uint32_t i = 0; i < kMaxKeySize; i++) {
87             b->add32(i);
88         }
89     }
90
91 private:
92     typedef GrGLFragmentProcessor INHERITED;
93 };
94
95 /*
96  * Begin test code
97  */
98 static const int kRenderTargetHeight = 1;
99 static const int kRenderTargetWidth = 1;
100
101 static GrRenderTarget* random_render_target(GrGpuGL* gpu,
102                                             const GrCacheID& cacheId,
103                                             SkRandom* random) {
104     // setup render target
105     GrTextureParams params;
106     GrSurfaceDesc texDesc;
107     texDesc.fWidth = kRenderTargetWidth;
108     texDesc.fHeight = kRenderTargetHeight;
109     texDesc.fFlags = kRenderTarget_GrSurfaceFlag;
110     texDesc.fConfig = kRGBA_8888_GrPixelConfig;
111     texDesc.fOrigin = random->nextBool() == true ? kTopLeft_GrSurfaceOrigin :
112                                                    kBottomLeft_GrSurfaceOrigin;
113
114     SkAutoTUnref<GrTexture> texture(
115         gpu->getContext()->findAndRefTexture(texDesc, cacheId, &params));
116     if (!texture) {
117         texture.reset(gpu->getContext()->createTexture(&params, texDesc, cacheId, 0, 0));
118         if (!texture) {
119             return NULL;
120         }
121     }
122     return SkRef(texture->asRenderTarget());
123 }
124
125 // TODO clean this up, we have to do this to test geometry processors but there has got to be
126 // a better way.  In the mean time, we actually fill out these generic vertex attribs below with
127 // the correct vertex attribs from the GP.  We have to ensure, however, we don't try to add more
128 // than two attributes.  In addition, we 'pad' the below array with GPs up to 6 entries, 4 fixed
129 // function vertex attributes and 2 GP custom attributes.
130 GrVertexAttrib kGenericVertexAttribs[] = {
131     { kVec2f_GrVertexAttribType, 0,   kPosition_GrVertexAttribBinding },
132     { kVec2f_GrVertexAttribType, 0,   kGeometryProcessor_GrVertexAttribBinding },
133     { kVec2f_GrVertexAttribType, 0,   kGeometryProcessor_GrVertexAttribBinding },
134     { kVec2f_GrVertexAttribType, 0,   kGeometryProcessor_GrVertexAttribBinding },
135     { kVec2f_GrVertexAttribType, 0,   kGeometryProcessor_GrVertexAttribBinding },
136     { kVec2f_GrVertexAttribType, 0,   kGeometryProcessor_GrVertexAttribBinding }
137 };
138
139 /*
140  * convert sl type to vertexattrib type, not a complete implementation, only use for debugging
141  */
142 static GrVertexAttribType convert_sltype_to_attribtype(GrSLType type) {
143     switch (type) {
144         case kFloat_GrSLType:
145             return kFloat_GrVertexAttribType;
146         case kVec2f_GrSLType:
147             return kVec2f_GrVertexAttribType;
148         case kVec3f_GrSLType:
149             return kVec3f_GrVertexAttribType;
150         case kVec4f_GrSLType:
151             return kVec4f_GrVertexAttribType;
152         default:
153             SkFAIL("Type isn't convertible");
154             return kFloat_GrVertexAttribType;
155     }
156 }
157 // end test hack
158
159 static void setup_random_ff_attribute(GrVertexAttribBinding binding, GrVertexAttribType type,
160                                       SkRandom* random, int* attribIndex, int* runningStride) {
161     if (random->nextBool()) {
162         kGenericVertexAttribs[*attribIndex].fType = type;
163         kGenericVertexAttribs[*attribIndex].fOffset = *runningStride;
164         kGenericVertexAttribs[*attribIndex].fBinding = binding;
165         *runningStride += GrVertexAttribTypeSize(kGenericVertexAttribs[(*attribIndex)++].fType);
166     }
167 }
168
169 static void set_random_gp(GrGpuGL* gpu, SkRandom* random, GrTexture* dummyTextures[]) {
170     GrProgramElementRef<const GrGeometryProcessor> gp(
171             GrProcessorTestFactory<GrGeometryProcessor>::CreateStage(random,
172                                                                      gpu->getContext(),
173                                                                      *gpu->caps(),
174                                                                      dummyTextures));
175     SkASSERT(gp);
176
177     // we have to set dummy vertex attributes, first we setup the fixed function attributes
178     // always leave the position attribute untouched in the array
179     int attribIndex = 1;
180     int runningStride = GrVertexAttribTypeSize(kGenericVertexAttribs[0].fType);
181
182     // local coords
183     setup_random_ff_attribute(kLocalCoord_GrVertexAttribBinding, kVec2f_GrVertexAttribType,
184                               random, &attribIndex, &runningStride);
185
186     // color
187     setup_random_ff_attribute(kColor_GrVertexAttribBinding, kVec4f_GrVertexAttribType,
188                               random, &attribIndex, &runningStride);
189
190     // coverage
191     setup_random_ff_attribute(kCoverage_GrVertexAttribBinding, kUByte_GrVertexAttribType,
192                               random, &attribIndex, &runningStride);
193
194     // Update the geometry processor attributes
195     const GrGeometryProcessor::VertexAttribArray& v = gp->getVertexAttribs();
196     int numGPAttribs = v.count();
197     SkASSERT(numGPAttribs <= GrGeometryProcessor::kMaxVertexAttribs &&
198              GrGeometryProcessor::kMaxVertexAttribs == 2);
199
200     // we actually can't overflow if kMaxVertexAttribs == 2, but GCC 4.8 wants more proof
201     int maxIndex = SK_ARRAY_COUNT(kGenericVertexAttribs);
202     for (int i = 0; i < numGPAttribs && i + attribIndex < maxIndex; i++) {
203         kGenericVertexAttribs[i + attribIndex].fType =
204                 convert_sltype_to_attribtype(v[i].getType());
205         kGenericVertexAttribs[i + attribIndex].fOffset = runningStride;
206         kGenericVertexAttribs[i + attribIndex].fBinding = kGeometryProcessor_GrVertexAttribBinding;
207         runningStride += GrVertexAttribTypeSize(kGenericVertexAttribs[i + attribIndex].fType);
208     }
209
210     // update the vertex attributes with the ds
211     GrDrawState* ds = gpu->drawState();
212     ds->setVertexAttribs<kGenericVertexAttribs>(attribIndex + numGPAttribs, runningStride);
213     ds->setGeometryProcessor(gp);
214 }
215
216 static void set_random_color_coverage_stages(GrGpuGL* gpu,
217                                              int maxStages,
218                                              bool usePathRendering,
219                                              SkRandom* random,
220                                              GrTexture* dummyTextures[]) {
221     int numProcs = random->nextULessThan(maxStages + 1);
222     int numColorProcs = random->nextULessThan(numProcs + 1);
223
224     int currTextureCoordSet = 0;
225     for (int s = 0; s < numProcs;) {
226         GrProgramElementRef<GrFragmentProcessor> fp(
227                 GrProcessorTestFactory<GrFragmentProcessor>::CreateStage(random,
228                                                                          gpu->getContext(),
229                                                                          *gpu->caps(),
230                                                                          dummyTextures));
231         SkASSERT(fp);
232
233         // don't add dst color reads to coverage stage
234         if (s >= numColorProcs && fp->willReadDstColor()) {
235             continue;
236         }
237
238         // If adding this effect would exceed the max texture coord set count then generate a
239         // new random effect.
240         if (usePathRendering && gpu->glPathRendering()->texturingMode() ==
241                                 GrGLPathRendering::FixedFunction_TexturingMode) {;
242             int numTransforms = fp->numTransforms();
243             if (currTextureCoordSet + numTransforms >
244                 gpu->glCaps().maxFixedFunctionTextureCoords()) {
245                 continue;
246             }
247             currTextureCoordSet += numTransforms;
248         }
249
250         // finally add the stage to the correct pipeline in the drawstate
251         GrDrawState* ds = gpu->drawState();
252         if (s < numColorProcs) {
253             ds->addColorProcessor(fp);
254         } else {
255             ds->addCoverageProcessor(fp);
256         }
257         ++s;
258     }
259 }
260
261 // There are only a few cases of random colors which interest us
262 enum ColorMode {
263     kAllOnes_ColorMode,
264     kAllZeros_ColorMode,
265     kAlphaOne_ColorMode,
266     kRandom_ColorMode,
267     kLast_ColorMode = kRandom_ColorMode
268 };
269
270 static void set_random_color(GrGpuGL* gpu, SkRandom* random) {
271     ColorMode colorMode = ColorMode(random->nextULessThan(kLast_ColorMode + 1));
272     GrColor color;
273     switch (colorMode) {
274         case kAllOnes_ColorMode:
275             color = GrColorPackRGBA(0xFF, 0xFF, 0xFF, 0xFF);
276             break;
277         case kAllZeros_ColorMode:
278             color = GrColorPackRGBA(0, 0, 0, 0);
279             break;
280         case kAlphaOne_ColorMode:
281             color = GrColorPackRGBA(random->nextULessThan(256),
282                                     random->nextULessThan(256),
283                                     random->nextULessThan(256),
284                                     0xFF);
285             break;
286         case kRandom_ColorMode:
287             uint8_t alpha = random->nextULessThan(256);
288             color = GrColorPackRGBA(random->nextRangeU(0, alpha),
289                                     random->nextRangeU(0, alpha),
290                                     random->nextRangeU(0, alpha),
291                                     alpha);
292             break;
293     }
294     GrColorIsPMAssert(color);
295     gpu->drawState()->setColor(color);
296 }
297
298 // There are only a few cases of random coverages which interest us
299 enum CoverageMode {
300     kZero_CoverageMode,
301     kFF_CoverageMode,
302     kRandom_CoverageMode,
303     kLast_CoverageMode = kRandom_CoverageMode
304 };
305
306 static void set_random_coverage(GrGpuGL* gpu, SkRandom* random) {
307     CoverageMode coverageMode = CoverageMode(random->nextULessThan(kLast_CoverageMode + 1));
308     uint8_t coverage;
309     switch (coverageMode) {
310         case kZero_CoverageMode:
311             coverage = 0;
312             break;
313         case kFF_CoverageMode:
314             coverage = 0xFF;
315             break;
316         case kRandom_CoverageMode:
317             coverage = uint8_t(random->nextU());
318             break;
319     }
320     gpu->drawState()->setCoverage(coverage);
321 }
322
323 static void set_random_hints(GrGpuGL* gpu, SkRandom* random) {
324     for (int i = 1; i <= GrDrawState::kLast_Hint; i <<= 1) {
325         gpu->drawState()->setHint(GrDrawState::Hints(i), random->nextBool());
326     }
327 }
328
329 static void set_random_state(GrGpuGL* gpu, SkRandom* random) {
330     int state = 0;
331     for (int i = 1; i <= GrDrawState::kLast_StateBit; i <<= 1) {
332         state |= random->nextBool() * i;
333     }
334     gpu->drawState()->enableState(state);
335 }
336
337 // this function will randomly pick non-self referencing blend modes
338 static void set_random_blend_func(GrGpuGL* gpu, SkRandom* random) {
339     GrBlendCoeff src;
340     do {
341         src = GrBlendCoeff(random->nextRangeU(kFirstPublicGrBlendCoeff, kLastPublicGrBlendCoeff));
342     } while (GrBlendCoeffRefsSrc(src));
343
344     GrBlendCoeff dst;
345     do {
346         dst = GrBlendCoeff(random->nextRangeU(kFirstPublicGrBlendCoeff, kLastPublicGrBlendCoeff));
347     } while (GrBlendCoeffRefsDst(dst));
348
349     gpu->drawState()->setBlendFunc(src, dst);
350 }
351
352 // right now, the only thing we seem to care about in drawState's stencil is 'doesWrite()'
353 static void set_random_stencil(GrGpuGL* gpu, SkRandom* random) {
354     GR_STATIC_CONST_SAME_STENCIL(kDoesWriteStencil,
355                                  kReplace_StencilOp,
356                                  kReplace_StencilOp,
357                                  kAlways_StencilFunc,
358                                  0xffff,
359                                  0xffff,
360                                  0xffff);
361     GR_STATIC_CONST_SAME_STENCIL(kDoesNotWriteStencil,
362                                  kKeep_StencilOp,
363                                  kKeep_StencilOp,
364                                  kNever_StencilFunc,
365                                  0xffff,
366                                  0xffff,
367                                  0xffff);
368
369     if (random->nextBool()) {
370         gpu->drawState()->setStencil(kDoesWriteStencil);
371     } else {
372         gpu->drawState()->setStencil(kDoesNotWriteStencil);
373     }
374 }
375
376 bool GrGpuGL::programUnitTest(int maxStages) {
377     // setup dummy textures
378     GrSurfaceDesc dummyDesc;
379     dummyDesc.fFlags = kRenderTarget_GrSurfaceFlag;
380     dummyDesc.fConfig = kSkia8888_GrPixelConfig;
381     dummyDesc.fWidth = 34;
382     dummyDesc.fHeight = 18;
383     SkAutoTUnref<GrTexture> dummyTexture1(this->createTexture(dummyDesc, NULL, 0));
384     dummyDesc.fFlags = kNone_GrSurfaceFlags;
385     dummyDesc.fConfig = kAlpha_8_GrPixelConfig;
386     dummyDesc.fWidth = 16;
387     dummyDesc.fHeight = 22;
388     SkAutoTUnref<GrTexture> dummyTexture2(this->createTexture(dummyDesc, NULL, 0));
389
390     if (!dummyTexture1 || ! dummyTexture2) {
391         SkDebugf("Could not allocate dummy textures");
392         return false;
393     }
394
395     GrTexture* dummyTextures[] = {dummyTexture1.get(), dummyTexture2.get()};
396
397     // Setup texture cache id key
398     const GrCacheID::Domain glProgramsDomain = GrCacheID::GenerateDomain();
399     GrCacheID::Key key;
400     memset(&key, 0, sizeof(key));
401     key.fData32[0] = kRenderTargetWidth;
402     key.fData32[1] = kRenderTargetHeight;
403     GrCacheID glProgramsCacheID(glProgramsDomain, key);
404
405     // setup clip
406     SkRect screen =
407             SkRect::MakeWH(SkIntToScalar(kRenderTargetWidth), SkIntToScalar(kRenderTargetHeight));
408
409     SkClipStack stack;
410     stack.clipDevRect(screen, SkRegion::kReplace_Op, false);
411
412     // wrap the SkClipStack in a GrClipData
413     GrClipData clipData;
414     clipData.fClipStack = &stack;
415     this->setClip(&clipData);
416
417     SkRandom random;
418     static const int NUM_TESTS = 512;
419     for (int t = 0; t < NUM_TESTS;) {
420         // setup random render target(can fail)
421         SkAutoTUnref<GrRenderTarget> rt(random_render_target(this, glProgramsCacheID, &random));
422         if (!rt) {
423             SkDebugf("Could not allocate render target");
424             return false;
425         }
426
427         GrDrawState* ds = this->drawState();
428         ds->setRenderTarget(rt.get());
429
430         // if path rendering we have to setup a couple of things like the draw type
431         bool usePathRendering = this->glCaps().pathRenderingSupport() && random.nextBool();
432
433         GrGpu::DrawType drawType = usePathRendering ? GrGpu::kDrawPath_DrawType :
434                                                       GrGpu::kDrawPoints_DrawType;
435
436         // twiddle drawstate knobs randomly
437         bool hasGeometryProcessor = usePathRendering ? false : random.nextBool();
438         if (hasGeometryProcessor) {
439             set_random_gp(this, &random, dummyTextures);
440         }
441         set_random_color_coverage_stages(this, maxStages - hasGeometryProcessor, usePathRendering,
442                                          &random, dummyTextures);
443         set_random_color(this, &random);
444         set_random_coverage(this, &random);
445         set_random_hints(this, &random);
446         set_random_state(this, &random);
447         set_random_blend_func(this, &random);
448         set_random_stencil(this, &random);
449
450         GrDeviceCoordTexture dstCopy;
451
452         if (!this->setupDstReadIfNecessary(&dstCopy, NULL)) {
453             SkDebugf("Couldn't setup dst read texture");
454             return false;
455         }
456
457         // create optimized draw state, setup readDst texture if required, and build a descriptor
458         // and program.  ODS creation can fail, so we have to check
459         SkAutoTUnref<GrOptDrawState> ods(GrOptDrawState::Create(this->getDrawState(),
460                                                                 this,
461                                                                 &dstCopy,
462                                                                 drawType));
463         if (!ods.get()) {
464             ds->reset();
465             continue;
466         }
467         SkAutoTUnref<GrGLProgram> program(GrGLProgramBuilder::CreateProgram(*ods, drawType, this));
468         if (NULL == program.get()) {
469             SkDebugf("Failed to create program!");
470             return false;
471         }
472
473         // We have to reset the drawstate because we might have added a gp
474         ds->reset();
475
476         // because occasionally optimized drawstate creation will fail for valid reasons, we only
477         // want to increment on success
478         ++t;
479     }
480     return true;
481 }
482
483 DEF_GPUTEST(GLPrograms, reporter, factory) {
484     for (int type = 0; type < GrContextFactory::kLastGLContextType; ++type) {
485         GrContext* context = factory->get(static_cast<GrContextFactory::GLContextType>(type));
486         if (context) {
487             GrGpuGL* gpu = static_cast<GrGpuGL*>(context->getGpu());
488
489             /*
490              * For the time being, we only support the test with desktop GL or for android on
491              * ARM platforms
492              * TODO When we run ES 3.00 GLSL in more places, test again
493              */
494             int maxStages;
495             if (kGL_GrGLStandard == gpu->glStandard() ||
496                 kARM_GrGLVendor == gpu->ctxInfo().vendor()) {
497                 maxStages = 6;
498             } else if (kTegra3_GrGLRenderer == gpu->ctxInfo().renderer() ||
499                        kOther_GrGLRenderer == gpu->ctxInfo().renderer()) {
500                 maxStages = 1;
501             } else {
502                 return;
503             }
504 #if SK_ANGLE
505             // Some long shaders run out of temporary registers in the D3D compiler on ANGLE.
506             if (type == GrContextFactory::kANGLE_GLContextType) {
507                 maxStages = 3;
508             }
509 #endif
510             REPORTER_ASSERT(reporter, gpu->programUnitTest(maxStages));
511         }
512     }
513 }
514
515 #endif