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