1/*-------------------------------------------------------------------------
2 * drawElements Quality Program OpenGL ES 2.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 Multisampling tests.
22 *//*--------------------------------------------------------------------*/
23
24#include "es2fMultisampleTests.hpp"
25#include "gluPixelTransfer.hpp"
26#include "gluShaderProgram.hpp"
27#include "tcuSurface.hpp"
28#include "tcuImageCompare.hpp"
29#include "tcuRenderTarget.hpp"
30#include "tcuTestLog.hpp"
31#include "tcuTextureUtil.hpp"
32#include "tcuCommandLine.hpp"
33#include "deStringUtil.hpp"
34#include "deRandom.hpp"
35#include "deMath.h"
36#include "deString.h"
37
38#include "glw.h"
39
40#include <string>
41#include <vector>
42
43namespace deqp
44{
45namespace gles2
46{
47namespace Functional
48{
49
50using tcu::Vec2;
51using tcu::Vec3;
52using tcu::Vec4;
53using tcu::IVec2;
54using tcu::IVec4;
55using tcu::TestLog;
56using std::vector;
57
58static const float SQRT_HALF = 0.707107f;
59
60namespace
61{
62
63struct QuadCorners
64{
65	Vec2 p0;
66	Vec2 p1;
67	Vec2 p2;
68	Vec2 p3;
69
70	QuadCorners(const Vec2& p0_, const Vec2& p1_, const Vec2& p2_, const Vec2& p3_) : p0(p0_), p1(p1_), p2(p2_), p3(p3_) {}
71};
72
73} // anonymous
74
75static inline int getIterationCount (const tcu::TestContext& ctx, int defaultCount)
76{
77	int cmdLineValue = ctx.getCommandLine().getTestIterationCount();
78	return cmdLineValue > 0 ? cmdLineValue : defaultCount;
79}
80
81static inline int getGLInteger (GLenum name)
82{
83	int result;
84	GLU_CHECK_CALL(glGetIntegerv(name, &result));
85	return result;
86}
87
88template<typename T>
89static inline T min4 (T a, T b, T c, T d)
90{
91	return de::min(de::min(de::min(a, b), c), d);
92}
93
94template<typename T>
95static inline T max4 (T a, T b, T c, T d)
96{
97	return de::max(de::max(de::max(a, b), c), d);
98}
99
100static inline bool isInsideQuad (const IVec2& point, const IVec2& p0, const IVec2& p1, const IVec2& p2, const IVec2& p3)
101{
102	int dot0 = (point.x()-p0.x()) * (p1.y()-p0.y()) + (point.y()-p0.y()) * (p0.x()-p1.x());
103	int dot1 = (point.x()-p1.x()) * (p2.y()-p1.y()) + (point.y()-p1.y()) * (p1.x()-p2.x());
104	int dot2 = (point.x()-p2.x()) * (p3.y()-p2.y()) + (point.y()-p2.y()) * (p2.x()-p3.x());
105	int dot3 = (point.x()-p3.x()) * (p0.y()-p3.y()) + (point.y()-p3.y()) * (p3.x()-p0.x());
106
107	return (dot0 > 0) == (dot1 > 0) && (dot1 > 0) == (dot2 > 0) && (dot2 > 0) == (dot3 > 0);
108}
109
110/*--------------------------------------------------------------------*//*!
111 * \brief Check if a region in an image is unicolored.
112 *
113 * Checks if the pixels in img inside the convex quadilateral defined by
114 * p0, p1, p2 and p3 are all (approximately) of the same color.
115 *//*--------------------------------------------------------------------*/
116static bool isPixelRegionUnicolored (const tcu::Surface& img, const IVec2& p0, const IVec2& p1, const IVec2& p2, const IVec2& p3)
117{
118	int			xMin				= de::clamp(min4(p0.x(), p1.x(), p2.x(), p3.x()), 0, img.getWidth()-1);
119	int			yMin				= de::clamp(min4(p0.y(), p1.y(), p2.y(), p3.y()), 0, img.getHeight()-1);
120	int			xMax				= de::clamp(max4(p0.x(), p1.x(), p2.x(), p3.x()), 0, img.getWidth()-1);
121	int			yMax				= de::clamp(max4(p0.y(), p1.y(), p2.y(), p3.y()), 0, img.getHeight()-1);
122	bool		insideEncountered	= false;	//!< Whether we have already seen at least one pixel inside the region.
123	tcu::RGBA	insideColor;					//!< Color of the first pixel inside the region.
124
125	for (int y = yMin; y <= yMax; y++)
126	for (int x = xMin; x <= xMax; x++)
127	{
128		if (isInsideQuad(IVec2(x, y), p0, p1, p2, p3))
129		{
130			tcu::RGBA pixColor = img.getPixel(x, y);
131
132			if (insideEncountered)
133			{
134				if (!tcu::compareThreshold(pixColor, insideColor, tcu::RGBA(3, 3, 3, 3))) // Pixel color differs from already-detected color inside same region - region not unicolored.
135					return false;
136			}
137			else
138			{
139				insideEncountered = true;
140				insideColor = pixColor;
141			}
142		}
143	}
144
145	return true;
146}
147
148static bool drawUnicolorTestErrors (tcu::Surface& img, const tcu::PixelBufferAccess& errorImg, const IVec2& p0, const IVec2& p1, const IVec2& p2, const IVec2& p3)
149{
150	int			xMin		= de::clamp(min4(p0.x(), p1.x(), p2.x(), p3.x()), 0, img.getWidth()-1);
151	int			yMin		= de::clamp(min4(p0.y(), p1.y(), p2.y(), p3.y()), 0, img.getHeight()-1);
152	int			xMax		= de::clamp(max4(p0.x(), p1.x(), p2.x(), p3.x()), 0, img.getWidth()-1);
153	int			yMax		= de::clamp(max4(p0.y(), p1.y(), p2.y(), p3.y()), 0, img.getHeight()-1);
154	tcu::RGBA	refColor	= img.getPixel((xMin + xMax) / 2, (yMin + yMax) / 2);
155
156	for (int y = yMin; y <= yMax; y++)
157	for (int x = xMin; x <= xMax; x++)
158	{
159		if (isInsideQuad(IVec2(x, y), p0, p1, p2, p3))
160		{
161			if (!tcu::compareThreshold(img.getPixel(x, y), refColor, tcu::RGBA(3, 3, 3, 3)))
162			{
163				img.setPixel(x, y, tcu::RGBA::red);
164				errorImg.setPixel(Vec4(1.0f, 0.0f, 0.0f, 1.0f), x, y);
165			}
166		}
167	}
168
169	return true;
170}
171
172/*--------------------------------------------------------------------*//*!
173 * \brief Abstract base class handling common stuff for multisample cases.
174 *//*--------------------------------------------------------------------*/
175class MultisampleCase : public TestCase
176{
177public:
178						MultisampleCase			(Context& context, const char* name, const char* desc);
179	virtual				~MultisampleCase		(void);
180
181	virtual void		init					(void);
182	virtual void		deinit					(void);
183
184protected:
185	virtual int			getDesiredViewportSize	(void) const = 0;
186
187	void				renderTriangle			(const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec4& c0, const Vec4& c1, const Vec4& c2) const;
188	void				renderTriangle			(const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec4& color) const;
189	void				renderTriangle			(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec4& c0, const Vec4& c1, const Vec4& c2) const;
190	void				renderTriangle			(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec4& color) const;
191	void				renderQuad				(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec4& c0, const Vec4& c1, const Vec4& c2, const Vec4& c3) const;
192	void				renderQuad				(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec4& color) const;
193	void				renderLine				(const Vec2& p0, const Vec2& p1, const Vec4& color) const;
194
195	void				randomizeViewport		(void);
196	void				readImage				(tcu::Surface& dst) const;
197
198	int					m_numSamples;
199
200	int					m_viewportSize;
201
202private:
203						MultisampleCase			(const MultisampleCase& other);
204	MultisampleCase&	operator=				(const MultisampleCase& other);
205
206	glu::ShaderProgram*	m_program;
207	int					m_attrPositionLoc;
208	int					m_attrColorLoc;
209
210	int					m_viewportX;
211	int					m_viewportY;
212	de::Random			m_rnd;
213};
214
215MultisampleCase::MultisampleCase (Context& context, const char* name, const char* desc)
216	: TestCase			(context, name, desc)
217	, m_numSamples		(0)
218	, m_viewportSize	(0)
219	, m_program			(DE_NULL)
220	, m_attrPositionLoc	(-1)
221	, m_attrColorLoc	(-1)
222	, m_viewportX		(0)
223	, m_viewportY		(0)
224	, m_rnd				(deStringHash(name))
225{
226}
227
228void MultisampleCase::renderTriangle (const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec4& c0, const Vec4& c1, const Vec4& c2) const
229{
230	float vertexPositions[] =
231	{
232		p0.x(), p0.y(), p0.z(), 1.0f,
233		p1.x(), p1.y(), p1.z(), 1.0f,
234		p2.x(), p2.y(), p2.z(), 1.0f
235	};
236	float vertexColors[] =
237	{
238		c0.x(), c0.y(), c0.z(), c0.w(),
239		c1.x(), c1.y(), c1.z(), c1.w(),
240		c2.x(), c2.y(), c2.z(), c2.w(),
241	};
242
243	GLU_CHECK_CALL(glEnableVertexAttribArray(m_attrPositionLoc));
244	GLU_CHECK_CALL(glVertexAttribPointer(m_attrPositionLoc, 4, GL_FLOAT, false, 0, &vertexPositions[0]));
245
246	GLU_CHECK_CALL(glEnableVertexAttribArray(m_attrColorLoc));
247	GLU_CHECK_CALL(glVertexAttribPointer(m_attrColorLoc, 4, GL_FLOAT, false, 0, &vertexColors[0]));
248
249	GLU_CHECK_CALL(glUseProgram(m_program->getProgram()));
250	GLU_CHECK_CALL(glDrawArrays(GL_TRIANGLES, 0, 3));
251}
252
253void MultisampleCase::renderTriangle (const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec4& color) const
254{
255	renderTriangle(p0, p1, p2, color, color, color);
256}
257
258void MultisampleCase::renderTriangle (const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec4& c0, const Vec4& c1, const Vec4& c2) const
259{
260	renderTriangle(Vec3(p0.x(), p0.y(), 0.0f),
261				   Vec3(p1.x(), p1.y(), 0.0f),
262				   Vec3(p2.x(), p2.y(), 0.0f),
263				   c0, c1, c2);
264}
265
266void MultisampleCase::renderTriangle (const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec4& color) const
267{
268	renderTriangle(p0, p1, p2, color, color, color);
269}
270
271void MultisampleCase::renderQuad (const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec4& c0, const Vec4& c1, const Vec4& c2, const Vec4& c3) const
272{
273	renderTriangle(p0, p1, p2, c0, c1, c2);
274	renderTriangle(p2, p1, p3, c2, c1, c3);
275}
276
277void MultisampleCase::renderQuad (const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& p3, const Vec4& color) const
278{
279	renderQuad(p0, p1, p2, p3, color, color, color, color);
280}
281
282void MultisampleCase::renderLine (const Vec2& p0, const Vec2& p1, const Vec4& color) const
283{
284	float vertexPositions[] =
285	{
286		p0.x(), p0.y(), 0.0f, 1.0f,
287		p1.x(), p1.y(), 0.0f, 1.0f
288	};
289	float vertexColors[] =
290	{
291		color.x(), color.y(), color.z(), color.w(),
292		color.x(), color.y(), color.z(), color.w()
293	};
294
295	GLU_CHECK_CALL(glEnableVertexAttribArray(m_attrPositionLoc));
296	GLU_CHECK_CALL(glVertexAttribPointer(m_attrPositionLoc, 4, GL_FLOAT, false, 0, &vertexPositions[0]));
297
298	GLU_CHECK_CALL(glEnableVertexAttribArray(m_attrColorLoc));
299	GLU_CHECK_CALL(glVertexAttribPointer(m_attrColorLoc, 4, GL_FLOAT, false, 0, &vertexColors[0]));
300
301	GLU_CHECK_CALL(glUseProgram(m_program->getProgram()));
302	GLU_CHECK_CALL(glDrawArrays(GL_LINES, 0, 2));
303}
304
305void MultisampleCase::randomizeViewport (void)
306{
307	m_viewportX = m_rnd.getInt(0, m_context.getRenderTarget().getWidth() - m_viewportSize);
308	m_viewportY = m_rnd.getInt(0, m_context.getRenderTarget().getHeight() - m_viewportSize);
309
310	GLU_CHECK_CALL(glViewport(m_viewportX, m_viewportY, m_viewportSize, m_viewportSize));
311}
312
313void MultisampleCase::readImage (tcu::Surface& dst) const
314{
315	glu::readPixels(m_context.getRenderContext(), m_viewportX, m_viewportY, dst.getAccess());
316}
317
318void MultisampleCase::init (void)
319{
320	static const char* vertShaderSource =
321		"attribute highp vec4 a_position;\n"
322		"attribute mediump vec4 a_color;\n"
323		"varying mediump vec4 v_color;\n"
324		"void main()\n"
325		"{\n"
326		"	gl_Position = a_position;\n"
327		"	v_color = a_color;\n"
328		"}\n";
329
330	static const char* fragShaderSource =
331		"varying mediump vec4 v_color;\n"
332		"void main()\n"
333		"{\n"
334		"	gl_FragColor = v_color;\n"
335		"}\n";
336
337	// Check multisample support.
338
339	if (m_context.getRenderTarget().getNumSamples() <= 1)
340		throw tcu::NotSupportedError("No multisample buffers");
341
342	// Prepare program.
343
344	DE_ASSERT(!m_program);
345
346	m_program = new glu::ShaderProgram(m_context.getRenderContext(), glu::makeVtxFragSources(vertShaderSource, fragShaderSource));
347	if (!m_program->isOk())
348		throw tcu::TestError("Failed to compile program", DE_NULL, __FILE__, __LINE__);
349
350	GLU_CHECK_CALL(m_attrPositionLoc	= glGetAttribLocation(m_program->getProgram(), "a_position"));
351	GLU_CHECK_CALL(m_attrColorLoc		= glGetAttribLocation(m_program->getProgram(), "a_color"));
352
353	if (m_attrPositionLoc < 0 || m_attrColorLoc < 0)
354	{
355		delete m_program;
356		throw tcu::TestError("Invalid attribute locations", DE_NULL, __FILE__, __LINE__);
357	}
358
359	// Get suitable viewport size.
360
361	m_viewportSize = de::min<int>(getDesiredViewportSize(), de::min(m_context.getRenderTarget().getWidth(), m_context.getRenderTarget().getHeight()));
362	randomizeViewport();
363
364	// Query and log number of samples per pixel.
365
366	m_numSamples = getGLInteger(GL_SAMPLES);
367	m_testCtx.getLog() << TestLog::Message << "GL_SAMPLES = " << m_numSamples << TestLog::EndMessage;
368}
369
370MultisampleCase::~MultisampleCase (void)
371{
372	delete m_program;
373}
374
375void MultisampleCase::deinit (void)
376{
377	delete m_program;
378
379	m_program = DE_NULL;
380}
381
382/*--------------------------------------------------------------------*//*!
383 * \brief Base class for cases testing the value of GL_SAMPLES.
384 *
385 * Draws a test pattern (defined by renderPattern() of an inheriting class)
386 * and counts the number of distinct colors in the resulting image. That
387 * number should be at least the value of GL_SAMPLES plus one. This is
388 * repeated with increased values of m_currentIteration until this correct
389 * number of colors is detected or m_currentIteration reaches
390 * m_maxNumIterations.
391 *//*--------------------------------------------------------------------*/
392class NumSamplesCase : public MultisampleCase
393{
394public:
395						NumSamplesCase			(Context& context, const char* name, const char* description);
396						~NumSamplesCase			(void) {}
397
398	IterateResult		iterate					(void);
399
400protected:
401	int					getDesiredViewportSize	(void) const { return 256; }
402	virtual void		renderPattern			(void) const = 0;
403
404	int					m_currentIteration;
405
406private:
407	enum { DEFAULT_MAX_NUM_ITERATIONS = 16 };
408
409	const int			m_maxNumIterations;
410	vector<tcu::RGBA>	m_detectedColors;
411};
412
413NumSamplesCase::NumSamplesCase (Context& context, const char* name, const char* description)
414	: MultisampleCase		(context, name, description)
415	, m_currentIteration	(0)
416	, m_maxNumIterations	(getIterationCount(m_testCtx, DEFAULT_MAX_NUM_ITERATIONS))
417{
418}
419
420NumSamplesCase::IterateResult NumSamplesCase::iterate (void)
421{
422	TestLog&		log				= m_testCtx.getLog();
423	tcu::Surface	renderedImg		(m_viewportSize, m_viewportSize);
424
425	randomizeViewport();
426
427	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
428	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
429
430	renderPattern();
431
432	// Read and log rendered image.
433
434	readImage(renderedImg);
435
436	log << TestLog::Image("RenderedImage", "Rendered image", renderedImg, QP_IMAGE_COMPRESSION_MODE_PNG);
437
438	// Detect new, previously unseen colors from image.
439
440	int requiredNumDistinctColors = m_numSamples + 1;
441
442	for (int y = 0; y < renderedImg.getHeight() && (int)m_detectedColors.size() < requiredNumDistinctColors; y++)
443	for (int x = 0; x < renderedImg.getWidth() && (int)m_detectedColors.size() < requiredNumDistinctColors; x++)
444	{
445		tcu::RGBA color = renderedImg.getPixel(x, y);
446
447		int i;
448		for (i = 0; i < (int)m_detectedColors.size(); i++)
449		{
450			if (tcu::compareThreshold(color, m_detectedColors[i], tcu::RGBA(3, 3, 3, 3)))
451				break;
452		}
453
454		if (i == (int)m_detectedColors.size())
455			m_detectedColors.push_back(color); // Color not previously detected.
456	}
457
458	// Log results.
459
460	log << TestLog::Message
461		<< "Number of distinct colors detected so far: "
462		<< ((int)m_detectedColors.size() >= requiredNumDistinctColors ? "at least " : "")
463		<< de::toString(m_detectedColors.size())
464		<< TestLog::EndMessage;
465
466	if ((int)m_detectedColors.size() < requiredNumDistinctColors)
467	{
468		// Haven't detected enough different colors yet.
469
470		m_currentIteration++;
471
472		if (m_currentIteration >= m_maxNumIterations)
473		{
474			log << TestLog::Message << "Failure: Number of distinct colors detected is lower than GL_SAMPLES+1" << TestLog::EndMessage;
475			m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
476			return STOP;
477		}
478		else
479		{
480			log << TestLog::Message << "The number of distinct colors detected is lower than GL_SAMPLES+1 - trying again with a slightly altered pattern" << TestLog::EndMessage;
481			return CONTINUE;
482		}
483	}
484	else
485	{
486		log << TestLog::Message << "Success: The number of distinct colors detected is at least GL_SAMPLES+1" << TestLog::EndMessage;
487		m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Passed");
488		return STOP;
489	}
490}
491
492class PolygonNumSamplesCase : public NumSamplesCase
493{
494public:
495			PolygonNumSamplesCase	(Context& context, const char* name, const char* description);
496			~PolygonNumSamplesCase	(void) {}
497
498protected:
499	void	renderPattern			(void) const;
500};
501
502PolygonNumSamplesCase::PolygonNumSamplesCase (Context& context, const char* name, const char* description)
503	: NumSamplesCase(context, name, description)
504{
505}
506
507void PolygonNumSamplesCase::renderPattern (void) const
508{
509	// The test pattern consists of several triangles with edges at different angles.
510
511	const int numTriangles = 25;
512	for (int i = 0; i < numTriangles; i++)
513	{
514		float angle0 = 2.0f*DE_PI * (float)i			/ (float)numTriangles + 0.001f*(float)m_currentIteration;
515		float angle1 = 2.0f*DE_PI * (float)(i + 0.5f)	/ (float)numTriangles + 0.001f*(float)m_currentIteration;
516
517		renderTriangle(Vec2(0.0f, 0.0f),
518					   Vec2(deFloatCos(angle0)*0.95f, deFloatSin(angle0)*0.95f),
519					   Vec2(deFloatCos(angle1)*0.95f, deFloatSin(angle1)*0.95f),
520					   Vec4(1.0f));
521	}
522}
523
524class LineNumSamplesCase : public NumSamplesCase
525{
526public:
527			LineNumSamplesCase		(Context& context, const char* name, const char* description);
528			~LineNumSamplesCase		(void) {}
529
530protected:
531	void	renderPattern			(void) const;
532};
533
534LineNumSamplesCase::LineNumSamplesCase (Context& context, const char* name, const char* description)
535	: NumSamplesCase (context, name, description)
536{
537}
538
539void LineNumSamplesCase::renderPattern (void) const
540{
541	// The test pattern consists of several lines at different angles.
542
543	// We scale the number of lines based on the viewport size. This is because a gl line's thickness is
544	// constant in pixel units, i.e. they get relatively thicker as viewport size decreases. Thus we must
545	// decrease the number of lines in order to decrease the extent of overlap among the lines in the
546	// center of the pattern.
547	const int numLines = (int)(100.0f * deFloatSqrt((float)m_viewportSize / 256.0f));
548
549	for (int i = 0; i < numLines; i++)
550	{
551		float angle = 2.0f*DE_PI * (float)i / (float)numLines + 0.001f*(float)m_currentIteration;
552		renderLine(Vec2(0.0f, 0.0f), Vec2(deFloatCos(angle)*0.95f, deFloatSin(angle)*0.95f), Vec4(1.0f));
553	}
554}
555
556/*--------------------------------------------------------------------*//*!
557 * \brief Case testing behaviour of common edges when multisampling.
558 *
559 * Draws a number of test patterns, each with a number of quads, each made
560 * of two triangles, rotated at different angles. The inner edge inside the
561 * quad (i.e. the common edge of the two triangles) still should not be
562 * visible, despite multisampling - i.e. the two triangles forming the quad
563 * should never get any common coverage bits in any pixel.
564 *//*--------------------------------------------------------------------*/
565class CommonEdgeCase : public MultisampleCase
566{
567public:
568	enum CaseType
569	{
570		CASETYPE_SMALL_QUADS = 0,				//!< Draw several small quads per iteration.
571		CASETYPE_BIGGER_THAN_VIEWPORT_QUAD,		//!< Draw one bigger-than-viewport quad per iteration.
572		CASETYPE_FIT_VIEWPORT_QUAD,				//!< Draw one exactly viewport-sized, axis aligned quad per iteration.
573
574		CASETYPE_LAST
575	};
576
577					CommonEdgeCase			(Context& context, const char* name, const char* description, CaseType caseType);
578					~CommonEdgeCase			(void) {}
579
580	void			init					(void);
581
582	IterateResult	iterate					(void);
583
584protected:
585	int				getDesiredViewportSize	(void) const { return m_caseType == CASETYPE_SMALL_QUADS ? 128 : 32; }
586
587private:
588	enum
589	{
590		DEFAULT_SMALL_QUADS_ITERATIONS					= 16,
591		DEFAULT_BIGGER_THAN_VIEWPORT_QUAD_ITERATIONS	= 8*8
592		// \note With CASETYPE_FIT_VIEWPORT_QUAD, we don't do rotations other than multiples of 90 deg -> constant number of iterations.
593	};
594
595	const CaseType	m_caseType;
596
597	const int		m_numIterations;
598	int				m_currentIteration;
599};
600
601CommonEdgeCase::CommonEdgeCase (Context& context, const char* name, const char* description, CaseType caseType)
602	: MultisampleCase		(context, name, description)
603	, m_caseType			(caseType)
604	, m_numIterations		(caseType == CASETYPE_SMALL_QUADS					? getIterationCount(m_testCtx, DEFAULT_SMALL_QUADS_ITERATIONS)
605							: caseType == CASETYPE_BIGGER_THAN_VIEWPORT_QUAD	? getIterationCount(m_testCtx, DEFAULT_BIGGER_THAN_VIEWPORT_QUAD_ITERATIONS)
606							: 8)
607	, m_currentIteration	(0)
608{
609}
610
611void CommonEdgeCase::init (void)
612{
613	MultisampleCase::init();
614
615	if (m_caseType == CASETYPE_SMALL_QUADS)
616	{
617		// Check for a big enough viewport. With too small viewports the test case can't analyze the resulting image well enough.
618
619		const int minViewportSize = 32;
620
621		DE_ASSERT(minViewportSize <= getDesiredViewportSize());
622
623		if (m_viewportSize < minViewportSize)
624			throw tcu::InternalError("Render target width or height too low (is " + de::toString(m_viewportSize) + ", should be at least " + de::toString(minViewportSize) + ")");
625	}
626
627	GLU_CHECK_CALL(glEnable(GL_BLEND));
628	GLU_CHECK_CALL(glBlendEquation(GL_FUNC_ADD));
629	GLU_CHECK_CALL(glBlendFunc(GL_ONE, GL_ONE));
630
631	m_testCtx.getLog() << TestLog::Message << "Additive blending enabled in order to detect (erroneously) overlapping samples" << TestLog::EndMessage;
632}
633
634CommonEdgeCase::IterateResult CommonEdgeCase::iterate (void)
635{
636	TestLog&		log				= m_testCtx.getLog();
637	tcu::Surface	renderedImg		(m_viewportSize, m_viewportSize);
638	tcu::Surface	errorImg		(m_viewportSize, m_viewportSize);
639
640	randomizeViewport();
641
642	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
643	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
644
645	// Draw test pattern. Test patterns consist of quads formed with two triangles.
646	// After drawing the pattern, we check that the interior pixels of each quad are
647	// all the same color - this is meant to verify that there are no artifacts on the inner edge.
648
649	vector<QuadCorners> unicoloredRegions;
650
651	if (m_caseType == CASETYPE_SMALL_QUADS)
652	{
653		// Draw several quads, rotated at different angles.
654
655		const float		quadDiagLen = 2.0f / 3.0f * 0.9f; // \note Fit 3 quads in both x and y directions.
656		float			angleCos;
657		float			angleSin;
658
659		// \note First and second iteration get exact 0 (and 90, 180, 270) and 45 (and 135, 225, 315) angle quads, as they are kind of a special case.
660
661		if (m_currentIteration == 0)
662		{
663			angleCos = 1.0f;
664			angleSin = 0.0f;
665		}
666		else if (m_currentIteration == 1)
667		{
668			angleCos = SQRT_HALF;
669			angleSin = SQRT_HALF;
670		}
671		else
672		{
673			float angle = 0.5f * DE_PI * (float)(m_currentIteration-1) / (float)(m_numIterations-1);
674			angleCos = deFloatCos(angle);
675			angleSin = deFloatSin(angle);
676		}
677
678		Vec2 corners[4] =
679		{
680			0.5f * quadDiagLen * Vec2( angleCos,  angleSin),
681			0.5f * quadDiagLen * Vec2(-angleSin,  angleCos),
682			0.5f * quadDiagLen * Vec2(-angleCos, -angleSin),
683			0.5f * quadDiagLen * Vec2( angleSin, -angleCos)
684		};
685
686		unicoloredRegions.reserve(8);
687
688		// Draw 8 quads.
689		// First four are rotated at angles angle+0, angle+90, angle+180 and angle+270.
690		// Last four are rotated the same angles as the first four, but the ordering of the last triangle's vertices is reversed.
691
692		for (int quadNdx = 0; quadNdx < 8; quadNdx++)
693		{
694			Vec2 center = (2.0f-quadDiagLen) * Vec2((float)(quadNdx%3), (float)(quadNdx/3)) / 2.0f - 0.5f*(2.0f-quadDiagLen);
695
696			renderTriangle(corners[(0+quadNdx) % 4] + center,
697						   corners[(1+quadNdx) % 4] + center,
698						   corners[(2+quadNdx) % 4] + center,
699						   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
700
701			if (quadNdx >= 4)
702			{
703				renderTriangle(corners[(3+quadNdx) % 4] + center,
704							   corners[(2+quadNdx) % 4] + center,
705							   corners[(0+quadNdx) % 4] + center,
706							   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
707			}
708			else
709			{
710				renderTriangle(corners[(0+quadNdx) % 4] + center,
711							   corners[(2+quadNdx) % 4] + center,
712							   corners[(3+quadNdx) % 4] + center,
713							   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
714			}
715
716			// The size of the "interior" of a quad is assumed to be approximately unicolorRegionScale*<actual size of quad>.
717			// By "interior" we here mean the region of non-boundary pixels of the rendered quad for which we can safely assume
718			// that it has all coverage bits set to 1, for every pixel.
719			float unicolorRegionScale = 1.0f - 6.0f*2.0f / (float)m_viewportSize / quadDiagLen;
720			unicoloredRegions.push_back(QuadCorners((center + corners[0]*unicolorRegionScale),
721													(center + corners[1]*unicolorRegionScale),
722													(center + corners[2]*unicolorRegionScale),
723													(center + corners[3]*unicolorRegionScale)));
724		}
725	}
726	else if (m_caseType == CASETYPE_BIGGER_THAN_VIEWPORT_QUAD)
727	{
728		// Draw a bigger-than-viewport quad, rotated at an angle depending on m_currentIteration.
729
730		int				quadBaseAngleNdx		= m_currentIteration / 8;
731		int				quadSubAngleNdx			= m_currentIteration % 8;
732		float			angleCos;
733		float			angleSin;
734
735		if (quadBaseAngleNdx == 0)
736		{
737			angleCos = 1.0f;
738			angleSin = 0.0f;
739		}
740		else if (quadBaseAngleNdx == 1)
741		{
742			angleCos = SQRT_HALF;
743			angleSin = SQRT_HALF;
744		}
745		else
746		{
747			float angle = 0.5f * DE_PI * (float)(m_currentIteration-1) / (float)(m_numIterations-1);
748			angleCos = deFloatCos(angle);
749			angleSin = deFloatSin(angle);
750		}
751
752		float quadDiagLen = 2.5f / de::max(angleCos, angleSin);
753
754		Vec2 corners[4] =
755		{
756			0.5f * quadDiagLen * Vec2( angleCos,  angleSin),
757			0.5f * quadDiagLen * Vec2(-angleSin,  angleCos),
758			0.5f * quadDiagLen * Vec2(-angleCos, -angleSin),
759			0.5f * quadDiagLen * Vec2( angleSin, -angleCos)
760		};
761
762		renderTriangle(corners[(0+quadSubAngleNdx) % 4],
763					   corners[(1+quadSubAngleNdx) % 4],
764					   corners[(2+quadSubAngleNdx) % 4],
765					   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
766
767		if (quadSubAngleNdx >= 4)
768		{
769			renderTriangle(corners[(3+quadSubAngleNdx) % 4],
770						   corners[(2+quadSubAngleNdx) % 4],
771						   corners[(0+quadSubAngleNdx) % 4],
772						   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
773		}
774		else
775		{
776			renderTriangle(corners[(0+quadSubAngleNdx) % 4],
777						   corners[(2+quadSubAngleNdx) % 4],
778						   corners[(3+quadSubAngleNdx) % 4],
779						   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
780		}
781
782		float unicolorRegionScale = 1.0f - 6.0f*2.0f / (float)m_viewportSize / quadDiagLen;
783		unicoloredRegions.push_back(QuadCorners((corners[0]*unicolorRegionScale),
784												(corners[1]*unicolorRegionScale),
785												(corners[2]*unicolorRegionScale),
786												(corners[3]*unicolorRegionScale)));
787	}
788	else if (m_caseType == CASETYPE_FIT_VIEWPORT_QUAD)
789	{
790		// Draw an exactly viewport-sized quad, rotated by multiples of 90 degrees angle depending on m_currentIteration.
791
792		int quadSubAngleNdx = m_currentIteration % 8;
793
794		Vec2 corners[4] =
795		{
796			Vec2( 1.0f,  1.0f),
797			Vec2(-1.0f,  1.0f),
798			Vec2(-1.0f, -1.0f),
799			Vec2( 1.0f, -1.0f)
800		};
801
802		renderTriangle(corners[(0+quadSubAngleNdx) % 4],
803					   corners[(1+quadSubAngleNdx) % 4],
804					   corners[(2+quadSubAngleNdx) % 4],
805					   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
806
807		if (quadSubAngleNdx >= 4)
808		{
809			renderTriangle(corners[(3+quadSubAngleNdx) % 4],
810						   corners[(2+quadSubAngleNdx) % 4],
811						   corners[(0+quadSubAngleNdx) % 4],
812						   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
813		}
814		else
815		{
816			renderTriangle(corners[(0+quadSubAngleNdx) % 4],
817						   corners[(2+quadSubAngleNdx) % 4],
818						   corners[(3+quadSubAngleNdx) % 4],
819						   Vec4(0.5f, 0.5f, 0.5f, 1.0f));
820		}
821
822		unicoloredRegions.push_back(QuadCorners(corners[0], corners[1], corners[2], corners[3]));
823	}
824	else
825		DE_ASSERT(false);
826
827	// Read pixels and check unicolored regions.
828
829	readImage(renderedImg);
830
831	tcu::clear(errorImg.getAccess(), Vec4(0.0f, 1.0f, 0.0f, 1.0f));
832
833	log << TestLog::Image("RenderedImage", "Rendered image", renderedImg, QP_IMAGE_COMPRESSION_MODE_PNG);
834
835	bool errorsDetected = false;
836	for (int i = 0; i < (int)unicoloredRegions.size(); i++)
837	{
838		const QuadCorners&	region					= unicoloredRegions[i];
839		IVec2				p0Win					= ((region.p0+1.0f) * 0.5f * (float)(m_viewportSize-1) + 0.5f).asInt();
840		IVec2				p1Win					= ((region.p1+1.0f) * 0.5f * (float)(m_viewportSize-1) + 0.5f).asInt();
841		IVec2				p2Win					= ((region.p2+1.0f) * 0.5f * (float)(m_viewportSize-1) + 0.5f).asInt();
842		IVec2				p3Win					= ((region.p3+1.0f) * 0.5f * (float)(m_viewportSize-1) + 0.5f).asInt();
843		bool				errorsInCurrentRegion	= !isPixelRegionUnicolored(renderedImg, p0Win, p1Win, p2Win, p3Win);
844
845		if (errorsInCurrentRegion)
846			drawUnicolorTestErrors(renderedImg, errorImg.getAccess(), p0Win, p1Win, p2Win, p3Win);
847
848		errorsDetected = errorsDetected || errorsInCurrentRegion;
849	}
850
851	m_currentIteration++;
852
853	if (errorsDetected)
854	{
855		log << TestLog::Message << "Failure: Not all quad interiors seem unicolored - common-edge artifacts?" << TestLog::EndMessage;
856		log << TestLog::Message << "Erroneous pixels are drawn red in the following image" << TestLog::EndMessage;
857		log << TestLog::Image("RenderedImageWithErrors",	"Rendered image with errors marked",	renderedImg,	QP_IMAGE_COMPRESSION_MODE_PNG);
858		log << TestLog::Image("ErrorsOnly",					"Image with error pixels only",			errorImg,		QP_IMAGE_COMPRESSION_MODE_PNG);
859		m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
860		return STOP;
861	}
862	else if (m_currentIteration < m_numIterations)
863	{
864		log << TestLog::Message << "Quads seem OK - moving on to next pattern" << TestLog::EndMessage;
865		return CONTINUE;
866	}
867	else
868	{
869		log << TestLog::Message << "Success: All quad interiors seem unicolored (no common-edge artifacts)" << TestLog::EndMessage;
870		m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Passed");
871		return STOP;
872	}
873}
874
875/*--------------------------------------------------------------------*//*!
876 * \brief Test that depth values are per-sample.
877 *
878 * Draws intersecting, differently-colored polygons and checks that there
879 * are at least GL_SAMPLES+1 distinct colors present, due to some of the
880 * samples at the intersection line belonging to one and some to another
881 * polygon.
882 *//*--------------------------------------------------------------------*/
883class SampleDepthCase : public NumSamplesCase
884{
885public:
886						SampleDepthCase			(Context& context, const char* name, const char* description);
887						~SampleDepthCase		(void) {}
888
889	void				init					(void);
890
891protected:
892	void				renderPattern			(void) const;
893};
894
895SampleDepthCase::SampleDepthCase (Context& context, const char* name, const char* description)
896	: NumSamplesCase (context, name, description)
897{
898}
899
900void SampleDepthCase::init (void)
901{
902	TestLog& log = m_testCtx.getLog();
903
904	MultisampleCase::init();
905
906	GLU_CHECK_CALL(glEnable(GL_DEPTH_TEST));
907	GLU_CHECK_CALL(glDepthFunc(GL_LESS));
908
909	log << TestLog::Message << "Depth test enabled, depth func is GL_LESS" << TestLog::EndMessage;
910	log << TestLog::Message << "Drawing several bigger-than-viewport black or white polygons intersecting each other" << TestLog::EndMessage;
911}
912
913void SampleDepthCase::renderPattern (void) const
914{
915	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
916	GLU_CHECK_CALL(glClearDepthf(1.0f));
917	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
918
919	{
920		const int numPolygons = 50;
921
922		for (int i = 0; i < numPolygons; i++)
923		{
924			Vec4	color	= i % 2 == 0 ? Vec4(1.0f, 1.0f, 1.0f, 1.0f) : Vec4(0.0f, 0.0f, 0.0f, 1.0f);
925			float	angle	= 2.0f * DE_PI * (float)i / (float)numPolygons + 0.001f*(float)m_currentIteration;
926			Vec3	pt0		(3.0f*deFloatCos(angle + 2.0f*DE_PI*0.0f/3.0f), 3.0f*deFloatSin(angle + 2.0f*DE_PI*0.0f/3.0f), 1.0f);
927			Vec3	pt1		(3.0f*deFloatCos(angle + 2.0f*DE_PI*1.0f/3.0f), 3.0f*deFloatSin(angle + 2.0f*DE_PI*1.0f/3.0f), 0.0f);
928			Vec3	pt2		(3.0f*deFloatCos(angle + 2.0f*DE_PI*2.0f/3.0f), 3.0f*deFloatSin(angle + 2.0f*DE_PI*2.0f/3.0f), 0.0f);
929
930			renderTriangle(pt0, pt1, pt2, color);
931		}
932	}
933}
934
935/*--------------------------------------------------------------------*//*!
936 * \brief Test that stencil buffer values are per-sample.
937 *
938 * Draws a unicolored pattern and marks drawn samples in stencil buffer;
939 * then clears and draws a viewport-size quad with that color and with
940 * proper stencil test such that the resulting image should be exactly the
941 * same as after the pattern was first drawn.
942 *//*--------------------------------------------------------------------*/
943class SampleStencilCase : public MultisampleCase
944{
945public:
946						SampleStencilCase		(Context& context, const char* name, const char* description);
947						~SampleStencilCase		(void) {}
948
949	IterateResult		iterate					(void);
950
951protected:
952	int					getDesiredViewportSize	(void) const { return 256; }
953};
954
955SampleStencilCase::SampleStencilCase (Context& context, const char* name, const char* description)
956	: MultisampleCase (context, name, description)
957{
958}
959
960SampleStencilCase::IterateResult SampleStencilCase::iterate (void)
961{
962	TestLog&		log					= m_testCtx.getLog();
963	tcu::Surface	renderedImgFirst	(m_viewportSize, m_viewportSize);
964	tcu::Surface	renderedImgSecond	(m_viewportSize, m_viewportSize);
965
966	randomizeViewport();
967
968	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
969	GLU_CHECK_CALL(glClearStencil(0));
970	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT));
971	GLU_CHECK_CALL(glEnable(GL_STENCIL_TEST));
972	GLU_CHECK_CALL(glStencilFunc(GL_ALWAYS, 1, 1));
973	GLU_CHECK_CALL(glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE));
974
975	log << TestLog::Message << "Drawing a pattern with glStencilFunc(GL_ALWAYS, 1, 1) and glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE)" << TestLog::EndMessage;
976
977	{
978		const int numTriangles = 25;
979		for (int i = 0; i < numTriangles; i++)
980		{
981			float angle0 = 2.0f*DE_PI * (float)i			/ (float)numTriangles;
982			float angle1 = 2.0f*DE_PI * (float)(i + 0.5f)	/ (float)numTriangles;
983
984			renderTriangle(Vec2(0.0f, 0.0f),
985						   Vec2(deFloatCos(angle0)*0.95f, deFloatSin(angle0)*0.95f),
986						   Vec2(deFloatCos(angle1)*0.95f, deFloatSin(angle1)*0.95f),
987						   Vec4(1.0f));
988		}
989	}
990
991	readImage(renderedImgFirst);
992	log << TestLog::Image("RenderedImgFirst", "First image rendered", renderedImgFirst, QP_IMAGE_COMPRESSION_MODE_PNG);
993
994	log << TestLog::Message << "Clearing color buffer to black" << TestLog::EndMessage;
995
996	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
997	GLU_CHECK_CALL(glStencilFunc(GL_EQUAL, 1, 1));
998	GLU_CHECK_CALL(glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP));
999
1000	{
1001		log << TestLog::Message << "Checking that color buffer was actually cleared to black" << TestLog::EndMessage;
1002
1003		tcu::Surface clearedImg(m_viewportSize, m_viewportSize);
1004		readImage(clearedImg);
1005
1006		for (int y = 0; y < clearedImg.getHeight(); y++)
1007		for (int x = 0; x < clearedImg.getWidth(); x++)
1008		{
1009			const tcu::RGBA& clr = clearedImg.getPixel(x, y);
1010			if (clr != tcu::RGBA::black)
1011			{
1012				log << TestLog::Message << "Failure: first non-black pixel, color " << clr << ", detected at coordinates (" << x << ", " << y << ")" << TestLog::EndMessage;
1013				log << TestLog::Image("ClearedImg", "Image after clearing, erroneously non-black", clearedImg);
1014				m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
1015				return STOP;
1016			}
1017		}
1018	}
1019
1020	log << TestLog::Message << "Drawing a viewport-sized quad with glStencilFunc(GL_EQUAL, 1, 1) and glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP) - should result in same image as the first" << TestLog::EndMessage;
1021
1022	renderQuad(Vec2(-1.0f, -1.0f),
1023			   Vec2( 1.0f, -1.0f),
1024			   Vec2(-1.0f,  1.0f),
1025			   Vec2( 1.0f,  1.0f),
1026			   Vec4(1.0f));
1027
1028	readImage(renderedImgSecond);
1029	log << TestLog::Image("RenderedImgSecond", "Second image rendered", renderedImgSecond, QP_IMAGE_COMPRESSION_MODE_PNG);
1030
1031	bool passed = tcu::pixelThresholdCompare(log,
1032											 "ImageCompare",
1033											 "Image comparison",
1034											 renderedImgFirst,
1035											 renderedImgSecond,
1036											 tcu::RGBA(0),
1037											 tcu::COMPARE_LOG_ON_ERROR);
1038
1039	if (passed)
1040		log << TestLog::Message << "Success: The two images rendered are identical" << TestLog::EndMessage;
1041
1042	m_context.getTestContext().setTestResult(passed ? QP_TEST_RESULT_PASS	: QP_TEST_RESULT_FAIL,
1043											 passed ? "Passed"				: "Failed");
1044
1045	return STOP;
1046}
1047
1048/*--------------------------------------------------------------------*//*!
1049 * \brief Tests coverage mask generation proportionality property.
1050 *
1051 * Tests that the number of coverage bits in a coverage mask created by
1052 * GL_SAMPLE_ALPHA_TO_COVERAGE or GL_SAMPLE_COVERAGE is, on average,
1053 * proportional to the alpha or coverage value, respectively. Draws
1054 * multiple frames, each time increasing the alpha or coverage value used,
1055 * and checks that the average color is changing appropriately.
1056 *//*--------------------------------------------------------------------*/
1057class MaskProportionalityCase : public MultisampleCase
1058{
1059public:
1060	enum CaseType
1061	{
1062		CASETYPE_ALPHA_TO_COVERAGE = 0,
1063		CASETYPE_SAMPLE_COVERAGE,
1064		CASETYPE_SAMPLE_COVERAGE_INVERTED,
1065
1066		CASETYPE_LAST
1067	};
1068
1069					MaskProportionalityCase				(Context& context, const char* name, const char* description, CaseType type);
1070					~MaskProportionalityCase			(void) {}
1071
1072	void			init								(void);
1073
1074	IterateResult	iterate								(void);
1075
1076protected:
1077	int				getDesiredViewportSize				(void) const { return 32; }
1078
1079private:
1080	const CaseType	m_type;
1081
1082	int				m_numIterations;
1083	int				m_currentIteration;
1084
1085	deInt32			m_previousIterationColorSum;
1086};
1087
1088MaskProportionalityCase::MaskProportionalityCase (Context& context, const char* name, const char* description, CaseType type)
1089	: MultisampleCase				(context, name, description)
1090	, m_type						(type)
1091	, m_currentIteration			(0)
1092	, m_previousIterationColorSum	(-1)
1093{
1094}
1095
1096void MaskProportionalityCase::init (void)
1097{
1098	TestLog& log = m_testCtx.getLog();
1099
1100	MultisampleCase::init();
1101
1102	if (m_type == CASETYPE_ALPHA_TO_COVERAGE)
1103	{
1104		GLU_CHECK_CALL(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE));
1105		log << TestLog::Message << "GL_SAMPLE_ALPHA_TO_COVERAGE is enabled" << TestLog::EndMessage;
1106	}
1107	else
1108	{
1109		DE_ASSERT(m_type == CASETYPE_SAMPLE_COVERAGE || m_type == CASETYPE_SAMPLE_COVERAGE_INVERTED);
1110
1111		GLU_CHECK_CALL(glEnable(GL_SAMPLE_COVERAGE));
1112		log << TestLog::Message << "GL_SAMPLE_COVERAGE is enabled" << TestLog::EndMessage;
1113	}
1114
1115	m_numIterations = de::max(2, getIterationCount(m_testCtx, m_numSamples * 5));
1116
1117	randomizeViewport(); // \note Using the same viewport for every iteration since coverage mask may depend on window-relative pixel coordinate.
1118}
1119
1120MaskProportionalityCase::IterateResult MaskProportionalityCase::iterate (void)
1121{
1122	TestLog&		log				= m_testCtx.getLog();
1123	tcu::Surface	renderedImg		(m_viewportSize, m_viewportSize);
1124	deInt32			numPixels		= (deInt32)renderedImg.getWidth()*(deInt32)renderedImg.getHeight();
1125
1126	log << TestLog::Message << "Clearing color to black" << TestLog::EndMessage;
1127	GLU_CHECK_CALL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE));
1128	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
1129	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
1130
1131	if (m_type == CASETYPE_ALPHA_TO_COVERAGE)
1132	{
1133		GLU_CHECK_CALL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE));
1134		log << TestLog::Message << "Using color mask TRUE, TRUE, TRUE, FALSE" << TestLog::EndMessage;
1135	}
1136
1137	// Draw quad.
1138
1139	{
1140		const Vec2		pt0						(-1.0f, -1.0f);
1141		const Vec2		pt1						( 1.0f, -1.0f);
1142		const Vec2		pt2						(-1.0f,  1.0f);
1143		const Vec2		pt3						( 1.0f,  1.0f);
1144		Vec4			quadColor				(1.0f, 0.0f, 0.0f, 1.0f);
1145		float			alphaOrCoverageValue	= (float)m_currentIteration / (float)(m_numIterations-1);
1146
1147		if (m_type == CASETYPE_ALPHA_TO_COVERAGE)
1148		{
1149			log << TestLog::Message << "Drawing a red quad using alpha value " + de::floatToString(alphaOrCoverageValue, 2) << TestLog::EndMessage;
1150			quadColor.w() = alphaOrCoverageValue;
1151		}
1152		else
1153		{
1154			DE_ASSERT(m_type == CASETYPE_SAMPLE_COVERAGE || m_type == CASETYPE_SAMPLE_COVERAGE_INVERTED);
1155
1156			bool	isInverted		= m_type == CASETYPE_SAMPLE_COVERAGE_INVERTED;
1157			float	coverageValue	= isInverted ? 1.0f - alphaOrCoverageValue : alphaOrCoverageValue;
1158			log << TestLog::Message << "Drawing a red quad using sample coverage value " + de::floatToString(coverageValue, 2) << (isInverted ? " (inverted)" : "") << TestLog::EndMessage;
1159			GLU_CHECK_CALL(glSampleCoverage(coverageValue, isInverted ? GL_TRUE : GL_FALSE));
1160		}
1161
1162		renderQuad(pt0, pt1, pt2, pt3, quadColor);
1163	}
1164
1165	// Read ang log image.
1166
1167	readImage(renderedImg);
1168
1169	log << TestLog::Image("RenderedImage", "Rendered image", renderedImg, QP_IMAGE_COMPRESSION_MODE_PNG);
1170
1171	// Compute average red component in rendered image.
1172
1173	deInt32 sumRed = 0;
1174
1175	for (int y = 0; y < renderedImg.getHeight(); y++)
1176	for (int x = 0; x < renderedImg.getWidth(); x++)
1177		sumRed += renderedImg.getPixel(x, y).getRed();
1178
1179	log << TestLog::Message << "Average red color component: " << de::floatToString((float)sumRed / 255.0f / (float)numPixels, 2) << TestLog::EndMessage;
1180
1181	// Check if average color has decreased from previous frame's color.
1182
1183	if (sumRed < m_previousIterationColorSum)
1184	{
1185		log << TestLog::Message << "Failure: Current average red color component is lower than previous" << TestLog::EndMessage;
1186		m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
1187		return STOP;
1188	}
1189
1190	// Check if coverage mask is not all-zeros if alpha or coverage value is 0 (or 1, if inverted).
1191
1192	if (m_currentIteration == 0 && sumRed != 0)
1193	{
1194		log << TestLog::Message << "Failure: Image should be completely black" << TestLog::EndMessage;
1195		m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
1196		return STOP;
1197	}
1198
1199	if (m_currentIteration == m_numIterations-1 && sumRed != 0xff*numPixels)
1200	{
1201		log << TestLog::Message << "Failure: Image should be completely red" << TestLog::EndMessage;
1202
1203		m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
1204		return STOP;
1205	}
1206
1207	m_previousIterationColorSum = sumRed;
1208
1209	m_currentIteration++;
1210
1211	if (m_currentIteration >= m_numIterations)
1212	{
1213		log << TestLog::Message
1214			<< "Success: Number of coverage mask bits set appears to be, on average, proportional to "
1215			<< (m_type == CASETYPE_ALPHA_TO_COVERAGE ? "alpha" : m_type == CASETYPE_SAMPLE_COVERAGE ? "sample coverage value" : "inverted sample coverage value")
1216			<< TestLog::EndMessage;
1217
1218		m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Passed");
1219		return STOP;
1220	}
1221	else
1222		return CONTINUE;
1223}
1224
1225/*--------------------------------------------------------------------*//*!
1226 * \brief Tests coverage mask generation constancy property.
1227 *
1228 * Tests that the coverage mask created by GL_SAMPLE_ALPHA_TO_COVERAGE or
1229 * GL_SAMPLE_COVERAGE is constant at given pixel coordinates, with a given
1230 * alpha component or coverage value, respectively. Draws two quads, with
1231 * the second one fully overlapping the first one such that at any given
1232 * pixel, both quads have the same alpha or coverage value. This way, if
1233 * the constancy property is fulfilled, only the second quad should be
1234 * visible.
1235 *//*--------------------------------------------------------------------*/
1236class MaskConstancyCase : public MultisampleCase
1237{
1238public:
1239	enum CaseType
1240	{
1241		CASETYPE_ALPHA_TO_COVERAGE = 0,		//!< Use only alpha-to-coverage.
1242		CASETYPE_SAMPLE_COVERAGE,			//!< Use only sample coverage.
1243		CASETYPE_SAMPLE_COVERAGE_INVERTED,	//!< Use only inverted sample coverage.
1244		CASETYPE_BOTH,						//!< Use both alpha-to-coverage and sample coverage.
1245		CASETYPE_BOTH_INVERTED,				//!< Use both alpha-to-coverage and inverted sample coverage.
1246
1247		CASETYPE_LAST
1248	};
1249
1250					MaskConstancyCase			(Context& context, const char* name, const char* description, CaseType type);
1251					~MaskConstancyCase			(void) {}
1252
1253	IterateResult	iterate						(void);
1254
1255protected:
1256	int				getDesiredViewportSize		(void) const { return 256; }
1257
1258private:
1259	const bool		m_isAlphaToCoverageCase;
1260	const bool		m_isSampleCoverageCase;
1261	const bool		m_isInvertedSampleCoverageCase;
1262};
1263
1264MaskConstancyCase::MaskConstancyCase (Context& context, const char* name, const char* description, CaseType type)
1265	: MultisampleCase					(context, name, description)
1266	, m_isAlphaToCoverageCase			(type == CASETYPE_ALPHA_TO_COVERAGE			|| type == CASETYPE_BOTH						|| type == CASETYPE_BOTH_INVERTED)
1267	, m_isSampleCoverageCase			(type == CASETYPE_SAMPLE_COVERAGE			|| type == CASETYPE_SAMPLE_COVERAGE_INVERTED	|| type == CASETYPE_BOTH			|| type == CASETYPE_BOTH_INVERTED)
1268	, m_isInvertedSampleCoverageCase	(type == CASETYPE_SAMPLE_COVERAGE_INVERTED	|| type == CASETYPE_BOTH_INVERTED)
1269{
1270}
1271
1272MaskConstancyCase::IterateResult MaskConstancyCase::iterate (void)
1273{
1274	TestLog&		log				= m_testCtx.getLog();
1275	tcu::Surface	renderedImg		(m_viewportSize, m_viewportSize);
1276
1277	randomizeViewport();
1278
1279	log << TestLog::Message << "Clearing color to black" << TestLog::EndMessage;
1280	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
1281	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
1282
1283	if (m_isAlphaToCoverageCase)
1284	{
1285		GLU_CHECK_CALL(glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE));
1286		GLU_CHECK_CALL(glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_FALSE));
1287		log << TestLog::Message << "GL_SAMPLE_ALPHA_TO_COVERAGE is enabled" << TestLog::EndMessage;
1288		log << TestLog::Message << "Color mask is TRUE, TRUE, TRUE, FALSE" << TestLog::EndMessage;
1289	}
1290
1291	if (m_isSampleCoverageCase)
1292	{
1293		GLU_CHECK_CALL(glEnable(GL_SAMPLE_COVERAGE));
1294		log << TestLog::Message << "GL_SAMPLE_COVERAGE is enabled" << TestLog::EndMessage;
1295	}
1296
1297	log << TestLog::Message
1298		<< "Drawing several green quads, each fully overlapped by a red quad with the same "
1299		<< (m_isAlphaToCoverageCase ? "alpha" : "")
1300		<< (m_isAlphaToCoverageCase && m_isSampleCoverageCase ? " and " : "")
1301		<< (m_isInvertedSampleCoverageCase ? "inverted " : "")
1302		<< (m_isSampleCoverageCase ? "sample coverage" : "")
1303		<< " values"
1304		<< TestLog::EndMessage;
1305
1306	const int numQuadRowsCols = m_numSamples*4;
1307
1308	for (int row = 0; row < numQuadRowsCols; row++)
1309	{
1310		for (int col = 0; col < numQuadRowsCols; col++)
1311		{
1312			float		x0			= (float)(col+0) / (float)numQuadRowsCols * 2.0f - 1.0f;
1313			float		x1			= (float)(col+1) / (float)numQuadRowsCols * 2.0f - 1.0f;
1314			float		y0			= (float)(row+0) / (float)numQuadRowsCols * 2.0f - 1.0f;
1315			float		y1			= (float)(row+1) / (float)numQuadRowsCols * 2.0f - 1.0f;
1316			const Vec4	baseGreen	(0.0f, 1.0f, 0.0f, 0.0f);
1317			const Vec4	baseRed		(1.0f, 0.0f, 0.0f, 0.0f);
1318			Vec4		alpha0		(0.0f, 0.0f, 0.0f, m_isAlphaToCoverageCase ? (float)col / (float)(numQuadRowsCols-1) : 1.0f);
1319			Vec4		alpha1		(0.0f, 0.0f, 0.0f, m_isAlphaToCoverageCase ? (float)row / (float)(numQuadRowsCols-1) : 1.0f);
1320
1321			if (m_isSampleCoverageCase)
1322			{
1323				float value = (float)(row*numQuadRowsCols + col) / (float)(numQuadRowsCols*numQuadRowsCols-1);
1324				GLU_CHECK_CALL(glSampleCoverage(m_isInvertedSampleCoverageCase ? 1.0f - value : value, m_isInvertedSampleCoverageCase ? GL_TRUE : GL_FALSE));
1325			}
1326
1327			renderQuad(Vec2(x0, y0), Vec2(x1, y0), Vec2(x0, y1), Vec2(x1, y1), baseGreen + alpha0,	baseGreen + alpha1,	baseGreen + alpha0,	baseGreen + alpha1);
1328			renderQuad(Vec2(x0, y0), Vec2(x1, y0), Vec2(x0, y1), Vec2(x1, y1), baseRed + alpha0,	baseRed + alpha1,	baseRed + alpha0,	baseRed + alpha1);
1329		}
1330	}
1331
1332	readImage(renderedImg);
1333
1334	log << TestLog::Image("RenderedImage", "Rendered image", renderedImg, QP_IMAGE_COMPRESSION_MODE_PNG);
1335
1336	for (int y = 0; y < renderedImg.getHeight(); y++)
1337	for (int x = 0; x < renderedImg.getWidth(); x++)
1338	{
1339		if (renderedImg.getPixel(x, y).getGreen() > 0)
1340		{
1341			log << TestLog::Message << "Failure: Non-zero green color component detected - should have been completely overwritten by red quad" << TestLog::EndMessage;
1342			m_context.getTestContext().setTestResult(QP_TEST_RESULT_FAIL, "Failed");
1343			return STOP;
1344		}
1345	}
1346
1347	log << TestLog::Message
1348		<< "Success: Coverage mask appears to be constant at a given pixel coordinate with a given "
1349		<< (m_isAlphaToCoverageCase ? "alpha" : "")
1350		<< (m_isAlphaToCoverageCase && m_isSampleCoverageCase ? " and " : "")
1351		<< (m_isSampleCoverageCase ? "coverage value" : "")
1352		<< TestLog::EndMessage;
1353
1354	m_context.getTestContext().setTestResult(QP_TEST_RESULT_PASS, "Passed");
1355
1356	return STOP;
1357}
1358
1359/*--------------------------------------------------------------------*//*!
1360 * \brief Tests coverage mask inversion validity.
1361 *
1362 * Tests that the coverage masks obtained by glSampleCoverage(..., GL_TRUE)
1363 * and glSampleCoverage(..., GL_FALSE) are indeed each others' inverses.
1364 * This is done by drawing a pattern, with varying coverage values,
1365 * overlapped by a pattern that has inverted masks and is otherwise
1366 * identical. The resulting image is compared to one obtained by drawing
1367 * the same pattern but with all-ones coverage masks.
1368 *//*--------------------------------------------------------------------*/
1369class CoverageMaskInvertCase : public MultisampleCase
1370{
1371public:
1372					CoverageMaskInvertCase		(Context& context, const char* name, const char* description);
1373					~CoverageMaskInvertCase		(void) {}
1374
1375	IterateResult	iterate						(void);
1376
1377protected:
1378	int				getDesiredViewportSize		(void) const { return 256; }
1379
1380private:
1381	void			drawPattern					(bool invertSampleCoverage) const;
1382};
1383
1384CoverageMaskInvertCase::CoverageMaskInvertCase (Context& context, const char* name, const char* description)
1385	: MultisampleCase (context, name, description)
1386{
1387}
1388
1389void CoverageMaskInvertCase::drawPattern (bool invertSampleCoverage) const
1390{
1391	const int numTriangles = 25;
1392	for (int i = 0; i < numTriangles; i++)
1393	{
1394		GLU_CHECK_CALL(glSampleCoverage((float)i / (float)(numTriangles-1), invertSampleCoverage ? GL_TRUE : GL_FALSE));
1395
1396		float angle0 = 2.0f*DE_PI * (float)i			/ (float)numTriangles;
1397		float angle1 = 2.0f*DE_PI * (float)(i + 0.5f)	/ (float)numTriangles;
1398
1399		renderTriangle(Vec2(0.0f, 0.0f),
1400					   Vec2(deFloatCos(angle0)*0.95f, deFloatSin(angle0)*0.95f),
1401					   Vec2(deFloatCos(angle1)*0.95f, deFloatSin(angle1)*0.95f),
1402					   Vec4(0.4f + (float)i/(float)numTriangles*0.6f,
1403							0.5f + (float)i/(float)numTriangles*0.3f,
1404							0.6f - (float)i/(float)numTriangles*0.5f,
1405							0.7f - (float)i/(float)numTriangles*0.7f));
1406	}
1407}
1408
1409CoverageMaskInvertCase::IterateResult CoverageMaskInvertCase::iterate (void)
1410{
1411	TestLog&		log								= m_testCtx.getLog();
1412	tcu::Surface	renderedImgNoSampleCoverage		(m_viewportSize, m_viewportSize);
1413	tcu::Surface	renderedImgSampleCoverage		(m_viewportSize, m_viewportSize);
1414
1415	randomizeViewport();
1416
1417	GLU_CHECK_CALL(glEnable(GL_BLEND));
1418	GLU_CHECK_CALL(glBlendEquation(GL_FUNC_ADD));
1419	GLU_CHECK_CALL(glBlendFunc(GL_ONE, GL_ONE));
1420	log << TestLog::Message << "Additive blending enabled in order to detect (erroneously) overlapping samples" << TestLog::EndMessage;
1421
1422	log << TestLog::Message << "Clearing color to all-zeros" << TestLog::EndMessage;
1423	GLU_CHECK_CALL(glClearColor(0.0f, 0.0f, 0.0f, 0.0f));
1424	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
1425	log << TestLog::Message << "Drawing the pattern with GL_SAMPLE_COVERAGE disabled" << TestLog::EndMessage;
1426	drawPattern(false);
1427	readImage(renderedImgNoSampleCoverage);
1428
1429	log << TestLog::Image("RenderedImageNoSampleCoverage", "Rendered image with GL_SAMPLE_COVERAGE disabled", renderedImgNoSampleCoverage, QP_IMAGE_COMPRESSION_MODE_PNG);
1430
1431	log << TestLog::Message << "Clearing color to all-zeros" << TestLog::EndMessage;
1432	GLU_CHECK_CALL(glClear(GL_COLOR_BUFFER_BIT));
1433	GLU_CHECK_CALL(glEnable(GL_SAMPLE_COVERAGE));
1434	log << TestLog::Message << "Drawing the pattern with GL_SAMPLE_COVERAGE enabled, using non-inverted masks" << TestLog::EndMessage;
1435	drawPattern(false);
1436	log << TestLog::Message << "Drawing the pattern with GL_SAMPLE_COVERAGE enabled, using same sample coverage values but inverted masks" << TestLog::EndMessage;
1437	drawPattern(true);
1438	readImage(renderedImgSampleCoverage);
1439
1440	log << TestLog::Image("RenderedImageSampleCoverage", "Rendered image with GL_SAMPLE_COVERAGE enabled", renderedImgSampleCoverage, QP_IMAGE_COMPRESSION_MODE_PNG);
1441
1442	bool passed = tcu::pixelThresholdCompare(log,
1443											 "CoverageVsNoCoverage",
1444											 "Comparison of same pattern with GL_SAMPLE_COVERAGE disabled and enabled",
1445											 renderedImgNoSampleCoverage,
1446											 renderedImgSampleCoverage,
1447											 tcu::RGBA(0),
1448											 tcu::COMPARE_LOG_ON_ERROR);
1449
1450	if (passed)
1451		log << TestLog::Message << "Success: The two images rendered are identical" << TestLog::EndMessage;
1452
1453	m_context.getTestContext().setTestResult(passed ? QP_TEST_RESULT_PASS	: QP_TEST_RESULT_FAIL,
1454											 passed ? "Passed"				: "Failed");
1455
1456	return STOP;
1457}
1458
1459MultisampleTests::MultisampleTests (Context& context)
1460	: TestCaseGroup(context, "multisample", "Multisampling tests")
1461{
1462}
1463
1464MultisampleTests::~MultisampleTests (void)
1465{
1466}
1467
1468void MultisampleTests::init (void)
1469{
1470	addChild(new PolygonNumSamplesCase		(m_context, "num_samples_polygon",			"Test sanity of the value of GL_SAMPLES, with polygons"));
1471	addChild(new LineNumSamplesCase			(m_context, "num_samples_line",				"Test sanity of the value of GL_SAMPLES, with lines"));
1472	addChild(new CommonEdgeCase				(m_context, "common_edge_small_quads",		"Test polygons' common edges with small quads",						CommonEdgeCase::CASETYPE_SMALL_QUADS));
1473	addChild(new CommonEdgeCase				(m_context, "common_edge_big_quad",			"Test polygons' common edges with bigger-than-viewport quads",		CommonEdgeCase::CASETYPE_BIGGER_THAN_VIEWPORT_QUAD));
1474	addChild(new CommonEdgeCase				(m_context, "common_edge_viewport_quad",	"Test polygons' common edges with exactly viewport-sized quads",	CommonEdgeCase::CASETYPE_FIT_VIEWPORT_QUAD));
1475	addChild(new SampleDepthCase			(m_context, "depth",						"Test that depth values are per-sample"));
1476	addChild(new SampleStencilCase			(m_context, "stencil",						"Test that stencil values are per-sample"));
1477	addChild(new CoverageMaskInvertCase		(m_context, "sample_coverage_invert",		"Test that non-inverted and inverted sample coverage masks are each other's negations"));
1478
1479	addChild(new MaskProportionalityCase(m_context, "proportionality_alpha_to_coverage",			"Test the proportionality property of GL_SAMPLE_ALPHA_TO_COVERAGE",			MaskProportionalityCase::CASETYPE_ALPHA_TO_COVERAGE));
1480	addChild(new MaskProportionalityCase(m_context, "proportionality_sample_coverage",				"Test the proportionality property of GL_SAMPLE_COVERAGE",					MaskProportionalityCase::CASETYPE_SAMPLE_COVERAGE));
1481	addChild(new MaskProportionalityCase(m_context, "proportionality_sample_coverage_inverted",		"Test the proportionality property of inverted-mask GL_SAMPLE_COVERAGE",	MaskProportionalityCase::CASETYPE_SAMPLE_COVERAGE_INVERTED));
1482
1483	addChild(new MaskConstancyCase(m_context, "constancy_alpha_to_coverage",			"Test that coverage mask is constant at given coordinates with a given alpha or coverage value, using GL_SAMPLE_ALPHA_TO_COVERAGE",											MaskConstancyCase::CASETYPE_ALPHA_TO_COVERAGE));
1484	addChild(new MaskConstancyCase(m_context, "constancy_sample_coverage",				"Test that coverage mask is constant at given coordinates with a given alpha or coverage value, using GL_SAMPLE_COVERAGE",													MaskConstancyCase::CASETYPE_SAMPLE_COVERAGE));
1485	addChild(new MaskConstancyCase(m_context, "constancy_sample_coverage_inverted",		"Test that coverage mask is constant at given coordinates with a given alpha or coverage value, using inverted-mask GL_SAMPLE_COVERAGE",									MaskConstancyCase::CASETYPE_SAMPLE_COVERAGE_INVERTED));
1486	addChild(new MaskConstancyCase(m_context, "constancy_both",							"Test that coverage mask is constant at given coordinates with a given alpha or coverage value, using GL_SAMPLE_ALPHA_TO_COVERAGE and GL_SAMPLE_COVERAGE",					MaskConstancyCase::CASETYPE_BOTH));
1487	addChild(new MaskConstancyCase(m_context, "constancy_both_inverted",				"Test that coverage mask is constant at given coordinates with a given alpha or coverage value, using GL_SAMPLE_ALPHA_TO_COVERAGE and inverted-mask GL_SAMPLE_COVERAGE",	MaskConstancyCase::CASETYPE_BOTH_INVERTED));
1488}
1489
1490} // Functional
1491} // gles2
1492} // deqp
1493