Home | History | Annotate | Download | only in functional
      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();
    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 inline tcu::Vec4 getDerivateThreshold (const glu::Precision precision, const tcu::Vec4& valueMin, const tcu::Vec4& valueMax, const tcu::Vec4& expectedDerivate)
    327 {
    328 	const int			baseBits		= getNumMantissaBits(precision);
    329 	const tcu::UVec4	derivExp		= getCompExpBits(expectedDerivate);
    330 	const tcu::UVec4	maxValueExp		= max(getCompExpBits(valueMin), getCompExpBits(valueMax));
    331 	const tcu::UVec4	numBitsLost		= maxValueExp - min(maxValueExp, derivExp);
    332 	const tcu::IVec4	numAccurateBits	= max(baseBits - numBitsLost.asInt() - (int)INTERPOLATION_LOST_BITS, tcu::IVec4(0));
    333 
    334 	return tcu::Vec4(computeFloatingPointError(expectedDerivate[0], numAccurateBits[0]),
    335 					 computeFloatingPointError(expectedDerivate[1], numAccurateBits[1]),
    336 					 computeFloatingPointError(expectedDerivate[2], numAccurateBits[2]),
    337 					 computeFloatingPointError(expectedDerivate[3], numAccurateBits[3]));
    338 }
    339 
    340 namespace
    341 {
    342 
    343 struct LogVecComps
    344 {
    345 	const tcu::Vec4&	v;
    346 	int					numComps;
    347 
    348 	LogVecComps (const tcu::Vec4& v_, int numComps_)
    349 		: v			(v_)
    350 		, numComps	(numComps_)
    351 	{
    352 	}
    353 };
    354 
    355 std::ostream& operator<< (std::ostream& str, const LogVecComps& v)
    356 {
    357 	DE_ASSERT(de::inRange(v.numComps, 1, 4));
    358 	if (v.numComps == 1)		return str << v.v[0];
    359 	else if (v.numComps == 2)	return str << v.v.toWidth<2>();
    360 	else if (v.numComps == 3)	return str << v.v.toWidth<3>();
    361 	else						return str << v.v;
    362 }
    363 
    364 } // anonymous
    365 
    366 enum VerificationLogging
    367 {
    368 	LOG_ALL = 0,
    369 	LOG_NOTHING
    370 };
    371 
    372 static bool verifyConstantDerivate (tcu::TestLog&						log,
    373 									const tcu::ConstPixelBufferAccess&	result,
    374 									const tcu::PixelBufferAccess&		errorMask,
    375 									glu::DataType						dataType,
    376 									const tcu::Vec4&					reference,
    377 									const tcu::Vec4&					threshold,
    378 									const tcu::Vec4&					scale,
    379 									const tcu::Vec4&					bias,
    380 									VerificationLogging					logPolicy = LOG_ALL)
    381 {
    382 	const int			numComps		= glu::getDataTypeFloatScalars(dataType);
    383 	const tcu::BVec4	mask			= tcu::logicalNot(getDerivateMask(dataType));
    384 	int					numFailedPixels	= 0;
    385 
    386 	if (logPolicy == LOG_ALL)
    387 		log << TestLog::Message << "Expecting " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps) << TestLog::EndMessage;
    388 
    389 	for (int y = 0; y < result.getHeight(); y++)
    390 	{
    391 		for (int x = 0; x < result.getWidth(); x++)
    392 		{
    393 			const tcu::Vec4		resDerivate		= readDerivate(result, scale, bias, x, y);
    394 			const bool			isOk			= tcu::allEqual(tcu::logicalOr(tcu::lessThanEqual(tcu::abs(reference - resDerivate), threshold), mask), tcu::BVec4(true));
    395 
    396 			if (!isOk)
    397 			{
    398 				if (numFailedPixels < MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
    399 					log << TestLog::Message << "FAIL: got " << LogVecComps(resDerivate, numComps)
    400 											<< ", diff = " << LogVecComps(tcu::abs(reference - resDerivate), numComps)
    401 											<< ", at x = " << x << ", y = " << y
    402 						<< TestLog::EndMessage;
    403 				numFailedPixels += 1;
    404 				errorMask.setPixel(tcu::RGBA::red().toVec(), x, y);
    405 			}
    406 		}
    407 	}
    408 
    409 	if (numFailedPixels >= MAX_FAILED_MESSAGES && logPolicy == LOG_ALL)
    410 		log << TestLog::Message << "..." << TestLog::EndMessage;
    411 
    412 	if (numFailedPixels > 0 && logPolicy == LOG_ALL)
    413 		log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
    414 
    415 	return numFailedPixels == 0;
    416 }
    417 
    418 struct Linear2DFunctionEvaluator
    419 {
    420 	tcu::Matrix<float, 4, 3> matrix;
    421 
    422 	//      .-----.
    423 	//      | s_x |
    424 	//  M x | s_y |
    425 	//      | 1.0 |
    426 	//      '-----'
    427 	tcu::Vec4 evaluateAt (float screenX, float screenY) const;
    428 };
    429 
    430 tcu::Vec4 Linear2DFunctionEvaluator::evaluateAt (float screenX, float screenY) const
    431 {
    432 	const tcu::Vec3 position(screenX, screenY, 1.0f);
    433 	return matrix * position;
    434 }
    435 
    436 static bool reverifyConstantDerivateWithFlushRelaxations (tcu::TestLog&							log,
    437 														  const tcu::ConstPixelBufferAccess&	result,
    438 														  const tcu::PixelBufferAccess&			errorMask,
    439 														  glu::DataType							dataType,
    440 														  glu::Precision						precision,
    441 														  const tcu::Vec4&						derivScale,
    442 														  const tcu::Vec4&						derivBias,
    443 														  const tcu::Vec4&						surfaceThreshold,
    444 														  DerivateFunc							derivateFunc,
    445 														  const Linear2DFunctionEvaluator&		function)
    446 {
    447 	DE_ASSERT(result.getWidth() == errorMask.getWidth());
    448 	DE_ASSERT(result.getHeight() == errorMask.getHeight());
    449 	DE_ASSERT(derivateFunc == DERIVATE_DFDX || derivateFunc == DERIVATE_DFDY);
    450 
    451 	const tcu::IVec4	red						(255, 0, 0, 255);
    452 	const tcu::IVec4	green					(0, 255, 0, 255);
    453 	const float			divisionErrorUlps		= 2.5f;
    454 
    455 	const int			numComponents			= glu::getDataTypeFloatScalars(dataType);
    456 	const int			numBits					= getNumMantissaBits(precision);
    457 	const int			minExponent				= getMinExponent(precision);
    458 
    459 	const int			numVaryingSampleBits	= numBits - INTERPOLATION_LOST_BITS;
    460 	int					numFailedPixels			= 0;
    461 
    462 	tcu::clear(errorMask, green);
    463 
    464 	// search for failed pixels
    465 	for (int y = 0; y < result.getHeight(); ++y)
    466 	for (int x = 0; x < result.getWidth(); ++x)
    467 	{
    468 		//                 flushToZero?(f2z?(functionValueCurrent) - f2z?(functionValueBefore))
    469 		// flushToZero? ( ------------------------------------------------------------------------ +- 2.5 ULP )
    470 		//                                                  dx
    471 
    472 		const tcu::Vec4	resultDerivative		= readDerivate(result, derivScale, derivBias, x, y);
    473 
    474 		// sample at the front of the back pixel and the back of the front pixel to cover the whole area of
    475 		// legal sample positions. In general case this is NOT OK, but we know that the target funtion is
    476 		// (mostly*) linear which allows us to take the sample points at arbitrary points. This gets us the
    477 		// maximum difference possible in exponents which are used in error bound calculations.
    478 		// * non-linearity may happen around zero or with very high function values due to subnorms not
    479 		//   behaving well.
    480 		const tcu::Vec4	functionValueForward	= (derivateFunc == DERIVATE_DFDX)
    481 													? (function.evaluateAt((float)x + 2.0f, (float)y + 0.5f))
    482 													: (function.evaluateAt((float)x + 0.5f, (float)y + 2.0f));
    483 		const tcu::Vec4	functionValueBackward	= (derivateFunc == DERIVATE_DFDX)
    484 													? (function.evaluateAt((float)x - 1.0f, (float)y + 0.5f))
    485 													: (function.evaluateAt((float)x + 0.5f, (float)y - 1.0f));
    486 
    487 		bool	anyComponentFailed				= false;
    488 
    489 		// check components separately
    490 		for (int c = 0; c < numComponents; ++c)
    491 		{
    492 			// Simulate interpolation. Add allowed interpolation error and round to target precision. Allow one half ULP (i.e. correct rounding)
    493 			const tcu::Interval	forwardComponent		(convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueForward[c],  -0.5f, numVaryingSampleBits), minExponent, numBits),
    494 														 convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueForward[c],  +0.5f, numVaryingSampleBits), minExponent, numBits));
    495 			const tcu::Interval	backwardComponent		(convertFloatFlushToZeroRtn(addErrorUlp((float)functionValueBackward[c], -0.5f, numVaryingSampleBits), minExponent, numBits),
    496 														 convertFloatFlushToZeroRtp(addErrorUlp((float)functionValueBackward[c], +0.5f, numVaryingSampleBits), minExponent, numBits));
    497 			const int			maxValueExp				= de::max(de::max(tcu::Float32(forwardComponent.lo()).exponent(),   tcu::Float32(forwardComponent.hi()).exponent()),
    498 																  de::max(tcu::Float32(backwardComponent.lo()).exponent(),  tcu::Float32(backwardComponent.hi()).exponent()));
    499 
    500 			// subtraction in numerator will likely cause a cancellation of the most
    501 			// significant bits. Apply error bounds.
    502 
    503 			const tcu::Interval	numerator				(forwardComponent - backwardComponent);
    504 			const int			numeratorLoExp			= tcu::Float32(numerator.lo()).exponent();
    505 			const int			numeratorHiExp			= tcu::Float32(numerator.hi()).exponent();
    506 			const int			numeratorLoBitsLost		= de::max(0, maxValueExp - numeratorLoExp); //!< must clamp to zero since if forward and backward components have different
    507 			const int			numeratorHiBitsLost		= de::max(0, maxValueExp - numeratorHiExp); //!< sign, numerator might have larger exponent than its operands.
    508 			const int			numeratorLoBits			= de::max(0, numBits - numeratorLoBitsLost);
    509 			const int			numeratorHiBits			= de::max(0, numBits - numeratorHiBitsLost);
    510 
    511 			const tcu::Interval	numeratorRange			(convertFloatFlushToZeroRtn((float)numerator.lo(), minExponent, numeratorLoBits),
    512 														 convertFloatFlushToZeroRtp((float)numerator.hi(), minExponent, numeratorHiBits));
    513 
    514 			const tcu::Interval	divisionRange			= numeratorRange / 3.0f; // legal sample area is anywhere within this and neighboring pixels (i.e. size = 3)
    515 			const tcu::Interval	divisionResultRange		(convertFloatFlushToZeroRtn(addErrorUlp((float)divisionRange.lo(), -divisionErrorUlps, numBits), minExponent, numBits),
    516 														 convertFloatFlushToZeroRtp(addErrorUlp((float)divisionRange.hi(), +divisionErrorUlps, numBits), minExponent, numBits));
    517 			const tcu::Interval	finalResultRange		(divisionResultRange.lo() - surfaceThreshold[c], divisionResultRange.hi() + surfaceThreshold[c]);
    518 
    519 			if (resultDerivative[c] >= finalResultRange.lo() && resultDerivative[c] <= finalResultRange.hi())
    520 			{
    521 				// value ok
    522 			}
    523 			else
    524 			{
    525 				if (numFailedPixels < MAX_FAILED_MESSAGES)
    526 					log << tcu::TestLog::Message
    527 						<< "Error in pixel at " << x << ", " << y << " with component " << c << " (channel " << ("rgba"[c]) << ")\n"
    528 						<< "\tGot pixel value " << result.getPixelInt(x, y) << "\n"
    529 						<< "\t\tdFd" << ((derivateFunc == DERIVATE_DFDX) ? ('x') : ('y')) << " ~= " << resultDerivative[c] << "\n"
    530 						<< "\t\tdifference to a valid range: "
    531 							<< ((resultDerivative[c] < finalResultRange.lo()) ? ("-") : ("+"))
    532 							<< ((resultDerivative[c] < finalResultRange.lo()) ? (finalResultRange.lo() - resultDerivative[c]) : (resultDerivative[c] - finalResultRange.hi()))
    533 							<< "\n"
    534 						<< "\tDerivative value range:\n"
    535 						<< "\t\tMin: " << finalResultRange.lo() << "\n"
    536 						<< "\t\tMax: " << finalResultRange.hi() << "\n"
    537 						<< tcu::TestLog::EndMessage;
    538 
    539 				++numFailedPixels;
    540 				anyComponentFailed = true;
    541 			}
    542 		}
    543 
    544 		if (anyComponentFailed)
    545 			errorMask.setPixel(red, x, y);
    546 	}
    547 
    548 	if (numFailedPixels >= MAX_FAILED_MESSAGES)
    549 		log << TestLog::Message << "..." << TestLog::EndMessage;
    550 
    551 	if (numFailedPixels > 0)
    552 		log << TestLog::Message << "FAIL: found " << numFailedPixels << " failed pixels" << TestLog::EndMessage;
    553 
    554 	return numFailedPixels == 0;
    555 }
    556 
    557 // TriangleDerivateCase
    558 
    559 class TriangleDerivateCase : public TestCase
    560 {
    561 public:
    562 						TriangleDerivateCase	(Context& context, const char* name, const char* description);
    563 						~TriangleDerivateCase	(void);
    564 
    565 	IterateResult		iterate					(void);
    566 
    567 protected:
    568 	virtual void		setupRenderState		(deUint32 program) { DE_UNREF(program); }
    569 	virtual bool		verify					(const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask) = DE_NULL;
    570 
    571 	tcu::IVec2			getViewportSize			(void) const;
    572 	tcu::Vec4			getSurfaceThreshold		(void) const;
    573 
    574 	glu::DataType		m_dataType;
    575 	glu::Precision		m_precision;
    576 
    577 	glu::DataType		m_coordDataType;
    578 	glu::Precision		m_coordPrecision;
    579 
    580 	std::string			m_fragmentSrc;
    581 
    582 	tcu::Vec4			m_coordMin;
    583 	tcu::Vec4			m_coordMax;
    584 	tcu::Vec4			m_derivScale;
    585 	tcu::Vec4			m_derivBias;
    586 
    587 	SurfaceType			m_surfaceType;
    588 	int					m_numSamples;
    589 	deUint32			m_hint;
    590 };
    591 
    592 TriangleDerivateCase::TriangleDerivateCase (Context& context, const char* name, const char* description)
    593 	: TestCase			(context, name, description)
    594 	, m_dataType		(glu::TYPE_LAST)
    595 	, m_precision		(glu::PRECISION_LAST)
    596 	, m_coordDataType	(glu::TYPE_LAST)
    597 	, m_coordPrecision	(glu::PRECISION_LAST)
    598 	, m_surfaceType		(SURFACETYPE_DEFAULT_FRAMEBUFFER)
    599 	, m_numSamples		(0)
    600 	, m_hint			(GL_DONT_CARE)
    601 {
    602 	DE_ASSERT(m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER || m_numSamples == 0);
    603 }
    604 
    605 TriangleDerivateCase::~TriangleDerivateCase (void)
    606 {
    607 	TriangleDerivateCase::deinit();
    608 }
    609 
    610 static std::string genVertexSource (glu::DataType coordType, glu::Precision precision)
    611 {
    612 	DE_ASSERT(glu::isDataTypeFloatOrVec(coordType));
    613 
    614 	const char* vertexTmpl =
    615 		"#version 300 es\n"
    616 		"in highp vec4 a_position;\n"
    617 		"in ${PRECISION} ${DATATYPE} a_coord;\n"
    618 		"out ${PRECISION} ${DATATYPE} v_coord;\n"
    619 		"void main (void)\n"
    620 		"{\n"
    621 		"	gl_Position = a_position;\n"
    622 		"	v_coord = a_coord;\n"
    623 		"}\n";
    624 
    625 	map<string, string> vertexParams;
    626 
    627 	vertexParams["PRECISION"]	= glu::getPrecisionName(precision);
    628 	vertexParams["DATATYPE"]	= glu::getDataTypeName(coordType);
    629 
    630 	return tcu::StringTemplate(vertexTmpl).specialize(vertexParams);
    631 }
    632 
    633 inline tcu::IVec2 TriangleDerivateCase::getViewportSize (void) const
    634 {
    635 	if (m_surfaceType == SURFACETYPE_DEFAULT_FRAMEBUFFER)
    636 	{
    637 		const int	width	= de::min<int>(m_context.getRenderTarget().getWidth(),	VIEWPORT_WIDTH);
    638 		const int	height	= de::min<int>(m_context.getRenderTarget().getHeight(),	VIEWPORT_HEIGHT);
    639 		return tcu::IVec2(width, height);
    640 	}
    641 	else
    642 		return tcu::IVec2(FBO_WIDTH, FBO_HEIGHT);
    643 }
    644 
    645 TriangleDerivateCase::IterateResult TriangleDerivateCase::iterate (void)
    646 {
    647 	const glw::Functions&		gl				= m_context.getRenderContext().getFunctions();
    648 	const glu::ShaderProgram	program			(m_context.getRenderContext(), glu::makeVtxFragSources(genVertexSource(m_coordDataType, m_coordPrecision), m_fragmentSrc));
    649 	de::Random					rnd				(deStringHash(getName()) ^ 0xbbc24);
    650 	const bool					useFbo			= m_surfaceType != SURFACETYPE_DEFAULT_FRAMEBUFFER;
    651 	const deUint32				fboFormat		= m_surfaceType == SURFACETYPE_FLOAT_FBO ? GL_RGBA32UI : GL_RGBA8;
    652 	const tcu::IVec2			viewportSize	= getViewportSize();
    653 	const int					viewportX		= useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getWidth()		- viewportSize.x());
    654 	const int					viewportY		= useFbo ? 0 : rnd.getInt(0, m_context.getRenderTarget().getHeight()	- viewportSize.y());
    655 	AutoFbo						fbo				(gl);
    656 	AutoRbo						rbo				(gl);
    657 	tcu::TextureLevel			result;
    658 
    659 	m_testCtx.getLog() << program;
    660 
    661 	if (!program.isOk())
    662 		TCU_FAIL("Compile failed");
    663 
    664 	if (useFbo)
    665 	{
    666 		m_testCtx.getLog() << TestLog::Message
    667 						   << "Rendering to FBO, format = " << glu::getTextureFormatStr(fboFormat)
    668 						   << ", samples = " << m_numSamples
    669 						   << TestLog::EndMessage;
    670 
    671 		fbo.gen();
    672 		rbo.gen();
    673 
    674 		gl.bindRenderbuffer(GL_RENDERBUFFER, *rbo);
    675 		gl.renderbufferStorageMultisample(GL_RENDERBUFFER, m_numSamples, fboFormat, viewportSize.x(), viewportSize.y());
    676 		gl.bindFramebuffer(GL_FRAMEBUFFER, *fbo);
    677 		gl.framebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *rbo);
    678 		TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
    679 	}
    680 	else
    681 	{
    682 		const tcu::PixelFormat pixelFormat = m_context.getRenderTarget().getPixelFormat();
    683 
    684 		m_testCtx.getLog()
    685 			<< TestLog::Message
    686 			<< "Rendering to default framebuffer\n"
    687 			<< "\tColor depth: R=" << pixelFormat.redBits << ", G=" << pixelFormat.greenBits << ", B=" << pixelFormat.blueBits << ", A=" << pixelFormat.alphaBits
    688 			<< TestLog::EndMessage;
    689 	}
    690 
    691 	m_testCtx.getLog() << TestLog::Message << "in: " << m_coordMin << " -> " << m_coordMax << "\n"
    692 										   << "v_coord.x = in.x * x\n"
    693 										   << "v_coord.y = in.y * y\n"
    694 										   << "v_coord.z = in.z * (x+y)/2\n"
    695 										   << "v_coord.w = in.w * (1 - (x+y)/2)\n"
    696 					   << TestLog::EndMessage
    697 					   << TestLog::Message << "u_scale: " << m_derivScale << ", u_bias: " << m_derivBias << " (displayed values have scale/bias removed)" << TestLog::EndMessage
    698 					   << TestLog::Message << "Viewport: " << viewportSize.x() << "x" << viewportSize.y() << TestLog::EndMessage
    699 					   << TestLog::Message << "GL_FRAGMENT_SHADER_DERIVATE_HINT: " << glu::getHintModeStr(m_hint) << TestLog::EndMessage;
    700 
    701 	// Draw
    702 	{
    703 		const float positions[] =
    704 		{
    705 			-1.0f, -1.0f, 0.0f, 1.0f,
    706 			-1.0f,  1.0f, 0.0f, 1.0f,
    707 			 1.0f, -1.0f, 0.0f, 1.0f,
    708 			 1.0f,  1.0f, 0.0f, 1.0f
    709 		};
    710 		const float coords[] =
    711 		{
    712 			m_coordMin.x(), m_coordMin.y(), m_coordMin.z(),							m_coordMax.w(),
    713 			m_coordMin.x(), m_coordMax.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,	(m_coordMin.w()+m_coordMax.w())*0.5f,
    714 			m_coordMax.x(), m_coordMin.y(), (m_coordMin.z()+m_coordMax.z())*0.5f,	(m_coordMin.w()+m_coordMax.w())*0.5f,
    715 			m_coordMax.x(), m_coordMax.y(), m_coordMax.z(),							m_coordMin.w()
    716 		};
    717 		const glu::VertexArrayBinding vertexArrays[] =
    718 		{
    719 			glu::va::Float("a_position",	4, 4, 0, &positions[0]),
    720 			glu::va::Float("a_coord",		4, 4, 0, &coords[0])
    721 		};
    722 		const deUint16 indices[] = { 0, 2, 1, 2, 3, 1 };
    723 
    724 		gl.clearColor(0.125f, 0.25f, 0.5f, 1.0f);
    725 		gl.clear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
    726 		gl.disable(GL_DITHER);
    727 
    728 		gl.useProgram(program.getProgram());
    729 
    730 		{
    731 			const int	scaleLoc	= gl.getUniformLocation(program.getProgram(), "u_scale");
    732 			const int	biasLoc		= gl.getUniformLocation(program.getProgram(), "u_bias");
    733 
    734 			switch (m_dataType)
    735 			{
    736 				case glu::TYPE_FLOAT:
    737 					gl.uniform1f(scaleLoc, m_derivScale.x());
    738 					gl.uniform1f(biasLoc, m_derivBias.x());
    739 					break;
    740 
    741 				case glu::TYPE_FLOAT_VEC2:
    742 					gl.uniform2fv(scaleLoc, 1, m_derivScale.getPtr());
    743 					gl.uniform2fv(biasLoc, 1, m_derivBias.getPtr());
    744 					break;
    745 
    746 				case glu::TYPE_FLOAT_VEC3:
    747 					gl.uniform3fv(scaleLoc, 1, m_derivScale.getPtr());
    748 					gl.uniform3fv(biasLoc, 1, m_derivBias.getPtr());
    749 					break;
    750 
    751 				case glu::TYPE_FLOAT_VEC4:
    752 					gl.uniform4fv(scaleLoc, 1, m_derivScale.getPtr());
    753 					gl.uniform4fv(biasLoc, 1, m_derivBias.getPtr());
    754 					break;
    755 
    756 				default:
    757 					DE_ASSERT(false);
    758 			}
    759 		}
    760 
    761 		gls::setupDefaultUniforms(m_context.getRenderContext(), program.getProgram());
    762 		setupRenderState(program.getProgram());
    763 
    764 		gl.hint(GL_FRAGMENT_SHADER_DERIVATIVE_HINT, m_hint);
    765 		GLU_EXPECT_NO_ERROR(gl.getError(), "Setup program state");
    766 
    767 		gl.viewport(viewportX, viewportY, viewportSize.x(), viewportSize.y());
    768 		glu::draw(m_context.getRenderContext(), program.getProgram(), DE_LENGTH_OF_ARRAY(vertexArrays), &vertexArrays[0],
    769 				  glu::pr::Triangles(DE_LENGTH_OF_ARRAY(indices), &indices[0]));
    770 		GLU_EXPECT_NO_ERROR(gl.getError(), "Draw");
    771 	}
    772 
    773 	// Read back results
    774 	{
    775 		const bool		isMSAA		= useFbo && m_numSamples > 0;
    776 		AutoFbo			resFbo		(gl);
    777 		AutoRbo			resRbo		(gl);
    778 
    779 		// Resolve if necessary
    780 		if (isMSAA)
    781 		{
    782 			resFbo.gen();
    783 			resRbo.gen();
    784 
    785 			gl.bindRenderbuffer(GL_RENDERBUFFER, *resRbo);
    786 			gl.renderbufferStorageMultisample(GL_RENDERBUFFER, 0, fboFormat, viewportSize.x(), viewportSize.y());
    787 			gl.bindFramebuffer(GL_DRAW_FRAMEBUFFER, *resFbo);
    788 			gl.framebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, *resRbo);
    789 			TCU_CHECK(gl.checkFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE);
    790 
    791 			gl.blitFramebuffer(0, 0, viewportSize.x(), viewportSize.y(), 0, 0, viewportSize.x(), viewportSize.y(), GL_COLOR_BUFFER_BIT, GL_NEAREST);
    792 			GLU_EXPECT_NO_ERROR(gl.getError(), "Resolve blit");
    793 
    794 			gl.bindFramebuffer(GL_READ_FRAMEBUFFER, *resFbo);
    795 		}
    796 
    797 		switch (m_surfaceType)
    798 		{
    799 			case SURFACETYPE_DEFAULT_FRAMEBUFFER:
    800 			case SURFACETYPE_UNORM_FBO:
    801 				result.setStorage(tcu::TextureFormat(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNORM_INT8), viewportSize.x(), viewportSize.y());
    802 				glu::readPixels(m_context.getRenderContext(), viewportX, viewportY, result);
    803 				break;
    804 
    805 			case SURFACETYPE_FLOAT_FBO:
    806 			{
    807 				const tcu::TextureFormat	dataFormat		(tcu::TextureFormat::RGBA, tcu::TextureFormat::FLOAT);
    808 				const tcu::TextureFormat	transferFormat	(tcu::TextureFormat::RGBA, tcu::TextureFormat::UNSIGNED_INT32);
    809 
    810 				result.setStorage(dataFormat, viewportSize.x(), viewportSize.y());
    811 				glu::readPixels(m_context.getRenderContext(), viewportX, viewportY,
    812 								tcu::PixelBufferAccess(transferFormat, result.getWidth(), result.getHeight(), result.getDepth(), result.getAccess().getDataPtr()));
    813 				break;
    814 			}
    815 
    816 			default:
    817 				DE_ASSERT(false);
    818 		}
    819 
    820 		GLU_EXPECT_NO_ERROR(gl.getError(), "Read pixels");
    821 	}
    822 
    823 	// Verify
    824 	{
    825 		tcu::Surface errorMask(result.getWidth(), result.getHeight());
    826 		tcu::clear(errorMask.getAccess(), tcu::RGBA::green().toVec());
    827 
    828 		const bool isOk = verify(result.getAccess(), errorMask.getAccess());
    829 
    830 		m_testCtx.getLog() << TestLog::ImageSet("Result", "Result images")
    831 						   << TestLog::Image("Rendered", "Rendered image", result);
    832 
    833 		if (!isOk)
    834 			m_testCtx.getLog() << TestLog::Image("ErrorMask", "Error mask", errorMask);
    835 
    836 		m_testCtx.getLog() << TestLog::EndImageSet;
    837 
    838 		m_testCtx.setTestResult(isOk ? QP_TEST_RESULT_PASS	: QP_TEST_RESULT_FAIL,
    839 								isOk ? "Pass"				: "Image comparison failed");
    840 	}
    841 
    842 	return STOP;
    843 }
    844 
    845 tcu::Vec4 TriangleDerivateCase::getSurfaceThreshold (void) const
    846 {
    847 	switch (m_surfaceType)
    848 	{
    849 		case SURFACETYPE_DEFAULT_FRAMEBUFFER:
    850 		{
    851 			const tcu::PixelFormat	pixelFormat		= m_context.getRenderTarget().getPixelFormat();
    852 			const tcu::IVec4		channelBits		(pixelFormat.redBits, pixelFormat.greenBits, pixelFormat.blueBits, pixelFormat.alphaBits);
    853 			const tcu::IVec4		intThreshold	= tcu::IVec4(1) << (8 - channelBits);
    854 			const tcu::Vec4			normThreshold	= intThreshold.asFloat() / 255.0f;
    855 
    856 			return normThreshold;
    857 		}
    858 
    859 		case SURFACETYPE_UNORM_FBO:				return tcu::IVec4(1).asFloat() / 255.0f;
    860 		case SURFACETYPE_FLOAT_FBO:				return tcu::Vec4(0.0f);
    861 		default:
    862 			DE_ASSERT(false);
    863 			return tcu::Vec4(0.0f);
    864 	}
    865 }
    866 
    867 // ConstantDerivateCase
    868 
    869 class ConstantDerivateCase : public TriangleDerivateCase
    870 {
    871 public:
    872 						ConstantDerivateCase		(Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type);
    873 						~ConstantDerivateCase		(void) {}
    874 
    875 	void				init						(void);
    876 
    877 protected:
    878 	bool				verify						(const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
    879 
    880 private:
    881 	DerivateFunc		m_func;
    882 };
    883 
    884 ConstantDerivateCase::ConstantDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type)
    885 	: TriangleDerivateCase	(context, name, description)
    886 	, m_func				(func)
    887 {
    888 	m_dataType			= type;
    889 	m_precision			= glu::PRECISION_HIGHP;
    890 	m_coordDataType		= m_dataType;
    891 	m_coordPrecision	= m_precision;
    892 }
    893 
    894 void ConstantDerivateCase::init (void)
    895 {
    896 	const char* fragmentTmpl =
    897 		"#version 300 es\n"
    898 		"layout(location = 0) out mediump vec4 o_color;\n"
    899 		"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
    900 		"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
    901 		"void main (void)\n"
    902 		"{\n"
    903 		"	${PRECISION} ${DATATYPE} res = ${FUNC}(${VALUE}) * u_scale + u_bias;\n"
    904 		"	o_color = ${CAST_TO_OUTPUT};\n"
    905 		"}\n";
    906 	map<string, string> fragmentParams;
    907 	fragmentParams["PRECISION"]			= glu::getPrecisionName(m_precision);
    908 	fragmentParams["DATATYPE"]			= glu::getDataTypeName(m_dataType);
    909 	fragmentParams["FUNC"]				= getDerivateFuncName(m_func);
    910 	fragmentParams["VALUE"]				= m_dataType == glu::TYPE_FLOAT_VEC4 ? "vec4(1.0, 7.2, -1e5, 0.0)" :
    911 										  m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec3(1e2, 8.0, 0.01)" :
    912 										  m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec2(-0.0, 2.7)" :
    913 										  /* TYPE_FLOAT */					   "7.7";
    914 	fragmentParams["CAST_TO_OUTPUT"]	= m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
    915 										  m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
    916 										  m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
    917 										  /* TYPE_FLOAT */					   "vec4(res, 0.0, 0.0, 1.0)";
    918 
    919 	m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
    920 
    921 	m_derivScale	= tcu::Vec4(1e3f, 1e3f, 1e3f, 1e3f);
    922 	m_derivBias		= tcu::Vec4(0.5f, 0.5f, 0.5f, 0.5f);
    923 }
    924 
    925 bool ConstantDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
    926 {
    927 	const tcu::Vec4 reference	(0.0f); // Derivate of constant argument should always be 0
    928 	const tcu::Vec4	threshold	= getSurfaceThreshold() / abs(m_derivScale);
    929 
    930 	return verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
    931 								  reference, threshold, m_derivScale, m_derivBias);
    932 }
    933 
    934 // LinearDerivateCase
    935 
    936 class LinearDerivateCase : public TriangleDerivateCase
    937 {
    938 public:
    939 						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);
    940 						~LinearDerivateCase		(void) {}
    941 
    942 	void				init					(void);
    943 
    944 protected:
    945 	bool				verify					(const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
    946 
    947 private:
    948 	DerivateFunc		m_func;
    949 	std::string			m_fragmentTmpl;
    950 };
    951 
    952 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)
    953 	: TriangleDerivateCase	(context, name, description)
    954 	, m_func				(func)
    955 	, m_fragmentTmpl		(fragmentSrcTmpl)
    956 {
    957 	m_dataType			= type;
    958 	m_precision			= precision;
    959 	m_coordDataType		= m_dataType;
    960 	m_coordPrecision	= m_precision;
    961 	m_hint				= hint;
    962 	m_surfaceType		= surfaceType;
    963 	m_numSamples		= numSamples;
    964 }
    965 
    966 void LinearDerivateCase::init (void)
    967 {
    968 	const tcu::IVec2	viewportSize	= getViewportSize();
    969 	const float			w				= float(viewportSize.x());
    970 	const float			h				= float(viewportSize.y());
    971 	const bool			packToInt		= m_surfaceType == SURFACETYPE_FLOAT_FBO;
    972 	map<string, string>	fragmentParams;
    973 
    974 	fragmentParams["OUTPUT_TYPE"]		= glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
    975 	fragmentParams["OUTPUT_PREC"]		= glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
    976 	fragmentParams["PRECISION"]			= glu::getPrecisionName(m_precision);
    977 	fragmentParams["DATATYPE"]			= glu::getDataTypeName(m_dataType);
    978 	fragmentParams["FUNC"]				= getDerivateFuncName(m_func);
    979 
    980 	if (packToInt)
    981 	{
    982 		fragmentParams["CAST_TO_OUTPUT"]	= m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
    983 											  m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
    984 											  m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
    985 											  /* TYPE_FLOAT */					   "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
    986 	}
    987 	else
    988 	{
    989 		fragmentParams["CAST_TO_OUTPUT"]	= m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
    990 											  m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
    991 											  m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
    992 											  /* TYPE_FLOAT */					   "vec4(res, 0.0, 0.0, 1.0)";
    993 	}
    994 
    995 	m_fragmentSrc = tcu::StringTemplate(m_fragmentTmpl.c_str()).specialize(fragmentParams);
    996 
    997 	switch (m_precision)
    998 	{
    999 		case glu::PRECISION_HIGHP:
   1000 			m_coordMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
   1001 			m_coordMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
   1002 			break;
   1003 
   1004 		case glu::PRECISION_MEDIUMP:
   1005 			m_coordMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
   1006 			m_coordMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
   1007 			break;
   1008 
   1009 		case glu::PRECISION_LOWP:
   1010 			m_coordMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
   1011 			m_coordMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
   1012 			break;
   1013 
   1014 		default:
   1015 			DE_ASSERT(false);
   1016 	}
   1017 
   1018 	if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
   1019 	{
   1020 		// No scale or bias used for accuracy.
   1021 		m_derivScale	= tcu::Vec4(1.0f);
   1022 		m_derivBias		= tcu::Vec4(0.0f);
   1023 	}
   1024 	else
   1025 	{
   1026 		// Compute scale - bias that normalizes to 0..1 range.
   1027 		const tcu::Vec4 dx = (m_coordMax - m_coordMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
   1028 		const tcu::Vec4 dy = (m_coordMax - m_coordMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
   1029 
   1030 		switch (m_func)
   1031 		{
   1032 			case DERIVATE_DFDX:
   1033 				m_derivScale = 0.5f / dx;
   1034 				break;
   1035 
   1036 			case DERIVATE_DFDY:
   1037 				m_derivScale = 0.5f / dy;
   1038 				break;
   1039 
   1040 			case DERIVATE_FWIDTH:
   1041 				m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
   1042 				break;
   1043 
   1044 			default:
   1045 				DE_ASSERT(false);
   1046 		}
   1047 
   1048 		m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
   1049 	}
   1050 }
   1051 
   1052 bool LinearDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
   1053 {
   1054 	const tcu::Vec4		xScale				= tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
   1055 	const tcu::Vec4		yScale				= tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
   1056 	const tcu::Vec4		surfaceThreshold	= getSurfaceThreshold() / abs(m_derivScale);
   1057 
   1058 	if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
   1059 	{
   1060 		const bool			isX			= m_func == DERIVATE_DFDX;
   1061 		const float			div			= isX ? float(result.getWidth()) : float(result.getHeight());
   1062 		const tcu::Vec4		scale		= isX ? xScale : yScale;
   1063 		const tcu::Vec4		reference	= ((m_coordMax - m_coordMin) / div) * scale;
   1064 		const tcu::Vec4		opThreshold	= getDerivateThreshold(m_precision, m_coordMin*scale, m_coordMax*scale, reference);
   1065 		const tcu::Vec4		threshold	= max(surfaceThreshold, opThreshold);
   1066 		const int			numComps	= glu::getDataTypeFloatScalars(m_dataType);
   1067 
   1068 		m_testCtx.getLog()
   1069 			<< tcu::TestLog::Message
   1070 			<< "Verifying result image.\n"
   1071 			<< "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
   1072 			<< tcu::TestLog::EndMessage;
   1073 
   1074 		// short circuit if result is strictly within the normal value error bounds.
   1075 		// This improves performance significantly.
   1076 		if (verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
   1077 								   reference, threshold, m_derivScale, m_derivBias,
   1078 								   LOG_NOTHING))
   1079 		{
   1080 			m_testCtx.getLog()
   1081 				<< tcu::TestLog::Message
   1082 				<< "No incorrect derivatives found, result valid."
   1083 				<< tcu::TestLog::EndMessage;
   1084 
   1085 			return true;
   1086 		}
   1087 
   1088 		// some pixels exceed error bounds calculated for normal values. Verify that these
   1089 		// potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
   1090 
   1091 		m_testCtx.getLog()
   1092 			<< tcu::TestLog::Message
   1093 			<< "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
   1094 			<< "\tVerifying each result derivative is within its range of legal result values."
   1095 			<< tcu::TestLog::EndMessage;
   1096 
   1097 		{
   1098 			const tcu::IVec2			viewportSize	= getViewportSize();
   1099 			const float					w				= float(viewportSize.x());
   1100 			const float					h				= float(viewportSize.y());
   1101 			const tcu::Vec4				valueRamp		= (m_coordMax - m_coordMin);
   1102 			Linear2DFunctionEvaluator	function;
   1103 
   1104 			function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_coordMin.x()));
   1105 			function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_coordMin.y()));
   1106 			function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_coordMin.z() + m_coordMin.z()) / 2.0f);
   1107 			function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_coordMax.w() + m_coordMax.w()) / 2.0f);
   1108 
   1109 			return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), result, errorMask,
   1110 																m_dataType, m_precision, m_derivScale,
   1111 																m_derivBias, surfaceThreshold, m_func,
   1112 																function);
   1113 		}
   1114 	}
   1115 	else
   1116 	{
   1117 		DE_ASSERT(m_func == DERIVATE_FWIDTH);
   1118 		const float			w			= float(result.getWidth());
   1119 		const float			h			= float(result.getHeight());
   1120 
   1121 		const tcu::Vec4		dx			= ((m_coordMax - m_coordMin) / w) * xScale;
   1122 		const tcu::Vec4		dy			= ((m_coordMax - m_coordMin) / h) * yScale;
   1123 		const tcu::Vec4		reference	= tcu::abs(dx) + tcu::abs(dy);
   1124 		const tcu::Vec4		dxThreshold	= getDerivateThreshold(m_precision, m_coordMin*xScale, m_coordMax*xScale, dx);
   1125 		const tcu::Vec4		dyThreshold	= getDerivateThreshold(m_precision, m_coordMin*yScale, m_coordMax*yScale, dy);
   1126 		const tcu::Vec4		threshold	= max(surfaceThreshold, max(dxThreshold, dyThreshold));
   1127 
   1128 		return verifyConstantDerivate(m_testCtx.getLog(), result, errorMask, m_dataType,
   1129 									  reference, threshold, m_derivScale, m_derivBias);
   1130 	}
   1131 }
   1132 
   1133 // TextureDerivateCase
   1134 
   1135 class TextureDerivateCase : public TriangleDerivateCase
   1136 {
   1137 public:
   1138 						TextureDerivateCase		(Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples);
   1139 						~TextureDerivateCase	(void);
   1140 
   1141 	void				init					(void);
   1142 	void				deinit					(void);
   1143 
   1144 protected:
   1145 	void				setupRenderState		(deUint32 program);
   1146 	bool				verify					(const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask);
   1147 
   1148 private:
   1149 	DerivateFunc		m_func;
   1150 
   1151 	tcu::Vec4			m_texValueMin;
   1152 	tcu::Vec4			m_texValueMax;
   1153 	glu::Texture2D*		m_texture;
   1154 };
   1155 
   1156 TextureDerivateCase::TextureDerivateCase (Context& context, const char* name, const char* description, DerivateFunc func, glu::DataType type, glu::Precision precision, deUint32 hint, SurfaceType surfaceType, int numSamples)
   1157 	: TriangleDerivateCase	(context, name, description)
   1158 	, m_func				(func)
   1159 	, m_texture				(DE_NULL)
   1160 {
   1161 	m_dataType			= type;
   1162 	m_precision			= precision;
   1163 	m_coordDataType		= glu::TYPE_FLOAT_VEC2;
   1164 	m_coordPrecision	= glu::PRECISION_HIGHP;
   1165 	m_hint				= hint;
   1166 	m_surfaceType		= surfaceType;
   1167 	m_numSamples		= numSamples;
   1168 }
   1169 
   1170 TextureDerivateCase::~TextureDerivateCase (void)
   1171 {
   1172 	delete m_texture;
   1173 }
   1174 
   1175 void TextureDerivateCase::init (void)
   1176 {
   1177 	// Generate shader
   1178 	{
   1179 		const char* fragmentTmpl =
   1180 			"#version 300 es\n"
   1181 			"in highp vec2 v_coord;\n"
   1182 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1183 			"uniform ${PRECISION} sampler2D u_sampler;\n"
   1184 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1185 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1186 			"void main (void)\n"
   1187 			"{\n"
   1188 			"	${PRECISION} vec4 tex = texture(u_sampler, v_coord);\n"
   1189 			"	${PRECISION} ${DATATYPE} res = ${FUNC}(tex${SWIZZLE}) * u_scale + u_bias;\n"
   1190 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1191 			"}\n";
   1192 
   1193 		const bool			packToInt		= m_surfaceType == SURFACETYPE_FLOAT_FBO;
   1194 		map<string, string> fragmentParams;
   1195 
   1196 		fragmentParams["OUTPUT_TYPE"]		= glu::getDataTypeName(packToInt ? glu::TYPE_UINT_VEC4 : glu::TYPE_FLOAT_VEC4);
   1197 		fragmentParams["OUTPUT_PREC"]		= glu::getPrecisionName(packToInt ? glu::PRECISION_HIGHP : m_precision);
   1198 		fragmentParams["PRECISION"]			= glu::getPrecisionName(m_precision);
   1199 		fragmentParams["DATATYPE"]			= glu::getDataTypeName(m_dataType);
   1200 		fragmentParams["FUNC"]				= getDerivateFuncName(m_func);
   1201 		fragmentParams["SWIZZLE"]			= m_dataType == glu::TYPE_FLOAT_VEC4 ? "" :
   1202 											  m_dataType == glu::TYPE_FLOAT_VEC3 ? ".xyz" :
   1203 											  m_dataType == glu::TYPE_FLOAT_VEC2 ? ".xy" :
   1204 											  /* TYPE_FLOAT */					   ".x";
   1205 
   1206 		if (packToInt)
   1207 		{
   1208 			fragmentParams["CAST_TO_OUTPUT"]	= m_dataType == glu::TYPE_FLOAT_VEC4 ? "floatBitsToUint(res)" :
   1209 												  m_dataType == glu::TYPE_FLOAT_VEC3 ? "floatBitsToUint(vec4(res, 1.0))" :
   1210 												  m_dataType == glu::TYPE_FLOAT_VEC2 ? "floatBitsToUint(vec4(res, 0.0, 1.0))" :
   1211 												  /* TYPE_FLOAT */					   "floatBitsToUint(vec4(res, 0.0, 0.0, 1.0))";
   1212 		}
   1213 		else
   1214 		{
   1215 			fragmentParams["CAST_TO_OUTPUT"]	= m_dataType == glu::TYPE_FLOAT_VEC4 ? "res" :
   1216 												  m_dataType == glu::TYPE_FLOAT_VEC3 ? "vec4(res, 1.0)" :
   1217 												  m_dataType == glu::TYPE_FLOAT_VEC2 ? "vec4(res, 0.0, 1.0)" :
   1218 												  /* TYPE_FLOAT */					   "vec4(res, 0.0, 0.0, 1.0)";
   1219 		}
   1220 
   1221 		m_fragmentSrc = tcu::StringTemplate(fragmentTmpl).specialize(fragmentParams);
   1222 	}
   1223 
   1224 	// Texture size matches viewport and nearest sampling is used. Thus texture sampling
   1225 	// is equal to just interpolating the texture value range.
   1226 
   1227 	// Determine value range for texture.
   1228 
   1229 	switch (m_precision)
   1230 	{
   1231 		case glu::PRECISION_HIGHP:
   1232 			m_texValueMin = tcu::Vec4(-97.f, 0.2f, 71.f, 74.f);
   1233 			m_texValueMax = tcu::Vec4(-13.2f, -77.f, 44.f, 76.f);
   1234 			break;
   1235 
   1236 		case glu::PRECISION_MEDIUMP:
   1237 			m_texValueMin = tcu::Vec4(-37.0f, 47.f, -7.f, 0.0f);
   1238 			m_texValueMax = tcu::Vec4(-1.0f, 12.f, 7.f, 19.f);
   1239 			break;
   1240 
   1241 		case glu::PRECISION_LOWP:
   1242 			m_texValueMin = tcu::Vec4(0.0f, -1.0f, 0.0f, 1.0f);
   1243 			m_texValueMax = tcu::Vec4(1.0f, 1.0f, -1.0f, -1.0f);
   1244 			break;
   1245 
   1246 		default:
   1247 			DE_ASSERT(false);
   1248 	}
   1249 
   1250 	// Lowp and mediump cases use RGBA16F format, while highp uses RGBA32F.
   1251 	{
   1252 		const tcu::IVec2 viewportSize = getViewportSize();
   1253 		DE_ASSERT(!m_texture);
   1254 		m_texture = new glu::Texture2D(m_context.getRenderContext(), m_precision == glu::PRECISION_HIGHP ? GL_RGBA32F : GL_RGBA16F, viewportSize.x(), viewportSize.y());
   1255 		m_texture->getRefTexture().allocLevel(0);
   1256 	}
   1257 
   1258 	// Texture coordinates
   1259 	m_coordMin = tcu::Vec4(0.0f);
   1260 	m_coordMax = tcu::Vec4(1.0f);
   1261 
   1262 	// Fill with gradients.
   1263 	{
   1264 		const tcu::PixelBufferAccess level0 = m_texture->getRefTexture().getLevel(0);
   1265 		for (int y = 0; y < level0.getHeight(); y++)
   1266 		{
   1267 			for (int x = 0; x < level0.getWidth(); x++)
   1268 			{
   1269 				const float		xf		= (float(x)+0.5f) / float(level0.getWidth());
   1270 				const float		yf		= (float(y)+0.5f) / float(level0.getHeight());
   1271 				const tcu::Vec4	s		= tcu::Vec4(xf, yf, (xf+yf)/2.0f, 1.0f - (xf+yf)/2.0f);
   1272 
   1273 				level0.setPixel(m_texValueMin + (m_texValueMax - m_texValueMin)*s, x, y);
   1274 			}
   1275 		}
   1276 	}
   1277 
   1278 	m_texture->upload();
   1279 
   1280 	if (m_surfaceType == SURFACETYPE_FLOAT_FBO)
   1281 	{
   1282 		// No scale or bias used for accuracy.
   1283 		m_derivScale	= tcu::Vec4(1.0f);
   1284 		m_derivBias		= tcu::Vec4(0.0f);
   1285 	}
   1286 	else
   1287 	{
   1288 		// Compute scale - bias that normalizes to 0..1 range.
   1289 		const tcu::IVec2	viewportSize	= getViewportSize();
   1290 		const float			w				= float(viewportSize.x());
   1291 		const float			h				= float(viewportSize.y());
   1292 		const tcu::Vec4		dx				= (m_texValueMax - m_texValueMin) / tcu::Vec4(w, w, w*0.5f, -w*0.5f);
   1293 		const tcu::Vec4		dy				= (m_texValueMax - m_texValueMin) / tcu::Vec4(h, h, h*0.5f, -h*0.5f);
   1294 
   1295 		switch (m_func)
   1296 		{
   1297 			case DERIVATE_DFDX:
   1298 				m_derivScale = 0.5f / dx;
   1299 				break;
   1300 
   1301 			case DERIVATE_DFDY:
   1302 				m_derivScale = 0.5f / dy;
   1303 				break;
   1304 
   1305 			case DERIVATE_FWIDTH:
   1306 				m_derivScale = 0.5f / (tcu::abs(dx) + tcu::abs(dy));
   1307 				break;
   1308 
   1309 			default:
   1310 				DE_ASSERT(false);
   1311 		}
   1312 
   1313 		m_derivBias = tcu::Vec4(0.0f, 0.0f, 0.0f, 0.0f);
   1314 	}
   1315 }
   1316 
   1317 void TextureDerivateCase::deinit (void)
   1318 {
   1319 	delete m_texture;
   1320 	m_texture = DE_NULL;
   1321 }
   1322 
   1323 void TextureDerivateCase::setupRenderState (deUint32 program)
   1324 {
   1325 	const glw::Functions&	gl			= m_context.getRenderContext().getFunctions();
   1326 	const int				texUnit		= 1;
   1327 
   1328 	gl.activeTexture	(GL_TEXTURE0+texUnit);
   1329 	gl.bindTexture		(GL_TEXTURE_2D, m_texture->getGLTexture());
   1330 	gl.texParameteri	(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,	GL_NEAREST);
   1331 	gl.texParameteri	(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER,	GL_NEAREST);
   1332 	gl.texParameteri	(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,		GL_CLAMP_TO_EDGE);
   1333 	gl.texParameteri	(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,		GL_CLAMP_TO_EDGE);
   1334 
   1335 	gl.uniform1i		(gl.getUniformLocation(program, "u_sampler"), texUnit);
   1336 }
   1337 
   1338 bool TextureDerivateCase::verify (const tcu::ConstPixelBufferAccess& result, const tcu::PixelBufferAccess& errorMask)
   1339 {
   1340 	// \note Edges are ignored in comparison
   1341 	if (result.getWidth() < 2 || result.getHeight() < 2)
   1342 		throw tcu::NotSupportedError("Too small viewport");
   1343 
   1344 	tcu::ConstPixelBufferAccess	compareArea			= tcu::getSubregion(result, 1, 1, result.getWidth()-2, result.getHeight()-2);
   1345 	tcu::PixelBufferAccess		maskArea			= tcu::getSubregion(errorMask, 1, 1, errorMask.getWidth()-2, errorMask.getHeight()-2);
   1346 	const tcu::Vec4				xScale				= tcu::Vec4(1.0f, 0.0f, 0.5f, -0.5f);
   1347 	const tcu::Vec4				yScale				= tcu::Vec4(0.0f, 1.0f, 0.5f, -0.5f);
   1348 	const float					w					= float(result.getWidth());
   1349 	const float					h					= float(result.getHeight());
   1350 
   1351 	const tcu::Vec4				surfaceThreshold	= getSurfaceThreshold() / abs(m_derivScale);
   1352 
   1353 	if (m_func == DERIVATE_DFDX || m_func == DERIVATE_DFDY)
   1354 	{
   1355 		const bool			isX			= m_func == DERIVATE_DFDX;
   1356 		const float			div			= isX ? w : h;
   1357 		const tcu::Vec4		scale		= isX ? xScale : yScale;
   1358 		const tcu::Vec4		reference	= ((m_texValueMax - m_texValueMin) / div) * scale;
   1359 		const tcu::Vec4		opThreshold	= getDerivateThreshold(m_precision, m_texValueMin*scale, m_texValueMax*scale, reference);
   1360 		const tcu::Vec4		threshold	= max(surfaceThreshold, opThreshold);
   1361 		const int			numComps	= glu::getDataTypeFloatScalars(m_dataType);
   1362 
   1363 		m_testCtx.getLog()
   1364 			<< tcu::TestLog::Message
   1365 			<< "Verifying result image.\n"
   1366 			<< "\tValid derivative is " << LogVecComps(reference, numComps) << " with threshold " << LogVecComps(threshold, numComps)
   1367 			<< tcu::TestLog::EndMessage;
   1368 
   1369 		// short circuit if result is strictly within the normal value error bounds.
   1370 		// This improves performance significantly.
   1371 		if (verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
   1372 								   reference, threshold, m_derivScale, m_derivBias,
   1373 								   LOG_NOTHING))
   1374 		{
   1375 			m_testCtx.getLog()
   1376 				<< tcu::TestLog::Message
   1377 				<< "No incorrect derivatives found, result valid."
   1378 				<< tcu::TestLog::EndMessage;
   1379 
   1380 			return true;
   1381 		}
   1382 
   1383 		// some pixels exceed error bounds calculated for normal values. Verify that these
   1384 		// potentially invalid pixels are in fact valid due to (for example) subnorm flushing.
   1385 
   1386 		m_testCtx.getLog()
   1387 			<< tcu::TestLog::Message
   1388 			<< "Initial verification failed, verifying image by calculating accurate error bounds for each result pixel.\n"
   1389 			<< "\tVerifying each result derivative is within its range of legal result values."
   1390 			<< tcu::TestLog::EndMessage;
   1391 
   1392 		{
   1393 			const tcu::Vec4				valueRamp		= (m_texValueMax - m_texValueMin);
   1394 			Linear2DFunctionEvaluator	function;
   1395 
   1396 			function.matrix.setRow(0, tcu::Vec3(valueRamp.x() / w, 0.0f, m_texValueMin.x()));
   1397 			function.matrix.setRow(1, tcu::Vec3(0.0f, valueRamp.y() / h, m_texValueMin.y()));
   1398 			function.matrix.setRow(2, tcu::Vec3(valueRamp.z() / w, valueRamp.z() / h, m_texValueMin.z() + m_texValueMin.z()) / 2.0f);
   1399 			function.matrix.setRow(3, tcu::Vec3(-valueRamp.w() / w, -valueRamp.w() / h, m_texValueMax.w() + m_texValueMax.w()) / 2.0f);
   1400 
   1401 			return reverifyConstantDerivateWithFlushRelaxations(m_testCtx.getLog(), compareArea, maskArea,
   1402 																m_dataType, m_precision, m_derivScale,
   1403 																m_derivBias, surfaceThreshold, m_func,
   1404 																function);
   1405 		}
   1406 	}
   1407 	else
   1408 	{
   1409 		DE_ASSERT(m_func == DERIVATE_FWIDTH);
   1410 		const tcu::Vec4	dx			= ((m_texValueMax - m_texValueMin) / w) * xScale;
   1411 		const tcu::Vec4	dy			= ((m_texValueMax - m_texValueMin) / h) * yScale;
   1412 		const tcu::Vec4	reference	= tcu::abs(dx) + tcu::abs(dy);
   1413 		const tcu::Vec4	dxThreshold	= getDerivateThreshold(m_precision, m_texValueMin*xScale, m_texValueMax*xScale, dx);
   1414 		const tcu::Vec4	dyThreshold	= getDerivateThreshold(m_precision, m_texValueMin*yScale, m_texValueMax*yScale, dy);
   1415 		const tcu::Vec4	threshold	= max(surfaceThreshold, max(dxThreshold, dyThreshold));
   1416 
   1417 		return verifyConstantDerivate(m_testCtx.getLog(), compareArea, maskArea, m_dataType,
   1418 									  reference, threshold, m_derivScale, m_derivBias);
   1419 	}
   1420 }
   1421 
   1422 ShaderDerivateTests::ShaderDerivateTests (Context& context)
   1423 	: TestCaseGroup(context, "derivate", "Derivate Function Tests")
   1424 {
   1425 }
   1426 
   1427 ShaderDerivateTests::~ShaderDerivateTests (void)
   1428 {
   1429 }
   1430 
   1431 struct FunctionSpec
   1432 {
   1433 	std::string		name;
   1434 	DerivateFunc	function;
   1435 	glu::DataType	dataType;
   1436 	glu::Precision	precision;
   1437 
   1438 	FunctionSpec (const std::string& name_, DerivateFunc function_, glu::DataType dataType_, glu::Precision precision_)
   1439 		: name		(name_)
   1440 		, function	(function_)
   1441 		, dataType	(dataType_)
   1442 		, precision	(precision_)
   1443 	{
   1444 	}
   1445 };
   1446 
   1447 void ShaderDerivateTests::init (void)
   1448 {
   1449 	static const struct
   1450 	{
   1451 		const char*		name;
   1452 		const char*		description;
   1453 		const char*		source;
   1454 	} s_linearDerivateCases[] =
   1455 	{
   1456 		{
   1457 			"linear",
   1458 			"Basic derivate of linearly interpolated argument",
   1459 
   1460 			"#version 300 es\n"
   1461 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1462 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1463 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1464 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1465 			"void main (void)\n"
   1466 			"{\n"
   1467 			"	${PRECISION} ${DATATYPE} res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
   1468 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1469 			"}\n"
   1470 		},
   1471 		{
   1472 			"in_function",
   1473 			"Derivate of linear function argument",
   1474 
   1475 			"#version 300 es\n"
   1476 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1477 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1478 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1479 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1480 			"\n"
   1481 			"${PRECISION} ${DATATYPE} computeRes (${PRECISION} ${DATATYPE} value)\n"
   1482 			"{\n"
   1483 			"	return ${FUNC}(v_coord) * u_scale + u_bias;\n"
   1484 			"}\n"
   1485 			"\n"
   1486 			"void main (void)\n"
   1487 			"{\n"
   1488 			"	${PRECISION} ${DATATYPE} res = computeRes(v_coord);\n"
   1489 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1490 			"}\n"
   1491 		},
   1492 		{
   1493 			"static_if",
   1494 			"Derivate of linearly interpolated value in static if",
   1495 
   1496 			"#version 300 es\n"
   1497 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1498 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1499 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1500 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1501 			"void main (void)\n"
   1502 			"{\n"
   1503 			"	${PRECISION} ${DATATYPE} res;\n"
   1504 			"	if (false)\n"
   1505 			"		res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
   1506 			"	else\n"
   1507 			"		res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
   1508 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1509 			"}\n"
   1510 		},
   1511 		{
   1512 			"static_loop",
   1513 			"Derivate of linearly interpolated value in static loop",
   1514 
   1515 			"#version 300 es\n"
   1516 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1517 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1518 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1519 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1520 			"void main (void)\n"
   1521 			"{\n"
   1522 			"	${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
   1523 			"	for (int i = 0; i < 2; i++)\n"
   1524 			"		res += ${FUNC}(v_coord * float(i));\n"
   1525 			"	res = res * u_scale + u_bias;\n"
   1526 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1527 			"}\n"
   1528 		},
   1529 		{
   1530 			"static_switch",
   1531 			"Derivate of linearly interpolated value in static switch",
   1532 
   1533 			"#version 300 es\n"
   1534 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1535 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1536 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1537 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1538 			"void main (void)\n"
   1539 			"{\n"
   1540 			"	${PRECISION} ${DATATYPE} res;\n"
   1541 			"	switch (1)\n"
   1542 			"	{\n"
   1543 			"		case 0:	res = ${FUNC}(-v_coord) * u_scale + u_bias;	break;\n"
   1544 			"		case 1:	res = ${FUNC}(v_coord) * u_scale + u_bias;	break;\n"
   1545 			"	}\n"
   1546 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1547 			"}\n"
   1548 		},
   1549 		{
   1550 			"uniform_if",
   1551 			"Derivate of linearly interpolated value in uniform if",
   1552 
   1553 			"#version 300 es\n"
   1554 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1555 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1556 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1557 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1558 			"uniform bool ub_true;\n"
   1559 			"void main (void)\n"
   1560 			"{\n"
   1561 			"	${PRECISION} ${DATATYPE} res;\n"
   1562 			"	if (ub_true)"
   1563 			"		res = ${FUNC}(v_coord) * u_scale + u_bias;\n"
   1564 			"	else\n"
   1565 			"		res = ${FUNC}(-v_coord) * u_scale + u_bias;\n"
   1566 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1567 			"}\n"
   1568 		},
   1569 		{
   1570 			"uniform_loop",
   1571 			"Derivate of linearly interpolated value in uniform loop",
   1572 
   1573 			"#version 300 es\n"
   1574 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1575 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1576 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1577 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1578 			"uniform int ui_two;\n"
   1579 			"void main (void)\n"
   1580 			"{\n"
   1581 			"	${PRECISION} ${DATATYPE} res = ${DATATYPE}(0.0);\n"
   1582 			"	for (int i = 0; i < ui_two; i++)\n"
   1583 			"		res += ${FUNC}(v_coord * float(i));\n"
   1584 			"	res = res * u_scale + u_bias;\n"
   1585 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1586 			"}\n"
   1587 		},
   1588 		{
   1589 			"uniform_switch",
   1590 			"Derivate of linearly interpolated value in uniform switch",
   1591 
   1592 			"#version 300 es\n"
   1593 			"in ${PRECISION} ${DATATYPE} v_coord;\n"
   1594 			"layout(location = 0) out ${OUTPUT_PREC} ${OUTPUT_TYPE} o_color;\n"
   1595 			"uniform ${PRECISION} ${DATATYPE} u_scale;\n"
   1596 			"uniform ${PRECISION} ${DATATYPE} u_bias;\n"
   1597 			"uniform int ui_one;\n"
   1598 			"void main (void)\n"
   1599 			"{\n"
   1600 			"	${PRECISION} ${DATATYPE} res;\n"
   1601 			"	switch (ui_one)\n"
   1602 			"	{\n"
   1603 			"		case 0:	res = ${FUNC}(-v_coord) * u_scale + u_bias;	break;\n"
   1604 			"		case 1:	res = ${FUNC}(v_coord) * u_scale + u_bias;	break;\n"
   1605 			"	}\n"
   1606 			"	o_color = ${CAST_TO_OUTPUT};\n"
   1607 			"}\n"
   1608 		},
   1609 	};
   1610 
   1611 	static const struct
   1612 	{
   1613 		const char*		name;
   1614 		SurfaceType		surfaceType;
   1615 		int				numSamples;
   1616 	} s_fboConfigs[] =
   1617 	{
   1618 		{ "fbo",		SURFACETYPE_DEFAULT_FRAMEBUFFER,	0 },
   1619 		{ "fbo_msaa2",	SURFACETYPE_UNORM_FBO,				2 },
   1620 		{ "fbo_msaa4",	SURFACETYPE_UNORM_FBO,				4 },
   1621 		{ "fbo_float",	SURFACETYPE_FLOAT_FBO,				0 },
   1622 	};
   1623 
   1624 	static const struct
   1625 	{
   1626 		const char*		name;
   1627 		deUint32		hint;
   1628 	} s_hints[] =
   1629 	{
   1630 		{ "fastest",	GL_FASTEST	},
   1631 		{ "nicest",		GL_NICEST	},
   1632 	};
   1633 
   1634 	static const struct
   1635 	{
   1636 		const char*		name;
   1637 		SurfaceType		surfaceType;
   1638 		int				numSamples;
   1639 	} s_hintFboConfigs[] =
   1640 	{
   1641 		{ "default",		SURFACETYPE_DEFAULT_FRAMEBUFFER,	0 },
   1642 		{ "fbo_msaa4",		SURFACETYPE_UNORM_FBO,				4 },
   1643 		{ "fbo_float",		SURFACETYPE_FLOAT_FBO,				0 }
   1644 	};
   1645 
   1646 	static const struct
   1647 	{
   1648 		const char*		name;
   1649 		SurfaceType		surfaceType;
   1650 		int				numSamples;
   1651 		deUint32		hint;
   1652 	} s_textureConfigs[] =
   1653 	{
   1654 		{ "basic",			SURFACETYPE_DEFAULT_FRAMEBUFFER,	0,	GL_DONT_CARE	},
   1655 		{ "msaa4",			SURFACETYPE_UNORM_FBO,				4,	GL_DONT_CARE	},
   1656 		{ "float_fastest",	SURFACETYPE_FLOAT_FBO,				0,	GL_FASTEST		},
   1657 		{ "float_nicest",	SURFACETYPE_FLOAT_FBO,				0,	GL_NICEST		},
   1658 	};
   1659 
   1660 	// .dfdx, .dfdy, .fwidth
   1661 	for (int funcNdx = 0; funcNdx < DERIVATE_LAST; funcNdx++)
   1662 	{
   1663 		const DerivateFunc			function		= DerivateFunc(funcNdx);
   1664 		tcu::TestCaseGroup* const	functionGroup	= new tcu::TestCaseGroup(m_testCtx, getDerivateFuncCaseName(function), getDerivateFuncName(function));
   1665 		addChild(functionGroup);
   1666 
   1667 		// .constant - no precision variants, checks that derivate of constant arguments is 0
   1668 		{
   1669 			tcu::TestCaseGroup* const constantGroup = new tcu::TestCaseGroup(m_testCtx, "constant", "Derivate of constant argument");
   1670 			functionGroup->addChild(constantGroup);
   1671 
   1672 			for (int vecSize = 1; vecSize <= 4; vecSize++)
   1673 			{
   1674 				const glu::DataType dataType = vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
   1675 				constantGroup->addChild(new ConstantDerivateCase(m_context, glu::getDataTypeName(dataType), "", function, dataType));
   1676 			}
   1677 		}
   1678 
   1679 		// Cases based on LinearDerivateCase
   1680 		for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_linearDerivateCases); caseNdx++)
   1681 		{
   1682 			tcu::TestCaseGroup* const linearCaseGroup	= new tcu::TestCaseGroup(m_testCtx, s_linearDerivateCases[caseNdx].name, s_linearDerivateCases[caseNdx].description);
   1683 			const char*			source					= s_linearDerivateCases[caseNdx].source;
   1684 			functionGroup->addChild(linearCaseGroup);
   1685 
   1686 			for (int vecSize = 1; vecSize <= 4; vecSize++)
   1687 			{
   1688 				for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
   1689 				{
   1690 					const glu::DataType		dataType		= vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
   1691 					const glu::Precision	precision		= glu::Precision(precNdx);
   1692 					const SurfaceType		surfaceType		= SURFACETYPE_DEFAULT_FRAMEBUFFER;
   1693 					const int				numSamples		= 0;
   1694 					const deUint32			hint			= GL_DONT_CARE;
   1695 					ostringstream			caseName;
   1696 
   1697 					if (caseNdx != 0 && precision == glu::PRECISION_LOWP)
   1698 						continue; // Skip as lowp doesn't actually produce any bits when rendered to default FB.
   1699 
   1700 					caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
   1701 
   1702 					linearCaseGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
   1703 				}
   1704 			}
   1705 		}
   1706 
   1707 		// Fbo cases
   1708 		for (int caseNdx = 0; caseNdx < DE_LENGTH_OF_ARRAY(s_fboConfigs); caseNdx++)
   1709 		{
   1710 			tcu::TestCaseGroup*	const	fboGroup		= new tcu::TestCaseGroup(m_testCtx, s_fboConfigs[caseNdx].name, "Derivate usage when rendering into FBO");
   1711 			const char*					source			= s_linearDerivateCases[0].source; // use source from .linear group
   1712 			const SurfaceType			surfaceType		= s_fboConfigs[caseNdx].surfaceType;
   1713 			const int					numSamples		= s_fboConfigs[caseNdx].numSamples;
   1714 			functionGroup->addChild(fboGroup);
   1715 
   1716 			for (int vecSize = 1; vecSize <= 4; vecSize++)
   1717 			{
   1718 				for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
   1719 				{
   1720 					const glu::DataType		dataType		= vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
   1721 					const glu::Precision	precision		= glu::Precision(precNdx);
   1722 					const deUint32			hint			= GL_DONT_CARE;
   1723 					ostringstream			caseName;
   1724 
   1725 					if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
   1726 						continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
   1727 
   1728 					caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
   1729 
   1730 					fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
   1731 				}
   1732 			}
   1733 		}
   1734 
   1735 		// .fastest, .nicest
   1736 		for (int hintCaseNdx = 0; hintCaseNdx < DE_LENGTH_OF_ARRAY(s_hints); hintCaseNdx++)
   1737 		{
   1738 			tcu::TestCaseGroup* const	hintGroup		= new tcu::TestCaseGroup(m_testCtx, s_hints[hintCaseNdx].name, "Shader derivate hints");
   1739 			const char*					source			= s_linearDerivateCases[0].source; // use source from .linear group
   1740 			const deUint32				hint			= s_hints[hintCaseNdx].hint;
   1741 			functionGroup->addChild(hintGroup);
   1742 
   1743 			for (int fboCaseNdx = 0; fboCaseNdx < DE_LENGTH_OF_ARRAY(s_hintFboConfigs); fboCaseNdx++)
   1744 			{
   1745 				tcu::TestCaseGroup*	const	fboGroup		= new tcu::TestCaseGroup(m_testCtx, s_hintFboConfigs[fboCaseNdx].name, "");
   1746 				const SurfaceType			surfaceType		= s_hintFboConfigs[fboCaseNdx].surfaceType;
   1747 				const int					numSamples		= s_hintFboConfigs[fboCaseNdx].numSamples;
   1748 				hintGroup->addChild(fboGroup);
   1749 
   1750 				for (int vecSize = 1; vecSize <= 4; vecSize++)
   1751 				{
   1752 					for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
   1753 					{
   1754 						const glu::DataType		dataType		= vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
   1755 						const glu::Precision	precision		= glu::Precision(precNdx);
   1756 						ostringstream			caseName;
   1757 
   1758 						if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
   1759 							continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
   1760 
   1761 						caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
   1762 
   1763 						fboGroup->addChild(new LinearDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples, source));
   1764 					}
   1765 				}
   1766 			}
   1767 		}
   1768 
   1769 		// .texture
   1770 		{
   1771 			tcu::TestCaseGroup* const textureGroup = new tcu::TestCaseGroup(m_testCtx, "texture", "Derivate of texture lookup result");
   1772 			functionGroup->addChild(textureGroup);
   1773 
   1774 			for (int texCaseNdx = 0; texCaseNdx < DE_LENGTH_OF_ARRAY(s_textureConfigs); texCaseNdx++)
   1775 			{
   1776 				tcu::TestCaseGroup*	const	caseGroup		= new tcu::TestCaseGroup(m_testCtx, s_textureConfigs[texCaseNdx].name, "");
   1777 				const SurfaceType			surfaceType		= s_textureConfigs[texCaseNdx].surfaceType;
   1778 				const int					numSamples		= s_textureConfigs[texCaseNdx].numSamples;
   1779 				const deUint32				hint			= s_textureConfigs[texCaseNdx].hint;
   1780 				textureGroup->addChild(caseGroup);
   1781 
   1782 				for (int vecSize = 1; vecSize <= 4; vecSize++)
   1783 				{
   1784 					for (int precNdx = 0; precNdx < glu::PRECISION_LAST; precNdx++)
   1785 					{
   1786 						const glu::DataType		dataType		= vecSize > 1 ? glu::getDataTypeFloatVec(vecSize) : glu::TYPE_FLOAT;
   1787 						const glu::Precision	precision		= glu::Precision(precNdx);
   1788 						ostringstream			caseName;
   1789 
   1790 						if (surfaceType != SURFACETYPE_FLOAT_FBO && precision == glu::PRECISION_LOWP)
   1791 							continue; // Skip as lowp doesn't actually produce any bits when rendered to U8 RT.
   1792 
   1793 						caseName << glu::getDataTypeName(dataType) << "_" << glu::getPrecisionName(precision);
   1794 
   1795 						caseGroup->addChild(new TextureDerivateCase(m_context, caseName.str().c_str(), "", function, dataType, precision, hint, surfaceType, numSamples));
   1796 					}
   1797 				}
   1798 			}
   1799 		}
   1800 	}
   1801 }
   1802 
   1803 } // Functional
   1804 } // gles3
   1805 } // deqp
   1806