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