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