Relax the precision requirements for derivate built-ins
[platform/upstream/VK-GL-CTS.git] / modules / gles3 / functional / es3fShaderDerivateTests.cpp
1 /*-------------------------------------------------------------------------
2  * drawElements Quality Program OpenGL ES 3.0 Module
3  * -------------------------------------------------
4  *
5  * Copyright 2014 The Android Open Source Project
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  *//*!
20  * \file
21  * \brief Shader derivate function tests.
22  *
23  * \todo [2013-06-25 pyry] Missing features:
24  *  - lines and points
25  *  - projected coordinates
26  *  - continous non-trivial functions (sin, exp)
27  *  - non-continous functions (step)
28  *//*--------------------------------------------------------------------*/
29
30 #include "es3fShaderDerivateTests.hpp"
31 #include "gluShaderProgram.hpp"
32 #include "gluRenderContext.hpp"
33 #include "gluDrawUtil.hpp"
34 #include "gluPixelTransfer.hpp"
35 #include "gluShaderUtil.hpp"
36 #include "gluStrUtil.hpp"
37 #include "gluTextureUtil.hpp"
38 #include "gluTexture.hpp"
39 #include "tcuStringTemplate.hpp"
40 #include "tcuRenderTarget.hpp"
41 #include "tcuSurface.hpp"
42 #include "tcuTestLog.hpp"
43 #include "tcuVectorUtil.hpp"
44 #include "tcuTextureUtil.hpp"
45 #include "tcuRGBA.hpp"
46 #include "tcuFloat.hpp"
47 #include "tcuInterval.hpp"
48 #include "deRandom.hpp"
49 #include "deUniquePtr.hpp"
50 #include "deString.h"
51 #include "glwEnums.hpp"
52 #include "glwFunctions.hpp"
53 #include "glsShaderRenderCase.hpp" // gls::setupDefaultUniforms()
54
55 #include <sstream>
56
57 namespace deqp
58 {
59 namespace gles3
60 {
61 namespace Functional
62 {
63
64 using std::vector;
65 using std::string;
66 using std::map;
67 using tcu::TestLog;
68 using std::ostringstream;
69
70 enum
71 {
72         VIEWPORT_WIDTH          = 167,
73         VIEWPORT_HEIGHT         = 103,
74         FBO_WIDTH                       = 99,
75         FBO_HEIGHT                      = 133,
76         MAX_FAILED_MESSAGES     = 10
77 };
78
79 enum DerivateFunc
80 {
81         DERIVATE_DFDX   = 0,
82         DERIVATE_DFDY,
83         DERIVATE_FWIDTH,
84
85         DERIVATE_LAST
86 };
87
88 enum SurfaceType
89 {
90         SURFACETYPE_DEFAULT_FRAMEBUFFER = 0,
91         SURFACETYPE_UNORM_FBO,
92         SURFACETYPE_FLOAT_FBO,  // \note Uses RGBA32UI fbo actually, since FP rendertargets are not in core spec.
93
94         SURFACETYPE_LAST
95 };
96
97 // Utilities
98
99 namespace
100 {
101
102 class AutoFbo
103 {
104 public:
105         AutoFbo (const glw::Functions& gl)
106                 : m_gl  (gl)
107                 , m_fbo (0)
108         {
109         }
110
111         ~AutoFbo (void)
112         {
113                 if (m_fbo)
114                         m_gl.deleteFramebuffers(1, &m_fbo);
115         }
116
117         void gen (void)
118         {
119                 DE_ASSERT(!m_fbo);
120                 m_gl.genFramebuffers(1, &m_fbo);
121         }
122
123         deUint32 operator* (void) const { return m_fbo; }
124
125 private:
126         const glw::Functions&   m_gl;
127         deUint32                                m_fbo;
128 };
129
130 class AutoRbo
131 {
132 public:
133         AutoRbo (const glw::Functions& gl)
134                 : m_gl  (gl)
135                 , m_rbo (0)
136         {
137         }
138
139         ~AutoRbo (void)
140         {
141                 if (m_rbo)
142                         m_gl.deleteRenderbuffers(1, &m_rbo);
143         }
144
145         void gen (void)
146         {
147                 DE_ASSERT(!m_rbo);
148                 m_gl.genRenderbuffers(1, &m_rbo);
149         }
150
151         deUint32 operator* (void) const { return m_rbo; }
152
153 private:
154         const glw::Functions&   m_gl;
155         deUint32                                m_rbo;
156 };
157
158 } // anonymous
159
160 static const char* getDerivateFuncName (DerivateFunc func)
161 {
162         switch (func)
163         {
164                 case DERIVATE_DFDX:             return "dFdx";
165                 case DERIVATE_DFDY:             return "dFdy";
166                 case DERIVATE_FWIDTH:   return "fwidth";
167                 default:
168                         DE_ASSERT(false);
169                         return DE_NULL;
170         }
171 }
172
173 static const char* getDerivateFuncCaseName (DerivateFunc func)
174 {
175         switch (func)
176         {
177                 case DERIVATE_DFDX:             return "dfdx";
178                 case DERIVATE_DFDY:             return "dfdy";
179                 case DERIVATE_FWIDTH:   return "fwidth";
180                 default:
181                         DE_ASSERT(false);
182                         return DE_NULL;
183         }
184 }
185
186 static inline tcu::BVec4 getDerivateMask (glu::DataType type)
187 {
188         switch (type)
189         {
190                 case glu::TYPE_FLOAT:           return tcu::BVec4(true, false, false, false);
191                 case glu::TYPE_FLOAT_VEC2:      return tcu::BVec4(true, true, false, false);
192                 case glu::TYPE_FLOAT_VEC3:      return tcu::BVec4(true, true, true, false);
193                 case glu::TYPE_FLOAT_VEC4:      return tcu::BVec4(true, true, true, true);
194                 default:
195                         DE_ASSERT(false);
196                         return tcu::BVec4(true);
197         }
198 }
199
200 static inline tcu::Vec4 readDerivate (const tcu::ConstPixelBufferAccess& surface, const tcu::Vec4& derivScale, const tcu::Vec4& derivBias, int x, int y)
201 {
202         return (surface.getPixel(x, y) - derivBias) / derivScale;
203 }
204
205 static inline tcu::UVec4 getCompExpBits (const tcu::Vec4& v)
206 {
207         return tcu::UVec4(tcu::Float32(v[0]).exponentBits(),
208                                           tcu::Float32(v[1]).exponentBits(),
209                                           tcu::Float32(v[2]).exponentBits(),
210                                           tcu::Float32(v[3]).exponentBits());
211 }
212
213 float computeFloatingPointError (const float value, const int numAccurateBits)
214 {
215         const int               numGarbageBits  = 23-numAccurateBits;
216         const deUint32  mask                    = (1u<<numGarbageBits)-1u;
217         const int               exp                             = (tcu::Float32(value).exponent() < -3) ? -3 : tcu::Float32(value).exponent();
218
219         return tcu::Float32::construct(+1, exp, (1u<<23) | mask).asFloat() - tcu::Float32::construct(+1, exp, 1u<<23).asFloat();
220 }
221
222 static int getNumMantissaBits (const glu::Precision precision)
223 {
224         switch (precision)
225         {
226                 case glu::PRECISION_HIGHP:              return 23;
227                 case glu::PRECISION_MEDIUMP:    return 10;
228                 case glu::PRECISION_LOWP:               return 6;
229                 default:
230                         DE_ASSERT(false);
231                         return 0;
232         }
233 }
234
235 static int getMinExponent (const glu::Precision precision)
236 {
237         switch (precision)
238         {
239                 case glu::PRECISION_HIGHP:              return -126;
240                 case glu::PRECISION_MEDIUMP:    return -14;
241                 case glu::PRECISION_LOWP:               return -8;
242                 default:
243                         DE_ASSERT(false);
244                         return 0;
245         }
246 }
247
248 static float getSingleULPForExponent (int exp, int numMantissaBits)
249 {
250         if (numMantissaBits > 0)
251         {
252                 DE_ASSERT(numMantissaBits <= 23);
253
254                 const int ulpBitNdx = 23-numMantissaBits;
255                 return tcu::Float32::construct(+1, exp, (1<<23) | (1 << ulpBitNdx)).asFloat() - tcu::Float32::construct(+1, exp, (1<<23)).asFloat();
256         }
257         else
258         {
259                 DE_ASSERT(numMantissaBits == 0);
260                 return tcu::Float32::construct(+1, exp, (1<<23)).asFloat();
261         }
262 }
263
264 static float getSingleULPForValue (float value, int numMantissaBits)
265 {
266         const int exp = tcu::Float32(value).exponent();
267         return getSingleULPForExponent(exp, numMantissaBits);
268 }
269
270 static float convertFloatFlushToZeroRtn (float value, int minExponent, int numAccurateBits)
271 {
272         if (value == 0.0f)
273         {
274                 return 0.0f;
275         }
276         else
277         {
278                 const tcu::Float32      inputFloat                      = tcu::Float32(value);
279                 const int                       numTruncatedBits        = 23-numAccurateBits;
280                 const deUint32          truncMask                       = (1u<<numTruncatedBits)-1u;
281
282                 if (value > 0.0f)
283                 {
284                         if (value > 0.0f && tcu::Float32(value).exponent() < minExponent)
285                         {
286                                 // flush to zero if possible
287                                 return 0.0f;
288                         }
289                         else
290                         {
291                                 // just mask away non-representable bits
292                                 return tcu::Float32::construct(+1, inputFloat.exponent(), inputFloat.mantissa() & ~truncMask).asFloat();
293                         }
294                 }
295                 else
296                 {
297                         if (inputFloat.mantissa() & truncMask)
298                         {
299                                 // decrement one ulp if truncated bits are non-zero (i.e. if value is not representable)
300                                 return tcu::Float32::construct(-1, inputFloat.exponent(), inputFloat.mantissa() & ~truncMask).asFloat() - getSingleULPForExponent(inputFloat.exponent(), numAccurateBits);
301                         }
302                         else
303                         {
304                                 // value is representable, no need to do anything
305                                 return value;
306                         }
307                 }
308         }
309 }
310
311 static float convertFloatFlushToZeroRtp (float value, int minExponent, int numAccurateBits)
312 {
313         return -convertFloatFlushToZeroRtn(-value, minExponent, numAccurateBits);
314 }
315
316 static float addErrorUlp (float value, float numUlps, int numMantissaBits)
317 {
318         return value + numUlps * getSingleULPForValue(value, numMantissaBits);
319 }
320
321 enum
322 {
323         INTERPOLATION_LOST_BITS = 3, // number mantissa of bits allowed to be lost in varying interpolation
324 };
325
326 static int getInterpolationLostBitsWarning (const glu::Precision precision)
327 {
328         // number mantissa of bits allowed to be lost in varying interpolation
329         switch (precision)
330         {
331                 case glu::PRECISION_HIGHP:              return 9;
332                 case glu::PRECISION_MEDIUMP:    return 3;
333                 case glu::PRECISION_LOWP:               return 3;
334                 default:
335                         DE_ASSERT(false);
336                         return 0;
337         }
338 }
339
340 static inline tcu::Vec4 getDerivateThreshold (const glu::Precision precision, const tcu::Vec4& valueMin, const tcu::Vec4& valueMax, const tcu::Vec4& expectedDerivate)
341 {
342         const int                       baseBits                = getNumMantissaBits(precision);
343         const tcu::UVec4        derivExp                = getCompExpBits(expectedDerivate);
344         const tcu::UVec4        maxValueExp             = max(getCompExpBits(valueMin), getCompExpBits(valueMax));
345         const tcu::UVec4        numBitsLost             = maxValueExp - min(maxValueExp, derivExp);
346         const tcu::IVec4        numAccurateBits = max(baseBits - numBitsLost.asInt() - (int)INTERPOLATION_LOST_BITS, tcu::IVec4(0));
347
348         return tcu::Vec4(computeFloatingPointError(expectedDerivate[0], numAccurateBits[0]),
349                                          computeFloatingPointError(expectedDerivate[1], numAccurateBits[1]),
350                                          computeFloatingPointError(expectedDerivate[2], numAccurateBits[2]),
351                                          computeFloatingPointError(expectedDerivate[3], numAccurateBits[3]));
352 }
353
354 static inline tcu::Vec4 getDerivateThresholdWarning (const glu::Precision precision, const tcu::Vec4& valueMin, const tcu::Vec4& valueMax, const tcu::Vec4& expectedDerivate)
355 {
356         const int                       baseBits                = getNumMantissaBits(precision);
357         const tcu::UVec4        derivExp                = getCompExpBits(expectedDerivate);
358         const tcu::UVec4        maxValueExp             = max(getCompExpBits(valueMin), getCompExpBits(valueMax));
359         const tcu::UVec4        numBitsLost             = maxValueExp - min(maxValueExp, derivExp);
360         const tcu::IVec4        numAccurateBits = max(baseBits - numBitsLost.asInt() - getInterpolationLostBitsWarning(precision), tcu::IVec4(0));
361
362         return tcu::Vec4(computeFloatingPointError(expectedDerivate[0], numAccurateBits[0]),
363                                          computeFloatingPointError(expectedDerivate[1], numAccurateBits[1]),
364                                          computeFloatingPointError(expectedDerivate[2], numAccurateBits[2]),
365                                          computeFloatingPointError(expectedDerivate[3], numAccurateBits[3]));
366 }
367
368
369 namespace
370 {
371
372 struct LogVecComps
373 {
374         const tcu::Vec4&        v;
375         int                                     numComps;
376
377         LogVecComps (const tcu::Vec4& v_, int numComps_)
378                 : v                     (v_)
379                 , numComps      (numComps_)
380         {
381         }
382 };
383
384 std::ostream& operator<< (std::ostream& str, const LogVecComps& v)
385 {
386         DE_ASSERT(de::inRange(v.numComps, 1, 4));
387         if (v.numComps == 1)            return str << v.v[0];
388         else if (v.numComps == 2)       return str << v.v.toWidth<2>();
389         else if (v.numComps == 3)       return str << v.v.toWidth<3>();
390         else                                            return str << v.v;
391 }
392
393 } // anonymous
394
395 enum VerificationLogging
396 {
397         LOG_ALL = 0,
398         LOG_NOTHING
399 };
400
401 static qpTestResult verifyConstantDerivate (tcu::TestLog&                               log,
402                                                                         const tcu::ConstPixelBufferAccess&      result,
403                                                                         const tcu::PixelBufferAccess&           errorMask,
404                                                                         glu::DataType                                           dataType,
405                                                                         const tcu::Vec4&                                        reference,
406                                                                         const tcu::Vec4&                                        threshold,
407                                                                         const tcu::Vec4&                                        scale,
408                                                                         const tcu::Vec4&                                        bias,
409                                                                         VerificationLogging                                     logPolicy = LOG_ALL)
410 {
411         const int                       numComps                = glu::getDataTypeFloatScalars(dataType);
412         const tcu::BVec4        mask                    = tcu::logicalNot(getDerivateMask(dataType));
413         int                                     numFailedPixels = 0;
414
415         if (logPolicy == LOG_ALL)
416                 log << TestLog::Message << "Expecting " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps) << TestLog::EndMessage;
417
418         for (int y = 0; y < result.getHeight(); y++)
419         {
420                 for (int x = 0; x < result.getWidth(); x++)
421                 {
422                         const tcu::Vec4         resDerivate             = readDerivate(result, scale, bias, x, y);
423                         const bool                      isOk                    = tcu::allEqual(tcu::logicalOr(tcu::lessThanEqual(tcu::abs(reference - resDerivate), threshold), mask), tcu::BVec4(true));
424
425                         if (!isOk)
426                         {
427                                 if (numFailedPixels < MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
428                                         log << TestLog::Message << "FAIL: got " << LogVecComps(resDerivate, numComps)
429                                                                                         << ", diff = " << LogVecComps(tcu::abs(reference - resDerivate), numComps)
430                                                                                         << ", at x = " << x << ", y = " << y
431                                                 << TestLog::EndMessage;
432                                 numFailedPixels += 1;
433                                 errorMask.setPixel(tcu::RGBA::red().toVec(), x, y);
434                         }
435                 }
436         }
437
438         if (numFailedPixels >= MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
439                 log << TestLog::Message << "..." << TestLog::EndMessage;
440
441         if (numFailedPixels > 0 && logPolicy == LOG_ALL)
442                 log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
443
444         return (numFailedPixels == 0) ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL;
445 }
446
447 struct Linear2DFunctionEvaluator
448 {
449         tcu::Matrix<float, 4, 3> matrix;
450
451         //      .-----.
452         //      | s_x |
453         //  M x | s_y |
454         //      | 1.0 |
455         //      '-----'
456         tcu::Vec4 evaluateAt (float screenX, float screenY) const;
457 };
458
459 tcu::Vec4 Linear2DFunctionEvaluator::evaluateAt (float screenX, float screenY) const
460 {
461         const tcu::Vec3 position(screenX, screenY, 1.0f);
462         return matrix * position;
463 }
464
465 static qpTestResult reverifyConstantDerivateWithFlushRelaxations (tcu::TestLog&                                                 log,
466                                                                                                                   const tcu::ConstPixelBufferAccess&    result,
467                                                                                                                   const tcu::PixelBufferAccess&                 errorMask,
468                                                                                                                   glu::DataType                                                 dataType,
469                                                                                                                   glu::Precision                                                precision,
470                                                                                                                   const tcu::Vec4&                                              derivScale,
471                                                                                                                   const tcu::Vec4&                                              derivBias,
472                                                                                                                   const tcu::Vec4&                                              surfaceThreshold,
473                                                                                                                   DerivateFunc                                                  derivateFunc,
474                                                                                                                   const Linear2DFunctionEvaluator&              function)
475 {
476         DE_ASSERT(result.getWidth() == errorMask.getWidth());
477         DE_ASSERT(result.getHeight() == errorMask.getHeight());
478         DE_ASSERT(derivateFunc == DERIVATE_DFDX || derivateFunc == DERIVATE_DFDY);
479
480         const tcu::IVec4        red                                             (255, 0, 0, 255);
481         const tcu::IVec4        green                                   (0, 255, 0, 255);
482         const float                     divisionErrorUlps               = 2.5f;
483
484         const int                       numComponents                   = glu::getDataTypeFloatScalars(dataType);
485         const int                       numBits                                 = getNumMantissaBits(precision);
486         const int                       minExponent                             = getMinExponent(precision);
487
488         const int                       numVaryingSampleBits    = numBits - INTERPOLATION_LOST_BITS;
489         int                                     numFailedPixels                 = 0;
490
491         tcu::clear(errorMask, green);
492
493         // search for failed pixels
494         for (int y = 0; y < result.getHeight(); ++y)
495         for (int x = 0; x < result.getWidth(); ++x)
496         {
497                 //                 flushToZero?(f2z?(functionValueCurrent) - f2z?(functionValueBefore))
498                 // flushToZero? ( ------------------------------------------------------------------------ +- 2.5 ULP )
499                 //                                                  dx
500
501                 const tcu::Vec4 resultDerivative                = readDerivate(result, derivScale, derivBias, x, y);
502
503                 // sample at the front of the back pixel and the back of the front pixel to cover the whole area of
504                 // legal sample positions. In general case this is NOT OK, but we know that the target funtion is
505                 // (mostly*) linear which allows us to take the sample points at arbitrary points. This gets us the
506                 // maximum difference possible in exponents which are used in error bound calculations.
507                 // * non-linearity may happen around zero or with very high function values due to subnorms not
508                 //   behaving well.
509                 const tcu::Vec4 functionValueForward    = (derivateFunc == DERIVATE_DFDX)
510                                                                                                         ? (function.evaluateAt((float)x + 2.0f, (float)y + 0.5f))
511                                                                                                         : (function.evaluateAt((float)x + 0.5f, (float)y + 2.0f));
512                 const tcu::Vec4 functionValueBackward   = (derivateFunc == DERIVATE_DFDX)
513                                                                                                         ? (function.evaluateAt((float)x - 1.0f, (float)y + 0.5f))
514                                                                                                         : (function.evaluateAt((float)x + 0.5f, (float)y - 1.0f));
515
516                 bool    anyComponentFailed                              = false;
517
518                 // check components separately
519                 for (int c = 0; c < numComponents; ++c)
520                 {
521                         // Simulate interpolation. Add allowed interpolation error and round to target precision. Allow one half ULP (i.e. correct rounding)
522                         const tcu::Interval     forwardComponent                (convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueForward[c],  -0.5f, numVaryingSampleBits), minExponent, numBits),
523                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueForward[c],  +0.5f, numVaryingSampleBits), minExponent, numBits));
524                         const tcu::Interval     backwardComponent               (convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueBackward[c], -0.5f, numVaryingSampleBits), minExponent, numBits),
525                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueBackward[c], +0.5f, numVaryingSampleBits), minExponent, numBits));
526                         const int                       maxValueExp                             = de::max(de::max(tcu::Float32(forwardComponent.lo()).exponent(),   tcu::Float32(forwardComponent.hi()).exponent()),
527                                                                                                                                   de::max(tcu::Float32(backwardComponent.lo()).exponent(),  tcu::Float32(backwardComponent.hi()).exponent()));
528
529                         // subtraction in numerator will likely cause a cancellation of the most
530                         // significant bits. Apply error bounds.
531
532                         const tcu::Interval     numerator                               (forwardComponent - backwardComponent);
533                         const int                       numeratorLoExp                  = tcu::Float32(numerator.lo()).exponent();
534                         const int                       numeratorHiExp                  = tcu::Float32(numerator.hi()).exponent();
535                         const int                       numeratorLoBitsLost             = de::max(0, maxValueExp - numeratorLoExp); //!< must clamp to zero since if forward and backward components have different
536                         const int                       numeratorHiBitsLost             = de::max(0, maxValueExp - numeratorHiExp); //!< sign, numerator might have larger exponent than its operands.
537                         const int                       numeratorLoBits                 = de::max(0, numBits - numeratorLoBitsLost);
538                         const int                       numeratorHiBits                 = de::max(0, numBits - numeratorHiBitsLost);
539
540                         const tcu::Interval     numeratorRange                  (convertFloatFlushToZeroRtn((float)numerator.lo(), minExponent, numeratorLoBits),
541                                                                                                                  convertFloatFlushToZeroRtp((float)numerator.hi(), minExponent, numeratorHiBits));
542
543                         const tcu::Interval     divisionRange                   = numeratorRange / 3.0f; // legal sample area is anywhere within this and neighboring pixels (i.e. size = 3)
544                         const tcu::Interval     divisionResultRange             (convertFloatFlushToZeroRtn(addErrorUlp((float)divisionRange.lo(), -divisionErrorUlps, numBits), minExponent, numBits),
545                                                                                                                  convertFloatFlushToZeroRtp(addErrorUlp((float)divisionRange.hi(), +divisionErrorUlps, numBits), minExponent, numBits));
546                         const tcu::Interval     finalResultRange                (divisionResultRange.lo() - surfaceThreshold[c], divisionResultRange.hi() + surfaceThreshold[c]);
547
548                         if (resultDerivative[c] >= finalResultRange.lo() && resultDerivative[c] <= finalResultRange.hi())
549                         {
550                                 // value ok
551                         }
552                         else
553                         {
554                                 if (numFailedPixels < MAX_FAILED_MESSAGES)
555                                         log << tcu::TestLog::Message
556                                                 << "Error in pixel at " << x << ", " << y << " with component " << c << " (channel " << ("rgba"[c]) << ")\n"
557                                                 << "\tGot pixel value " << result.getPixelInt(x, y) << "\n"
558                                                 << "\t\tdFd" << ((derivateFunc == DERIVATE_DFDX) ? ('x') : ('y')) << " ~= " << resultDerivative[c] << "\n"
559                                                 << "\t\tdifference to a valid range: "
560                                                         << ((resultDerivative[c] < finalResultRange.lo()) ? ("-") : ("+"))
561                                                         << ((resultDerivative[c] < finalResultRange.lo()) ? (finalResultRange.lo() - resultDerivative[c]) : (resultDerivative[c] - finalResultRange.hi()))
562                                                         << "\n"
563                                                 << "\tDerivative value range:\n"
564                                                 << "\t\tMin: " << finalResultRange.lo() << "\n"
565                                                 << "\t\tMax: " << finalResultRange.hi() << "\n"
566                                                 << tcu::TestLog::EndMessage;
567
568                                 ++numFailedPixels;
569                                 anyComponentFailed = true;
570                         }
571                 }
572
573                 if (anyComponentFailed)
574                         errorMask.setPixel(red, x, y);
575         }
576
577         if (numFailedPixels >= MAX_FAILED_MESSAGES)
578                 log << TestLog::Message << "..." << TestLog::EndMessage;
579
580         if (numFailedPixels > 0)
581                 log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
582
583         return (numFailedPixels == 0) ? QP_TEST_RESULT_PASS : QP_TEST_RESULT_FAIL;
584 }
585
586 // TriangleDerivateCase
587
588 class TriangleDerivateCase : public TestCase
589 {
590 public:
591                                                         TriangleDerivateCase    (Context& context, const char* name, const char* description);
592                                                         ~TriangleDerivateCase   (void);
593
594         IterateResult                   iterate                                 (void);
595
596 protected:
597         virtual void                    setupRenderState                (deUint32 program) { DE_UNREF(program); }
598         virtual qpTestResult    verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask) = DE_NULL;
599
600         tcu::IVec2                              getViewportSize                 (void) const;
601         tcu::Vec4                               getSurfaceThreshold             (void) const;
602
603         glu::DataType                   m_dataType;
604         glu::Precision                  m_precision;
605
606         glu::DataType                   m_coordDataType;
607         glu::Precision                  m_coordPrecision;
608
609         std::string                             m_fragmentSrc;
610
611         tcu::Vec4                               m_coordMin;
612         tcu::Vec4                               m_coordMax;
613         tcu::Vec4                               m_derivScale;
614         tcu::Vec4                               m_derivBias;
615
616         SurfaceType                             m_surfaceType;
617         int                                             m_numSamples;
618         deUint32                                m_hint;
619 };
620
621 TriangleDerivateCase::TriangleDerivateCase (Context& context, const char* name, const char* description)
622         : TestCase                      (context, name, description)
623         , m_dataType            (glu::TYPE_LAST)
624         , m_precision           (glu::PRECISION_LAST)
625         , m_coordDataType       (glu::TYPE_LAST)
626         , m_coordPrecision      (glu::PRECISION_LAST)
627         , m_surfaceType         (SURFACETYPE_DEFAULT_FRAMEBUFFER)
628         , m_numSamples          (0)
629         , m_hint                        (GL_DONT_CARE)
630 {
631         DE_ASSERT(m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER || m_numSamples == 0);
632 }
633
634 TriangleDerivateCase::~TriangleDerivateCase (void)
635 {
636         TriangleDerivateCase::deinit();
637 }
638
639 static std::string genVertexSource (glu::DataType coordType, glu::Precision precision)
640 {
641         DE_ASSERT(glu::isDataTypeFloatOrVec(coordType));
642
643         const char* vertexTmpl =
644                 "#version 300 es\n"
645                 "in highp vec4 a_position;\n"
646                 "in ${PRECISION} ${DATATYPE} a_coord;\n"
647                 "out ${PRECISION} ${DATATYPE} v_coord;\n"
648                 "void main (void)\n"
649                 "{\n"
650                 "       gl_Position = a_position;\n"
651                 "       v_coord = a_coord;\n"
652                 "}\n";
653
654         map<string, string> vertexParams;
655
656         vertexParams["PRECISION"]       = glu::getPrecisionName(precision);
657         vertexParams["DATATYPE"]        = glu::getDataTypeName(coordType);
658
659         return tcu::StringTemplate(vertexTmpl).specialize(vertexParams);
660 }
661
662 inline tcu::IVec2 TriangleDerivateCase::getViewportSize (void) const
663 {
664         if (m_surfaceType == SURFACETYPE_DEFAULT_FRAMEBUFFER)
665         {
666                 const int       width   = de::min<int>(m_context.getRenderTarget().getWidth(),  VIEWPORT_WIDTH);
667                 const int       height  = de::min<int>(m_context.getRenderTarget().getHeight(), VIEWPORT_HEIGHT);
668                 return tcu::IVec2(width, height);
669         }
670         else
671                 return tcu::IVec2(FBO_WIDTH, FBO_HEIGHT);
672 }
673
674 TriangleDerivateCase::IterateResult TriangleDerivateCase::iterate (void)
675 {
676         const glw::Functions&           gl                              = m_context.getRenderContext().getFunctions();
677         const glu::ShaderProgram        program                 (m_context.getRenderContext(), glu::makeVtxFragSources(genVertexSource(m_coordDataType, m_coordPrecision), m_fragmentSrc));
678         de::Random                                      rnd                             (deStringHash(getName()) ^ 0xbbc24);
679         const bool                                      useFbo                  = m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER;
680         const deUint32                          fboFormat               = m_surfaceType == SURFACETYPE_FLOAT_FBO ? GL_RGBA32UI : GL_RGBA8;
681         const tcu::IVec2                        viewportSize    = getViewportSize();
682         const int                                       viewportX               = useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getWidth()             - viewportSize.x());
683         const int                                       viewportY               = useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getHeight()    - viewportSize.y());
684         AutoFbo                                         fbo                             (gl);
685         AutoRbo                                         rbo                             (gl);
686         tcu::TextureLevel                       result;
687
688         m_testCtx.getLog() << program;
689
690         if (!program.isOk())
691                 TCU_FAIL("Compile failed");
692
693         if (useFbo)
694         {
695                 m_testCtx.getLog() << TestLog::Message
696                                                    << "Rendering to FBO, format = " << glu::getTextureFormatStr(fboFormat)
697                                                    << ", samples = " << m_numSamples
698                                                    << TestLog::EndMessage;
699
700                 fbo.gen();
701                 rbo.gen();
702
703                 gl.bindRenderbuffer(GL_RENDERBUFFER, *rbo);
704                 gl.renderbufferStorageMultisample(GL_RENDERBUFFER, m_numSamples, fboFormat, viewportSize.x(), viewportSize.y());
705                 gl.bindFramebuffer(GL_FRAMEBUFFER, *fbo);
706                 gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *rbo);
707                 TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
708         }
709         else
710         {
711                 const tcu::PixelFormat pixelFormat = m_context.getRenderTarget().getPixelFormat();
712
713                 m_testCtx.getLog()
714                         << TestLog::Message
715                         << "Rendering to default framebuffer\n"
716                         << "\tColor depth: R=" << pixelFormat.redBits << ", G=" << pixelFormat.greenBits << ", B=" << pixelFormat.blueBits << ", A=" << pixelFormat.alphaBits
717                         << TestLog::EndMessage;
718         }
719
720         m_testCtx.getLog() << TestLog::Message << "in: " << m_coordMin << " -> " << m_coordMax << "\n"
721                                                                                    << "v_coord.x = in.x * x\n"
722                                                                                    << "v_coord.y = in.y * y\n"
723                                                                                    << "v_coord.z = in.z * (x+y)/2\n"
724                                                                                    << "v_coord.w = in.w * (1 - (x+y)/2)\n"
725                                            << TestLog::EndMessage
726                                            << TestLog::Message << "u_scale: " << m_derivScale << ", u_bias: " << m_derivBias << " (displayed values have scale/bias removed)" << TestLog::EndMessage
727                                            << TestLog::Message << "Viewport: " << viewportSize.x() << "x" << viewportSize.y() << TestLog::EndMessage
728                                            << TestLog::Message << "GL_FRAGMENT_SHADER_DERIVATE_HINT: " << glu::getHintModeStr(m_hint) << TestLog::EndMessage;
729
730         // Draw
731         {
732                 const float positions[] =
733                 {
734                         -1.0f, -1.0f, 0.0f, 1.0f,
735                         -1.0f,  1.0f, 0.0f, 1.0f,
736                          1.0f, -1.0f, 0.0f, 1.0f,
737                          1.0f,  1.0f, 0.0f, 1.0f
738                 };
739                 const float coords[] =
740                 {
741                         m_coordMin.x(), m_coordMin.y(), m_coordMin.z(),                                                 m_coordMax.w(),
742                         m_coordMin.x(), m_coordMax.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,   (m_coordMin.w()+m_coordMax.w())*0.5f,
743                         m_coordMax.x(), m_coordMin.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,   (m_coordMin.w()+m_coordMax.w())*0.5f,
744                         m_coordMax.x(), m_coordMax.y(), m_coordMax.z(),                                                 m_coordMin.w()
745                 };
746                 const glu::VertexArrayBinding vertexArrays[] =
747                 {
748                         glu::va::Float("a_position",    4, 4, 0, &positions[0]),
749                         glu::va::Float("a_coord",               4, 4, 0, &coords[0])
750                 };
751                 const deUint16 indices[] = { 0, 2, 1, 2, 3, 1 };
752
753                 gl.clearColor(0.125f, 0.25f, 0.5f, 1.0f);
754                 gl.clear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
755                 gl.disable(GL_DITHER);
756
757                 gl.useProgram(program.getProgram());
758
759                 {
760                         const int       scaleLoc        = gl.getUniformLocation(program.getProgram(), "u_scale");
761                         const int       biasLoc         = gl.getUniformLocation(program.getProgram(), "u_bias");
762
763                         switch (m_dataType)
764                         {
765                                 case glu::TYPE_FLOAT:
766                                         gl.uniform1f(scaleLoc, m_derivScale.x());
767                                         gl.uniform1f(biasLoc, m_derivBias.x());
768                                         break;
769
770                                 case glu::TYPE_FLOAT_VEC2:
771                                         gl.uniform2fv(scaleLoc, 1, m_derivScale.getPtr());
772                                         gl.uniform2fv(biasLoc, 1, m_derivBias.getPtr());
773                                         break;
774
775                                 case glu::TYPE_FLOAT_VEC3:
776                                         gl.uniform3fv(scaleLoc, 1, m_derivScale.getPtr());
777                                         gl.uniform3fv(biasLoc, 1, m_derivBias.getPtr());
778                                         break;
779
780                                 case glu::TYPE_FLOAT_VEC4:
781                                         gl.uniform4fv(scaleLoc, 1, m_derivScale.getPtr());
782                                         gl.uniform4fv(biasLoc, 1, m_derivBias.getPtr());
783                                         break;
784
785                                 default:
786                                         DE_ASSERT(false);
787                         }
788                 }
789
790                 gls::setupDefaultUniforms(m_context.getRenderContext(), program.getProgram());
791                 setupRenderState(program.getProgram());
792
793                 gl.hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, m_hint);
794                 GLU_EXPECT_NO_ERROR(gl.getError(), "Setup program state");
795
796                 gl.viewport(viewportX, viewportY, viewportSize.x(), viewportSize.y());
797                 glu::draw(m_context.getRenderContext(), program.getProgram(), DE_LENGTH_OF_ARRAY(vertexArrays), &vertexArrays[0],
798                                   glu::pr::Triangles(DE_LENGTH_OF_ARRAY(indices), &indices[0]));
799                 GLU_EXPECT_NO_ERROR(gl.getError(), "Draw");
800         }
801
802         // Read back results
803         {
804                 const bool              isMSAA          = useFbo && m_numSamples > 0;
805                 AutoFbo                 resFbo          (gl);
806                 AutoRbo                 resRbo          (gl);
807
808                 // Resolve if necessary
809                 if (isMSAA)
810                 {
811                         resFbo.gen();
812                         resRbo.gen();
813
814                         gl.bindRenderbuffer(GL_RENDERBUFFER, *resRbo);
815                         gl.renderbufferStorageMultisample(GL_RENDERBUFFER, 0, fboFormat, viewportSize.x(), viewportSize.y());
816                         gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, *resFbo);
817                         gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *resRbo);
818                         TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
819
820                         gl.blitFramebuffer(0, 0, viewportSize.x(), viewportSize.y(), 0, 0, viewportSize.x(), viewportSize.y(), GL_COLOR_BUFFER_BIT, GL_NEAREST);
821                         GLU_EXPECT_NO_ERROR(gl.getError(), "Resolve blit");
822
823                         gl.bindFramebuffer(GL_READ_FRAMEBUFFER, *resFbo);
824                 }
825
826                 switch (m_surfaceType)
827                 {
828                         case SURFACETYPE_DEFAULT_FRAMEBUFFER:
829                         case SURFACETYPE_UNORM_FBO:
830                                 result.setStorage(tcu::TextureFormat(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNORM_INT8), viewportSize.x(), viewportSize.y());
831                                 glu::readPixels(m_context.getRenderContext(), viewportX, viewportY, result);
832                                 break;
833
834                         case SURFACETYPE_FLOAT_FBO:
835                         {
836                                 const tcu::TextureFormat        dataFormat              (tcu::TextureFormat::RGBA, tcu::TextureFormat::FLOAT);
837                                 const tcu::TextureFormat        transferFormat  (tcu::TextureFormat::RGBA, tcu::TextureFormat::UNSIGNED_INT32);
838
839                                 result.setStorage(dataFormat, viewportSize.x(), viewportSize.y());
840                                 glu::readPixels(m_context.getRenderContext(), viewportX, viewportY,
841                                                                 tcu::PixelBufferAccess(transferFormat, result.getWidth(), result.getHeight(), result.getDepth(), result.getAccess().getDataPtr()));
842                                 break;
843                         }
844
845                         default:
846                                 DE_ASSERT(false);
847                 }
848
849                 GLU_EXPECT_NO_ERROR(gl.getError(), "Read pixels");
850         }
851
852         // Verify
853         {
854                 tcu::Surface errorMask(result.getWidth(), result.getHeight());
855                 tcu::clear(errorMask.getAccess(), tcu::RGBA::green().toVec());
856
857                 const qpTestResult testResult = verify(result.getAccess(), errorMask.getAccess());
858                 const char* failStr = "Fail";
859
860                 m_testCtx.getLog() << TestLog::ImageSet("Result", "Result images")
861                                                    << TestLog::Image("Rendered", "Rendered image", result);
862
863                 if (testResult != QP_TEST_RESULT_PASS)
864                         m_testCtx.getLog() << TestLog::Image("ErrorMask", "Error mask", errorMask);
865
866                 m_testCtx.getLog() << TestLog::EndImageSet;
867
868                 if (testResult == QP_TEST_RESULT_PASS)
869                         failStr = "Pass";
870                 else if (testResult == QP_TEST_RESULT_QUALITY_WARNING)
871                         failStr = "QualityWarning";
872
873                 m_testCtx.setTestResult(testResult, failStr);
874
875         }
876
877         return STOP;
878 }
879
880 tcu::Vec4 TriangleDerivateCase::getSurfaceThreshold (void) const
881 {
882         switch (m_surfaceType)
883         {
884                 case SURFACETYPE_DEFAULT_FRAMEBUFFER:
885                 {
886                         const tcu::PixelFormat  pixelFormat             = m_context.getRenderTarget().getPixelFormat();
887                         const tcu::IVec4                channelBits             (pixelFormat.redBits, pixelFormat.greenBits, pixelFormat.blueBits, pixelFormat.alphaBits);
888                         const tcu::IVec4                intThreshold    = tcu::IVec4(1) << (8 - channelBits);
889                         const tcu::Vec4                 normThreshold   = intThreshold.asFloat() / 255.0f;
890
891                         return normThreshold;
892                 }
893
894                 case SURFACETYPE_UNORM_FBO:                             return tcu::IVec4(1).asFloat() / 255.0f;
895                 case SURFACETYPE_FLOAT_FBO:                             return tcu::Vec4(0.0f);
896                 default:
897                         DE_ASSERT(false);
898                         return tcu::Vec4(0.0f);
899         }
900 }
901
902 // ConstantDerivateCase
903
904 class ConstantDerivateCase : public TriangleDerivateCase
905 {
906 public:
907                                                 ConstantDerivateCase            (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type);
908                                                 ~ConstantDerivateCase           (void) {}
909
910         void                            init                                            (void);
911
912 protected:
913         qpTestResult            verify                                          (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
914
915 private:
916         DerivateFunc            m_func;
917 };
918
919 ConstantDerivateCase::ConstantDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type)
920         : TriangleDerivateCase  (context, name, description)
921         , m_func                                (func)
922 {
923         m_dataType                      = type;
924         m_precision                     = glu::PRECISION_HIGHP;
925         m_coordDataType         = m_dataType;
926         m_coordPrecision        = m_precision;
927 }
928
929 void ConstantDerivateCase::init (void)
930 {
931         const char* fragmentTmpl =
932                 "#version 300 es\n"
933                 "layout(location = 0) out mediump vec4 o_color;\n"
934                 "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
935                 "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
936                 "void main (void)\n"
937                 "{\n"
938                 "       ${PRECISION} ${DATATYPE} res = ${FUNC}(${VALUE}) * u_scale + u_bias;\n"
939                 "       o_color = ${CAST_TO_OUTPUT};\n"
940                 "}\n";
941         map<string, string> fragmentParams;
942         fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
943         fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
944         fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
945         fragmentParams["VALUE"]                         = m_dataType == glu::TYPE_FLOAT_VEC4 ? "vec4(1.0, 7.2, -1e5, 0.0)" :
946                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec3(1e2, 8.0, 0.01)" :
947                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec2(-0.0, 2.7)" :
948                                                                                   /* TYPE_FLOAT */                                         "7.7";
949         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
950                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
951                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
952                                                                                   /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
953
954         m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
955
956         m_derivScale    = tcu::Vec4(1e3f, 1e3f, 1e3f, 1e3f);
957         m_derivBias             = tcu::Vec4(0.5f, 0.5f, 0.5f, 0.5f);
958 }
959
960 qpTestResult ConstantDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
961 {
962         const tcu::Vec4 reference       (0.0f); // Derivate of constant argument should always be 0
963         const tcu::Vec4 threshold       = getSurfaceThreshold() / abs(m_derivScale);
964
965         return verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
966                                                                   reference, threshold, m_derivScale, m_derivBias);
967 }
968
969 // LinearDerivateCase
970
971 class LinearDerivateCase : public TriangleDerivateCase
972 {
973 public:
974                                                 LinearDerivateCase              (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples, const char* fragmentSrcTmpl);
975                                                 ~LinearDerivateCase             (void) {}
976
977         void                            init                                    (void);
978
979 protected:
980         qpTestResult            verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
981
982 private:
983         DerivateFunc            m_func;
984         std::string                     m_fragmentTmpl;
985 };
986
987 LinearDerivateCase::LinearDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples, const char* fragmentSrcTmpl)
988         : TriangleDerivateCase  (context, name, description)
989         , m_func                                (func)
990         , m_fragmentTmpl                (fragmentSrcTmpl)
991 {
992         m_dataType                      = type;
993         m_precision                     = precision;
994         m_coordDataType         = m_dataType;
995         m_coordPrecision        = m_precision;
996         m_hint                          = hint;
997         m_surfaceType           = surfaceType;
998         m_numSamples            = numSamples;
999 }
1000
1001 void LinearDerivateCase::init (void)
1002 {
1003         const tcu::IVec2        viewportSize    = getViewportSize();
1004         const float                     w                               = float(viewportSize.x());
1005         const float                     h                               = float(viewportSize.y());
1006         const bool                      packToInt               = m_surfaceType == SURFACETYPE_FLOAT_FBO;
1007         map<string, string>     fragmentParams;
1008
1009         fragmentParams["OUTPUT_TYPE"]           = glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
1010         fragmentParams["OUTPUT_PREC"]           = glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
1011         fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
1012         fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
1013         fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
1014
1015         if (packToInt)
1016         {
1017                 fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
1018                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
1019                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
1020                                                                                           /* TYPE_FLOAT */                                         "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
1021         }
1022         else
1023         {
1024                 fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
1025                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
1026                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
1027                                                                                           /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
1028         }
1029
1030         m_fragmentSrc = tcu::StringTemplate(m_fragmentTmpl.c_str()).specialize(fragmentParams);
1031
1032         switch (m_precision)
1033         {
1034                 case glu::PRECISION_HIGHP:
1035                         m_coordMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
1036                         m_coordMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
1037                         break;
1038
1039                 case glu::PRECISION_MEDIUMP:
1040                         m_coordMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
1041                         m_coordMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
1042                         break;
1043
1044                 case glu::PRECISION_LOWP:
1045                         m_coordMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
1046                         m_coordMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
1047                         break;
1048
1049                 default:
1050                         DE_ASSERT(false);
1051         }
1052
1053         if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
1054         {
1055                 // No scale or bias used for accuracy.
1056                 m_derivScale    = tcu::Vec4(1.0f);
1057                 m_derivBias             = tcu::Vec4(0.0f);
1058         }
1059         else
1060         {
1061                 // Compute scale - bias that normalizes to 0..1 range.
1062                 const tcu::Vec4 dx = (m_coordMax - m_coordMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
1063                 const tcu::Vec4 dy = (m_coordMax - m_coordMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
1064
1065                 switch (m_func)
1066                 {
1067                         case DERIVATE_DFDX:
1068                                 m_derivScale = 0.5f / dx;
1069                                 break;
1070
1071                         case DERIVATE_DFDY:
1072                                 m_derivScale = 0.5f / dy;
1073                                 break;
1074
1075                         case DERIVATE_FWIDTH:
1076                                 m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
1077                                 break;
1078
1079                         default:
1080                                 DE_ASSERT(false);
1081                 }
1082
1083                 m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
1084         }
1085 }
1086
1087 qpTestResult LinearDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
1088 {
1089         const tcu::Vec4         xScale                          = tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
1090         const tcu::Vec4         yScale                          = tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
1091         const tcu::Vec4         surfaceThreshold        = getSurfaceThreshold() / abs(m_derivScale);
1092
1093         if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
1094         {
1095                 const bool                      isX                             = m_func == DERIVATE_DFDX;
1096                 const float                     div                             = isX ? float(result.getWidth()) : float(result.getHeight());
1097                 const tcu::Vec4         scale                   = isX ? xScale : yScale;
1098                 const tcu::Vec4         reference               = ((m_coordMax - m_coordMin) / div) * scale;
1099                 const tcu::Vec4         opThreshold             = getDerivateThreshold(m_precision, m_coordMin*scale, m_coordMax*scale, reference);
1100                 const tcu::Vec4         opThresholdW    = getDerivateThresholdWarning(m_precision, m_coordMin*scale, m_coordMax*scale, reference);
1101                 const tcu::Vec4         threshold               = max(surfaceThreshold, opThreshold);
1102                 const tcu::Vec4         thresholdW              = max(surfaceThreshold, opThresholdW);
1103                 const int                       numComps                = glu::getDataTypeFloatScalars(m_dataType);
1104
1105                 m_testCtx.getLog()
1106                         << tcu::TestLog::Message
1107                         << "Verifying result image.\n"
1108                         << "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
1109                         << tcu::TestLog::EndMessage;
1110
1111                 // short circuit if result is strictly within the normal value error bounds.
1112                 // This improves performance significantly.
1113                 if (verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1114                                                                    reference, threshold, m_derivScale, m_derivBias,
1115                                                                    LOG_NOTHING) == QP_TEST_RESULT_PASS)
1116                 {
1117                         m_testCtx.getLog()
1118                                 << tcu::TestLog::Message
1119                                 << "No incorrect derivatives found, result valid."
1120                                 << tcu::TestLog::EndMessage;
1121
1122                         return QP_TEST_RESULT_PASS;
1123                 }
1124
1125                 // Check with relaxed threshold value
1126                 if (verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1127                                                                    reference, thresholdW, m_derivScale, m_derivBias,
1128                                                                    LOG_NOTHING) == QP_TEST_RESULT_PASS)
1129                 {
1130                         m_testCtx.getLog()
1131                                 << tcu::TestLog::Message
1132                                 << "No incorrect derivatives found, result valid with quality warning."
1133                                 << tcu::TestLog::EndMessage;
1134
1135                         return QP_TEST_RESULT_QUALITY_WARNING;
1136                 }
1137
1138                 // some pixels exceed error bounds calculated for normal values. Verify that these
1139                 // potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
1140
1141                 m_testCtx.getLog()
1142                         << tcu::TestLog::Message
1143                         << "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
1144                         << "\tVerifying each result derivative is within its range of legal result values."
1145                         << tcu::TestLog::EndMessage;
1146
1147                 {
1148                         const tcu::IVec2                        viewportSize    = getViewportSize();
1149                         const float                                     w                               = float(viewportSize.x());
1150                         const float                                     h                               = float(viewportSize.y());
1151                         const tcu::Vec4                         valueRamp               = (m_coordMax - m_coordMin);
1152                         Linear2DFunctionEvaluator       function;
1153
1154                         function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_coordMin.x()));
1155                         function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_coordMin.y()));
1156                         function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_coordMin.z() + m_coordMin.z()) / 2.0f);
1157                         function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_coordMax.w() + m_coordMax.w()) / 2.0f);
1158
1159                         return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), result, errorMask,
1160                                                                                                                                 m_dataType, m_precision, m_derivScale,
1161                                                                                                                                 m_derivBias, surfaceThreshold, m_func,
1162                                                                                                                                 function);
1163                 }
1164         }
1165         else
1166         {
1167                 DE_ASSERT(m_func == DERIVATE_FWIDTH);
1168                 const float                     w                               = float(result.getWidth());
1169                 const float                     h                               = float(result.getHeight());
1170
1171                 const tcu::Vec4         dx                              = ((m_coordMax - m_coordMin) / w) * xScale;
1172                 const tcu::Vec4         dy                              = ((m_coordMax - m_coordMin) / h) * yScale;
1173                 const tcu::Vec4         reference               = tcu::abs(dx) + tcu::abs(dy);
1174                 const tcu::Vec4         dxThreshold             = getDerivateThreshold(m_precision, m_coordMin*xScale, m_coordMax*xScale, dx);
1175                 const tcu::Vec4         dyThreshold             = getDerivateThreshold(m_precision, m_coordMin*yScale, m_coordMax*yScale, dy);
1176                 const tcu::Vec4         dxThresholdW    = getDerivateThresholdWarning(m_precision, m_coordMin*xScale, m_coordMax*xScale, dx);
1177                 const tcu::Vec4         dyThresholdW    = getDerivateThresholdWarning(m_precision, m_coordMin*yScale, m_coordMax*yScale, dy);
1178                 const tcu::Vec4         threshold               = max(surfaceThreshold, max(dxThreshold, dyThreshold));
1179                 const tcu::Vec4         thresholdW              = max(surfaceThreshold, max(dxThresholdW, dyThresholdW));
1180                 qpTestResult        testResult          = QP_TEST_RESULT_FAIL;
1181
1182                 testResult = verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1183                                                                           reference, threshold, m_derivScale, m_derivBias);
1184
1185                 // return if result is pass
1186                 if (testResult == QP_TEST_RESULT_PASS)
1187                         return testResult;
1188
1189                 // re-check with relaxed threshold
1190                 testResult = verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
1191                                                                           reference, thresholdW, m_derivScale, m_derivBias);
1192
1193                 // if with relaxed threshold test is passing then mark the result with quality warning.
1194                 if (testResult == QP_TEST_RESULT_PASS)
1195                         testResult = QP_TEST_RESULT_QUALITY_WARNING;
1196
1197                 return testResult;
1198         }
1199 }
1200
1201 // TextureDerivateCase
1202
1203 class TextureDerivateCase : public TriangleDerivateCase
1204 {
1205 public:
1206                                                 TextureDerivateCase             (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples);
1207                                                 ~TextureDerivateCase    (void);
1208
1209         void                            init                                    (void);
1210         void                            deinit                                  (void);
1211
1212 protected:
1213         void                            setupRenderState                (deUint32 program);
1214         qpTestResult            verify                                  (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
1215
1216 private:
1217         DerivateFunc            m_func;
1218
1219         tcu::Vec4                       m_texValueMin;
1220         tcu::Vec4                       m_texValueMax;
1221         glu::Texture2D*         m_texture;
1222 };
1223
1224 TextureDerivateCase::TextureDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples)
1225         : TriangleDerivateCase  (context, name, description)
1226         , m_func                                (func)
1227         , m_texture                             (DE_NULL)
1228 {
1229         m_dataType                      = type;
1230         m_precision                     = precision;
1231         m_coordDataType         = glu::TYPE_FLOAT_VEC2;
1232         m_coordPrecision        = glu::PRECISION_HIGHP;
1233         m_hint                          = hint;
1234         m_surfaceType           = surfaceType;
1235         m_numSamples            = numSamples;
1236 }
1237
1238 TextureDerivateCase::~TextureDerivateCase (void)
1239 {
1240         delete m_texture;
1241 }
1242
1243 void TextureDerivateCase::init (void)
1244 {
1245         // Generate shader
1246         {
1247                 const char* fragmentTmpl =
1248                         "#version 300 es\n"
1249                         "in highp vec2 v_coord;\n"
1250                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1251                         "uniform ${PRECISION} sampler2D u_sampler;\n"
1252                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1253                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1254                         "void main (void)\n"
1255                         "{\n"
1256                         "       ${PRECISION} vec4 tex = texture(u_sampler, v_coord);\n"
1257                         "       ${PRECISION} ${DATATYPE} res = ${FUNC}(tex${SWIZZLE}) * u_scale + u_bias;\n"
1258                         "       o_color = ${CAST_TO_OUTPUT};\n"
1259                         "}\n";
1260
1261                 const bool                      packToInt               = m_surfaceType == SURFACETYPE_FLOAT_FBO;
1262                 map<string, string> fragmentParams;
1263
1264                 fragmentParams["OUTPUT_TYPE"]           = glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
1265                 fragmentParams["OUTPUT_PREC"]           = glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
1266                 fragmentParams["PRECISION"]                     = glu::getPrecisionName(m_precision);
1267                 fragmentParams["DATATYPE"]                      = glu::getDataTypeName(m_dataType);
1268                 fragmentParams["FUNC"]                          = getDerivateFuncName(m_func);
1269                 fragmentParams["SWIZZLE"]                       = m_dataType == glu::TYPE_FLOAT_VEC4 ? "" :
1270                                                                                           m_dataType == glu::TYPE_FLOAT_VEC3 ? ".xyz" :
1271                                                                                           m_dataType == glu::TYPE_FLOAT_VEC2 ? ".xy" :
1272                                                                                           /* TYPE_FLOAT */                                         ".x";
1273
1274                 if (packToInt)
1275                 {
1276                         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
1277                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
1278                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
1279                                                                                                   /* TYPE_FLOAT */                                         "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
1280                 }
1281                 else
1282                 {
1283                         fragmentParams["CAST_TO_OUTPUT"]        = m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
1284                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
1285                                                                                                   m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
1286                                                                                                   /* TYPE_FLOAT */                                         "vec4(res, 0.0, 0.0, 1.0)";
1287                 }
1288
1289                 m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
1290         }
1291
1292         // Texture size matches viewport and nearest sampling is used. Thus texture sampling
1293         // is equal to just interpolating the texture value range.
1294
1295         // Determine value range for texture.
1296
1297         switch (m_precision)
1298         {
1299                 case glu::PRECISION_HIGHP:
1300                         m_texValueMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
1301                         m_texValueMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
1302                         break;
1303
1304                 case glu::PRECISION_MEDIUMP:
1305                         m_texValueMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
1306                         m_texValueMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
1307                         break;
1308
1309                 case glu::PRECISION_LOWP:
1310                         m_texValueMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
1311                         m_texValueMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
1312                         break;
1313
1314                 default:
1315                         DE_ASSERT(false);
1316         }
1317
1318         // Lowp and mediump cases use RGBA16F format, while highp uses RGBA32F.
1319         {
1320                 const tcu::IVec2 viewportSize = getViewportSize();
1321                 DE_ASSERT(!m_texture);
1322                 m_texture = new glu::Texture2D(m_context.getRenderContext(), m_precision == glu::PRECISION_HIGHP ? GL_RGBA32F : GL_RGBA16F, viewportSize.x(), viewportSize.y());
1323                 m_texture->getRefTexture().allocLevel(0);
1324         }
1325
1326         // Texture coordinates
1327         m_coordMin = tcu::Vec4(0.0f);
1328         m_coordMax = tcu::Vec4(1.0f);
1329
1330         // Fill with gradients.
1331         {
1332                 const tcu::PixelBufferAccess level0 = m_texture->getRefTexture().getLevel(0);
1333                 for (int y = 0; y < level0.getHeight(); y++)
1334                 {
1335                         for (int x = 0; x < level0.getWidth(); x++)
1336                         {
1337                                 const float             xf              = (float(x)+0.5f) / float(level0.getWidth());
1338                                 const float             yf              = (float(y)+0.5f) / float(level0.getHeight());
1339                                 const tcu::Vec4 s               = tcu::Vec4(xf, yf, (xf+yf)/2.0f, 1.0f - (xf+yf)/2.0f);
1340
1341                                 level0.setPixel(m_texValueMin + (m_texValueMax - m_texValueMin)*s, x, y);
1342                         }
1343                 }
1344         }
1345
1346         m_texture->upload();
1347
1348         if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
1349         {
1350                 // No scale or bias used for accuracy.
1351                 m_derivScale    = tcu::Vec4(1.0f);
1352                 m_derivBias             = tcu::Vec4(0.0f);
1353         }
1354         else
1355         {
1356                 // Compute scale - bias that normalizes to 0..1 range.
1357                 const tcu::IVec2        viewportSize    = getViewportSize();
1358                 const float                     w                               = float(viewportSize.x());
1359                 const float                     h                               = float(viewportSize.y());
1360                 const tcu::Vec4         dx                              = (m_texValueMax - m_texValueMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
1361                 const tcu::Vec4         dy                              = (m_texValueMax - m_texValueMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
1362
1363                 switch (m_func)
1364                 {
1365                         case DERIVATE_DFDX:
1366                                 m_derivScale = 0.5f / dx;
1367                                 break;
1368
1369                         case DERIVATE_DFDY:
1370                                 m_derivScale = 0.5f / dy;
1371                                 break;
1372
1373                         case DERIVATE_FWIDTH:
1374                                 m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
1375                                 break;
1376
1377                         default:
1378                                 DE_ASSERT(false);
1379                 }
1380
1381                 m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
1382         }
1383 }
1384
1385 void TextureDerivateCase::deinit (void)
1386 {
1387         delete m_texture;
1388         m_texture = DE_NULL;
1389 }
1390
1391 void TextureDerivateCase::setupRenderState (deUint32 program)
1392 {
1393         const glw::Functions&   gl                      = m_context.getRenderContext().getFunctions();
1394         const int                               texUnit         = 1;
1395
1396         gl.activeTexture        (GL_TEXTURE0+texUnit);
1397         gl.bindTexture          (GL_TEXTURE_2D, m_texture->getGLTexture());
1398         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,  GL_NEAREST);
1399         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,  GL_NEAREST);
1400         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,              GL_CLAMP_TO_EDGE);
1401         gl.texParameteri        (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,              GL_CLAMP_TO_EDGE);
1402
1403         gl.uniform1i            (gl.getUniformLocation(program, "u_sampler"), texUnit);
1404 }
1405
1406 qpTestResult TextureDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
1407 {
1408         // \note Edges are ignored in comparison
1409         if (result.getWidth() < 2 || result.getHeight() < 2)
1410                 throw tcu::NotSupportedError("Too small viewport");
1411
1412         tcu::ConstPixelBufferAccess     compareArea                     = tcu::getSubregion(result, 1, 1, result.getWidth()-2, result.getHeight()-2);
1413         tcu::PixelBufferAccess          maskArea                        = tcu::getSubregion(errorMask, 1, 1, errorMask.getWidth()-2, errorMask.getHeight()-2);
1414         const tcu::Vec4                         xScale                          = tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
1415         const tcu::Vec4                         yScale                          = tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
1416         const float                                     w                                       = float(result.getWidth());
1417         const float                                     h                                       = float(result.getHeight());
1418
1419         const tcu::Vec4                         surfaceThreshold        = getSurfaceThreshold() / abs(m_derivScale);
1420
1421         if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
1422         {
1423                 const bool                      isX                             = m_func == DERIVATE_DFDX;
1424                 const float                     div                             = isX ? w : h;
1425                 const tcu::Vec4         scale                   = isX ? xScale : yScale;
1426                 const tcu::Vec4         reference               = ((m_texValueMax - m_texValueMin) / div) * scale;
1427                 const tcu::Vec4         opThreshold             = getDerivateThreshold(m_precision, m_texValueMin*scale, m_texValueMax*scale, reference);
1428                 const tcu::Vec4         opThresholdW    = getDerivateThresholdWarning(m_precision, m_texValueMin*scale, m_texValueMax*scale, reference);
1429                 const tcu::Vec4         threshold               = max(surfaceThreshold, opThreshold);
1430                 const tcu::Vec4         thresholdW              = max(surfaceThreshold, opThresholdW);
1431                 const int                       numComps                = glu::getDataTypeFloatScalars(m_dataType);
1432
1433                 m_testCtx.getLog()
1434                         << tcu::TestLog::Message
1435                         << "Verifying result image.\n"
1436                         << "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
1437                         << tcu::TestLog::EndMessage;
1438
1439                 // short circuit if result is strictly within the normal value error bounds.
1440                 // This improves performance significantly.
1441                 if (verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1442                                                                    reference, threshold, m_derivScale, m_derivBias,
1443                                                                    LOG_NOTHING) == QP_TEST_RESULT_PASS)
1444                 {
1445                         m_testCtx.getLog()
1446                                 << tcu::TestLog::Message
1447                                 << "No incorrect derivatives found, result valid."
1448                                 << tcu::TestLog::EndMessage;
1449
1450                         return QP_TEST_RESULT_PASS;
1451                 }
1452
1453                 m_testCtx.getLog()
1454                         << tcu::TestLog::Message
1455                         << "Verifying result image.\n"
1456                         << "\tValid derivative is " << LogVecComps(reference, numComps) << " with Warning threshold " << LogVecComps(thresholdW, numComps)
1457                         << tcu::TestLog::EndMessage;
1458
1459                 // Re-check with relaxed threshold
1460                 if (verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1461                                                                    reference, thresholdW, m_derivScale, m_derivBias,
1462                                                                    LOG_NOTHING) == QP_TEST_RESULT_PASS)
1463                 {
1464                         m_testCtx.getLog()
1465                                 << tcu::TestLog::Message
1466                                 << "No incorrect derivatives found, result valid with quality warning."
1467                                 << tcu::TestLog::EndMessage;
1468
1469                         return QP_TEST_RESULT_QUALITY_WARNING;
1470                 }
1471
1472
1473                 // some pixels exceed error bounds calculated for normal values. Verify that these
1474                 // potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
1475
1476                 m_testCtx.getLog()
1477                         << tcu::TestLog::Message
1478                         << "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
1479                         << "\tVerifying each result derivative is within its range of legal result values."
1480                         << tcu::TestLog::EndMessage;
1481
1482                 {
1483                         const tcu::Vec4                         valueRamp               = (m_texValueMax - m_texValueMin);
1484                         Linear2DFunctionEvaluator       function;
1485
1486                         function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_texValueMin.x()));
1487                         function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_texValueMin.y()));
1488                         function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_texValueMin.z() + m_texValueMin.z()) / 2.0f);
1489                         function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_texValueMax.w() + m_texValueMax.w()) / 2.0f);
1490
1491                         return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), compareArea, maskArea,
1492                                                                                                                                 m_dataType, m_precision, m_derivScale,
1493                                                                                                                                 m_derivBias, surfaceThreshold, m_func,
1494                                                                                                                                 function);
1495                 }
1496         }
1497         else
1498         {
1499                 DE_ASSERT(m_func == DERIVATE_FWIDTH);
1500                 const tcu::Vec4 dx                              = ((m_texValueMax - m_texValueMin) / w) * xScale;
1501                 const tcu::Vec4 dy                              = ((m_texValueMax - m_texValueMin) / h) * yScale;
1502                 const tcu::Vec4 reference               = tcu::abs(dx) + tcu::abs(dy);
1503                 const tcu::Vec4 dxThreshold             = getDerivateThreshold(m_precision, m_texValueMin*xScale, m_texValueMax*xScale, dx);
1504                 const tcu::Vec4 dyThreshold             = getDerivateThreshold(m_precision, m_texValueMin*yScale, m_texValueMax*yScale, dy);
1505                 const tcu::Vec4 dxThresholdW    = getDerivateThresholdWarning(m_precision, m_texValueMin*xScale, m_texValueMax*xScale, dx);
1506                 const tcu::Vec4 dyThresholdW    = getDerivateThresholdWarning(m_precision, m_texValueMin*yScale, m_texValueMax*yScale, dy);
1507                 const tcu::Vec4 threshold               = max(surfaceThreshold, max(dxThreshold, dyThreshold));
1508                 const tcu::Vec4 thresholdW              = max(surfaceThreshold, max(dxThresholdW, dyThresholdW));
1509                 qpTestResult    testResult              = QP_TEST_RESULT_FAIL;
1510
1511                 testResult = verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1512                                                                           reference, threshold, m_derivScale, m_derivBias);
1513
1514                 if (testResult == QP_TEST_RESULT_PASS)
1515                         return testResult;
1516
1517                 // Re-Check with relaxed threshold
1518                 testResult = verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
1519                                                                           reference, thresholdW, m_derivScale, m_derivBias);
1520
1521                 // If test is passing with relaxed threshold then mark quality warning
1522                 if (testResult == QP_TEST_RESULT_PASS)
1523                         testResult = QP_TEST_RESULT_QUALITY_WARNING;
1524
1525                 return testResult;
1526         }
1527 }
1528
1529 ShaderDerivateTests::ShaderDerivateTests (Context& context)
1530         : TestCaseGroup(context, "derivate", "Derivate Function Tests")
1531 {
1532 }
1533
1534 ShaderDerivateTests::~ShaderDerivateTests (void)
1535 {
1536 }
1537
1538 struct FunctionSpec
1539 {
1540         std::string             name;
1541         DerivateFunc    function;
1542         glu::DataType   dataType;
1543         glu::Precision  precision;
1544
1545         FunctionSpec (const std::string& name_, DerivateFunc function_, glu::DataType dataType_, glu::Precision precision_)
1546                 : name          (name_)
1547                 , function      (function_)
1548                 , dataType      (dataType_)
1549                 , precision     (precision_)
1550         {
1551         }
1552 };
1553
1554 void ShaderDerivateTests::init (void)
1555 {
1556         static const struct
1557         {
1558                 const char*             name;
1559                 const char*             description;
1560                 const char*             source;
1561         } s_linearDerivateCases[] =
1562         {
1563                 {
1564                         "linear",
1565                         "Basic derivate of linearly interpolated argument",
1566
1567                         "#version 300 es\n"
1568                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1569                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1570                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1571                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1572                         "void main (void)\n"
1573                         "{\n"
1574                         "       ${PRECISION} ${DATATYPE} res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1575                         "       o_color = ${CAST_TO_OUTPUT};\n"
1576                         "}\n"
1577                 },
1578                 {
1579                         "in_function",
1580                         "Derivate of linear function argument",
1581
1582                         "#version 300 es\n"
1583                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1584                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1585                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1586                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1587                         "\n"
1588                         "${PRECISION} ${DATATYPE} computeRes (${PRECISION} ${DATATYPE} value)\n"
1589                         "{\n"
1590                         "       return ${FUNC}(v_coord) * u_scale + u_bias;\n"
1591                         "}\n"
1592                         "\n"
1593                         "void main (void)\n"
1594                         "{\n"
1595                         "       ${PRECISION} ${DATATYPE} res = computeRes(v_coord);\n"
1596                         "       o_color = ${CAST_TO_OUTPUT};\n"
1597                         "}\n"
1598                 },
1599                 {
1600                         "static_if",
1601                         "Derivate of linearly interpolated value in static if",
1602
1603                         "#version 300 es\n"
1604                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1605                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1606                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1607                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1608                         "void main (void)\n"
1609                         "{\n"
1610                         "       ${PRECISION} ${DATATYPE} res;\n"
1611                         "       if (false)\n"
1612                         "               res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
1613                         "       else\n"
1614                         "               res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1615                         "       o_color = ${CAST_TO_OUTPUT};\n"
1616                         "}\n"
1617                 },
1618                 {
1619                         "static_loop",
1620                         "Derivate of linearly interpolated value in static loop",
1621
1622                         "#version 300 es\n"
1623                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1624                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1625                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1626                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1627                         "void main (void)\n"
1628                         "{\n"
1629                         "       ${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
1630                         "       for (int i = 0; i < 2; i++)\n"
1631                         "               res += ${FUNC}(v_coord * float(i));\n"
1632                         "       res = res * u_scale + u_bias;\n"
1633                         "       o_color = ${CAST_TO_OUTPUT};\n"
1634                         "}\n"
1635                 },
1636                 {
1637                         "static_switch",
1638                         "Derivate of linearly interpolated value in static switch",
1639
1640                         "#version 300 es\n"
1641                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1642                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1643                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1644                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1645                         "void main (void)\n"
1646                         "{\n"
1647                         "       ${PRECISION} ${DATATYPE} res;\n"
1648                         "       switch (1)\n"
1649                         "       {\n"
1650                         "               case 0: res = ${FUNC}(-v_coord) * u_scale + u_bias;     break;\n"
1651                         "               case 1: res = ${FUNC}(v_coord) * u_scale + u_bias;      break;\n"
1652                         "       }\n"
1653                         "       o_color = ${CAST_TO_OUTPUT};\n"
1654                         "}\n"
1655                 },
1656                 {
1657                         "uniform_if",
1658                         "Derivate of linearly interpolated value in uniform if",
1659
1660                         "#version 300 es\n"
1661                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1662                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1663                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1664                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1665                         "uniform bool ub_true;\n"
1666                         "void main (void)\n"
1667                         "{\n"
1668                         "       ${PRECISION} ${DATATYPE} res;\n"
1669                         "       if (ub_true)"
1670                         "               res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
1671                         "       else\n"
1672                         "               res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
1673                         "       o_color = ${CAST_TO_OUTPUT};\n"
1674                         "}\n"
1675                 },
1676                 {
1677                         "uniform_loop",
1678                         "Derivate of linearly interpolated value in uniform loop",
1679
1680                         "#version 300 es\n"
1681                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1682                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1683                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1684                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1685                         "uniform int ui_two;\n"
1686                         "void main (void)\n"
1687                         "{\n"
1688                         "       ${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
1689                         "       for (int i = 0; i < ui_two; i++)\n"
1690                         "               res += ${FUNC}(v_coord * float(i));\n"
1691                         "       res = res * u_scale + u_bias;\n"
1692                         "       o_color = ${CAST_TO_OUTPUT};\n"
1693                         "}\n"
1694                 },
1695                 {
1696                         "uniform_switch",
1697                         "Derivate of linearly interpolated value in uniform switch",
1698
1699                         "#version 300 es\n"
1700                         "in ${PRECISION} ${DATATYPE} v_coord;\n"
1701                         "layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
1702                         "uniform ${PRECISION} ${DATATYPE} u_scale;\n"
1703                         "uniform ${PRECISION} ${DATATYPE} u_bias;\n"
1704                         "uniform int ui_one;\n"
1705                         "void main (void)\n"
1706                         "{\n"
1707                         "       ${PRECISION} ${DATATYPE} res;\n"
1708                         "       switch (ui_one)\n"
1709                         "       {\n"
1710                         "               case 0: res = ${FUNC}(-v_coord) * u_scale + u_bias;     break;\n"
1711                         "               case 1: res = ${FUNC}(v_coord) * u_scale + u_bias;      break;\n"
1712                         "       }\n"
1713                         "       o_color = ${CAST_TO_OUTPUT};\n"
1714                         "}\n"
1715                 },
1716         };
1717
1718         static const struct
1719         {
1720                 const char*             name;
1721                 SurfaceType             surfaceType;
1722                 int                             numSamples;
1723         } s_fboConfigs[] =
1724         {
1725                 { "fbo",                SURFACETYPE_DEFAULT_FRAMEBUFFER,        0 },
1726                 { "fbo_msaa2",  SURFACETYPE_UNORM_FBO,                          2 },
1727                 { "fbo_msaa4",  SURFACETYPE_UNORM_FBO,                          4 },
1728                 { "fbo_float",  SURFACETYPE_FLOAT_FBO,                          0 },
1729         };
1730
1731         static const struct
1732         {
1733                 const char*             name;
1734                 deUint32                hint;
1735         } s_hints[] =
1736         {
1737                 { "fastest",    GL_FASTEST      },
1738                 { "nicest",             GL_NICEST       },
1739         };
1740
1741         static const struct
1742         {
1743                 const char*             name;
1744                 SurfaceType             surfaceType;
1745                 int                             numSamples;
1746         } s_hintFboConfigs[] =
1747         {
1748                 { "default",            SURFACETYPE_DEFAULT_FRAMEBUFFER,        0 },
1749                 { "fbo_msaa4",          SURFACETYPE_UNORM_FBO,                          4 },
1750                 { "fbo_float",          SURFACETYPE_FLOAT_FBO,                          0 }
1751         };
1752
1753         static const struct
1754         {
1755                 const char*             name;
1756                 SurfaceType             surfaceType;
1757                 int                             numSamples;
1758                 deUint32                hint;
1759         } s_textureConfigs[] =
1760         {
1761                 { "basic",                      SURFACETYPE_DEFAULT_FRAMEBUFFER,        0,      GL_DONT_CARE    },
1762                 { "msaa4",                      SURFACETYPE_UNORM_FBO,                          4,      GL_DONT_CARE    },
1763                 { "float_fastest",      SURFACETYPE_FLOAT_FBO,                          0,      GL_FASTEST              },
1764                 { "float_nicest",       SURFACETYPE_FLOAT_FBO,                          0,      GL_NICEST               },
1765         };
1766
1767         // .dfdx, .dfdy, .fwidth
1768         for (int funcNdx = 0; funcNdx < DERIVATE_LAST; funcNdx++)
1769         {
1770                 const DerivateFunc                      function                = DerivateFunc(funcNdx);
1771                 tcu::TestCaseGroup* const       functionGroup   = new tcu::TestCaseGroup(m_testCtx, getDerivateFuncCaseName(function), getDerivateFuncName(function));
1772                 addChild(functionGroup);
1773
1774                 // .constant - no precision variants, checks that derivate of constant arguments is 0
1775                 {
1776                         tcu::TestCaseGroup* const constantGroup = new tcu::TestCaseGroup(m_testCtx, "constant", "Derivate of constant argument");
1777                         functionGroup->addChild(constantGroup);
1778
1779                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1780                         {
1781                                 const glu::DataType dataType = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1782                                 constantGroup->addChild(new ConstantDerivateCase(m_context, glu::getDataTypeName(dataType), "", function, dataType));
1783                         }
1784                 }
1785
1786                 // Cases based on LinearDerivateCase
1787                 for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_linearDerivateCases); caseNdx++)
1788                 {
1789                         tcu::TestCaseGroup* const linearCaseGroup       = new tcu::TestCaseGroup(m_testCtx, s_linearDerivateCases[caseNdx].name, s_linearDerivateCases[caseNdx].description);
1790                         const char*                     source                                  = s_linearDerivateCases[caseNdx].source;
1791                         functionGroup->addChild(linearCaseGroup);
1792
1793                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1794                         {
1795                                 for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1796                                 {
1797                                         const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1798                                         const glu::Precision    precision               = glu::Precision(precNdx);
1799                                         const SurfaceType               surfaceType             = SURFACETYPE_DEFAULT_FRAMEBUFFER;
1800                                         const int                               numSamples              = 0;
1801                                         const deUint32                  hint                    = GL_DONT_CARE;
1802                                         ostringstream                   caseName;
1803
1804                                         if (caseNdx != 0 && precision == glu::PRECISION_LOWP)
1805                                                 continue; // Skip as lowp doesn't actually produce any bits when rendered to default FB.
1806
1807                                         caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1808
1809                                         linearCaseGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1810                                 }
1811                         }
1812                 }
1813
1814                 // Fbo cases
1815                 for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_fboConfigs); caseNdx++)
1816                 {
1817                         tcu::TestCaseGroup*     const   fboGroup                = new tcu::TestCaseGroup(m_testCtx, s_fboConfigs[caseNdx].name, "Derivate usage when rendering into FBO");
1818                         const char*                                     source                  = s_linearDerivateCases[0].source; // use source from .linear group
1819                         const SurfaceType                       surfaceType             = s_fboConfigs[caseNdx].surfaceType;
1820                         const int                                       numSamples              = s_fboConfigs[caseNdx].numSamples;
1821                         functionGroup->addChild(fboGroup);
1822
1823                         for (int vecSize = 1; vecSize <= 4; vecSize++)
1824                         {
1825                                 for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1826                                 {
1827                                         const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1828                                         const glu::Precision    precision               = glu::Precision(precNdx);
1829                                         const deUint32                  hint                    = GL_DONT_CARE;
1830                                         ostringstream                   caseName;
1831
1832                                         if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1833                                                 continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1834
1835                                         caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1836
1837                                         fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1838                                 }
1839                         }
1840                 }
1841
1842                 // .fastest, .nicest
1843                 for (int hintCaseNdx = 0; hintCaseNdx < DE_LENGTH_OF_ARRAY(s_hints); hintCaseNdx++)
1844                 {
1845                         tcu::TestCaseGroup* const       hintGroup               = new tcu::TestCaseGroup(m_testCtx, s_hints[hintCaseNdx].name, "Shader derivate hints");
1846                         const char*                                     source                  = s_linearDerivateCases[0].source; // use source from .linear group
1847                         const deUint32                          hint                    = s_hints[hintCaseNdx].hint;
1848                         functionGroup->addChild(hintGroup);
1849
1850                         for (int fboCaseNdx = 0; fboCaseNdx < DE_LENGTH_OF_ARRAY(s_hintFboConfigs); fboCaseNdx++)
1851                         {
1852                                 tcu::TestCaseGroup*     const   fboGroup                = new tcu::TestCaseGroup(m_testCtx, s_hintFboConfigs[fboCaseNdx].name, "");
1853                                 const SurfaceType                       surfaceType             = s_hintFboConfigs[fboCaseNdx].surfaceType;
1854                                 const int                                       numSamples              = s_hintFboConfigs[fboCaseNdx].numSamples;
1855                                 hintGroup->addChild(fboGroup);
1856
1857                                 for (int vecSize = 1; vecSize <= 4; vecSize++)
1858                                 {
1859                                         for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1860                                         {
1861                                                 const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1862                                                 const glu::Precision    precision               = glu::Precision(precNdx);
1863                                                 ostringstream                   caseName;
1864
1865                                                 if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1866                                                         continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1867
1868                                                 caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1869
1870                                                 fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
1871                                         }
1872                                 }
1873                         }
1874                 }
1875
1876                 // .texture
1877                 {
1878                         tcu::TestCaseGroup* const textureGroup = new tcu::TestCaseGroup(m_testCtx, "texture", "Derivate of texture lookup result");
1879                         functionGroup->addChild(textureGroup);
1880
1881                         for (int texCaseNdx = 0; texCaseNdx < DE_LENGTH_OF_ARRAY(s_textureConfigs); texCaseNdx++)
1882                         {
1883                                 tcu::TestCaseGroup*     const   caseGroup               = new tcu::TestCaseGroup(m_testCtx, s_textureConfigs[texCaseNdx].name, "");
1884                                 const SurfaceType                       surfaceType             = s_textureConfigs[texCaseNdx].surfaceType;
1885                                 const int                                       numSamples              = s_textureConfigs[texCaseNdx].numSamples;
1886                                 const deUint32                          hint                    = s_textureConfigs[texCaseNdx].hint;
1887                                 textureGroup->addChild(caseGroup);
1888
1889                                 for (int vecSize = 1; vecSize <= 4; vecSize++)
1890                                 {
1891                                         for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
1892                                         {
1893                                                 const glu::DataType             dataType                = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
1894                                                 const glu::Precision    precision               = glu::Precision(precNdx);
1895                                                 ostringstream                   caseName;
1896
1897                                                 if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
1898                                                         continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
1899
1900                                                 caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
1901
1902                                                 caseGroup->addChild(new TextureDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples));
1903                                         }
1904                                 }
1905                         }
1906                 }
1907         }
1908 }
1909
1910 } // Functional
1911 } // gles3
1912 } // deqp