Context.cpp revision 58ead9eca5847f06bf9c0455b2b85a1a7835dd13
1// Copyright 2016 The SwiftShader Authors. All Rights Reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//    http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// Context.cpp: Implements the es2::Context class, managing all GL state and performing
16// rendering operations. It is the GLES2 specific implementation of EGLContext.
17
18#include "Context.h"
19
20#include "main.h"
21#include "mathutil.h"
22#include "utilities.h"
23#include "ResourceManager.h"
24#include "Buffer.h"
25#include "Fence.h"
26#include "Framebuffer.h"
27#include "Program.h"
28#include "Query.h"
29#include "Renderbuffer.h"
30#include "Sampler.h"
31#include "Shader.h"
32#include "Texture.h"
33#include "TransformFeedback.h"
34#include "VertexArray.h"
35#include "VertexDataManager.h"
36#include "IndexDataManager.h"
37#include "libEGL/Display.h"
38#include "libEGL/Surface.h"
39#include "Common/Half.hpp"
40
41#include <EGL/eglext.h>
42
43namespace es2
44{
45Context::Context(egl::Display *display, const Context *shareContext, EGLint clientVersion)
46	: egl::Context(display), clientVersion(clientVersion)
47{
48	sw::Context *context = new sw::Context();
49	device = new es2::Device(context);
50
51	setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
52
53	mState.depthClearValue = 1.0f;
54	mState.stencilClearValue = 0;
55
56	mState.cullFaceEnabled = false;
57	mState.cullMode = GL_BACK;
58	mState.frontFace = GL_CCW;
59	mState.depthTestEnabled = false;
60	mState.depthFunc = GL_LESS;
61	mState.blendEnabled = false;
62	mState.sourceBlendRGB = GL_ONE;
63	mState.sourceBlendAlpha = GL_ONE;
64	mState.destBlendRGB = GL_ZERO;
65	mState.destBlendAlpha = GL_ZERO;
66	mState.blendEquationRGB = GL_FUNC_ADD;
67	mState.blendEquationAlpha = GL_FUNC_ADD;
68	mState.blendColor.red = 0;
69	mState.blendColor.green = 0;
70	mState.blendColor.blue = 0;
71	mState.blendColor.alpha = 0;
72	mState.stencilTestEnabled = false;
73	mState.stencilFunc = GL_ALWAYS;
74	mState.stencilRef = 0;
75	mState.stencilMask = 0xFFFFFFFFu;
76	mState.stencilWritemask = 0xFFFFFFFFu;
77	mState.stencilBackFunc = GL_ALWAYS;
78	mState.stencilBackRef = 0;
79	mState.stencilBackMask = 0xFFFFFFFFu;
80	mState.stencilBackWritemask = 0xFFFFFFFFu;
81	mState.stencilFail = GL_KEEP;
82	mState.stencilPassDepthFail = GL_KEEP;
83	mState.stencilPassDepthPass = GL_KEEP;
84	mState.stencilBackFail = GL_KEEP;
85	mState.stencilBackPassDepthFail = GL_KEEP;
86	mState.stencilBackPassDepthPass = GL_KEEP;
87	mState.polygonOffsetFillEnabled = false;
88	mState.polygonOffsetFactor = 0.0f;
89	mState.polygonOffsetUnits = 0.0f;
90	mState.sampleAlphaToCoverageEnabled = false;
91	mState.sampleCoverageEnabled = false;
92	mState.sampleCoverageValue = 1.0f;
93	mState.sampleCoverageInvert = false;
94	mState.scissorTestEnabled = false;
95	mState.ditherEnabled = true;
96	mState.primitiveRestartFixedIndexEnabled = false;
97	mState.rasterizerDiscardEnabled = false;
98	mState.generateMipmapHint = GL_DONT_CARE;
99	mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
100
101	mState.lineWidth = 1.0f;
102
103	mState.viewportX = 0;
104	mState.viewportY = 0;
105	mState.viewportWidth = 0;
106	mState.viewportHeight = 0;
107	mState.zNear = 0.0f;
108	mState.zFar = 1.0f;
109
110	mState.scissorX = 0;
111	mState.scissorY = 0;
112	mState.scissorWidth = 0;
113	mState.scissorHeight = 0;
114
115	mState.colorMaskRed = true;
116	mState.colorMaskGreen = true;
117	mState.colorMaskBlue = true;
118	mState.colorMaskAlpha = true;
119	mState.depthMask = true;
120
121	if(shareContext)
122	{
123		mResourceManager = shareContext->mResourceManager;
124		mResourceManager->addRef();
125	}
126	else
127	{
128		mResourceManager = new ResourceManager();
129	}
130
131	// [OpenGL ES 2.0.24] section 3.7 page 83:
132	// In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
133	// and cube map texture state vectors respectively associated with them.
134	// In order that access to these initial textures not be lost, they are treated as texture
135	// objects all of whose names are 0.
136
137	mTexture2DZero = new Texture2D(0);
138	mTexture3DZero = new Texture3D(0);
139	mTexture2DArrayZero = new Texture2DArray(0);
140	mTextureCubeMapZero = new TextureCubeMap(0);
141	mTextureExternalZero = new TextureExternal(0);
142
143	mState.activeSampler = 0;
144	bindVertexArray(0);
145	bindArrayBuffer(0);
146	bindElementArrayBuffer(0);
147	bindTextureCubeMap(0);
148	bindTexture2D(0);
149	bindReadFramebuffer(0);
150	bindDrawFramebuffer(0);
151	bindRenderbuffer(0);
152	bindGenericUniformBuffer(0);
153	bindTransformFeedback(0);
154
155	mState.currentProgram = 0;
156
157	mState.packAlignment = 4;
158	mState.unpackInfo.alignment = 4;
159	mState.packRowLength = 0;
160	mState.packImageHeight = 0;
161	mState.packSkipPixels = 0;
162	mState.packSkipRows = 0;
163	mState.packSkipImages = 0;
164	mState.unpackInfo.rowLength = 0;
165	mState.unpackInfo.imageHeight = 0;
166	mState.unpackInfo.skipPixels = 0;
167	mState.unpackInfo.skipRows = 0;
168	mState.unpackInfo.skipImages = 0;
169
170	mVertexDataManager = nullptr;
171	mIndexDataManager = nullptr;
172
173	mInvalidEnum = false;
174	mInvalidValue = false;
175	mInvalidOperation = false;
176	mOutOfMemory = false;
177	mInvalidFramebufferOperation = false;
178
179	mHasBeenCurrent = false;
180
181	markAllStateDirty();
182}
183
184Context::~Context()
185{
186	if(mState.currentProgram != 0)
187	{
188		Program *programObject = mResourceManager->getProgram(mState.currentProgram);
189		if(programObject)
190		{
191			programObject->release();
192		}
193		mState.currentProgram = 0;
194	}
195
196	while(!mFramebufferNameSpace.empty())
197	{
198		deleteFramebuffer(mFramebufferNameSpace.firstName());
199	}
200
201	while(!mFenceNameSpace.empty())
202	{
203		deleteFence(mFenceNameSpace.firstName());
204	}
205
206	while(!mQueryNameSpace.empty())
207	{
208		deleteQuery(mQueryNameSpace.firstName());
209	}
210
211	while(!mVertexArrayNameSpace.empty())
212	{
213		deleteVertexArray(mVertexArrayNameSpace.firstName());
214	}
215
216	while(!mTransformFeedbackNameSpace.empty())
217	{
218		deleteTransformFeedback(mTransformFeedbackNameSpace.firstName());
219	}
220
221	for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
222	{
223		for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
224		{
225			mState.samplerTexture[type][sampler] = nullptr;
226		}
227	}
228
229	for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
230	{
231		mState.vertexAttribute[i].mBoundBuffer = nullptr;
232	}
233
234	for(int i = 0; i < QUERY_TYPE_COUNT; i++)
235	{
236		mState.activeQuery[i] = nullptr;
237	}
238
239	mState.arrayBuffer = nullptr;
240	mState.copyReadBuffer = nullptr;
241	mState.copyWriteBuffer = nullptr;
242	mState.pixelPackBuffer = nullptr;
243	mState.pixelUnpackBuffer = nullptr;
244	mState.genericUniformBuffer = nullptr;
245	mState.renderbuffer = nullptr;
246
247	for(int i = 0; i < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++i)
248	{
249		mState.sampler[i] = nullptr;
250	}
251
252	mTexture2DZero = nullptr;
253	mTexture3DZero = nullptr;
254	mTexture2DArrayZero = nullptr;
255	mTextureCubeMapZero = nullptr;
256	mTextureExternalZero = nullptr;
257
258	delete mVertexDataManager;
259	delete mIndexDataManager;
260
261	mResourceManager->release();
262	delete device;
263}
264
265void Context::makeCurrent(egl::Surface *surface)
266{
267	if(!mHasBeenCurrent)
268	{
269		mVertexDataManager = new VertexDataManager(this);
270		mIndexDataManager = new IndexDataManager();
271
272		mState.viewportX = 0;
273		mState.viewportY = 0;
274		mState.viewportWidth = surface->getWidth();
275		mState.viewportHeight = surface->getHeight();
276
277		mState.scissorX = 0;
278		mState.scissorY = 0;
279		mState.scissorWidth = surface->getWidth();
280		mState.scissorHeight = surface->getHeight();
281
282		mHasBeenCurrent = true;
283	}
284
285	// Wrap the existing resources into GL objects and assign them to the '0' names
286	egl::Image *defaultRenderTarget = surface->getRenderTarget();
287	egl::Image *depthStencil = surface->getDepthStencil();
288
289	Colorbuffer *colorbufferZero = new Colorbuffer(defaultRenderTarget);
290	DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(depthStencil);
291	Framebuffer *framebufferZero = new DefaultFramebuffer(colorbufferZero, depthStencilbufferZero);
292
293	setFramebufferZero(framebufferZero);
294
295	if(defaultRenderTarget)
296	{
297		defaultRenderTarget->release();
298	}
299
300	if(depthStencil)
301	{
302		depthStencil->release();
303	}
304
305	markAllStateDirty();
306}
307
308EGLint Context::getClientVersion() const
309{
310	return clientVersion;
311}
312
313// This function will set all of the state-related dirty flags, so that all state is set during next pre-draw.
314void Context::markAllStateDirty()
315{
316	mAppliedProgramSerial = 0;
317
318	mDepthStateDirty = true;
319	mMaskStateDirty = true;
320	mBlendStateDirty = true;
321	mStencilStateDirty = true;
322	mPolygonOffsetStateDirty = true;
323	mSampleStateDirty = true;
324	mDitherStateDirty = true;
325	mFrontFaceDirty = true;
326}
327
328void Context::setClearColor(float red, float green, float blue, float alpha)
329{
330	mState.colorClearValue.red = red;
331	mState.colorClearValue.green = green;
332	mState.colorClearValue.blue = blue;
333	mState.colorClearValue.alpha = alpha;
334}
335
336void Context::setClearDepth(float depth)
337{
338	mState.depthClearValue = depth;
339}
340
341void Context::setClearStencil(int stencil)
342{
343	mState.stencilClearValue = stencil;
344}
345
346void Context::setCullFaceEnabled(bool enabled)
347{
348	mState.cullFaceEnabled = enabled;
349}
350
351bool Context::isCullFaceEnabled() const
352{
353	return mState.cullFaceEnabled;
354}
355
356void Context::setCullMode(GLenum mode)
357{
358   mState.cullMode = mode;
359}
360
361void Context::setFrontFace(GLenum front)
362{
363	if(mState.frontFace != front)
364	{
365		mState.frontFace = front;
366		mFrontFaceDirty = true;
367	}
368}
369
370void Context::setDepthTestEnabled(bool enabled)
371{
372	if(mState.depthTestEnabled != enabled)
373	{
374		mState.depthTestEnabled = enabled;
375		mDepthStateDirty = true;
376	}
377}
378
379bool Context::isDepthTestEnabled() const
380{
381	return mState.depthTestEnabled;
382}
383
384void Context::setDepthFunc(GLenum depthFunc)
385{
386	if(mState.depthFunc != depthFunc)
387	{
388		mState.depthFunc = depthFunc;
389		mDepthStateDirty = true;
390	}
391}
392
393void Context::setDepthRange(float zNear, float zFar)
394{
395	mState.zNear = zNear;
396	mState.zFar = zFar;
397}
398
399void Context::setBlendEnabled(bool enabled)
400{
401	if(mState.blendEnabled != enabled)
402	{
403		mState.blendEnabled = enabled;
404		mBlendStateDirty = true;
405	}
406}
407
408bool Context::isBlendEnabled() const
409{
410	return mState.blendEnabled;
411}
412
413void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
414{
415	if(mState.sourceBlendRGB != sourceRGB ||
416	   mState.sourceBlendAlpha != sourceAlpha ||
417	   mState.destBlendRGB != destRGB ||
418	   mState.destBlendAlpha != destAlpha)
419	{
420		mState.sourceBlendRGB = sourceRGB;
421		mState.destBlendRGB = destRGB;
422		mState.sourceBlendAlpha = sourceAlpha;
423		mState.destBlendAlpha = destAlpha;
424		mBlendStateDirty = true;
425	}
426}
427
428void Context::setBlendColor(float red, float green, float blue, float alpha)
429{
430	if(mState.blendColor.red != red ||
431	   mState.blendColor.green != green ||
432	   mState.blendColor.blue != blue ||
433	   mState.blendColor.alpha != alpha)
434	{
435		mState.blendColor.red = red;
436		mState.blendColor.green = green;
437		mState.blendColor.blue = blue;
438		mState.blendColor.alpha = alpha;
439		mBlendStateDirty = true;
440	}
441}
442
443void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
444{
445	if(mState.blendEquationRGB != rgbEquation ||
446	   mState.blendEquationAlpha != alphaEquation)
447	{
448		mState.blendEquationRGB = rgbEquation;
449		mState.blendEquationAlpha = alphaEquation;
450		mBlendStateDirty = true;
451	}
452}
453
454void Context::setStencilTestEnabled(bool enabled)
455{
456	if(mState.stencilTestEnabled != enabled)
457	{
458		mState.stencilTestEnabled = enabled;
459		mStencilStateDirty = true;
460	}
461}
462
463bool Context::isStencilTestEnabled() const
464{
465	return mState.stencilTestEnabled;
466}
467
468void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
469{
470	if(mState.stencilFunc != stencilFunc ||
471	   mState.stencilRef != stencilRef ||
472	   mState.stencilMask != stencilMask)
473	{
474		mState.stencilFunc = stencilFunc;
475		mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
476		mState.stencilMask = stencilMask;
477		mStencilStateDirty = true;
478	}
479}
480
481void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
482{
483	if(mState.stencilBackFunc != stencilBackFunc ||
484	   mState.stencilBackRef != stencilBackRef ||
485	   mState.stencilBackMask != stencilBackMask)
486	{
487		mState.stencilBackFunc = stencilBackFunc;
488		mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
489		mState.stencilBackMask = stencilBackMask;
490		mStencilStateDirty = true;
491	}
492}
493
494void Context::setStencilWritemask(GLuint stencilWritemask)
495{
496	if(mState.stencilWritemask != stencilWritemask)
497	{
498		mState.stencilWritemask = stencilWritemask;
499		mStencilStateDirty = true;
500	}
501}
502
503void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
504{
505	if(mState.stencilBackWritemask != stencilBackWritemask)
506	{
507		mState.stencilBackWritemask = stencilBackWritemask;
508		mStencilStateDirty = true;
509	}
510}
511
512void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
513{
514	if(mState.stencilFail != stencilFail ||
515	   mState.stencilPassDepthFail != stencilPassDepthFail ||
516	   mState.stencilPassDepthPass != stencilPassDepthPass)
517	{
518		mState.stencilFail = stencilFail;
519		mState.stencilPassDepthFail = stencilPassDepthFail;
520		mState.stencilPassDepthPass = stencilPassDepthPass;
521		mStencilStateDirty = true;
522	}
523}
524
525void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
526{
527	if(mState.stencilBackFail != stencilBackFail ||
528	   mState.stencilBackPassDepthFail != stencilBackPassDepthFail ||
529	   mState.stencilBackPassDepthPass != stencilBackPassDepthPass)
530	{
531		mState.stencilBackFail = stencilBackFail;
532		mState.stencilBackPassDepthFail = stencilBackPassDepthFail;
533		mState.stencilBackPassDepthPass = stencilBackPassDepthPass;
534		mStencilStateDirty = true;
535	}
536}
537
538void Context::setPolygonOffsetFillEnabled(bool enabled)
539{
540	if(mState.polygonOffsetFillEnabled != enabled)
541	{
542		mState.polygonOffsetFillEnabled = enabled;
543		mPolygonOffsetStateDirty = true;
544	}
545}
546
547bool Context::isPolygonOffsetFillEnabled() const
548{
549	return mState.polygonOffsetFillEnabled;
550}
551
552void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
553{
554	if(mState.polygonOffsetFactor != factor ||
555	   mState.polygonOffsetUnits != units)
556	{
557		mState.polygonOffsetFactor = factor;
558		mState.polygonOffsetUnits = units;
559		mPolygonOffsetStateDirty = true;
560	}
561}
562
563void Context::setSampleAlphaToCoverageEnabled(bool enabled)
564{
565	if(mState.sampleAlphaToCoverageEnabled != enabled)
566	{
567		mState.sampleAlphaToCoverageEnabled = enabled;
568		mSampleStateDirty = true;
569	}
570}
571
572bool Context::isSampleAlphaToCoverageEnabled() const
573{
574	return mState.sampleAlphaToCoverageEnabled;
575}
576
577void Context::setSampleCoverageEnabled(bool enabled)
578{
579	if(mState.sampleCoverageEnabled != enabled)
580	{
581		mState.sampleCoverageEnabled = enabled;
582		mSampleStateDirty = true;
583	}
584}
585
586bool Context::isSampleCoverageEnabled() const
587{
588	return mState.sampleCoverageEnabled;
589}
590
591void Context::setSampleCoverageParams(GLclampf value, bool invert)
592{
593	if(mState.sampleCoverageValue != value ||
594	   mState.sampleCoverageInvert != invert)
595	{
596		mState.sampleCoverageValue = value;
597		mState.sampleCoverageInvert = invert;
598		mSampleStateDirty = true;
599	}
600}
601
602void Context::setScissorTestEnabled(bool enabled)
603{
604	mState.scissorTestEnabled = enabled;
605}
606
607bool Context::isScissorTestEnabled() const
608{
609	return mState.scissorTestEnabled;
610}
611
612void Context::setDitherEnabled(bool enabled)
613{
614	if(mState.ditherEnabled != enabled)
615	{
616		mState.ditherEnabled = enabled;
617		mDitherStateDirty = true;
618	}
619}
620
621bool Context::isDitherEnabled() const
622{
623	return mState.ditherEnabled;
624}
625
626void Context::setPrimitiveRestartFixedIndexEnabled(bool enabled)
627{
628	UNIMPLEMENTED();
629	mState.primitiveRestartFixedIndexEnabled = enabled;
630}
631
632bool Context::isPrimitiveRestartFixedIndexEnabled() const
633{
634	return mState.primitiveRestartFixedIndexEnabled;
635}
636
637void Context::setRasterizerDiscardEnabled(bool enabled)
638{
639	mState.rasterizerDiscardEnabled = enabled;
640}
641
642bool Context::isRasterizerDiscardEnabled() const
643{
644	return mState.rasterizerDiscardEnabled;
645}
646
647void Context::setLineWidth(GLfloat width)
648{
649	mState.lineWidth = width;
650	device->setLineWidth(clamp(width, ALIASED_LINE_WIDTH_RANGE_MIN, ALIASED_LINE_WIDTH_RANGE_MAX));
651}
652
653void Context::setGenerateMipmapHint(GLenum hint)
654{
655	mState.generateMipmapHint = hint;
656}
657
658void Context::setFragmentShaderDerivativeHint(GLenum hint)
659{
660	mState.fragmentShaderDerivativeHint = hint;
661	// TODO: Propagate the hint to shader translator so we can write
662	// ddx, ddx_coarse, or ddx_fine depending on the hint.
663	// Ignore for now. It is valid for implementations to ignore hint.
664}
665
666void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
667{
668	mState.viewportX = x;
669	mState.viewportY = y;
670	mState.viewportWidth = width;
671	mState.viewportHeight = height;
672}
673
674void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
675{
676	mState.scissorX = x;
677	mState.scissorY = y;
678	mState.scissorWidth = width;
679	mState.scissorHeight = height;
680}
681
682void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
683{
684	if(mState.colorMaskRed != red || mState.colorMaskGreen != green ||
685	   mState.colorMaskBlue != blue || mState.colorMaskAlpha != alpha)
686	{
687		mState.colorMaskRed = red;
688		mState.colorMaskGreen = green;
689		mState.colorMaskBlue = blue;
690		mState.colorMaskAlpha = alpha;
691		mMaskStateDirty = true;
692	}
693}
694
695unsigned int Context::getColorMask() const
696{
697	return (mState.colorMaskRed ? 0x1 : 0) |
698	       (mState.colorMaskGreen ? 0x2 : 0) |
699	       (mState.colorMaskBlue ? 0x4 : 0) |
700	       (mState.colorMaskAlpha ? 0x8 : 0);
701}
702
703void Context::setDepthMask(bool mask)
704{
705	if(mState.depthMask != mask)
706	{
707		mState.depthMask = mask;
708		mMaskStateDirty = true;
709	}
710}
711
712void Context::setActiveSampler(unsigned int active)
713{
714	mState.activeSampler = active;
715}
716
717GLuint Context::getReadFramebufferName() const
718{
719	return mState.readFramebuffer;
720}
721
722GLuint Context::getDrawFramebufferName() const
723{
724	return mState.drawFramebuffer;
725}
726
727GLuint Context::getRenderbufferName() const
728{
729	return mState.renderbuffer.name();
730}
731
732void Context::setFramebufferReadBuffer(GLuint buf)
733{
734	getReadFramebuffer()->setReadBuffer(buf);
735}
736
737void Context::setFramebufferDrawBuffers(GLsizei n, const GLenum *bufs)
738{
739	Framebuffer *drawFramebuffer = getDrawFramebuffer();
740
741	for(int i = 0; i < MAX_COLOR_ATTACHMENTS; i++)
742	{
743		drawFramebuffer->setDrawBuffer(i, (i < n) ? bufs[i] : GL_NONE);
744	}
745}
746
747GLuint Context::getReadFramebufferColorIndex() const
748{
749	GLenum buf = getReadFramebuffer()->getReadBuffer();
750	switch(buf)
751	{
752	case GL_BACK:
753		return 0;
754	case GL_NONE:
755		return GL_INVALID_INDEX;
756	default:
757		return buf - GL_COLOR_ATTACHMENT0;
758}
759}
760
761GLuint Context::getArrayBufferName() const
762{
763	return mState.arrayBuffer.name();
764}
765
766GLuint Context::getElementArrayBufferName() const
767{
768	Buffer* elementArrayBuffer = getCurrentVertexArray()->getElementArrayBuffer();
769	return elementArrayBuffer ? elementArrayBuffer->name : 0;
770}
771
772GLuint Context::getActiveQuery(GLenum target) const
773{
774	Query *queryObject = nullptr;
775
776	switch(target)
777	{
778	case GL_ANY_SAMPLES_PASSED_EXT:
779		queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED];
780		break;
781	case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
782		queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE];
783		break;
784	case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
785		queryObject = mState.activeQuery[QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN];
786		break;
787	default:
788		ASSERT(false);
789	}
790
791	if(queryObject)
792	{
793		return queryObject->name;
794	}
795
796	return 0;
797}
798
799void Context::setVertexAttribArrayEnabled(unsigned int attribNum, bool enabled)
800{
801	getCurrentVertexArray()->enableAttribute(attribNum, enabled);
802}
803
804void Context::setVertexAttribDivisor(unsigned int attribNum, GLuint divisor)
805{
806	getCurrentVertexArray()->setVertexAttribDivisor(attribNum, divisor);
807}
808
809const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum) const
810{
811	return getCurrentVertexArray()->getVertexAttribute(attribNum);
812}
813
814void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
815                                   GLsizei stride, const void *pointer)
816{
817	getCurrentVertexArray()->setAttributeState(attribNum, boundBuffer, size, type, normalized, stride, pointer);
818}
819
820const void *Context::getVertexAttribPointer(unsigned int attribNum) const
821{
822	return getCurrentVertexArray()->getVertexAttribute(attribNum).mPointer;
823}
824
825const VertexAttributeArray &Context::getVertexArrayAttributes()
826{
827	return getCurrentVertexArray()->getVertexAttributes();
828}
829
830const VertexAttributeArray &Context::getCurrentVertexAttributes()
831{
832	return mState.vertexAttribute;
833}
834
835void Context::setPackAlignment(GLint alignment)
836{
837	mState.packAlignment = alignment;
838}
839
840void Context::setUnpackAlignment(GLint alignment)
841{
842	mState.unpackInfo.alignment = alignment;
843}
844
845const egl::Image::UnpackInfo& Context::getUnpackInfo() const
846{
847	return mState.unpackInfo;
848}
849
850void Context::setPackRowLength(GLint rowLength)
851{
852	mState.packRowLength = rowLength;
853}
854
855void Context::setPackImageHeight(GLint imageHeight)
856{
857	mState.packImageHeight = imageHeight;
858}
859
860void Context::setPackSkipPixels(GLint skipPixels)
861{
862	mState.packSkipPixels = skipPixels;
863}
864
865void Context::setPackSkipRows(GLint skipRows)
866{
867	mState.packSkipRows = skipRows;
868}
869
870void Context::setPackSkipImages(GLint skipImages)
871{
872	mState.packSkipImages = skipImages;
873}
874
875void Context::setUnpackRowLength(GLint rowLength)
876{
877	mState.unpackInfo.rowLength = rowLength;
878}
879
880void Context::setUnpackImageHeight(GLint imageHeight)
881{
882	mState.unpackInfo.imageHeight = imageHeight;
883}
884
885void Context::setUnpackSkipPixels(GLint skipPixels)
886{
887	mState.unpackInfo.skipPixels = skipPixels;
888}
889
890void Context::setUnpackSkipRows(GLint skipRows)
891{
892	mState.unpackInfo.skipRows = skipRows;
893}
894
895void Context::setUnpackSkipImages(GLint skipImages)
896{
897	mState.unpackInfo.skipImages = skipImages;
898}
899
900GLuint Context::createBuffer()
901{
902	return mResourceManager->createBuffer();
903}
904
905GLuint Context::createProgram()
906{
907	return mResourceManager->createProgram();
908}
909
910GLuint Context::createShader(GLenum type)
911{
912	return mResourceManager->createShader(type);
913}
914
915GLuint Context::createTexture()
916{
917	return mResourceManager->createTexture();
918}
919
920GLuint Context::createRenderbuffer()
921{
922	return mResourceManager->createRenderbuffer();
923}
924
925// Returns an unused framebuffer name
926GLuint Context::createFramebuffer()
927{
928	return mFramebufferNameSpace.allocate();
929}
930
931GLuint Context::createFence()
932{
933	return mFenceNameSpace.allocate(new Fence());
934}
935
936// Returns an unused query name
937GLuint Context::createQuery()
938{
939	return mQueryNameSpace.allocate();
940}
941
942// Returns an unused vertex array name
943GLuint Context::createVertexArray()
944{
945	return mVertexArrayNameSpace.allocate();
946}
947
948GLsync Context::createFenceSync(GLenum condition, GLbitfield flags)
949{
950	GLuint handle = mResourceManager->createFenceSync(condition, flags);
951
952	return reinterpret_cast<GLsync>(static_cast<uintptr_t>(handle));
953}
954
955// Returns an unused transform feedback name
956GLuint Context::createTransformFeedback()
957{
958	return mTransformFeedbackNameSpace.allocate();
959}
960
961// Returns an unused sampler name
962GLuint Context::createSampler()
963{
964	return mResourceManager->createSampler();
965}
966
967void Context::deleteBuffer(GLuint buffer)
968{
969	detachBuffer(buffer);
970
971	mResourceManager->deleteBuffer(buffer);
972}
973
974void Context::deleteShader(GLuint shader)
975{
976	mResourceManager->deleteShader(shader);
977}
978
979void Context::deleteProgram(GLuint program)
980{
981	mResourceManager->deleteProgram(program);
982}
983
984void Context::deleteTexture(GLuint texture)
985{
986	detachTexture(texture);
987
988	mResourceManager->deleteTexture(texture);
989}
990
991void Context::deleteRenderbuffer(GLuint renderbuffer)
992{
993	if(mResourceManager->getRenderbuffer(renderbuffer))
994	{
995		detachRenderbuffer(renderbuffer);
996	}
997
998	mResourceManager->deleteRenderbuffer(renderbuffer);
999}
1000
1001void Context::deleteFramebuffer(GLuint framebuffer)
1002{
1003	detachFramebuffer(framebuffer);
1004
1005	Framebuffer *framebufferObject = mFramebufferNameSpace.remove(framebuffer);
1006
1007	if(framebufferObject)
1008	{
1009		delete framebufferObject;
1010	}
1011}
1012
1013void Context::deleteFence(GLuint fence)
1014{
1015	Fence *fenceObject = mFenceNameSpace.remove(fence);
1016
1017	if(fenceObject)
1018	{
1019		delete fenceObject;
1020	}
1021}
1022
1023void Context::deleteQuery(GLuint query)
1024{
1025	Query *queryObject = mQueryNameSpace.remove(query);
1026
1027	if(queryObject)
1028	{
1029		queryObject->release();
1030	}
1031}
1032
1033void Context::deleteVertexArray(GLuint vertexArray)
1034{
1035	// [OpenGL ES 3.0.2] section 2.10 page 43:
1036	// If a vertex array object that is currently bound is deleted, the binding
1037	// for that object reverts to zero and the default vertex array becomes current.
1038	if(getCurrentVertexArray()->name == vertexArray)
1039	{
1040		bindVertexArray(0);
1041	}
1042
1043	VertexArray *vertexArrayObject = mVertexArrayNameSpace.remove(vertexArray);
1044
1045	if(vertexArrayObject)
1046	{
1047		delete vertexArrayObject;
1048	}
1049}
1050
1051void Context::deleteFenceSync(GLsync fenceSync)
1052{
1053	// The spec specifies the underlying Fence object is not deleted until all current
1054	// wait commands finish. However, since the name becomes invalid, we cannot query the fence,
1055	// and since our API is currently designed for being called from a single thread, we can delete
1056	// the fence immediately.
1057	mResourceManager->deleteFenceSync(static_cast<GLuint>(reinterpret_cast<uintptr_t>(fenceSync)));
1058}
1059
1060void Context::deleteTransformFeedback(GLuint transformFeedback)
1061{
1062	TransformFeedback *transformFeedbackObject = mTransformFeedbackNameSpace.remove(transformFeedback);
1063
1064	if(transformFeedbackObject)
1065	{
1066		delete transformFeedbackObject;
1067	}
1068}
1069
1070void Context::deleteSampler(GLuint sampler)
1071{
1072	detachSampler(sampler);
1073
1074	mResourceManager->deleteSampler(sampler);
1075}
1076
1077Buffer *Context::getBuffer(GLuint handle) const
1078{
1079	return mResourceManager->getBuffer(handle);
1080}
1081
1082Shader *Context::getShader(GLuint handle) const
1083{
1084	return mResourceManager->getShader(handle);
1085}
1086
1087Program *Context::getProgram(GLuint handle) const
1088{
1089	return mResourceManager->getProgram(handle);
1090}
1091
1092Texture *Context::getTexture(GLuint handle) const
1093{
1094	return mResourceManager->getTexture(handle);
1095}
1096
1097Renderbuffer *Context::getRenderbuffer(GLuint handle) const
1098{
1099	return mResourceManager->getRenderbuffer(handle);
1100}
1101
1102Framebuffer *Context::getReadFramebuffer() const
1103{
1104	return getFramebuffer(mState.readFramebuffer);
1105}
1106
1107Framebuffer *Context::getDrawFramebuffer() const
1108{
1109	return getFramebuffer(mState.drawFramebuffer);
1110}
1111
1112void Context::bindArrayBuffer(unsigned int buffer)
1113{
1114	mResourceManager->checkBufferAllocation(buffer);
1115
1116	mState.arrayBuffer = getBuffer(buffer);
1117}
1118
1119void Context::bindElementArrayBuffer(unsigned int buffer)
1120{
1121	mResourceManager->checkBufferAllocation(buffer);
1122
1123	getCurrentVertexArray()->setElementArrayBuffer(getBuffer(buffer));
1124}
1125
1126void Context::bindCopyReadBuffer(GLuint buffer)
1127{
1128	mResourceManager->checkBufferAllocation(buffer);
1129
1130	mState.copyReadBuffer = getBuffer(buffer);
1131}
1132
1133void Context::bindCopyWriteBuffer(GLuint buffer)
1134{
1135	mResourceManager->checkBufferAllocation(buffer);
1136
1137	mState.copyWriteBuffer = getBuffer(buffer);
1138}
1139
1140void Context::bindPixelPackBuffer(GLuint buffer)
1141{
1142	mResourceManager->checkBufferAllocation(buffer);
1143
1144	mState.pixelPackBuffer = getBuffer(buffer);
1145}
1146
1147void Context::bindPixelUnpackBuffer(GLuint buffer)
1148{
1149	mResourceManager->checkBufferAllocation(buffer);
1150
1151	mState.pixelUnpackBuffer = getBuffer(buffer);
1152}
1153
1154void Context::bindTransformFeedbackBuffer(GLuint buffer)
1155{
1156	mResourceManager->checkBufferAllocation(buffer);
1157
1158	TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1159
1160	if(transformFeedback)
1161	{
1162		transformFeedback->setGenericBuffer(getBuffer(buffer));
1163	}
1164}
1165
1166void Context::bindTexture2D(GLuint texture)
1167{
1168	mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
1169
1170	mState.samplerTexture[TEXTURE_2D][mState.activeSampler] = getTexture(texture);
1171}
1172
1173void Context::bindTextureCubeMap(GLuint texture)
1174{
1175	mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
1176
1177	mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler] = getTexture(texture);
1178}
1179
1180void Context::bindTextureExternal(GLuint texture)
1181{
1182	mResourceManager->checkTextureAllocation(texture, TEXTURE_EXTERNAL);
1183
1184	mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler] = getTexture(texture);
1185}
1186
1187void Context::bindTexture3D(GLuint texture)
1188{
1189	mResourceManager->checkTextureAllocation(texture, TEXTURE_3D);
1190
1191	mState.samplerTexture[TEXTURE_3D][mState.activeSampler] = getTexture(texture);
1192}
1193
1194void Context::bindTexture2DArray(GLuint texture)
1195{
1196	mResourceManager->checkTextureAllocation(texture, TEXTURE_2D_ARRAY);
1197
1198	mState.samplerTexture[TEXTURE_2D_ARRAY][mState.activeSampler] = getTexture(texture);
1199}
1200
1201void Context::bindReadFramebuffer(GLuint framebuffer)
1202{
1203	if(!getFramebuffer(framebuffer))
1204	{
1205		mFramebufferNameSpace.insert(framebuffer, new Framebuffer());
1206	}
1207
1208	mState.readFramebuffer = framebuffer;
1209}
1210
1211void Context::bindDrawFramebuffer(GLuint framebuffer)
1212{
1213	if(!getFramebuffer(framebuffer))
1214	{
1215		mFramebufferNameSpace.insert(framebuffer, new Framebuffer());
1216	}
1217
1218	mState.drawFramebuffer = framebuffer;
1219}
1220
1221void Context::bindRenderbuffer(GLuint renderbuffer)
1222{
1223	mResourceManager->checkRenderbufferAllocation(renderbuffer);
1224
1225	mState.renderbuffer = getRenderbuffer(renderbuffer);
1226}
1227
1228void Context::bindVertexArray(GLuint array)
1229{
1230	VertexArray *vertexArray = getVertexArray(array);
1231
1232	if(!vertexArray)
1233	{
1234		vertexArray = new VertexArray(array);
1235		mVertexArrayNameSpace.insert(array, vertexArray);
1236	}
1237
1238	mState.vertexArray = array;
1239}
1240
1241void Context::bindGenericUniformBuffer(GLuint buffer)
1242{
1243	mResourceManager->checkBufferAllocation(buffer);
1244
1245	mState.genericUniformBuffer = getBuffer(buffer);
1246}
1247
1248void Context::bindIndexedUniformBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1249{
1250	mResourceManager->checkBufferAllocation(buffer);
1251
1252	Buffer* bufferObject = getBuffer(buffer);
1253	mState.uniformBuffers[index].set(bufferObject, static_cast<int>(offset), static_cast<int>(size));
1254}
1255
1256void Context::bindGenericTransformFeedbackBuffer(GLuint buffer)
1257{
1258	mResourceManager->checkBufferAllocation(buffer);
1259
1260	getTransformFeedback()->setGenericBuffer(getBuffer(buffer));
1261}
1262
1263void Context::bindIndexedTransformFeedbackBuffer(GLuint buffer, GLuint index, GLintptr offset, GLsizeiptr size)
1264{
1265	mResourceManager->checkBufferAllocation(buffer);
1266
1267	Buffer* bufferObject = getBuffer(buffer);
1268	getTransformFeedback()->setBuffer(index, bufferObject, offset, size);
1269}
1270
1271void Context::bindTransformFeedback(GLuint id)
1272{
1273	if(!getTransformFeedback(id))
1274	{
1275		mTransformFeedbackNameSpace.insert(id, new TransformFeedback(id));
1276	}
1277
1278	mState.transformFeedback = id;
1279}
1280
1281bool Context::bindSampler(GLuint unit, GLuint sampler)
1282{
1283	mResourceManager->checkSamplerAllocation(sampler);
1284
1285	Sampler* samplerObject = getSampler(sampler);
1286
1287	mState.sampler[unit] = samplerObject;
1288
1289	return !!samplerObject;
1290}
1291
1292void Context::useProgram(GLuint program)
1293{
1294	GLuint priorProgram = mState.currentProgram;
1295	mState.currentProgram = program;               // Must switch before trying to delete, otherwise it only gets flagged.
1296
1297	if(priorProgram != program)
1298	{
1299		Program *newProgram = mResourceManager->getProgram(program);
1300		Program *oldProgram = mResourceManager->getProgram(priorProgram);
1301
1302		if(newProgram)
1303		{
1304			newProgram->addRef();
1305		}
1306
1307		if(oldProgram)
1308		{
1309			oldProgram->release();
1310		}
1311	}
1312}
1313
1314void Context::beginQuery(GLenum target, GLuint query)
1315{
1316	// From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1317	// of zero, if the active query object name for <target> is non-zero (for the
1318	// targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1319	// the active query for either target is non-zero), if <id> is the name of an
1320	// existing query object whose type does not match <target>, or if <id> is the
1321	// active query object name for any query type, the error INVALID_OPERATION is
1322	// generated.
1323
1324	// Ensure no other queries are active
1325	// NOTE: If other queries than occlusion are supported, we will need to check
1326	// separately that:
1327	//    a) The query ID passed is not the current active query for any target/type
1328	//    b) There are no active queries for the requested target (and in the case
1329	//       of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1330	//       no query may be active for either if glBeginQuery targets either.
1331	for(int i = 0; i < QUERY_TYPE_COUNT; i++)
1332	{
1333		if(mState.activeQuery[i])
1334		{
1335			return error(GL_INVALID_OPERATION);
1336		}
1337	}
1338
1339	QueryType qType;
1340	switch(target)
1341	{
1342	case GL_ANY_SAMPLES_PASSED_EXT:
1343		qType = QUERY_ANY_SAMPLES_PASSED;
1344		break;
1345	case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1346		qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1347		break;
1348	case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN:
1349		qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN;
1350		break;
1351	default:
1352		UNREACHABLE(target);
1353		return error(GL_INVALID_ENUM);
1354	}
1355
1356	Query *queryObject = createQuery(query, target);
1357
1358	// Check that name was obtained with glGenQueries
1359	if(!queryObject)
1360	{
1361		return error(GL_INVALID_OPERATION);
1362	}
1363
1364	// Check for type mismatch
1365	if(queryObject->getType() != target)
1366	{
1367		return error(GL_INVALID_OPERATION);
1368	}
1369
1370	// Set query as active for specified target
1371	mState.activeQuery[qType] = queryObject;
1372
1373	// Begin query
1374	queryObject->begin();
1375}
1376
1377void Context::endQuery(GLenum target)
1378{
1379	QueryType qType;
1380
1381	switch(target)
1382	{
1383	case GL_ANY_SAMPLES_PASSED_EXT:                qType = QUERY_ANY_SAMPLES_PASSED;                    break;
1384	case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:   qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;       break;
1385	case GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN: qType = QUERY_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN; break;
1386	default: UNREACHABLE(target); return;
1387	}
1388
1389	Query *queryObject = mState.activeQuery[qType];
1390
1391	if(!queryObject)
1392	{
1393		return error(GL_INVALID_OPERATION);
1394	}
1395
1396	queryObject->end();
1397
1398	mState.activeQuery[qType] = nullptr;
1399}
1400
1401void Context::setFramebufferZero(Framebuffer *buffer)
1402{
1403	delete mFramebufferNameSpace.remove(0);
1404	mFramebufferNameSpace.insert(0, buffer);
1405}
1406
1407void Context::setRenderbufferStorage(RenderbufferStorage *renderbuffer)
1408{
1409	Renderbuffer *renderbufferObject = mState.renderbuffer;
1410	renderbufferObject->setStorage(renderbuffer);
1411}
1412
1413Framebuffer *Context::getFramebuffer(unsigned int handle) const
1414{
1415	return mFramebufferNameSpace.find(handle);
1416}
1417
1418Fence *Context::getFence(unsigned int handle) const
1419{
1420	return mFenceNameSpace.find(handle);
1421}
1422
1423FenceSync *Context::getFenceSync(GLsync handle) const
1424{
1425	return mResourceManager->getFenceSync(static_cast<GLuint>(reinterpret_cast<uintptr_t>(handle)));
1426}
1427
1428Query *Context::getQuery(unsigned int handle) const
1429{
1430	return mQueryNameSpace.find(handle);
1431}
1432
1433Query *Context::createQuery(unsigned int handle, GLenum type)
1434{
1435	if(!mQueryNameSpace.isReserved(handle))
1436	{
1437		return nullptr;
1438	}
1439	else
1440	{
1441		Query *query = mQueryNameSpace.find(handle);
1442		if(!query)
1443		{
1444			query = new Query(handle, type);
1445			query->addRef();
1446			mQueryNameSpace.insert(handle, query);
1447		}
1448
1449		return query;
1450	}
1451}
1452
1453VertexArray *Context::getVertexArray(GLuint array) const
1454{
1455	return mVertexArrayNameSpace.find(array);
1456}
1457
1458VertexArray *Context::getCurrentVertexArray() const
1459{
1460	return getVertexArray(mState.vertexArray);
1461}
1462
1463bool Context::isVertexArray(GLuint array) const
1464{
1465	return mVertexArrayNameSpace.isReserved(array);
1466}
1467
1468bool Context::hasZeroDivisor() const
1469{
1470	// Verify there is at least one active attribute with a divisor of zero
1471	es2::Program *programObject = getCurrentProgram();
1472	for(int attributeIndex = 0; attributeIndex < MAX_VERTEX_ATTRIBS; attributeIndex++)
1473	{
1474		bool active = (programObject->getAttributeStream(attributeIndex) != -1);
1475		if(active && getCurrentVertexArray()->getVertexAttribute(attributeIndex).mDivisor == 0)
1476		{
1477			return true;
1478		}
1479	}
1480
1481	return false;
1482}
1483
1484TransformFeedback *Context::getTransformFeedback(GLuint transformFeedback) const
1485{
1486	return mTransformFeedbackNameSpace.find(transformFeedback);
1487}
1488
1489Sampler *Context::getSampler(GLuint sampler) const
1490{
1491	return mResourceManager->getSampler(sampler);
1492}
1493
1494bool Context::isSampler(GLuint sampler) const
1495{
1496	return mResourceManager->isSampler(sampler);
1497}
1498
1499Buffer *Context::getArrayBuffer() const
1500{
1501	return mState.arrayBuffer;
1502}
1503
1504Buffer *Context::getElementArrayBuffer() const
1505{
1506	return getCurrentVertexArray()->getElementArrayBuffer();
1507}
1508
1509Buffer *Context::getCopyReadBuffer() const
1510{
1511	return mState.copyReadBuffer;
1512}
1513
1514Buffer *Context::getCopyWriteBuffer() const
1515{
1516	return mState.copyWriteBuffer;
1517}
1518
1519Buffer *Context::getPixelPackBuffer() const
1520{
1521	return mState.pixelPackBuffer;
1522}
1523
1524Buffer *Context::getPixelUnpackBuffer() const
1525{
1526	return mState.pixelUnpackBuffer;
1527}
1528
1529Buffer *Context::getGenericUniformBuffer() const
1530{
1531	return mState.genericUniformBuffer;
1532}
1533
1534const GLvoid* Context::getPixels(const GLvoid* data) const
1535{
1536	es2::Buffer* unpackBuffer = getPixelUnpackBuffer();
1537	const unsigned char* unpackBufferData = unpackBuffer ? static_cast<const unsigned char*>(unpackBuffer->data()) : nullptr;
1538	return unpackBufferData ? unpackBufferData + (ptrdiff_t)(data) : data;
1539}
1540
1541bool Context::getBuffer(GLenum target, es2::Buffer **buffer) const
1542{
1543	switch(target)
1544	{
1545	case GL_ARRAY_BUFFER:
1546		*buffer = getArrayBuffer();
1547		break;
1548	case GL_ELEMENT_ARRAY_BUFFER:
1549		*buffer = getElementArrayBuffer();
1550		break;
1551	case GL_COPY_READ_BUFFER:
1552		if(clientVersion >= 3)
1553		{
1554			*buffer = getCopyReadBuffer();
1555			break;
1556		}
1557		else return false;
1558	case GL_COPY_WRITE_BUFFER:
1559		if(clientVersion >= 3)
1560		{
1561			*buffer = getCopyWriteBuffer();
1562			break;
1563		}
1564		else return false;
1565	case GL_PIXEL_PACK_BUFFER:
1566		if(clientVersion >= 3)
1567		{
1568			*buffer = getPixelPackBuffer();
1569			break;
1570		}
1571		else return false;
1572	case GL_PIXEL_UNPACK_BUFFER:
1573		if(clientVersion >= 3)
1574		{
1575			*buffer = getPixelUnpackBuffer();
1576			break;
1577		}
1578		else return false;
1579	case GL_TRANSFORM_FEEDBACK_BUFFER:
1580		if(clientVersion >= 3)
1581		{
1582			TransformFeedback* transformFeedback = getTransformFeedback();
1583			*buffer = transformFeedback ? static_cast<es2::Buffer*>(transformFeedback->getGenericBuffer()) : nullptr;
1584			break;
1585		}
1586		else return false;
1587	case GL_UNIFORM_BUFFER:
1588		if(clientVersion >= 3)
1589		{
1590			*buffer = getGenericUniformBuffer();
1591			break;
1592		}
1593		else return false;
1594	default:
1595		return false;
1596	}
1597	return true;
1598}
1599
1600TransformFeedback *Context::getTransformFeedback() const
1601{
1602	return getTransformFeedback(mState.transformFeedback);
1603}
1604
1605Program *Context::getCurrentProgram() const
1606{
1607	return mResourceManager->getProgram(mState.currentProgram);
1608}
1609
1610Texture2D *Context::getTexture2D() const
1611{
1612	return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1613}
1614
1615Texture3D *Context::getTexture3D() const
1616{
1617	return static_cast<Texture3D*>(getSamplerTexture(mState.activeSampler, TEXTURE_3D));
1618}
1619
1620Texture2DArray *Context::getTexture2DArray() const
1621{
1622	return static_cast<Texture2DArray*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D_ARRAY));
1623}
1624
1625TextureCubeMap *Context::getTextureCubeMap() const
1626{
1627	return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1628}
1629
1630TextureExternal *Context::getTextureExternal() const
1631{
1632	return static_cast<TextureExternal*>(getSamplerTexture(mState.activeSampler, TEXTURE_EXTERNAL));
1633}
1634
1635Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type) const
1636{
1637	GLuint texid = mState.samplerTexture[type][sampler].name();
1638
1639	if(texid == 0)   // Special case: 0 refers to different initial textures based on the target
1640	{
1641		switch(type)
1642		{
1643		case TEXTURE_2D: return mTexture2DZero;
1644		case TEXTURE_3D: return mTexture3DZero;
1645		case TEXTURE_2D_ARRAY: return mTexture2DArrayZero;
1646		case TEXTURE_CUBE: return mTextureCubeMapZero;
1647		case TEXTURE_EXTERNAL: return mTextureExternalZero;
1648		default: UNREACHABLE(type);
1649		}
1650	}
1651
1652	return mState.samplerTexture[type][sampler];
1653}
1654
1655void Context::samplerParameteri(GLuint sampler, GLenum pname, GLint param)
1656{
1657	mResourceManager->checkSamplerAllocation(sampler);
1658
1659	Sampler *samplerObject = getSampler(sampler);
1660	ASSERT(samplerObject);
1661
1662	switch(pname)
1663	{
1664	case GL_TEXTURE_MIN_FILTER:    samplerObject->setMinFilter(static_cast<GLenum>(param));       break;
1665	case GL_TEXTURE_MAG_FILTER:    samplerObject->setMagFilter(static_cast<GLenum>(param));       break;
1666	case GL_TEXTURE_WRAP_S:        samplerObject->setWrapS(static_cast<GLenum>(param));           break;
1667	case GL_TEXTURE_WRAP_T:        samplerObject->setWrapT(static_cast<GLenum>(param));           break;
1668	case GL_TEXTURE_WRAP_R:        samplerObject->setWrapR(static_cast<GLenum>(param));           break;
1669	case GL_TEXTURE_MIN_LOD:       samplerObject->setMinLod(static_cast<GLfloat>(param));         break;
1670	case GL_TEXTURE_MAX_LOD:       samplerObject->setMaxLod(static_cast<GLfloat>(param));         break;
1671	case GL_TEXTURE_COMPARE_MODE:  samplerObject->setComparisonMode(static_cast<GLenum>(param));  break;
1672	case GL_TEXTURE_COMPARE_FUNC:  samplerObject->setComparisonFunc(static_cast<GLenum>(param));  break;
1673	default:                       UNREACHABLE(pname); break;
1674	}
1675}
1676
1677void Context::samplerParameterf(GLuint sampler, GLenum pname, GLfloat param)
1678{
1679	mResourceManager->checkSamplerAllocation(sampler);
1680
1681	Sampler *samplerObject = getSampler(sampler);
1682	ASSERT(samplerObject);
1683
1684	switch(pname)
1685	{
1686	case GL_TEXTURE_MIN_FILTER:    samplerObject->setMinFilter(static_cast<GLenum>(roundf(param)));       break;
1687	case GL_TEXTURE_MAG_FILTER:    samplerObject->setMagFilter(static_cast<GLenum>(roundf(param)));       break;
1688	case GL_TEXTURE_WRAP_S:        samplerObject->setWrapS(static_cast<GLenum>(roundf(param)));           break;
1689	case GL_TEXTURE_WRAP_T:        samplerObject->setWrapT(static_cast<GLenum>(roundf(param)));           break;
1690	case GL_TEXTURE_WRAP_R:        samplerObject->setWrapR(static_cast<GLenum>(roundf(param)));           break;
1691	case GL_TEXTURE_MIN_LOD:       samplerObject->setMinLod(param);                                       break;
1692	case GL_TEXTURE_MAX_LOD:       samplerObject->setMaxLod(param);                                       break;
1693	case GL_TEXTURE_COMPARE_MODE:  samplerObject->setComparisonMode(static_cast<GLenum>(roundf(param)));  break;
1694	case GL_TEXTURE_COMPARE_FUNC:  samplerObject->setComparisonFunc(static_cast<GLenum>(roundf(param)));  break;
1695	default:                       UNREACHABLE(pname); break;
1696	}
1697}
1698
1699GLint Context::getSamplerParameteri(GLuint sampler, GLenum pname)
1700{
1701	mResourceManager->checkSamplerAllocation(sampler);
1702
1703	Sampler *samplerObject = getSampler(sampler);
1704	ASSERT(samplerObject);
1705
1706	switch(pname)
1707	{
1708	case GL_TEXTURE_MIN_FILTER:    return static_cast<GLint>(samplerObject->getMinFilter());
1709	case GL_TEXTURE_MAG_FILTER:    return static_cast<GLint>(samplerObject->getMagFilter());
1710	case GL_TEXTURE_WRAP_S:        return static_cast<GLint>(samplerObject->getWrapS());
1711	case GL_TEXTURE_WRAP_T:        return static_cast<GLint>(samplerObject->getWrapT());
1712	case GL_TEXTURE_WRAP_R:        return static_cast<GLint>(samplerObject->getWrapR());
1713	case GL_TEXTURE_MIN_LOD:       return static_cast<GLint>(roundf(samplerObject->getMinLod()));
1714	case GL_TEXTURE_MAX_LOD:       return static_cast<GLint>(roundf(samplerObject->getMaxLod()));
1715	case GL_TEXTURE_COMPARE_MODE:  return static_cast<GLint>(samplerObject->getComparisonMode());
1716	case GL_TEXTURE_COMPARE_FUNC:  return static_cast<GLint>(samplerObject->getComparisonFunc());
1717	default:                       UNREACHABLE(pname); return 0;
1718	}
1719}
1720
1721GLfloat Context::getSamplerParameterf(GLuint sampler, GLenum pname)
1722{
1723	mResourceManager->checkSamplerAllocation(sampler);
1724
1725	Sampler *samplerObject = getSampler(sampler);
1726	ASSERT(samplerObject);
1727
1728	switch(pname)
1729	{
1730	case GL_TEXTURE_MIN_FILTER:    return static_cast<GLfloat>(samplerObject->getMinFilter());
1731	case GL_TEXTURE_MAG_FILTER:    return static_cast<GLfloat>(samplerObject->getMagFilter());
1732	case GL_TEXTURE_WRAP_S:        return static_cast<GLfloat>(samplerObject->getWrapS());
1733	case GL_TEXTURE_WRAP_T:        return static_cast<GLfloat>(samplerObject->getWrapT());
1734	case GL_TEXTURE_WRAP_R:        return static_cast<GLfloat>(samplerObject->getWrapR());
1735	case GL_TEXTURE_MIN_LOD:       return samplerObject->getMinLod();
1736	case GL_TEXTURE_MAX_LOD:       return samplerObject->getMaxLod();
1737	case GL_TEXTURE_COMPARE_MODE:  return static_cast<GLfloat>(samplerObject->getComparisonMode());
1738	case GL_TEXTURE_COMPARE_FUNC:  return static_cast<GLfloat>(samplerObject->getComparisonFunc());
1739	default:                       UNREACHABLE(pname); return 0;
1740	}
1741}
1742
1743bool Context::getBooleanv(GLenum pname, GLboolean *params) const
1744{
1745	switch(pname)
1746	{
1747	case GL_SHADER_COMPILER:          *params = GL_TRUE;                          break;
1748	case GL_SAMPLE_COVERAGE_INVERT:   *params = mState.sampleCoverageInvert;      break;
1749	case GL_DEPTH_WRITEMASK:          *params = mState.depthMask;                 break;
1750	case GL_COLOR_WRITEMASK:
1751		params[0] = mState.colorMaskRed;
1752		params[1] = mState.colorMaskGreen;
1753		params[2] = mState.colorMaskBlue;
1754		params[3] = mState.colorMaskAlpha;
1755		break;
1756	case GL_CULL_FACE:                *params = mState.cullFaceEnabled;                  break;
1757	case GL_POLYGON_OFFSET_FILL:      *params = mState.polygonOffsetFillEnabled;         break;
1758	case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverageEnabled;     break;
1759	case GL_SAMPLE_COVERAGE:          *params = mState.sampleCoverageEnabled;            break;
1760	case GL_SCISSOR_TEST:             *params = mState.scissorTestEnabled;               break;
1761	case GL_STENCIL_TEST:             *params = mState.stencilTestEnabled;               break;
1762	case GL_DEPTH_TEST:               *params = mState.depthTestEnabled;                 break;
1763	case GL_BLEND:                    *params = mState.blendEnabled;                     break;
1764	case GL_DITHER:                   *params = mState.ditherEnabled;                    break;
1765	case GL_PRIMITIVE_RESTART_FIXED_INDEX: *params = mState.primitiveRestartFixedIndexEnabled; break;
1766	case GL_RASTERIZER_DISCARD:       *params = mState.rasterizerDiscardEnabled;         break;
1767	case GL_TRANSFORM_FEEDBACK_ACTIVE:
1768		{
1769			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1770			if(transformFeedback)
1771			{
1772				*params = transformFeedback->isActive();
1773				break;
1774			}
1775			else return false;
1776		}
1777	 case GL_TRANSFORM_FEEDBACK_PAUSED:
1778		{
1779			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
1780			if(transformFeedback)
1781			{
1782				*params = transformFeedback->isPaused();
1783				break;
1784			}
1785			else return false;
1786		}
1787	default:
1788		return false;
1789	}
1790
1791	return true;
1792}
1793
1794bool Context::getFloatv(GLenum pname, GLfloat *params) const
1795{
1796	// Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1797	// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1798	// GetIntegerv as its native query function. As it would require conversion in any
1799	// case, this should make no difference to the calling application.
1800	switch(pname)
1801	{
1802	case GL_LINE_WIDTH:               *params = mState.lineWidth;            break;
1803	case GL_SAMPLE_COVERAGE_VALUE:    *params = mState.sampleCoverageValue;  break;
1804	case GL_DEPTH_CLEAR_VALUE:        *params = mState.depthClearValue;      break;
1805	case GL_POLYGON_OFFSET_FACTOR:    *params = mState.polygonOffsetFactor;  break;
1806	case GL_POLYGON_OFFSET_UNITS:     *params = mState.polygonOffsetUnits;   break;
1807	case GL_ALIASED_LINE_WIDTH_RANGE:
1808		params[0] = ALIASED_LINE_WIDTH_RANGE_MIN;
1809		params[1] = ALIASED_LINE_WIDTH_RANGE_MAX;
1810		break;
1811	case GL_ALIASED_POINT_SIZE_RANGE:
1812		params[0] = ALIASED_POINT_SIZE_RANGE_MIN;
1813		params[1] = ALIASED_POINT_SIZE_RANGE_MAX;
1814		break;
1815	case GL_DEPTH_RANGE:
1816		params[0] = mState.zNear;
1817		params[1] = mState.zFar;
1818		break;
1819	case GL_COLOR_CLEAR_VALUE:
1820		params[0] = mState.colorClearValue.red;
1821		params[1] = mState.colorClearValue.green;
1822		params[2] = mState.colorClearValue.blue;
1823		params[3] = mState.colorClearValue.alpha;
1824		break;
1825	case GL_BLEND_COLOR:
1826		params[0] = mState.blendColor.red;
1827		params[1] = mState.blendColor.green;
1828		params[2] = mState.blendColor.blue;
1829		params[3] = mState.blendColor.alpha;
1830		break;
1831	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1832		*params = MAX_TEXTURE_MAX_ANISOTROPY;
1833		break;
1834	default:
1835		return false;
1836	}
1837
1838	return true;
1839}
1840
1841template bool Context::getIntegerv<GLint>(GLenum pname, GLint *params) const;
1842template bool Context::getIntegerv<GLint64>(GLenum pname, GLint64 *params) const;
1843
1844template<typename T> bool Context::getIntegerv(GLenum pname, T *params) const
1845{
1846	// Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1847	// because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1848	// GetIntegerv as its native query function. As it would require conversion in any
1849	// case, this should make no difference to the calling application. You may find it in
1850	// Context::getFloatv.
1851	switch(pname)
1852	{
1853	case GL_MAX_VERTEX_ATTRIBS:               *params = MAX_VERTEX_ATTRIBS;               break;
1854	case GL_MAX_VERTEX_UNIFORM_VECTORS:       *params = MAX_VERTEX_UNIFORM_VECTORS;       break;
1855	case GL_MAX_VARYING_VECTORS:              *params = MAX_VARYING_VECTORS;              break;
1856	case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = MAX_COMBINED_TEXTURE_IMAGE_UNITS; break;
1857	case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:   *params = MAX_VERTEX_TEXTURE_IMAGE_UNITS;   break;
1858	case GL_MAX_TEXTURE_IMAGE_UNITS:          *params = MAX_TEXTURE_IMAGE_UNITS;          break;
1859	case GL_MAX_FRAGMENT_UNIFORM_VECTORS:     *params = MAX_FRAGMENT_UNIFORM_VECTORS;     break;
1860	case GL_MAX_RENDERBUFFER_SIZE:            *params = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE; break;
1861	case GL_NUM_SHADER_BINARY_FORMATS:        *params = 0;                                    break;
1862	case GL_SHADER_BINARY_FORMATS:      /* no shader binary formats are supported */          break;
1863	case GL_ARRAY_BUFFER_BINDING:             *params = getArrayBufferName();                 break;
1864	case GL_ELEMENT_ARRAY_BUFFER_BINDING:     *params = getElementArrayBufferName();          break;
1865//	case GL_FRAMEBUFFER_BINDING:            // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1866	case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE:   *params = mState.drawFramebuffer;               break;
1867	case GL_READ_FRAMEBUFFER_BINDING_ANGLE:   *params = mState.readFramebuffer;               break;
1868	case GL_RENDERBUFFER_BINDING:             *params = mState.renderbuffer.name();           break;
1869	case GL_CURRENT_PROGRAM:                  *params = mState.currentProgram;                break;
1870	case GL_PACK_ALIGNMENT:                   *params = mState.packAlignment;                 break;
1871	case GL_UNPACK_ALIGNMENT:                 *params = mState.unpackInfo.alignment;          break;
1872	case GL_GENERATE_MIPMAP_HINT:             *params = mState.generateMipmapHint;            break;
1873	case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
1874	case GL_ACTIVE_TEXTURE:                   *params = (mState.activeSampler + GL_TEXTURE0); break;
1875	case GL_STENCIL_FUNC:                     *params = mState.stencilFunc;                   break;
1876	case GL_STENCIL_REF:                      *params = mState.stencilRef;                    break;
1877	case GL_STENCIL_VALUE_MASK:               *params = sw::clampToSignedInt(mState.stencilMask); break;
1878	case GL_STENCIL_BACK_FUNC:                *params = mState.stencilBackFunc;               break;
1879	case GL_STENCIL_BACK_REF:                 *params = mState.stencilBackRef;                break;
1880	case GL_STENCIL_BACK_VALUE_MASK:          *params = sw::clampToSignedInt(mState.stencilBackMask); break;
1881	case GL_STENCIL_FAIL:                     *params = mState.stencilFail;                   break;
1882	case GL_STENCIL_PASS_DEPTH_FAIL:          *params = mState.stencilPassDepthFail;          break;
1883	case GL_STENCIL_PASS_DEPTH_PASS:          *params = mState.stencilPassDepthPass;          break;
1884	case GL_STENCIL_BACK_FAIL:                *params = mState.stencilBackFail;               break;
1885	case GL_STENCIL_BACK_PASS_DEPTH_FAIL:     *params = mState.stencilBackPassDepthFail;      break;
1886	case GL_STENCIL_BACK_PASS_DEPTH_PASS:     *params = mState.stencilBackPassDepthPass;      break;
1887	case GL_DEPTH_FUNC:                       *params = mState.depthFunc;                     break;
1888	case GL_BLEND_SRC_RGB:                    *params = mState.sourceBlendRGB;                break;
1889	case GL_BLEND_SRC_ALPHA:                  *params = mState.sourceBlendAlpha;              break;
1890	case GL_BLEND_DST_RGB:                    *params = mState.destBlendRGB;                  break;
1891	case GL_BLEND_DST_ALPHA:                  *params = mState.destBlendAlpha;                break;
1892	case GL_BLEND_EQUATION_RGB:               *params = mState.blendEquationRGB;              break;
1893	case GL_BLEND_EQUATION_ALPHA:             *params = mState.blendEquationAlpha;            break;
1894	case GL_STENCIL_WRITEMASK:                *params = sw::clampToSignedInt(mState.stencilWritemask); break;
1895	case GL_STENCIL_BACK_WRITEMASK:           *params = sw::clampToSignedInt(mState.stencilBackWritemask); break;
1896	case GL_STENCIL_CLEAR_VALUE:              *params = mState.stencilClearValue;             break;
1897	case GL_SUBPIXEL_BITS:                    *params = 4;                                    break;
1898	case GL_MAX_TEXTURE_SIZE:                 *params = IMPLEMENTATION_MAX_TEXTURE_SIZE;          break;
1899	case GL_MAX_CUBE_MAP_TEXTURE_SIZE:        *params = IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE; break;
1900	case GL_NUM_COMPRESSED_TEXTURE_FORMATS:   *params = NUM_COMPRESSED_TEXTURE_FORMATS;           break;
1901	case GL_MAX_SAMPLES_ANGLE:                *params = IMPLEMENTATION_MAX_SAMPLES;               break;
1902	case GL_SAMPLE_BUFFERS:
1903	case GL_SAMPLES:
1904		{
1905			Framebuffer *framebuffer = getDrawFramebuffer();
1906			int width, height, samples;
1907
1908			if(framebuffer->completeness(width, height, samples) == GL_FRAMEBUFFER_COMPLETE)
1909			{
1910				switch(pname)
1911				{
1912				case GL_SAMPLE_BUFFERS:
1913					if(samples > 1)
1914					{
1915						*params = 1;
1916					}
1917					else
1918					{
1919						*params = 0;
1920					}
1921					break;
1922				case GL_SAMPLES:
1923					*params = samples;
1924					break;
1925				}
1926			}
1927			else
1928			{
1929				*params = 0;
1930			}
1931		}
1932		break;
1933	case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1934		{
1935			Framebuffer *framebuffer = getReadFramebuffer();
1936			*params = framebuffer->getImplementationColorReadType();
1937		}
1938		break;
1939	case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1940		{
1941			Framebuffer *framebuffer = getReadFramebuffer();
1942			*params = framebuffer->getImplementationColorReadFormat();
1943		}
1944		break;
1945	case GL_MAX_VIEWPORT_DIMS:
1946		{
1947			int maxDimension = IMPLEMENTATION_MAX_RENDERBUFFER_SIZE;
1948			params[0] = maxDimension;
1949			params[1] = maxDimension;
1950		}
1951		break;
1952	case GL_COMPRESSED_TEXTURE_FORMATS:
1953		{
1954			for(int i = 0; i < NUM_COMPRESSED_TEXTURE_FORMATS; i++)
1955			{
1956				params[i] = compressedTextureFormats[i];
1957			}
1958		}
1959		break;
1960	case GL_VIEWPORT:
1961		params[0] = mState.viewportX;
1962		params[1] = mState.viewportY;
1963		params[2] = mState.viewportWidth;
1964		params[3] = mState.viewportHeight;
1965		break;
1966	case GL_SCISSOR_BOX:
1967		params[0] = mState.scissorX;
1968		params[1] = mState.scissorY;
1969		params[2] = mState.scissorWidth;
1970		params[3] = mState.scissorHeight;
1971		break;
1972	case GL_CULL_FACE_MODE:                   *params = mState.cullMode;                 break;
1973	case GL_FRONT_FACE:                       *params = mState.frontFace;                break;
1974	case GL_RED_BITS:
1975	case GL_GREEN_BITS:
1976	case GL_BLUE_BITS:
1977	case GL_ALPHA_BITS:
1978		{
1979			Framebuffer *framebuffer = getDrawFramebuffer();
1980			Renderbuffer *colorbuffer = framebuffer->getColorbuffer(0);
1981
1982			if(colorbuffer)
1983			{
1984				switch(pname)
1985				{
1986				case GL_RED_BITS:   *params = colorbuffer->getRedSize();   break;
1987				case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
1988				case GL_BLUE_BITS:  *params = colorbuffer->getBlueSize();  break;
1989				case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
1990				}
1991			}
1992			else
1993			{
1994				*params = 0;
1995			}
1996		}
1997		break;
1998	case GL_DEPTH_BITS:
1999		{
2000			Framebuffer *framebuffer = getDrawFramebuffer();
2001			Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2002
2003			if(depthbuffer)
2004			{
2005				*params = depthbuffer->getDepthSize();
2006			}
2007			else
2008			{
2009				*params = 0;
2010			}
2011		}
2012		break;
2013	case GL_STENCIL_BITS:
2014		{
2015			Framebuffer *framebuffer = getDrawFramebuffer();
2016			Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2017
2018			if(stencilbuffer)
2019			{
2020				*params = stencilbuffer->getStencilSize();
2021			}
2022			else
2023			{
2024				*params = 0;
2025			}
2026		}
2027		break;
2028	case GL_TEXTURE_BINDING_2D:
2029		if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2030		{
2031			error(GL_INVALID_OPERATION);
2032			return false;
2033		}
2034
2035		*params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].name();
2036		break;
2037	case GL_TEXTURE_BINDING_CUBE_MAP:
2038		if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2039		{
2040			error(GL_INVALID_OPERATION);
2041			return false;
2042		}
2043
2044		*params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].name();
2045		break;
2046	case GL_TEXTURE_BINDING_EXTERNAL_OES:
2047		if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2048		{
2049			error(GL_INVALID_OPERATION);
2050			return false;
2051		}
2052
2053		*params = mState.samplerTexture[TEXTURE_EXTERNAL][mState.activeSampler].name();
2054		break;
2055	case GL_TEXTURE_BINDING_3D_OES:
2056		if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2057		{
2058			error(GL_INVALID_OPERATION);
2059			return false;
2060		}
2061
2062		*params = mState.samplerTexture[TEXTURE_3D][mState.activeSampler].name();
2063		break;
2064	case GL_TEXTURE_BINDING_2D_ARRAY: // GLES 3.0
2065		if(clientVersion < 3)
2066		{
2067			return false;
2068		}
2069		else if(mState.activeSampler > MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1)
2070		{
2071			error(GL_INVALID_OPERATION);
2072			return false;
2073		}
2074
2075		*params = mState.samplerTexture[TEXTURE_2D_ARRAY][mState.activeSampler].name();
2076		break;
2077	case GL_COPY_READ_BUFFER_BINDING: // name, initially 0
2078		if(clientVersion >= 3)
2079		{
2080			*params = mState.copyReadBuffer.name();
2081		}
2082		else
2083		{
2084			return false;
2085		}
2086		break;
2087	case GL_COPY_WRITE_BUFFER_BINDING: // name, initially 0
2088		if(clientVersion >= 3)
2089		{
2090			*params = mState.copyWriteBuffer.name();
2091		}
2092		else
2093		{
2094			return false;
2095		}
2096		break;
2097	case GL_DRAW_BUFFER0:
2098	case GL_DRAW_BUFFER1:
2099	case GL_DRAW_BUFFER2:
2100	case GL_DRAW_BUFFER3:
2101	case GL_DRAW_BUFFER4:
2102	case GL_DRAW_BUFFER5:
2103	case GL_DRAW_BUFFER6:
2104	case GL_DRAW_BUFFER7:
2105	case GL_DRAW_BUFFER8:
2106	case GL_DRAW_BUFFER9:
2107	case GL_DRAW_BUFFER10:
2108	case GL_DRAW_BUFFER11:
2109	case GL_DRAW_BUFFER12:
2110	case GL_DRAW_BUFFER13:
2111	case GL_DRAW_BUFFER14:
2112	case GL_DRAW_BUFFER15:
2113		*params = getDrawFramebuffer()->getDrawBuffer(pname - GL_DRAW_BUFFER0);
2114		break;
2115	case GL_MAJOR_VERSION:
2116		if(clientVersion >= 3)
2117		{
2118			*params = clientVersion;
2119		}
2120		else
2121		{
2122			return false;
2123		}
2124		break;
2125	case GL_MAX_3D_TEXTURE_SIZE: // GLint, at least 2048
2126		*params = IMPLEMENTATION_MAX_TEXTURE_SIZE;
2127		break;
2128	case GL_MAX_ARRAY_TEXTURE_LAYERS: // GLint, at least 2048
2129		*params = IMPLEMENTATION_MAX_TEXTURE_SIZE;
2130		break;
2131	case GL_MAX_COLOR_ATTACHMENTS:
2132		*params = MAX_COLOR_ATTACHMENTS;
2133		break;
2134	case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 50048
2135		*params = MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS;
2136		break;
2137	case GL_MAX_COMBINED_UNIFORM_BLOCKS: // integer, at least 70
2138		UNIMPLEMENTED();
2139		*params = 70;
2140		break;
2141	case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS: // integer, at least 50176
2142		*params = MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS;
2143		break;
2144	case GL_MAX_DRAW_BUFFERS:
2145		*params = MAX_DRAW_BUFFERS;
2146		break;
2147	case GL_MAX_ELEMENT_INDEX:
2148		*params = MAX_ELEMENT_INDEX;
2149		break;
2150	case GL_MAX_ELEMENTS_INDICES:
2151		*params = MAX_ELEMENTS_INDICES;
2152		break;
2153	case GL_MAX_ELEMENTS_VERTICES:
2154		*params = MAX_ELEMENTS_VERTICES;
2155		break;
2156	case GL_MAX_FRAGMENT_INPUT_COMPONENTS: // integer, at least 128
2157		UNIMPLEMENTED();
2158		*params = 128;
2159		break;
2160	case GL_MAX_FRAGMENT_UNIFORM_BLOCKS: // integer, at least 12
2161		*params = MAX_FRAGMENT_UNIFORM_BLOCKS;
2162		break;
2163	case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS: // integer, at least 896
2164		*params = MAX_FRAGMENT_UNIFORM_COMPONENTS;
2165		break;
2166	case GL_MAX_PROGRAM_TEXEL_OFFSET: // integer, minimum is 7
2167		UNIMPLEMENTED();
2168		*params = 7;
2169		break;
2170	case GL_MAX_SERVER_WAIT_TIMEOUT: // integer
2171		UNIMPLEMENTED();
2172		*params = 0;
2173		break;
2174	case GL_MAX_TEXTURE_LOD_BIAS: // integer,  at least 2.0
2175		UNIMPLEMENTED();
2176		*params = 2;
2177		break;
2178	case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS: // integer, at least 64
2179		*params = sw::MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS;
2180		break;
2181	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS: // integer, at least 4
2182		*params = MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS;
2183		break;
2184	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS: // integer, at least 4
2185		*params = sw::MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS;
2186		break;
2187	case GL_MAX_UNIFORM_BLOCK_SIZE: // integer, at least 16384
2188		*params = MAX_UNIFORM_BLOCK_SIZE;
2189		break;
2190	case GL_MAX_UNIFORM_BUFFER_BINDINGS: // integer, at least 24
2191		*params = MAX_UNIFORM_BUFFER_BINDINGS;
2192		break;
2193	case GL_MAX_VARYING_COMPONENTS: // integer, at least 60
2194		UNIMPLEMENTED();
2195		*params = 60;
2196		break;
2197	case GL_MAX_VERTEX_OUTPUT_COMPONENTS: // integer,  at least 64
2198		UNIMPLEMENTED();
2199		*params = 64;
2200		break;
2201	case GL_MAX_VERTEX_UNIFORM_BLOCKS: // integer,  at least 12
2202		*params = MAX_VERTEX_UNIFORM_BLOCKS;
2203		break;
2204	case GL_MAX_VERTEX_UNIFORM_COMPONENTS: // integer,  at least 1024
2205		*params = MAX_VERTEX_UNIFORM_COMPONENTS;
2206		break;
2207	case GL_MIN_PROGRAM_TEXEL_OFFSET: // integer, maximum is -8
2208		UNIMPLEMENTED();
2209		*params = -8;
2210		break;
2211	case GL_MINOR_VERSION: // integer
2212		UNIMPLEMENTED();
2213		*params = 0;
2214		break;
2215	case GL_NUM_EXTENSIONS: // integer
2216		GLuint numExtensions;
2217		getExtensions(0, &numExtensions);
2218		*params = numExtensions;
2219		break;
2220	case GL_NUM_PROGRAM_BINARY_FORMATS: // integer, at least 0
2221		UNIMPLEMENTED();
2222		*params = 0;
2223		break;
2224	case GL_PACK_ROW_LENGTH: // integer, initially 0
2225		*params = mState.packRowLength;
2226		break;
2227	case GL_PACK_SKIP_PIXELS: // integer, initially 0
2228		*params = mState.packSkipPixels;
2229		break;
2230	case GL_PACK_SKIP_ROWS: // integer, initially 0
2231		*params = mState.packSkipRows;
2232		break;
2233	case GL_PIXEL_PACK_BUFFER_BINDING: // integer, initially 0
2234		if(clientVersion >= 3)
2235		{
2236			*params = mState.pixelPackBuffer.name();
2237		}
2238		else
2239		{
2240			return false;
2241		}
2242		break;
2243	case GL_PIXEL_UNPACK_BUFFER_BINDING: // integer, initially 0
2244		if(clientVersion >= 3)
2245		{
2246			*params = mState.pixelUnpackBuffer.name();
2247		}
2248		else
2249		{
2250			return false;
2251		}
2252		break;
2253	case GL_PROGRAM_BINARY_FORMATS: // integer[GL_NUM_PROGRAM_BINARY_FORMATS​]
2254		UNIMPLEMENTED();
2255		*params = 0;
2256		break;
2257	case GL_READ_BUFFER: // symbolic constant,  initial value is GL_BACK​
2258		*params = getReadFramebuffer()->getReadBuffer();
2259		break;
2260	case GL_SAMPLER_BINDING: // GLint, default 0
2261		*params = mState.sampler[mState.activeSampler].name();
2262		break;
2263	case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2264		if(clientVersion >= 3)
2265		{
2266			*params = mState.genericUniformBuffer.name();
2267		}
2268		else
2269		{
2270			return false;
2271		}
2272		break;
2273	case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT: // integer, defaults to 1
2274		*params = UNIFORM_BUFFER_OFFSET_ALIGNMENT;
2275		break;
2276	case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2277		if(clientVersion >= 3)
2278		{
2279			*params = static_cast<T>(mState.genericUniformBuffer->size());
2280		}
2281		else
2282		{
2283			return false;
2284		}
2285		break;
2286	case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2287		if(clientVersion >= 3)
2288		{
2289			*params = static_cast<T>(mState.genericUniformBuffer->offset());
2290		}
2291		else
2292		{
2293			return false;
2294		}
2295		*params = 0;
2296		break;
2297	case GL_UNPACK_IMAGE_HEIGHT: // integer, initially 0
2298		*params = mState.unpackInfo.imageHeight;
2299		break;
2300	case GL_UNPACK_ROW_LENGTH: // integer, initially 0
2301		*params = mState.unpackInfo.rowLength;
2302		break;
2303	case GL_UNPACK_SKIP_IMAGES: // integer, initially 0
2304		*params = mState.unpackInfo.skipImages;
2305		break;
2306	case GL_UNPACK_SKIP_PIXELS: // integer, initially 0
2307		*params = mState.unpackInfo.skipPixels;
2308		break;
2309	case GL_UNPACK_SKIP_ROWS: // integer, initially 0
2310		*params = mState.unpackInfo.skipRows;
2311		break;
2312	case GL_VERTEX_ARRAY_BINDING: // GLint, initially 0
2313		*params = getCurrentVertexArray()->name;
2314		break;
2315	case GL_TRANSFORM_FEEDBACK_BINDING:
2316		{
2317			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2318			if(transformFeedback)
2319			{
2320				*params = transformFeedback->name;
2321			}
2322			else
2323			{
2324				return false;
2325			}
2326		}
2327		break;
2328	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2329		{
2330			TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2331			if(transformFeedback)
2332			{
2333				*params = transformFeedback->getGenericBufferName();
2334			}
2335			else
2336			{
2337				return false;
2338			}
2339		}
2340		break;
2341	default:
2342		return false;
2343	}
2344
2345	return true;
2346}
2347
2348template bool Context::getTransformFeedbackiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2349template bool Context::getTransformFeedbackiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2350
2351template<typename T> bool Context::getTransformFeedbackiv(GLuint index, GLenum pname, T *param) const
2352{
2353	TransformFeedback* transformFeedback = getTransformFeedback(mState.transformFeedback);
2354	if(!transformFeedback)
2355	{
2356		return false;
2357	}
2358
2359	switch(pname)
2360	{
2361	case GL_TRANSFORM_FEEDBACK_BINDING: // GLint, initially 0
2362		*param = transformFeedback->name;
2363		break;
2364	case GL_TRANSFORM_FEEDBACK_ACTIVE: // boolean, initially GL_FALSE
2365		*param = transformFeedback->isActive();
2366		break;
2367	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING: // name, initially 0
2368		*param = transformFeedback->getBufferName(index);
2369		break;
2370	case GL_TRANSFORM_FEEDBACK_PAUSED: // boolean, initially GL_FALSE
2371		*param = transformFeedback->isPaused();
2372		break;
2373	case GL_TRANSFORM_FEEDBACK_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2374		if(transformFeedback->getBuffer(index))
2375		{
2376			*param = transformFeedback->getSize(index);
2377			break;
2378		}
2379		else return false;
2380	case GL_TRANSFORM_FEEDBACK_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2381		if(transformFeedback->getBuffer(index))
2382		{
2383			*param = transformFeedback->getOffset(index);
2384		break;
2385		}
2386		else return false;
2387	default:
2388		return false;
2389	}
2390
2391	return true;
2392}
2393
2394template bool Context::getUniformBufferiv<GLint>(GLuint index, GLenum pname, GLint *param) const;
2395template bool Context::getUniformBufferiv<GLint64>(GLuint index, GLenum pname, GLint64 *param) const;
2396
2397template<typename T> bool Context::getUniformBufferiv(GLuint index, GLenum pname, T *param) const
2398{
2399	const BufferBinding& uniformBuffer = mState.uniformBuffers[index];
2400
2401	switch(pname)
2402	{
2403	case GL_UNIFORM_BUFFER_BINDING: // name, initially 0
2404		*param = uniformBuffer.get().name();
2405		break;
2406	case GL_UNIFORM_BUFFER_SIZE: // indexed[n] 64-bit integer, initially 0
2407		*param = uniformBuffer.getSize();
2408		break;
2409	case GL_UNIFORM_BUFFER_START: // indexed[n] 64-bit integer, initially 0
2410		*param = uniformBuffer.getOffset();
2411		break;
2412	default:
2413		return false;
2414	}
2415
2416	return true;
2417}
2418
2419bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams) const
2420{
2421	// Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
2422	// is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
2423	// to the fact that it is stored internally as a float, and so would require conversion
2424	// if returned from Context::getIntegerv. Since this conversion is already implemented
2425	// in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
2426	// place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
2427	// application.
2428	switch(pname)
2429	{
2430	case GL_COMPRESSED_TEXTURE_FORMATS:
2431		{
2432			*type = GL_INT;
2433			*numParams = NUM_COMPRESSED_TEXTURE_FORMATS;
2434		}
2435		break;
2436	case GL_SHADER_BINARY_FORMATS:
2437		{
2438			*type = GL_INT;
2439			*numParams = 0;
2440		}
2441		break;
2442	case GL_MAX_VERTEX_ATTRIBS:
2443	case GL_MAX_VERTEX_UNIFORM_VECTORS:
2444	case GL_MAX_VARYING_VECTORS:
2445	case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
2446	case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
2447	case GL_MAX_TEXTURE_IMAGE_UNITS:
2448	case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
2449	case GL_MAX_RENDERBUFFER_SIZE:
2450	case GL_NUM_SHADER_BINARY_FORMATS:
2451	case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
2452	case GL_ARRAY_BUFFER_BINDING:
2453	case GL_FRAMEBUFFER_BINDING: // Same as GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
2454	case GL_READ_FRAMEBUFFER_BINDING_ANGLE:
2455	case GL_RENDERBUFFER_BINDING:
2456	case GL_CURRENT_PROGRAM:
2457	case GL_PACK_ALIGNMENT:
2458	case GL_UNPACK_ALIGNMENT:
2459	case GL_GENERATE_MIPMAP_HINT:
2460	case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
2461	case GL_RED_BITS:
2462	case GL_GREEN_BITS:
2463	case GL_BLUE_BITS:
2464	case GL_ALPHA_BITS:
2465	case GL_DEPTH_BITS:
2466	case GL_STENCIL_BITS:
2467	case GL_ELEMENT_ARRAY_BUFFER_BINDING:
2468	case GL_CULL_FACE_MODE:
2469	case GL_FRONT_FACE:
2470	case GL_ACTIVE_TEXTURE:
2471	case GL_STENCIL_FUNC:
2472	case GL_STENCIL_VALUE_MASK:
2473	case GL_STENCIL_REF:
2474	case GL_STENCIL_FAIL:
2475	case GL_STENCIL_PASS_DEPTH_FAIL:
2476	case GL_STENCIL_PASS_DEPTH_PASS:
2477	case GL_STENCIL_BACK_FUNC:
2478	case GL_STENCIL_BACK_VALUE_MASK:
2479	case GL_STENCIL_BACK_REF:
2480	case GL_STENCIL_BACK_FAIL:
2481	case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
2482	case GL_STENCIL_BACK_PASS_DEPTH_PASS:
2483	case GL_DEPTH_FUNC:
2484	case GL_BLEND_SRC_RGB:
2485	case GL_BLEND_SRC_ALPHA:
2486	case GL_BLEND_DST_RGB:
2487	case GL_BLEND_DST_ALPHA:
2488	case GL_BLEND_EQUATION_RGB:
2489	case GL_BLEND_EQUATION_ALPHA:
2490	case GL_STENCIL_WRITEMASK:
2491	case GL_STENCIL_BACK_WRITEMASK:
2492	case GL_STENCIL_CLEAR_VALUE:
2493	case GL_SUBPIXEL_BITS:
2494	case GL_MAX_TEXTURE_SIZE:
2495	case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
2496	case GL_SAMPLE_BUFFERS:
2497	case GL_SAMPLES:
2498	case GL_IMPLEMENTATION_COLOR_READ_TYPE:
2499	case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
2500	case GL_TEXTURE_BINDING_2D:
2501	case GL_TEXTURE_BINDING_CUBE_MAP:
2502	case GL_TEXTURE_BINDING_EXTERNAL_OES:
2503	case GL_TEXTURE_BINDING_3D_OES:
2504	case GL_COPY_READ_BUFFER_BINDING:
2505	case GL_COPY_WRITE_BUFFER_BINDING:
2506	case GL_DRAW_BUFFER0:
2507	case GL_DRAW_BUFFER1:
2508	case GL_DRAW_BUFFER2:
2509	case GL_DRAW_BUFFER3:
2510	case GL_DRAW_BUFFER4:
2511	case GL_DRAW_BUFFER5:
2512	case GL_DRAW_BUFFER6:
2513	case GL_DRAW_BUFFER7:
2514	case GL_DRAW_BUFFER8:
2515	case GL_DRAW_BUFFER9:
2516	case GL_DRAW_BUFFER10:
2517	case GL_DRAW_BUFFER11:
2518	case GL_DRAW_BUFFER12:
2519	case GL_DRAW_BUFFER13:
2520	case GL_DRAW_BUFFER14:
2521	case GL_DRAW_BUFFER15:
2522	case GL_MAJOR_VERSION:
2523	case GL_MAX_3D_TEXTURE_SIZE:
2524	case GL_MAX_ARRAY_TEXTURE_LAYERS:
2525	case GL_MAX_COLOR_ATTACHMENTS:
2526	case GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS:
2527	case GL_MAX_COMBINED_UNIFORM_BLOCKS:
2528	case GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS:
2529	case GL_MAX_DRAW_BUFFERS:
2530	case GL_MAX_ELEMENT_INDEX:
2531	case GL_MAX_ELEMENTS_INDICES:
2532	case GL_MAX_ELEMENTS_VERTICES:
2533	case GL_MAX_FRAGMENT_INPUT_COMPONENTS:
2534	case GL_MAX_FRAGMENT_UNIFORM_BLOCKS:
2535	case GL_MAX_FRAGMENT_UNIFORM_COMPONENTS:
2536	case GL_MAX_PROGRAM_TEXEL_OFFSET:
2537	case GL_MAX_SERVER_WAIT_TIMEOUT:
2538	case GL_MAX_TEXTURE_LOD_BIAS:
2539	case GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS:
2540	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS:
2541	case GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS:
2542	case GL_MAX_UNIFORM_BLOCK_SIZE:
2543	case GL_MAX_UNIFORM_BUFFER_BINDINGS:
2544	case GL_MAX_VARYING_COMPONENTS:
2545	case GL_MAX_VERTEX_OUTPUT_COMPONENTS:
2546	case GL_MAX_VERTEX_UNIFORM_BLOCKS:
2547	case GL_MAX_VERTEX_UNIFORM_COMPONENTS:
2548	case GL_MIN_PROGRAM_TEXEL_OFFSET:
2549	case GL_MINOR_VERSION:
2550	case GL_NUM_EXTENSIONS:
2551	case GL_NUM_PROGRAM_BINARY_FORMATS:
2552	case GL_PACK_ROW_LENGTH:
2553	case GL_PACK_SKIP_PIXELS:
2554	case GL_PACK_SKIP_ROWS:
2555	case GL_PIXEL_PACK_BUFFER_BINDING:
2556	case GL_PIXEL_UNPACK_BUFFER_BINDING:
2557	case GL_PROGRAM_BINARY_FORMATS:
2558	case GL_READ_BUFFER:
2559	case GL_SAMPLER_BINDING:
2560	case GL_TEXTURE_BINDING_2D_ARRAY:
2561	case GL_UNIFORM_BUFFER_BINDING:
2562	case GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT:
2563	case GL_UNIFORM_BUFFER_SIZE:
2564	case GL_UNIFORM_BUFFER_START:
2565	case GL_UNPACK_IMAGE_HEIGHT:
2566	case GL_UNPACK_ROW_LENGTH:
2567	case GL_UNPACK_SKIP_IMAGES:
2568	case GL_UNPACK_SKIP_PIXELS:
2569	case GL_UNPACK_SKIP_ROWS:
2570	case GL_VERTEX_ARRAY_BINDING:
2571	case GL_TRANSFORM_FEEDBACK_BINDING:
2572	case GL_TRANSFORM_FEEDBACK_BUFFER_BINDING:
2573		{
2574			*type = GL_INT;
2575			*numParams = 1;
2576		}
2577		break;
2578	case GL_MAX_SAMPLES_ANGLE:
2579		{
2580			*type = GL_INT;
2581			*numParams = 1;
2582		}
2583		break;
2584	case GL_MAX_VIEWPORT_DIMS:
2585		{
2586			*type = GL_INT;
2587			*numParams = 2;
2588		}
2589		break;
2590	case GL_VIEWPORT:
2591	case GL_SCISSOR_BOX:
2592		{
2593			*type = GL_INT;
2594			*numParams = 4;
2595		}
2596		break;
2597	case GL_SHADER_COMPILER:
2598	case GL_SAMPLE_COVERAGE_INVERT:
2599	case GL_DEPTH_WRITEMASK:
2600	case GL_CULL_FACE:                // CULL_FACE through DITHER are natural to IsEnabled,
2601	case GL_POLYGON_OFFSET_FILL:      // but can be retrieved through the Get{Type}v queries.
2602	case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
2603	case GL_SAMPLE_COVERAGE:
2604	case GL_SCISSOR_TEST:
2605	case GL_STENCIL_TEST:
2606	case GL_DEPTH_TEST:
2607	case GL_BLEND:
2608	case GL_DITHER:
2609	case GL_PRIMITIVE_RESTART_FIXED_INDEX:
2610	case GL_RASTERIZER_DISCARD:
2611	case GL_TRANSFORM_FEEDBACK_ACTIVE:
2612	case GL_TRANSFORM_FEEDBACK_PAUSED:
2613		{
2614			*type = GL_BOOL;
2615			*numParams = 1;
2616		}
2617		break;
2618	case GL_COLOR_WRITEMASK:
2619		{
2620			*type = GL_BOOL;
2621			*numParams = 4;
2622		}
2623		break;
2624	case GL_POLYGON_OFFSET_FACTOR:
2625	case GL_POLYGON_OFFSET_UNITS:
2626	case GL_SAMPLE_COVERAGE_VALUE:
2627	case GL_DEPTH_CLEAR_VALUE:
2628	case GL_LINE_WIDTH:
2629		{
2630			*type = GL_FLOAT;
2631			*numParams = 1;
2632		}
2633		break;
2634	case GL_ALIASED_LINE_WIDTH_RANGE:
2635	case GL_ALIASED_POINT_SIZE_RANGE:
2636	case GL_DEPTH_RANGE:
2637		{
2638			*type = GL_FLOAT;
2639			*numParams = 2;
2640		}
2641		break;
2642	case GL_COLOR_CLEAR_VALUE:
2643	case GL_BLEND_COLOR:
2644		{
2645			*type = GL_FLOAT;
2646			*numParams = 4;
2647		}
2648		break;
2649	case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
2650		*type = GL_FLOAT;
2651		*numParams = 1;
2652		break;
2653	default:
2654		return false;
2655	}
2656
2657	return true;
2658}
2659
2660void Context::applyScissor(int width, int height)
2661{
2662	if(mState.scissorTestEnabled)
2663	{
2664		sw::Rect scissor = { mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight };
2665		scissor.clip(0, 0, width, height);
2666
2667		device->setScissorRect(scissor);
2668		device->setScissorEnable(true);
2669	}
2670	else
2671	{
2672		device->setScissorEnable(false);
2673	}
2674}
2675
2676// Applies the render target surface, depth stencil surface, viewport rectangle and scissor rectangle
2677bool Context::applyRenderTarget()
2678{
2679	Framebuffer *framebuffer = getDrawFramebuffer();
2680	int width, height, samples;
2681
2682	if(!framebuffer || framebuffer->completeness(width, height, samples) != GL_FRAMEBUFFER_COMPLETE)
2683	{
2684		return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
2685	}
2686
2687	for(int i = 0; i < MAX_DRAW_BUFFERS; i++)
2688	{
2689		if(framebuffer->getDrawBuffer(i) != GL_NONE)
2690		{
2691			egl::Image *renderTarget = framebuffer->getRenderTarget(i);
2692			device->setRenderTarget(i, renderTarget);
2693			if(renderTarget) renderTarget->release();
2694		}
2695		else
2696		{
2697			device->setRenderTarget(i, nullptr);
2698		}
2699	}
2700
2701	egl::Image *depthBuffer = framebuffer->getDepthBuffer();
2702	device->setDepthBuffer(depthBuffer);
2703	if(depthBuffer) depthBuffer->release();
2704
2705	egl::Image *stencilBuffer = framebuffer->getStencilBuffer();
2706	device->setStencilBuffer(stencilBuffer);
2707	if(stencilBuffer) stencilBuffer->release();
2708
2709	Viewport viewport;
2710	float zNear = clamp01(mState.zNear);
2711	float zFar = clamp01(mState.zFar);
2712
2713	viewport.x0 = mState.viewportX;
2714	viewport.y0 = mState.viewportY;
2715	viewport.width = mState.viewportWidth;
2716	viewport.height = mState.viewportHeight;
2717	viewport.minZ = zNear;
2718	viewport.maxZ = zFar;
2719
2720	device->setViewport(viewport);
2721
2722	applyScissor(width, height);
2723
2724	Program *program = getCurrentProgram();
2725
2726	if(program)
2727	{
2728		GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2729		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.near"), 1, &nearFarDiff[0]);
2730		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.far"), 1, &nearFarDiff[1]);
2731		program->setUniform1fv(program->getUniformLocation("gl_DepthRange.diff"), 1, &nearFarDiff[2]);
2732	}
2733
2734	return true;
2735}
2736
2737// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc)
2738void Context::applyState(GLenum drawMode)
2739{
2740	Framebuffer *framebuffer = getDrawFramebuffer();
2741
2742	if(mState.cullFaceEnabled)
2743	{
2744		device->setCullMode(es2sw::ConvertCullMode(mState.cullMode, mState.frontFace));
2745	}
2746	else
2747	{
2748		device->setCullMode(sw::CULL_NONE);
2749	}
2750
2751	if(mDepthStateDirty)
2752	{
2753		if(mState.depthTestEnabled)
2754		{
2755			device->setDepthBufferEnable(true);
2756			device->setDepthCompare(es2sw::ConvertDepthComparison(mState.depthFunc));
2757		}
2758		else
2759		{
2760			device->setDepthBufferEnable(false);
2761		}
2762
2763		mDepthStateDirty = false;
2764	}
2765
2766	if(mBlendStateDirty)
2767	{
2768		if(mState.blendEnabled)
2769		{
2770			device->setAlphaBlendEnable(true);
2771			device->setSeparateAlphaBlendEnable(true);
2772
2773			device->setBlendConstant(es2sw::ConvertColor(mState.blendColor));
2774
2775			device->setSourceBlendFactor(es2sw::ConvertBlendFunc(mState.sourceBlendRGB));
2776			device->setDestBlendFactor(es2sw::ConvertBlendFunc(mState.destBlendRGB));
2777			device->setBlendOperation(es2sw::ConvertBlendOp(mState.blendEquationRGB));
2778
2779			device->setSourceBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.sourceBlendAlpha));
2780			device->setDestBlendFactorAlpha(es2sw::ConvertBlendFunc(mState.destBlendAlpha));
2781			device->setBlendOperationAlpha(es2sw::ConvertBlendOp(mState.blendEquationAlpha));
2782		}
2783		else
2784		{
2785			device->setAlphaBlendEnable(false);
2786		}
2787
2788		mBlendStateDirty = false;
2789	}
2790
2791	if(mStencilStateDirty || mFrontFaceDirty)
2792	{
2793		if(mState.stencilTestEnabled && framebuffer->hasStencil())
2794		{
2795			device->setStencilEnable(true);
2796			device->setTwoSidedStencil(true);
2797
2798			// get the maximum size of the stencil ref
2799			Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
2800			GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2801
2802			if(mState.frontFace == GL_CCW)
2803			{
2804				device->setStencilWriteMask(mState.stencilWritemask);
2805				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilFunc));
2806
2807				device->setStencilReference((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2808				device->setStencilMask(mState.stencilMask);
2809
2810				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilFail));
2811				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2812				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2813
2814				device->setStencilWriteMaskCCW(mState.stencilBackWritemask);
2815				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2816
2817				device->setStencilReferenceCCW((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2818				device->setStencilMaskCCW(mState.stencilBackMask);
2819
2820				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackFail));
2821				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2822				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2823			}
2824			else
2825			{
2826				device->setStencilWriteMaskCCW(mState.stencilWritemask);
2827				device->setStencilCompareCCW(es2sw::ConvertStencilComparison(mState.stencilFunc));
2828
2829				device->setStencilReferenceCCW((mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2830				device->setStencilMaskCCW(mState.stencilMask);
2831
2832				device->setStencilFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilFail));
2833				device->setStencilZFailOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthFail));
2834				device->setStencilPassOperationCCW(es2sw::ConvertStencilOp(mState.stencilPassDepthPass));
2835
2836				device->setStencilWriteMask(mState.stencilBackWritemask);
2837				device->setStencilCompare(es2sw::ConvertStencilComparison(mState.stencilBackFunc));
2838
2839				device->setStencilReference((mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2840				device->setStencilMask(mState.stencilBackMask);
2841
2842				device->setStencilFailOperation(es2sw::ConvertStencilOp(mState.stencilBackFail));
2843				device->setStencilZFailOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthFail));
2844				device->setStencilPassOperation(es2sw::ConvertStencilOp(mState.stencilBackPassDepthPass));
2845			}
2846		}
2847		else
2848		{
2849			device->setStencilEnable(false);
2850		}
2851
2852		mStencilStateDirty = false;
2853		mFrontFaceDirty = false;
2854	}
2855
2856	if(mMaskStateDirty)
2857	{
2858		for(int i = 0; i < MAX_DRAW_BUFFERS; i++)
2859		{
2860			device->setColorWriteMask(i, es2sw::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2861		}
2862
2863		device->setDepthWriteEnable(mState.depthMask);
2864
2865		mMaskStateDirty = false;
2866	}
2867
2868	if(mPolygonOffsetStateDirty)
2869	{
2870		if(mState.polygonOffsetFillEnabled)
2871		{
2872			Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
2873			if(depthbuffer)
2874			{
2875				device->setSlopeDepthBias(mState.polygonOffsetFactor);
2876				float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2877				device->setDepthBias(depthBias);
2878			}
2879		}
2880		else
2881		{
2882			device->setSlopeDepthBias(0);
2883			device->setDepthBias(0);
2884		}
2885
2886		mPolygonOffsetStateDirty = false;
2887	}
2888
2889	if(mSampleStateDirty)
2890	{
2891		if(mState.sampleAlphaToCoverageEnabled)
2892		{
2893			device->setTransparencyAntialiasing(sw::TRANSPARENCY_ALPHA_TO_COVERAGE);
2894		}
2895		else
2896		{
2897			device->setTransparencyAntialiasing(sw::TRANSPARENCY_NONE);
2898		}
2899
2900		if(mState.sampleCoverageEnabled)
2901		{
2902			unsigned int mask = 0;
2903			if(mState.sampleCoverageValue != 0)
2904			{
2905				int width, height, samples;
2906				framebuffer->completeness(width, height, samples);
2907
2908				float threshold = 0.5f;
2909
2910				for(int i = 0; i < samples; i++)
2911				{
2912					mask <<= 1;
2913
2914					if((i + 1) * mState.sampleCoverageValue >= threshold)
2915					{
2916						threshold += 1.0f;
2917						mask |= 1;
2918					}
2919				}
2920			}
2921
2922			if(mState.sampleCoverageInvert)
2923			{
2924				mask = ~mask;
2925			}
2926
2927			device->setMultiSampleMask(mask);
2928		}
2929		else
2930		{
2931			device->setMultiSampleMask(0xFFFFFFFF);
2932		}
2933
2934		mSampleStateDirty = false;
2935	}
2936
2937	if(mDitherStateDirty)
2938	{
2939	//	UNIMPLEMENTED();   // FIXME
2940
2941		mDitherStateDirty = false;
2942	}
2943
2944	device->setRasterizerDiscard(mState.rasterizerDiscardEnabled);
2945}
2946
2947GLenum Context::applyVertexBuffer(GLint base, GLint first, GLsizei count, GLsizei instanceId)
2948{
2949	TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2950
2951	GLenum err = mVertexDataManager->prepareVertexData(first, count, attributes, instanceId);
2952	if(err != GL_NO_ERROR)
2953	{
2954		return err;
2955	}
2956
2957	Program *program = getCurrentProgram();
2958
2959	device->resetInputStreams(false);
2960
2961	for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2962	{
2963		if(program->getAttributeStream(i) == -1)
2964		{
2965			continue;
2966		}
2967
2968		sw::Resource *resource = attributes[i].vertexBuffer;
2969		const void *buffer = (char*)resource->data() + attributes[i].offset;
2970
2971		int stride = attributes[i].stride;
2972
2973		buffer = (char*)buffer + stride * base;
2974
2975		sw::Stream attribute(resource, buffer, stride);
2976
2977		attribute.type = attributes[i].type;
2978		attribute.count = attributes[i].count;
2979		attribute.normalized = attributes[i].normalized;
2980
2981		int stream = program->getAttributeStream(i);
2982		device->setInputStream(stream, attribute);
2983	}
2984
2985	return GL_NO_ERROR;
2986}
2987
2988// Applies the indices and element array bindings
2989GLenum Context::applyIndexBuffer(const void *indices, GLuint start, GLuint end, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2990{
2991	GLenum err = mIndexDataManager->prepareIndexData(type, start, end, count, getCurrentVertexArray()->getElementArrayBuffer(), indices, indexInfo);
2992
2993	if(err == GL_NO_ERROR)
2994	{
2995		device->setIndexBuffer(indexInfo->indexBuffer);
2996	}
2997
2998	return err;
2999}
3000
3001// Applies the shaders and shader constants
3002void Context::applyShaders()
3003{
3004	Program *programObject = getCurrentProgram();
3005	sw::VertexShader *vertexShader = programObject->getVertexShader();
3006	sw::PixelShader *pixelShader = programObject->getPixelShader();
3007
3008	device->setVertexShader(vertexShader);
3009	device->setPixelShader(pixelShader);
3010
3011	if(programObject->getSerial() != mAppliedProgramSerial)
3012	{
3013		programObject->dirtyAllUniforms();
3014		mAppliedProgramSerial = programObject->getSerial();
3015	}
3016
3017	programObject->applyTransformFeedback(getTransformFeedback());
3018	programObject->applyUniformBuffers(mState.uniformBuffers);
3019	programObject->applyUniforms();
3020}
3021
3022void Context::applyTextures()
3023{
3024	applyTextures(sw::SAMPLER_PIXEL);
3025	applyTextures(sw::SAMPLER_VERTEX);
3026}
3027
3028void Context::applyTextures(sw::SamplerType samplerType)
3029{
3030	Program *programObject = getCurrentProgram();
3031
3032	int samplerCount = (samplerType == sw::SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS;   // Range of samplers of given sampler type
3033
3034	for(int samplerIndex = 0; samplerIndex < samplerCount; samplerIndex++)
3035	{
3036		int textureUnit = programObject->getSamplerMapping(samplerType, samplerIndex);   // OpenGL texture image unit index
3037
3038		if(textureUnit != -1)
3039		{
3040			TextureType textureType = programObject->getSamplerTextureType(samplerType, samplerIndex);
3041
3042			Texture *texture = getSamplerTexture(textureUnit, textureType);
3043
3044			if(texture->isSamplerComplete())
3045			{
3046				GLenum wrapS, wrapT, wrapR, minFilter, magFilter;
3047				GLfloat minLOD, maxLOD;
3048
3049				Sampler *samplerObject = mState.sampler[textureUnit];
3050				if(samplerObject)
3051				{
3052					wrapS = samplerObject->getWrapS();
3053					wrapT = samplerObject->getWrapT();
3054					wrapR = samplerObject->getWrapR();
3055					minFilter = samplerObject->getMinFilter();
3056					magFilter = samplerObject->getMagFilter();
3057					minLOD = samplerObject->getMinLod();
3058					maxLOD = samplerObject->getMaxLod();
3059				}
3060				else
3061				{
3062					wrapS = texture->getWrapS();
3063					wrapT = texture->getWrapT();
3064					wrapR = texture->getWrapR();
3065					minFilter = texture->getMinFilter();
3066					magFilter = texture->getMagFilter();
3067					minLOD = texture->getMinLOD();
3068					maxLOD = texture->getMaxLOD();
3069				}
3070				GLfloat maxAnisotropy = texture->getMaxAnisotropy();
3071
3072				GLint baseLevel = texture->getBaseLevel();
3073				GLint maxLevel = texture->getMaxLevel();
3074				GLenum swizzleR = texture->getSwizzleR();
3075				GLenum swizzleG = texture->getSwizzleG();
3076				GLenum swizzleB = texture->getSwizzleB();
3077				GLenum swizzleA = texture->getSwizzleA();
3078
3079				device->setAddressingModeU(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapS));
3080				device->setAddressingModeV(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapT));
3081				device->setAddressingModeW(samplerType, samplerIndex, es2sw::ConvertTextureWrap(wrapR));
3082				device->setSwizzleR(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleR));
3083				device->setSwizzleG(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleG));
3084				device->setSwizzleB(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleB));
3085				device->setSwizzleA(samplerType, samplerIndex, es2sw::ConvertSwizzleType(swizzleA));
3086				device->setMinLod(samplerType, samplerIndex, minLOD);
3087				device->setMaxLod(samplerType, samplerIndex, maxLOD);
3088				device->setBaseLevel(samplerType, samplerIndex, baseLevel);
3089				device->setMaxLevel(samplerType, samplerIndex, maxLevel);
3090
3091				device->setTextureFilter(samplerType, samplerIndex, es2sw::ConvertTextureFilter(minFilter, magFilter, maxAnisotropy));
3092				device->setMipmapFilter(samplerType, samplerIndex, es2sw::ConvertMipMapFilter(minFilter));
3093				device->setMaxAnisotropy(samplerType, samplerIndex, maxAnisotropy);
3094
3095				applyTexture(samplerType, samplerIndex, texture);
3096			}
3097			else
3098			{
3099				applyTexture(samplerType, samplerIndex, nullptr);
3100			}
3101		}
3102		else
3103		{
3104			applyTexture(samplerType, samplerIndex, nullptr);
3105		}
3106	}
3107}
3108
3109void Context::applyTexture(sw::SamplerType type, int index, Texture *baseTexture)
3110{
3111	Program *program = getCurrentProgram();
3112	int sampler = (type == sw::SAMPLER_PIXEL) ? index : 16 + index;
3113	bool textureUsed = false;
3114
3115	if(type == sw::SAMPLER_PIXEL)
3116	{
3117		textureUsed = program->getPixelShader()->usesSampler(index);
3118	}
3119	else if(type == sw::SAMPLER_VERTEX)
3120	{
3121		textureUsed = program->getVertexShader()->usesSampler(index);
3122	}
3123	else UNREACHABLE(type);
3124
3125	sw::Resource *resource = 0;
3126
3127	if(baseTexture && textureUsed)
3128	{
3129		resource = baseTexture->getResource();
3130	}
3131
3132	device->setTextureResource(sampler, resource);
3133
3134	if(baseTexture && textureUsed)
3135	{
3136		int levelCount = baseTexture->getLevelCount();
3137
3138		if(baseTexture->getTarget() == GL_TEXTURE_2D || baseTexture->getTarget() == GL_TEXTURE_EXTERNAL_OES)
3139		{
3140			Texture2D *texture = static_cast<Texture2D*>(baseTexture);
3141
3142			for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3143			{
3144				int surfaceLevel = mipmapLevel;
3145
3146				if(surfaceLevel < 0)
3147				{
3148					surfaceLevel = 0;
3149				}
3150				else if(surfaceLevel >= levelCount)
3151				{
3152					surfaceLevel = levelCount - 1;
3153				}
3154
3155				egl::Image *surface = texture->getImage(surfaceLevel);
3156				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D);
3157			}
3158		}
3159		else if(baseTexture->getTarget() == GL_TEXTURE_3D_OES)
3160		{
3161			Texture3D *texture = static_cast<Texture3D*>(baseTexture);
3162
3163			for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3164			{
3165				int surfaceLevel = mipmapLevel;
3166
3167				if(surfaceLevel < 0)
3168				{
3169					surfaceLevel = 0;
3170				}
3171				else if(surfaceLevel >= levelCount)
3172				{
3173					surfaceLevel = levelCount - 1;
3174				}
3175
3176				egl::Image *surface = texture->getImage(surfaceLevel);
3177				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_3D);
3178			}
3179		}
3180		else if(baseTexture->getTarget() == GL_TEXTURE_2D_ARRAY)
3181		{
3182			Texture2DArray *texture = static_cast<Texture2DArray*>(baseTexture);
3183
3184			for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3185			{
3186				int surfaceLevel = mipmapLevel;
3187
3188				if(surfaceLevel < 0)
3189				{
3190					surfaceLevel = 0;
3191				}
3192				else if(surfaceLevel >= levelCount)
3193				{
3194					surfaceLevel = levelCount - 1;
3195				}
3196
3197				egl::Image *surface = texture->getImage(surfaceLevel);
3198				device->setTextureLevel(sampler, 0, mipmapLevel, surface, sw::TEXTURE_2D_ARRAY);
3199			}
3200		}
3201		else if(baseTexture->getTarget() == GL_TEXTURE_CUBE_MAP)
3202		{
3203			for(int face = 0; face < 6; face++)
3204			{
3205				TextureCubeMap *cubeTexture = static_cast<TextureCubeMap*>(baseTexture);
3206
3207				for(int mipmapLevel = 0; mipmapLevel < sw::MIPMAP_LEVELS; mipmapLevel++)
3208				{
3209					int surfaceLevel = mipmapLevel;
3210
3211					if(surfaceLevel < 0)
3212					{
3213						surfaceLevel = 0;
3214					}
3215					else if(surfaceLevel >= levelCount)
3216					{
3217						surfaceLevel = levelCount - 1;
3218					}
3219
3220					egl::Image *surface = cubeTexture->getImage(face, surfaceLevel);
3221					device->setTextureLevel(sampler, face, mipmapLevel, surface, sw::TEXTURE_CUBE);
3222				}
3223			}
3224		}
3225		else UNIMPLEMENTED();
3226	}
3227	else
3228	{
3229		device->setTextureLevel(sampler, 0, 0, 0, sw::TEXTURE_NULL);
3230	}
3231}
3232
3233void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
3234{
3235	Framebuffer *framebuffer = getReadFramebuffer();
3236	int framebufferWidth, framebufferHeight, framebufferSamples;
3237
3238	if(framebuffer->completeness(framebufferWidth, framebufferHeight, framebufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3239	{
3240		return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3241	}
3242
3243	if(getReadFramebufferName() != 0 && framebufferSamples != 0)
3244	{
3245		return error(GL_INVALID_OPERATION);
3246	}
3247
3248	GLenum readFormat = GL_NONE;
3249	GLenum readType = GL_NONE;
3250	switch(format)
3251	{
3252	case GL_DEPTH_COMPONENT:
3253		readFormat = framebuffer->getDepthReadFormat();
3254		readType = framebuffer->getDepthReadType();
3255		break;
3256	default:
3257		readFormat = framebuffer->getImplementationColorReadFormat();
3258		readType = framebuffer->getImplementationColorReadType();
3259		break;
3260	}
3261
3262	if(!(readFormat == format && readType == type) && !ValidReadPixelsFormatType(readFormat, readType, format, type, clientVersion))
3263	{
3264		return error(GL_INVALID_OPERATION);
3265	}
3266
3267	GLsizei outputWidth = (mState.packRowLength > 0) ? mState.packRowLength : width;
3268	GLsizei outputPitch = egl::ComputePitch(outputWidth, format, type, mState.packAlignment);
3269	GLsizei outputHeight = (mState.packImageHeight == 0) ? height : mState.packImageHeight;
3270	pixels = getPixelPackBuffer() ? (unsigned char*)getPixelPackBuffer()->data() + (ptrdiff_t)pixels : (unsigned char*)pixels;
3271	pixels = ((char*)pixels) + egl::ComputePackingOffset(format, type, outputWidth, outputHeight, mState.packAlignment, mState.packSkipImages, mState.packSkipRows, mState.packSkipPixels);
3272
3273	// Sized query sanity check
3274	if(bufSize)
3275	{
3276		int requiredSize = outputPitch * height;
3277		if(requiredSize > *bufSize)
3278		{
3279			return error(GL_INVALID_OPERATION);
3280		}
3281	}
3282
3283	egl::Image *renderTarget = nullptr;
3284	switch(format)
3285	{
3286	case GL_DEPTH_COMPONENT:
3287		renderTarget = framebuffer->getDepthBuffer();
3288		break;
3289	default:
3290		renderTarget = framebuffer->getReadRenderTarget();
3291		break;
3292	}
3293
3294	if(!renderTarget)
3295	{
3296		return error(GL_INVALID_OPERATION);
3297	}
3298
3299	sw::Rect rect = {x, y, x + width, y + height};
3300	sw::Rect dstRect = { 0, 0, width, height };
3301	rect.clip(0, 0, renderTarget->getWidth(), renderTarget->getHeight());
3302
3303	sw::Surface externalSurface(width, height, 1, egl::ConvertFormatType(format, type), pixels, outputPitch, outputPitch * outputHeight);
3304	sw::SliceRect sliceRect(rect);
3305	sw::SliceRect dstSliceRect(dstRect);
3306	device->blit(renderTarget, sliceRect, &externalSurface, dstSliceRect, false);
3307
3308	renderTarget->release();
3309}
3310
3311void Context::clear(GLbitfield mask)
3312{
3313	if(mState.rasterizerDiscardEnabled)
3314	{
3315		return;
3316	}
3317
3318	Framebuffer *framebuffer = getDrawFramebuffer();
3319
3320	if(!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3321	{
3322		return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3323	}
3324
3325	if(!applyRenderTarget())
3326	{
3327		return;
3328	}
3329
3330	if(mask & GL_COLOR_BUFFER_BIT)
3331	{
3332		unsigned int rgbaMask = getColorMask();
3333
3334		if(rgbaMask != 0)
3335		{
3336			device->clearColor(mState.colorClearValue.red, mState.colorClearValue.green, mState.colorClearValue.blue, mState.colorClearValue.alpha, rgbaMask);
3337		}
3338	}
3339
3340	if(mask & GL_DEPTH_BUFFER_BIT)
3341	{
3342		if(mState.depthMask != 0)
3343		{
3344			float depth = clamp01(mState.depthClearValue);
3345			device->clearDepth(depth);
3346		}
3347	}
3348
3349	if(mask & GL_STENCIL_BUFFER_BIT)
3350	{
3351		if(mState.stencilWritemask != 0)
3352		{
3353			int stencil = mState.stencilClearValue & 0x000000FF;
3354			device->clearStencil(stencil, mState.stencilWritemask);
3355		}
3356	}
3357}
3358
3359void Context::clearColorBuffer(GLint drawbuffer, void *value, sw::Format format)
3360{
3361	unsigned int rgbaMask = getColorMask();
3362	if(rgbaMask && !mState.rasterizerDiscardEnabled)
3363	{
3364		Framebuffer *framebuffer = getDrawFramebuffer();
3365		egl::Image *colorbuffer = framebuffer->getRenderTarget(drawbuffer);
3366
3367		if(colorbuffer)
3368		{
3369			sw::SliceRect clearRect = colorbuffer->getRect();
3370
3371			if(mState.scissorTestEnabled)
3372			{
3373				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3374			}
3375
3376			device->clear(value, format, colorbuffer, clearRect, rgbaMask);
3377
3378			colorbuffer->release();
3379		}
3380	}
3381}
3382
3383void Context::clearColorBuffer(GLint drawbuffer, const GLint *value)
3384{
3385	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32I);
3386}
3387
3388void Context::clearColorBuffer(GLint drawbuffer, const GLuint *value)
3389{
3390	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32UI);
3391}
3392
3393void Context::clearColorBuffer(GLint drawbuffer, const GLfloat *value)
3394{
3395	clearColorBuffer(drawbuffer, (void*)value, sw::FORMAT_A32B32G32R32F);
3396}
3397
3398void Context::clearDepthBuffer(const GLfloat value)
3399{
3400	if(mState.depthMask && !mState.rasterizerDiscardEnabled)
3401	{
3402		Framebuffer *framebuffer = getDrawFramebuffer();
3403		egl::Image *depthbuffer = framebuffer->getDepthBuffer();
3404
3405		if(depthbuffer)
3406		{
3407			float depth = clamp01(value);
3408			sw::SliceRect clearRect = depthbuffer->getRect();
3409
3410			if(mState.scissorTestEnabled)
3411			{
3412				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3413			}
3414
3415			depthbuffer->clearDepth(depth, clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3416
3417			depthbuffer->release();
3418		}
3419	}
3420}
3421
3422void Context::clearStencilBuffer(const GLint value)
3423{
3424	if(mState.stencilWritemask && !mState.rasterizerDiscardEnabled)
3425	{
3426		Framebuffer *framebuffer = getDrawFramebuffer();
3427		egl::Image *stencilbuffer = framebuffer->getStencilBuffer();
3428
3429		if(stencilbuffer)
3430		{
3431			unsigned char stencil = value < 0 ? 0 : static_cast<unsigned char>(value & 0x000000FF);
3432			sw::SliceRect clearRect = stencilbuffer->getRect();
3433
3434			if(mState.scissorTestEnabled)
3435			{
3436				clearRect.clip(mState.scissorX, mState.scissorY, mState.scissorX + mState.scissorWidth, mState.scissorY + mState.scissorHeight);
3437			}
3438
3439			stencilbuffer->clearStencil(stencil, static_cast<unsigned char>(mState.stencilWritemask), clearRect.x0, clearRect.y0, clearRect.width(), clearRect.height());
3440
3441			stencilbuffer->release();
3442		}
3443	}
3444}
3445
3446void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instanceCount)
3447{
3448	if(!mState.currentProgram)
3449	{
3450		return error(GL_INVALID_OPERATION);
3451	}
3452
3453	sw::DrawType primitiveType;
3454	int primitiveCount;
3455	int verticesPerPrimitive;
3456
3457	if(!es2sw::ConvertPrimitiveType(mode, count, GL_NONE, primitiveType, primitiveCount, verticesPerPrimitive))
3458		return error(GL_INVALID_ENUM);
3459
3460	if(primitiveCount <= 0)
3461	{
3462		return;
3463	}
3464
3465	if(!applyRenderTarget())
3466	{
3467		return;
3468	}
3469
3470	applyState(mode);
3471
3472	for(int i = 0; i < instanceCount; ++i)
3473	{
3474		device->setInstanceID(i);
3475
3476		GLenum err = applyVertexBuffer(0, first, count, i);
3477		if(err != GL_NO_ERROR)
3478		{
3479			return error(err);
3480		}
3481
3482		applyShaders();
3483		applyTextures();
3484
3485		if(!getCurrentProgram()->validateSamplers(false))
3486		{
3487			return error(GL_INVALID_OPERATION);
3488		}
3489
3490		TransformFeedback* transformFeedback = getTransformFeedback();
3491		if(!cullSkipsDraw(mode) || (transformFeedback->isActive() && !transformFeedback->isPaused()))
3492		{
3493			device->drawPrimitive(primitiveType, primitiveCount);
3494		}
3495		if(transformFeedback)
3496		{
3497			transformFeedback->addVertexOffset(primitiveCount * verticesPerPrimitive);
3498		}
3499	}
3500}
3501
3502void Context::drawElements(GLenum mode, GLuint start, GLuint end, GLsizei count, GLenum type, const void *indices, GLsizei instanceCount)
3503{
3504	if(!mState.currentProgram)
3505	{
3506		return error(GL_INVALID_OPERATION);
3507	}
3508
3509	if(!indices && !getCurrentVertexArray()->getElementArrayBuffer())
3510	{
3511		return error(GL_INVALID_OPERATION);
3512	}
3513
3514	sw::DrawType primitiveType;
3515	int primitiveCount;
3516	int verticesPerPrimitive;
3517
3518	if(!es2sw::ConvertPrimitiveType(mode, count, type, primitiveType, primitiveCount, verticesPerPrimitive))
3519		return error(GL_INVALID_ENUM);
3520
3521	if(primitiveCount <= 0)
3522	{
3523		return;
3524	}
3525
3526	if(!applyRenderTarget())
3527	{
3528		return;
3529	}
3530
3531	applyState(mode);
3532
3533	for(int i = 0; i < instanceCount; ++i)
3534	{
3535		device->setInstanceID(i);
3536
3537		TranslatedIndexData indexInfo;
3538		GLenum err = applyIndexBuffer(indices, start, end, count, mode, type, &indexInfo);
3539		if(err != GL_NO_ERROR)
3540		{
3541			return error(err);
3542		}
3543
3544		GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3545		err = applyVertexBuffer(-(int)indexInfo.minIndex, indexInfo.minIndex, vertexCount, i);
3546		if(err != GL_NO_ERROR)
3547		{
3548			return error(err);
3549		}
3550
3551		applyShaders();
3552		applyTextures();
3553
3554		if(!getCurrentProgram()->validateSamplers(false))
3555		{
3556			return error(GL_INVALID_OPERATION);
3557		}
3558
3559		TransformFeedback* transformFeedback = getTransformFeedback();
3560		if(!cullSkipsDraw(mode) || (transformFeedback->isActive() && !transformFeedback->isPaused()))
3561		{
3562			device->drawIndexedPrimitive(primitiveType, indexInfo.indexOffset, primitiveCount);
3563		}
3564		if(transformFeedback)
3565		{
3566			transformFeedback->addVertexOffset(primitiveCount * verticesPerPrimitive);
3567		}
3568	}
3569}
3570
3571void Context::finish()
3572{
3573	device->finish();
3574}
3575
3576void Context::flush()
3577{
3578	// We don't queue anything without processing it as fast as possible
3579}
3580
3581void Context::recordInvalidEnum()
3582{
3583	mInvalidEnum = true;
3584}
3585
3586void Context::recordInvalidValue()
3587{
3588	mInvalidValue = true;
3589}
3590
3591void Context::recordInvalidOperation()
3592{
3593	mInvalidOperation = true;
3594}
3595
3596void Context::recordOutOfMemory()
3597{
3598	mOutOfMemory = true;
3599}
3600
3601void Context::recordInvalidFramebufferOperation()
3602{
3603	mInvalidFramebufferOperation = true;
3604}
3605
3606// Get one of the recorded errors and clear its flag, if any.
3607// [OpenGL ES 2.0.24] section 2.5 page 13.
3608GLenum Context::getError()
3609{
3610	if(mInvalidEnum)
3611	{
3612		mInvalidEnum = false;
3613
3614		return GL_INVALID_ENUM;
3615	}
3616
3617	if(mInvalidValue)
3618	{
3619		mInvalidValue = false;
3620
3621		return GL_INVALID_VALUE;
3622	}
3623
3624	if(mInvalidOperation)
3625	{
3626		mInvalidOperation = false;
3627
3628		return GL_INVALID_OPERATION;
3629	}
3630
3631	if(mOutOfMemory)
3632	{
3633		mOutOfMemory = false;
3634
3635		return GL_OUT_OF_MEMORY;
3636	}
3637
3638	if(mInvalidFramebufferOperation)
3639	{
3640		mInvalidFramebufferOperation = false;
3641
3642		return GL_INVALID_FRAMEBUFFER_OPERATION;
3643	}
3644
3645	return GL_NO_ERROR;
3646}
3647
3648int Context::getSupportedMultisampleCount(int requested)
3649{
3650	int supported = 0;
3651
3652	for(int i = NUM_MULTISAMPLE_COUNTS - 1; i >= 0; i--)
3653	{
3654		if(supported >= requested)
3655		{
3656			return supported;
3657		}
3658
3659		supported = multisampleCount[i];
3660	}
3661
3662	return supported;
3663}
3664
3665void Context::detachBuffer(GLuint buffer)
3666{
3667	// [OpenGL ES 2.0.24] section 2.9 page 22:
3668	// If a buffer object is deleted while it is bound, all bindings to that object in the current context
3669	// (i.e. in the thread that called Delete-Buffers) are reset to zero.
3670
3671	if(mState.copyReadBuffer.name() == buffer)
3672	{
3673		mState.copyReadBuffer = nullptr;
3674	}
3675
3676	if(mState.copyWriteBuffer.name() == buffer)
3677	{
3678		mState.copyWriteBuffer = nullptr;
3679	}
3680
3681	if(mState.pixelPackBuffer.name() == buffer)
3682	{
3683		mState.pixelPackBuffer = nullptr;
3684	}
3685
3686	if(mState.pixelUnpackBuffer.name() == buffer)
3687	{
3688		mState.pixelUnpackBuffer = nullptr;
3689	}
3690
3691	if(mState.genericUniformBuffer.name() == buffer)
3692	{
3693		mState.genericUniformBuffer = nullptr;
3694	}
3695
3696	if(getArrayBufferName() == buffer)
3697	{
3698		mState.arrayBuffer = nullptr;
3699	}
3700
3701	// Only detach from the current transform feedback
3702	TransformFeedback* currentTransformFeedback = getTransformFeedback();
3703	if(currentTransformFeedback)
3704	{
3705		currentTransformFeedback->detachBuffer(buffer);
3706	}
3707
3708	// Only detach from the current vertex array
3709	VertexArray* currentVertexArray = getCurrentVertexArray();
3710	if(currentVertexArray)
3711	{
3712		currentVertexArray->detachBuffer(buffer);
3713	}
3714
3715	for(int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3716	{
3717		if(mState.vertexAttribute[attribute].mBoundBuffer.name() == buffer)
3718		{
3719			mState.vertexAttribute[attribute].mBoundBuffer = nullptr;
3720		}
3721	}
3722}
3723
3724void Context::detachTexture(GLuint texture)
3725{
3726	// [OpenGL ES 2.0.24] section 3.8 page 84:
3727	// If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3728	// rebound to texture object zero
3729
3730	for(int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3731	{
3732		for(int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS; sampler++)
3733		{
3734			if(mState.samplerTexture[type][sampler].name() == texture)
3735			{
3736				mState.samplerTexture[type][sampler] = nullptr;
3737			}
3738		}
3739	}
3740
3741	// [OpenGL ES 2.0.24] section 4.4 page 112:
3742	// If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3743	// as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3744	// image was attached in the currently bound framebuffer.
3745
3746	Framebuffer *readFramebuffer = getReadFramebuffer();
3747	Framebuffer *drawFramebuffer = getDrawFramebuffer();
3748
3749	if(readFramebuffer)
3750	{
3751		readFramebuffer->detachTexture(texture);
3752	}
3753
3754	if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3755	{
3756		drawFramebuffer->detachTexture(texture);
3757	}
3758}
3759
3760void Context::detachFramebuffer(GLuint framebuffer)
3761{
3762	// [OpenGL ES 2.0.24] section 4.4 page 107:
3763	// If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3764	// BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3765
3766	if(mState.readFramebuffer == framebuffer)
3767	{
3768		bindReadFramebuffer(0);
3769	}
3770
3771	if(mState.drawFramebuffer == framebuffer)
3772	{
3773		bindDrawFramebuffer(0);
3774	}
3775}
3776
3777void Context::detachRenderbuffer(GLuint renderbuffer)
3778{
3779	// [OpenGL ES 2.0.24] section 4.4 page 109:
3780	// If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3781	// had been executed with the target RENDERBUFFER and name of zero.
3782
3783	if(mState.renderbuffer.name() == renderbuffer)
3784	{
3785		bindRenderbuffer(0);
3786	}
3787
3788	// [OpenGL ES 2.0.24] section 4.4 page 111:
3789	// If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3790	// then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3791	// point to which this image was attached in the currently bound framebuffer.
3792
3793	Framebuffer *readFramebuffer = getReadFramebuffer();
3794	Framebuffer *drawFramebuffer = getDrawFramebuffer();
3795
3796	if(readFramebuffer)
3797	{
3798		readFramebuffer->detachRenderbuffer(renderbuffer);
3799	}
3800
3801	if(drawFramebuffer && drawFramebuffer != readFramebuffer)
3802	{
3803		drawFramebuffer->detachRenderbuffer(renderbuffer);
3804	}
3805}
3806
3807void Context::detachSampler(GLuint sampler)
3808{
3809	// [OpenGL ES 3.0.2] section 3.8.2 pages 123-124:
3810	// If a sampler object that is currently bound to one or more texture units is
3811	// deleted, it is as though BindSampler is called once for each texture unit to
3812	// which the sampler is bound, with unit set to the texture unit and sampler set to zero.
3813	for(size_t textureUnit = 0; textureUnit < MAX_COMBINED_TEXTURE_IMAGE_UNITS; ++textureUnit)
3814	{
3815		gl::BindingPointer<Sampler> &samplerBinding = mState.sampler[textureUnit];
3816		if(samplerBinding.name() == sampler)
3817		{
3818			samplerBinding = nullptr;
3819		}
3820	}
3821}
3822
3823bool Context::cullSkipsDraw(GLenum drawMode)
3824{
3825	return mState.cullFaceEnabled && mState.cullMode == GL_FRONT_AND_BACK && isTriangleMode(drawMode);
3826}
3827
3828bool Context::isTriangleMode(GLenum drawMode)
3829{
3830	switch(drawMode)
3831	{
3832	case GL_TRIANGLES:
3833	case GL_TRIANGLE_FAN:
3834	case GL_TRIANGLE_STRIP:
3835		return true;
3836	case GL_POINTS:
3837	case GL_LINES:
3838	case GL_LINE_LOOP:
3839	case GL_LINE_STRIP:
3840		return false;
3841	default: UNREACHABLE(drawMode);
3842	}
3843
3844	return false;
3845}
3846
3847void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3848{
3849	ASSERT(index < MAX_VERTEX_ATTRIBS);
3850
3851	mState.vertexAttribute[index].setCurrentValue(values);
3852
3853	mVertexDataManager->dirtyCurrentValue(index);
3854}
3855
3856void Context::setVertexAttrib(GLuint index, const GLint *values)
3857{
3858	ASSERT(index < MAX_VERTEX_ATTRIBS);
3859
3860	mState.vertexAttribute[index].setCurrentValue(values);
3861
3862	mVertexDataManager->dirtyCurrentValue(index);
3863}
3864
3865void Context::setVertexAttrib(GLuint index, const GLuint *values)
3866{
3867	ASSERT(index < MAX_VERTEX_ATTRIBS);
3868
3869	mState.vertexAttribute[index].setCurrentValue(values);
3870
3871	mVertexDataManager->dirtyCurrentValue(index);
3872}
3873
3874void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3875                              GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3876                              GLbitfield mask, bool filter, bool allowPartialDepthStencilBlit)
3877{
3878	Framebuffer *readFramebuffer = getReadFramebuffer();
3879	Framebuffer *drawFramebuffer = getDrawFramebuffer();
3880
3881	int readBufferWidth, readBufferHeight, readBufferSamples;
3882	int drawBufferWidth, drawBufferHeight, drawBufferSamples;
3883
3884	if(!readFramebuffer || readFramebuffer->completeness(readBufferWidth, readBufferHeight, readBufferSamples) != GL_FRAMEBUFFER_COMPLETE ||
3885	   !drawFramebuffer || drawFramebuffer->completeness(drawBufferWidth, drawBufferHeight, drawBufferSamples) != GL_FRAMEBUFFER_COMPLETE)
3886	{
3887		return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3888	}
3889
3890	if(drawBufferSamples > 1)
3891	{
3892		return error(GL_INVALID_OPERATION);
3893	}
3894
3895	sw::SliceRect sourceRect;
3896	sw::SliceRect destRect;
3897	bool flipX = (srcX0 < srcX1) ^ (dstX0 < dstX1);
3898	bool flipy = (srcY0 < srcY1) ^ (dstY0 < dstY1);
3899
3900	if(srcX0 < srcX1)
3901	{
3902		sourceRect.x0 = srcX0;
3903		sourceRect.x1 = srcX1;
3904	}
3905	else
3906	{
3907		sourceRect.x0 = srcX1;
3908		sourceRect.x1 = srcX0;
3909	}
3910
3911	if(dstX0 < dstX1)
3912	{
3913		destRect.x0 = dstX0;
3914		destRect.x1 = dstX1;
3915	}
3916	else
3917	{
3918		destRect.x0 = dstX1;
3919		destRect.x1 = dstX0;
3920	}
3921
3922	if(srcY0 < srcY1)
3923	{
3924		sourceRect.y0 = srcY0;
3925		sourceRect.y1 = srcY1;
3926	}
3927	else
3928	{
3929		sourceRect.y0 = srcY1;
3930		sourceRect.y1 = srcY0;
3931	}
3932
3933	if(dstY0 < dstY1)
3934	{
3935		destRect.y0 = dstY0;
3936		destRect.y1 = dstY1;
3937	}
3938	else
3939	{
3940		destRect.y0 = dstY1;
3941		destRect.y1 = dstY0;
3942	}
3943
3944	sw::Rect sourceScissoredRect = sourceRect;
3945	sw::Rect destScissoredRect = destRect;
3946
3947	if(mState.scissorTestEnabled)   // Only write to parts of the destination framebuffer which pass the scissor test
3948	{
3949		if(destRect.x0 < mState.scissorX)
3950		{
3951			int xDiff = mState.scissorX - destRect.x0;
3952			destScissoredRect.x0 = mState.scissorX;
3953			sourceScissoredRect.x0 += xDiff;
3954		}
3955
3956		if(destRect.x1 > mState.scissorX + mState.scissorWidth)
3957		{
3958			int xDiff = destRect.x1 - (mState.scissorX + mState.scissorWidth);
3959			destScissoredRect.x1 = mState.scissorX + mState.scissorWidth;
3960			sourceScissoredRect.x1 -= xDiff;
3961		}
3962
3963		if(destRect.y0 < mState.scissorY)
3964		{
3965			int yDiff = mState.scissorY - destRect.y0;
3966			destScissoredRect.y0 = mState.scissorY;
3967			sourceScissoredRect.y0 += yDiff;
3968		}
3969
3970		if(destRect.y1 > mState.scissorY + mState.scissorHeight)
3971		{
3972			int yDiff = destRect.y1 - (mState.scissorY + mState.scissorHeight);
3973			destScissoredRect.y1 = mState.scissorY + mState.scissorHeight;
3974			sourceScissoredRect.y1 -= yDiff;
3975		}
3976	}
3977
3978	sw::Rect sourceTrimmedRect = sourceScissoredRect;
3979	sw::Rect destTrimmedRect = destScissoredRect;
3980
3981	// The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
3982	// the actual draw and read surfaces.
3983	if(sourceTrimmedRect.x0 < 0)
3984	{
3985		int xDiff = 0 - sourceTrimmedRect.x0;
3986		sourceTrimmedRect.x0 = 0;
3987		destTrimmedRect.x0 += xDiff;
3988	}
3989
3990	if(sourceTrimmedRect.x1 > readBufferWidth)
3991	{
3992		int xDiff = sourceTrimmedRect.x1 - readBufferWidth;
3993		sourceTrimmedRect.x1 = readBufferWidth;
3994		destTrimmedRect.x1 -= xDiff;
3995	}
3996
3997	if(sourceTrimmedRect.y0 < 0)
3998	{
3999		int yDiff = 0 - sourceTrimmedRect.y0;
4000		sourceTrimmedRect.y0 = 0;
4001		destTrimmedRect.y0 += yDiff;
4002	}
4003
4004	if(sourceTrimmedRect.y1 > readBufferHeight)
4005	{
4006		int yDiff = sourceTrimmedRect.y1 - readBufferHeight;
4007		sourceTrimmedRect.y1 = readBufferHeight;
4008		destTrimmedRect.y1 -= yDiff;
4009	}
4010
4011	if(destTrimmedRect.x0 < 0)
4012	{
4013		int xDiff = 0 - destTrimmedRect.x0;
4014		destTrimmedRect.x0 = 0;
4015		sourceTrimmedRect.x0 += xDiff;
4016	}
4017
4018	if(destTrimmedRect.x1 > drawBufferWidth)
4019	{
4020		int xDiff = destTrimmedRect.x1 - drawBufferWidth;
4021		destTrimmedRect.x1 = drawBufferWidth;
4022		sourceTrimmedRect.x1 -= xDiff;
4023	}
4024
4025	if(destTrimmedRect.y0 < 0)
4026	{
4027		int yDiff = 0 - destTrimmedRect.y0;
4028		destTrimmedRect.y0 = 0;
4029		sourceTrimmedRect.y0 += yDiff;
4030	}
4031
4032	if(destTrimmedRect.y1 > drawBufferHeight)
4033	{
4034		int yDiff = destTrimmedRect.y1 - drawBufferHeight;
4035		destTrimmedRect.y1 = drawBufferHeight;
4036		sourceTrimmedRect.y1 -= yDiff;
4037	}
4038
4039	bool partialBufferCopy = false;
4040
4041	if(sourceTrimmedRect.y1 - sourceTrimmedRect.y0 < readBufferHeight ||
4042	   sourceTrimmedRect.x1 - sourceTrimmedRect.x0 < readBufferWidth ||
4043	   destTrimmedRect.y1 - destTrimmedRect.y0 < drawBufferHeight ||
4044	   destTrimmedRect.x1 - destTrimmedRect.x0 < drawBufferWidth ||
4045	   sourceTrimmedRect.y0 != 0 || destTrimmedRect.y0 != 0 || sourceTrimmedRect.x0 != 0 || destTrimmedRect.x0 != 0)
4046	{
4047		partialBufferCopy = true;
4048	}
4049
4050	bool blitRenderTarget = false;
4051	bool blitDepth = false;
4052	bool blitStencil = false;
4053
4054	if(mask & GL_COLOR_BUFFER_BIT)
4055	{
4056		GLenum readColorbufferType = readFramebuffer->getColorbufferType(getReadFramebufferColorIndex());
4057		GLenum drawColorbufferType = drawFramebuffer->getColorbufferType(0);
4058		const bool validReadType = readColorbufferType == GL_TEXTURE_2D || Framebuffer::IsRenderbuffer(readColorbufferType);
4059		const bool validDrawType = drawColorbufferType == GL_TEXTURE_2D || Framebuffer::IsRenderbuffer(drawColorbufferType);
4060		if(!validReadType || !validDrawType)
4061		{
4062			return error(GL_INVALID_OPERATION);
4063		}
4064
4065		if(partialBufferCopy && readBufferSamples > 1)
4066		{
4067			return error(GL_INVALID_OPERATION);
4068		}
4069
4070		blitRenderTarget = true;
4071	}
4072
4073	if(mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4074	{
4075		Renderbuffer *readDSBuffer = nullptr;
4076		Renderbuffer *drawDSBuffer = nullptr;
4077
4078		if(mask & GL_DEPTH_BUFFER_BIT)
4079		{
4080			if(readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4081			{
4082				if(readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType())
4083				{
4084					return error(GL_INVALID_OPERATION);
4085				}
4086
4087				blitDepth = true;
4088				readDSBuffer = readFramebuffer->getDepthbuffer();
4089				drawDSBuffer = drawFramebuffer->getDepthbuffer();
4090			}
4091		}
4092
4093		if(mask & GL_STENCIL_BUFFER_BIT)
4094		{
4095			if(readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4096			{
4097				if(readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType())
4098				{
4099					return error(GL_INVALID_OPERATION);
4100				}
4101
4102				blitStencil = true;
4103				readDSBuffer = readFramebuffer->getStencilbuffer();
4104				drawDSBuffer = drawFramebuffer->getStencilbuffer();
4105			}
4106		}
4107
4108		if(partialBufferCopy && !allowPartialDepthStencilBlit)
4109		{
4110			ERR("Only whole-buffer depth and stencil blits are supported by ANGLE_framebuffer_blit.");
4111			return error(GL_INVALID_OPERATION);   // Only whole-buffer copies are permitted
4112		}
4113
4114		// OpenGL ES 3.0.4 spec, p.199:
4115		// ...an INVALID_OPERATION error is generated if the formats of the read
4116		// and draw framebuffers are not identical or if the source and destination
4117		// rectangles are not defined with the same(X0, Y 0) and (X1, Y 1) bounds.
4118		// If SAMPLE_BUFFERS for the draw framebuffer is greater than zero, an
4119		// INVALID_OPERATION error is generated.
4120		if((drawDSBuffer && drawDSBuffer->getSamples() > 1) ||
4121		   ((readDSBuffer && readDSBuffer->getSamples() > 1) &&
4122		    ((srcX0 != dstX0 || srcY0 != dstY0 || srcX1 != dstX1 || srcY1 != dstY1) ||
4123		     (drawDSBuffer->getFormat() != readDSBuffer->getFormat()))))
4124		{
4125			return error(GL_INVALID_OPERATION);
4126		}
4127	}
4128
4129	if(blitRenderTarget || blitDepth || blitStencil)
4130	{
4131		if(blitRenderTarget)
4132		{
4133			egl::Image *readRenderTarget = readFramebuffer->getReadRenderTarget();
4134			egl::Image *drawRenderTarget = drawFramebuffer->getRenderTarget(0);
4135
4136			if(flipX)
4137			{
4138				swap(destRect.x0, destRect.x1);
4139			}
4140			if(flipy)
4141			{
4142				swap(destRect.y0, destRect.y1);
4143			}
4144
4145			bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, (filter ? Device::USE_FILTER : 0) | Device::COLOR_BUFFER);
4146
4147			readRenderTarget->release();
4148			drawRenderTarget->release();
4149
4150			if(!success)
4151			{
4152				ERR("BlitFramebuffer failed.");
4153				return;
4154			}
4155		}
4156
4157		if(blitDepth)
4158		{
4159			egl::Image *readRenderTarget = readFramebuffer->getDepthBuffer();
4160			egl::Image *drawRenderTarget = drawFramebuffer->getDepthBuffer();
4161
4162			bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, (filter ? Device::USE_FILTER : 0) | Device::DEPTH_BUFFER);
4163
4164			readRenderTarget->release();
4165			drawRenderTarget->release();
4166
4167			if(!success)
4168			{
4169				ERR("BlitFramebuffer failed.");
4170				return;
4171			}
4172		}
4173
4174		if(blitStencil)
4175		{
4176			egl::Image *readRenderTarget = readFramebuffer->getStencilBuffer();
4177			egl::Image *drawRenderTarget = drawFramebuffer->getStencilBuffer();
4178
4179			bool success = device->stretchRect(readRenderTarget, &sourceRect, drawRenderTarget, &destRect, (filter ? Device::USE_FILTER : 0) | Device::STENCIL_BUFFER);
4180
4181			readRenderTarget->release();
4182			drawRenderTarget->release();
4183
4184			if(!success)
4185			{
4186				ERR("BlitFramebuffer failed.");
4187				return;
4188			}
4189		}
4190	}
4191}
4192
4193void Context::bindTexImage(egl::Surface *surface)
4194{
4195	es2::Texture2D *textureObject = getTexture2D();
4196
4197	if(textureObject)
4198	{
4199		textureObject->bindTexImage(surface);
4200	}
4201}
4202
4203EGLenum Context::validateSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4204{
4205	GLenum textureTarget = GL_NONE;
4206
4207	switch(target)
4208	{
4209	case EGL_GL_TEXTURE_2D_KHR:
4210		textureTarget = GL_TEXTURE_2D;
4211		break;
4212	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR:
4213	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR:
4214	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR:
4215	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR:
4216	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR:
4217	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR:
4218		textureTarget = GL_TEXTURE_CUBE_MAP;
4219		break;
4220	case EGL_GL_RENDERBUFFER_KHR:
4221		break;
4222	default:
4223		return EGL_BAD_PARAMETER;
4224	}
4225
4226	if(textureLevel >= es2::IMPLEMENTATION_MAX_TEXTURE_LEVELS)
4227	{
4228		return EGL_BAD_MATCH;
4229	}
4230
4231	if(textureTarget != GL_NONE)
4232	{
4233		es2::Texture *texture = getTexture(name);
4234
4235		if(!texture || texture->getTarget() != textureTarget)
4236		{
4237			return EGL_BAD_PARAMETER;
4238		}
4239
4240		if(texture->isShared(textureTarget, textureLevel))   // Bound to an EGLSurface or already an EGLImage sibling
4241		{
4242			return EGL_BAD_ACCESS;
4243		}
4244
4245		if(textureLevel != 0 && !texture->isSamplerComplete())
4246		{
4247			return EGL_BAD_PARAMETER;
4248		}
4249
4250		if(textureLevel == 0 && !(texture->isSamplerComplete() && texture->getLevelCount() == 1))
4251		{
4252			return EGL_BAD_PARAMETER;
4253		}
4254	}
4255	else if(target == EGL_GL_RENDERBUFFER_KHR)
4256	{
4257		es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4258
4259		if(!renderbuffer)
4260		{
4261			return EGL_BAD_PARAMETER;
4262		}
4263
4264		if(renderbuffer->isShared())   // Already an EGLImage sibling
4265		{
4266			return EGL_BAD_ACCESS;
4267		}
4268	}
4269	else UNREACHABLE(target);
4270
4271	return EGL_SUCCESS;
4272}
4273
4274egl::Image *Context::createSharedImage(EGLenum target, GLuint name, GLuint textureLevel)
4275{
4276	GLenum textureTarget = GL_NONE;
4277
4278	switch(target)
4279	{
4280	case EGL_GL_TEXTURE_2D_KHR:                  textureTarget = GL_TEXTURE_2D;                  break;
4281	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_X; break;
4282	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_X_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_X; break;
4283	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Y; break;
4284	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; break;
4285	case EGL_GL_TEXTURE_CUBE_MAP_POSITIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_POSITIVE_Z; break;
4286	case EGL_GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_KHR: textureTarget = GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; break;
4287	}
4288
4289	if(textureTarget != GL_NONE)
4290	{
4291		es2::Texture *texture = getTexture(name);
4292
4293		return texture->createSharedImage(textureTarget, textureLevel);
4294	}
4295	else if(target == EGL_GL_RENDERBUFFER_KHR)
4296	{
4297		es2::Renderbuffer *renderbuffer = getRenderbuffer(name);
4298
4299		return renderbuffer->createSharedImage();
4300	}
4301	else UNREACHABLE(target);
4302
4303	return nullptr;
4304}
4305
4306egl::Image *Context::getSharedImage(GLeglImageOES image)
4307{
4308	return display->getSharedImage(image);
4309}
4310
4311Device *Context::getDevice()
4312{
4313	return device;
4314}
4315
4316const GLubyte* Context::getExtensions(GLuint index, GLuint* numExt) const
4317{
4318	// Keep list sorted in following order:
4319	// OES extensions
4320	// EXT extensions
4321	// Vendor extensions
4322	static const GLubyte* extensions[] = {
4323		(const GLubyte*)"GL_OES_compressed_ETC1_RGB8_texture",
4324		(const GLubyte*)"GL_OES_depth24",
4325		(const GLubyte*)"GL_OES_depth32",
4326		(const GLubyte*)"GL_OES_depth_texture",
4327		(const GLubyte*)"GL_OES_depth_texture_cube_map",
4328		(const GLubyte*)"GL_OES_EGL_image",
4329		(const GLubyte*)"GL_OES_EGL_image_external",
4330		(const GLubyte*)"GL_OES_EGL_sync",
4331		(const GLubyte*)"GL_OES_element_index_uint",
4332		(const GLubyte*)"GL_OES_framebuffer_object",
4333		(const GLubyte*)"GL_OES_packed_depth_stencil",
4334		(const GLubyte*)"GL_OES_rgb8_rgba8",
4335		(const GLubyte*)"GL_OES_standard_derivatives",
4336		(const GLubyte*)"GL_OES_texture_float",
4337		(const GLubyte*)"GL_OES_texture_float_linear",
4338		(const GLubyte*)"GL_OES_texture_half_float",
4339		(const GLubyte*)"GL_OES_texture_half_float_linear",
4340		(const GLubyte*)"GL_OES_texture_npot",
4341		(const GLubyte*)"GL_OES_texture_3D",
4342		(const GLubyte*)"GL_EXT_blend_minmax",
4343		(const GLubyte*)"GL_EXT_color_buffer_half_float",
4344		(const GLubyte*)"GL_EXT_draw_buffers",
4345		(const GLubyte*)"GL_EXT_occlusion_query_boolean",
4346		(const GLubyte*)"GL_EXT_read_format_bgra",
4347#if (S3TC_SUPPORT)
4348		(const GLubyte*)"GL_EXT_texture_compression_dxt1",
4349#endif
4350		(const GLubyte*)"GL_EXT_texture_filter_anisotropic",
4351		(const GLubyte*)"GL_EXT_texture_format_BGRA8888",
4352		(const GLubyte*)"GL_ANGLE_framebuffer_blit",
4353		(const GLubyte*)"GL_NV_framebuffer_blit",
4354		(const GLubyte*)"GL_ANGLE_framebuffer_multisample",
4355#if (S3TC_SUPPORT)
4356		(const GLubyte*)"GL_ANGLE_texture_compression_dxt3",
4357		(const GLubyte*)"GL_ANGLE_texture_compression_dxt5",
4358#endif
4359		(const GLubyte*)"GL_NV_fence",
4360		(const GLubyte*)"GL_NV_read_depth",
4361		(const GLubyte*)"GL_EXT_instanced_arrays",
4362		(const GLubyte*)"GL_ANGLE_instanced_arrays",
4363	};
4364	static const GLuint numExtensions = sizeof(extensions) / sizeof(*extensions);
4365
4366	if(numExt)
4367	{
4368		*numExt = numExtensions;
4369		return nullptr;
4370	}
4371
4372	if(index == GL_INVALID_INDEX)
4373	{
4374		static GLubyte* extensionsCat = nullptr;
4375		if(!extensionsCat && (numExtensions > 0))
4376		{
4377			size_t totalLength = numExtensions; // 1 space between each extension name + terminating null
4378			for(unsigned int i = 0; i < numExtensions; i++)
4379			{
4380				totalLength += strlen(reinterpret_cast<const char*>(extensions[i]));
4381			}
4382			extensionsCat = new GLubyte[totalLength];
4383			extensionsCat[0] = '\0';
4384			for(unsigned int i = 0; i < numExtensions; i++)
4385			{
4386				if(i != 0)
4387				{
4388					strcat(reinterpret_cast<char*>(extensionsCat), " ");
4389				}
4390				strcat(reinterpret_cast<char*>(extensionsCat), reinterpret_cast<const char*>(extensions[i]));
4391			}
4392		}
4393		return extensionsCat;
4394	}
4395
4396	if(index >= numExtensions)
4397	{
4398		return nullptr;
4399	}
4400
4401	return extensions[index];
4402}
4403
4404}
4405
4406egl::Context *es2CreateContext(egl::Display *display, const egl::Context *shareContext, int clientVersion)
4407{
4408	ASSERT(!shareContext || shareContext->getClientVersion() == clientVersion);   // Should be checked by eglCreateContext
4409	return new es2::Context(display, static_cast<const es2::Context*>(shareContext), clientVersion);
4410}
4411