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