blob: 4c1383a760c9890889940a557e181195ad3a564d [file] [log] [blame]
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001//
2// Copyright (c) 2002-2012 The ANGLE Project Authors. All rights reserved.
3// Use of this source code is governed by a BSD-style license that can be
4// found in the LICENSE file.
5//
6
7// Context.cpp: Implements the gl::Context class, managing all GL state and performing
8// rendering operations. It is the GLES2 specific implementation of EGLContext.
9
10#include "libGLESv2/Context.h"
11
12#include <algorithm>
13
14#include "libEGL/Display.h"
15
16#include "libGLESv2/main.h"
17#include "libGLESv2/mathutil.h"
18#include "libGLESv2/utilities.h"
daniel@transgaming.comd8e36562012-10-31 19:52:19 +000019#include "libGLESv2/renderer/renderer9_utils.h" // D3D9_REPLACE
apatrick@chromium.org144f2802012-07-12 01:42:34 +000020#include "libGLESv2/Blit.h"
21#include "libGLESv2/ResourceManager.h"
22#include "libGLESv2/Buffer.h"
23#include "libGLESv2/Fence.h"
daniel@transgaming.com29ab9522012-08-27 16:25:37 +000024#include "libGLESv2/Framebuffer.h"
apatrick@chromium.org144f2802012-07-12 01:42:34 +000025#include "libGLESv2/Program.h"
26#include "libGLESv2/ProgramBinary.h"
27#include "libGLESv2/Query.h"
daniel@transgaming.com29ab9522012-08-27 16:25:37 +000028#include "libGLESv2/Renderbuffer.h"
apatrick@chromium.org144f2802012-07-12 01:42:34 +000029#include "libGLESv2/Shader.h"
30#include "libGLESv2/Texture.h"
31#include "libGLESv2/VertexDataManager.h"
32#include "libGLESv2/IndexDataManager.h"
33
34#undef near
35#undef far
36
37namespace gl
38{
daniel@transgaming.com03d39092012-11-28 19:31:59 +000039Context::Context(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +000040{
41 ASSERT(robustAccess == false); // Unimplemented
42
daniel@transgaming.com03d39092012-11-28 19:31:59 +000043 ASSERT(dynamic_cast<rx::Renderer9*>(renderer) != NULL); // D3D9_REPLACE
44 mRenderer = static_cast<rx::Renderer9*>(renderer);
45
apatrick@chromium.org144f2802012-07-12 01:42:34 +000046 mDisplay = NULL;
47 mDevice = NULL;
48
49 mFenceHandleAllocator.setBaseHandle(0);
50
51 setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
52
53 mState.depthClearValue = 1.0f;
54 mState.stencilClearValue = 0;
55
56 mState.cullFace = false;
57 mState.cullMode = GL_BACK;
58 mState.frontFace = GL_CCW;
59 mState.depthTest = false;
60 mState.depthFunc = GL_LESS;
61 mState.blend = false;
62 mState.sourceBlendRGB = GL_ONE;
63 mState.sourceBlendAlpha = GL_ONE;
64 mState.destBlendRGB = GL_ZERO;
65 mState.destBlendAlpha = GL_ZERO;
66 mState.blendEquationRGB = GL_FUNC_ADD;
67 mState.blendEquationAlpha = GL_FUNC_ADD;
68 mState.blendColor.red = 0;
69 mState.blendColor.green = 0;
70 mState.blendColor.blue = 0;
71 mState.blendColor.alpha = 0;
72 mState.stencilTest = false;
73 mState.stencilFunc = GL_ALWAYS;
74 mState.stencilRef = 0;
75 mState.stencilMask = -1;
76 mState.stencilWritemask = -1;
77 mState.stencilBackFunc = GL_ALWAYS;
78 mState.stencilBackRef = 0;
79 mState.stencilBackMask = - 1;
80 mState.stencilBackWritemask = -1;
81 mState.stencilFail = GL_KEEP;
82 mState.stencilPassDepthFail = GL_KEEP;
83 mState.stencilPassDepthPass = GL_KEEP;
84 mState.stencilBackFail = GL_KEEP;
85 mState.stencilBackPassDepthFail = GL_KEEP;
86 mState.stencilBackPassDepthPass = GL_KEEP;
87 mState.polygonOffsetFill = false;
88 mState.polygonOffsetFactor = 0.0f;
89 mState.polygonOffsetUnits = 0.0f;
90 mState.sampleAlphaToCoverage = false;
91 mState.sampleCoverage = false;
92 mState.sampleCoverageValue = 1.0f;
93 mState.sampleCoverageInvert = false;
94 mState.scissorTest = false;
95 mState.dither = true;
96 mState.generateMipmapHint = GL_DONT_CARE;
97 mState.fragmentShaderDerivativeHint = GL_DONT_CARE;
98
99 mState.lineWidth = 1.0f;
100
101 mState.viewportX = 0;
102 mState.viewportY = 0;
daniel@transgaming.com21290e62012-10-31 18:38:28 +0000103 mState.viewportWidth = 0;
104 mState.viewportHeight = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000105 mState.zNear = 0.0f;
106 mState.zFar = 1.0f;
107
108 mState.scissorX = 0;
109 mState.scissorY = 0;
daniel@transgaming.com21290e62012-10-31 18:38:28 +0000110 mState.scissorWidth = 0;
111 mState.scissorHeight = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000112
113 mState.colorMaskRed = true;
114 mState.colorMaskGreen = true;
115 mState.colorMaskBlue = true;
116 mState.colorMaskAlpha = true;
117 mState.depthMask = true;
118
119 if (shareContext != NULL)
120 {
121 mResourceManager = shareContext->mResourceManager;
122 mResourceManager->addRef();
123 }
124 else
125 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +0000126 mResourceManager = new ResourceManager(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000127 }
128
129 // [OpenGL ES 2.0.24] section 3.7 page 83:
130 // In the initial state, TEXTURE_2D and TEXTURE_CUBE_MAP have twodimensional
131 // and cube map texture state vectors respectively associated with them.
132 // In order that access to these initial textures not be lost, they are treated as texture
133 // objects all of whose names are 0.
134
daniel@transgaming.com370482e2012-11-28 19:32:13 +0000135 mTexture2DZero.set(new Texture2D(mRenderer, 0));
136 mTextureCubeMapZero.set(new TextureCubeMap(mRenderer, 0));
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000137
138 mState.activeSampler = 0;
139 bindArrayBuffer(0);
140 bindElementArrayBuffer(0);
141 bindTextureCubeMap(0);
142 bindTexture2D(0);
143 bindReadFramebuffer(0);
144 bindDrawFramebuffer(0);
145 bindRenderbuffer(0);
146
147 mState.currentProgram = 0;
daniel@transgaming.com989c1c82012-07-24 18:40:38 +0000148 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000149
150 mState.packAlignment = 4;
151 mState.unpackAlignment = 4;
152 mState.packReverseRowOrder = false;
153
154 mVertexDataManager = NULL;
155 mIndexDataManager = NULL;
156 mBlit = NULL;
157 mLineLoopIB = NULL;
158
159 mInvalidEnum = false;
160 mInvalidValue = false;
161 mInvalidOperation = false;
162 mOutOfMemory = false;
163 mInvalidFramebufferOperation = false;
164
165 mHasBeenCurrent = false;
166 mContextLost = false;
167 mResetStatus = GL_NO_ERROR;
168 mResetStrategy = (notifyResets ? GL_LOSE_CONTEXT_ON_RESET_EXT : GL_NO_RESET_NOTIFICATION_EXT);
169 mRobustAccess = robustAccess;
170
171 mSupportsDXT1Textures = false;
172 mSupportsDXT3Textures = false;
173 mSupportsDXT5Textures = false;
174 mSupportsEventQueries = false;
175 mSupportsOcclusionQueries = false;
176 mNumCompressedTextureFormats = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000177 mMaskedClearSavedState = NULL;
178 markAllStateDirty();
179}
180
181Context::~Context()
182{
183 if (mState.currentProgram != 0)
184 {
185 Program *programObject = mResourceManager->getProgram(mState.currentProgram);
186 if (programObject)
187 {
188 programObject->release();
189 }
190 mState.currentProgram = 0;
191 }
daniel@transgaming.com989c1c82012-07-24 18:40:38 +0000192 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000193
194 while (!mFramebufferMap.empty())
195 {
196 deleteFramebuffer(mFramebufferMap.begin()->first);
197 }
198
199 while (!mFenceMap.empty())
200 {
201 deleteFence(mFenceMap.begin()->first);
202 }
203
204 while (!mQueryMap.empty())
205 {
206 deleteQuery(mQueryMap.begin()->first);
207 }
208
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000209 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
210 {
211 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
212 {
213 mState.samplerTexture[type][sampler].set(NULL);
214 }
215 }
216
217 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
218 {
219 mIncompleteTextures[type].set(NULL);
220 }
221
222 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
223 {
224 mState.vertexAttribute[i].mBoundBuffer.set(NULL);
225 }
226
227 for (int i = 0; i < QUERY_TYPE_COUNT; i++)
228 {
229 mState.activeQuery[i].set(NULL);
230 }
231
232 mState.arrayBuffer.set(NULL);
233 mState.elementArrayBuffer.set(NULL);
234 mState.renderbuffer.set(NULL);
235
236 mTexture2DZero.set(NULL);
237 mTextureCubeMapZero.set(NULL);
238
239 delete mVertexDataManager;
240 delete mIndexDataManager;
241 delete mBlit;
242 delete mLineLoopIB;
243
244 if (mMaskedClearSavedState)
245 {
246 mMaskedClearSavedState->Release();
247 }
248
249 mResourceManager->release();
250}
251
daniel@transgaming.comad629872012-11-28 19:32:06 +0000252void Context::makeCurrent(egl::Surface *surface)
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000253{
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000254 mDevice = mRenderer->getDevice(); // D3D9_REMOVE
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000255
256 if (!mHasBeenCurrent)
257 {
daniel@transgaming.com408caa52012-10-31 18:47:01 +0000258 mVertexDataManager = new VertexDataManager(mRenderer);
259 mIndexDataManager = new IndexDataManager(mRenderer);
daniel@transgaming.come4733d72012-10-31 18:07:01 +0000260 mBlit = new Blit(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000261
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000262 mSupportsShaderModel3 = mRenderer->getShaderModel3Support();
263 mMaximumPointSize = mRenderer->getMaxPointSize();
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000264 mSupportsVertexTexture = mRenderer->getVertexTextureSupport();
265 mSupportsNonPower2Texture = mRenderer->getNonPower2TextureSupport();
266 mSupportsInstancing = mRenderer->getInstancingSupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000267
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000268 mMaxTextureDimension = std::min(std::min(mRenderer->getMaxTextureWidth(), mRenderer->getMaxTextureHeight()),
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000269 (int)gl::IMPLEMENTATION_MAX_TEXTURE_SIZE);
270 mMaxCubeTextureDimension = std::min(mMaxTextureDimension, (int)gl::IMPLEMENTATION_MAX_CUBE_MAP_TEXTURE_SIZE);
271 mMaxRenderbufferDimension = mMaxTextureDimension;
272 mMaxTextureLevel = log2(mMaxTextureDimension) + 1;
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000273 mMaxTextureAnisotropy = mRenderer->getTextureMaxAnisotropy();
daniel@transgaming.com07ab8412012-07-12 15:17:09 +0000274 TRACE("MaxTextureDimension=%d, MaxCubeTextureDimension=%d, MaxRenderbufferDimension=%d, MaxTextureLevel=%d, MaxTextureAnisotropy=%f",
275 mMaxTextureDimension, mMaxCubeTextureDimension, mMaxRenderbufferDimension, mMaxTextureLevel, mMaxTextureAnisotropy);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000276
daniel@transgaming.com621ce052012-10-31 17:52:29 +0000277 mSupportsEventQueries = mRenderer->getEventQuerySupport();
278 mSupportsOcclusionQueries = mRenderer->getOcclusionQuerySupport();
279 mSupportsDXT1Textures = mRenderer->getDXT1TextureSupport();
280 mSupportsDXT3Textures = mRenderer->getDXT3TextureSupport();
281 mSupportsDXT5Textures = mRenderer->getDXT5TextureSupport();
282 mSupportsFloat32Textures = mRenderer->getFloat32TextureSupport(&mSupportsFloat32LinearFilter, &mSupportsFloat32RenderableTextures);
283 mSupportsFloat16Textures = mRenderer->getFloat16TextureSupport(&mSupportsFloat16LinearFilter, &mSupportsFloat16RenderableTextures);
284 mSupportsLuminanceTextures = mRenderer->getLuminanceTextureSupport();
285 mSupportsLuminanceAlphaTextures = mRenderer->getLuminanceAlphaTextureSupport();
286 mSupportsDepthTextures = mRenderer->getDepthTextureSupport();
daniel@transgaming.comba0570e2012-10-31 18:07:39 +0000287 mSupportsTextureFilterAnisotropy = mRenderer->getTextureFilterAnisotropySupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000288
daniel@transgaming.com5f4c1362012-10-31 18:29:00 +0000289 mSupports32bitIndices = mRenderer->get32BitIndexSupport();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000290
291 mNumCompressedTextureFormats = 0;
292 if (supportsDXT1Textures())
293 {
294 mNumCompressedTextureFormats += 2;
295 }
296 if (supportsDXT3Textures())
297 {
298 mNumCompressedTextureFormats += 1;
299 }
300 if (supportsDXT5Textures())
301 {
302 mNumCompressedTextureFormats += 1;
303 }
304
305 initExtensionString();
306 initRendererString();
307
308 mState.viewportX = 0;
309 mState.viewportY = 0;
310 mState.viewportWidth = surface->getWidth();
311 mState.viewportHeight = surface->getHeight();
312
313 mState.scissorX = 0;
314 mState.scissorY = 0;
315 mState.scissorWidth = surface->getWidth();
316 mState.scissorHeight = surface->getHeight();
317
318 mHasBeenCurrent = true;
319 }
320
daniel@transgaming.com024786d2012-10-31 18:42:55 +0000321 // Wrap the existing swapchain resources into GL objects and assign them to the '0' names
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +0000322 rx::SwapChain *swapchain = surface->getSwapChain();
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000323
daniel@transgaming.com70062c92012-11-28 19:32:30 +0000324 Colorbuffer *colorbufferZero = new Colorbuffer(mRenderer, swapchain);
325 DepthStencilbuffer *depthStencilbufferZero = new DepthStencilbuffer(mRenderer, swapchain);
daniel@transgaming.com16418b12012-11-28 19:32:22 +0000326 Framebuffer *framebufferZero = new DefaultFramebuffer(mRenderer, colorbufferZero, depthStencilbufferZero);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000327
328 setFramebufferZero(framebufferZero);
329
apatrick@chromium.org909f21c2012-08-17 20:06:02 +0000330 // Reset pixel shader to null to work around a bug that only happens with Intel GPUs.
331 // http://crbug.com/110343
332 mDevice->SetPixelShader(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000333
334 markAllStateDirty();
335}
336
337// This function will set all of the state-related dirty flags, so that all state is set during next pre-draw.
338void Context::markAllStateDirty()
339{
340 for (int t = 0; t < MAX_TEXTURE_IMAGE_UNITS; t++)
341 {
342 mAppliedTextureSerialPS[t] = 0;
343 }
344
345 for (int t = 0; t < MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; t++)
346 {
347 mAppliedTextureSerialVS[t] = 0;
348 }
349
daniel@transgaming.come6af4f92012-07-24 18:31:31 +0000350 mAppliedProgramBinarySerial = 0;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000351 mAppliedRenderTargetSerial = 0;
352 mAppliedDepthbufferSerial = 0;
353 mAppliedStencilbufferSerial = 0;
354 mAppliedIBSerial = 0;
355 mDepthStencilInitialized = false;
356 mViewportInitialized = false;
357 mRenderTargetDescInitialized = false;
358
359 mVertexDeclarationCache.markStateDirty();
360
361 mClearStateDirty = true;
362 mCullStateDirty = true;
363 mDepthStateDirty = true;
364 mMaskStateDirty = true;
365 mBlendStateDirty = true;
366 mStencilStateDirty = true;
367 mPolygonOffsetStateDirty = true;
368 mScissorStateDirty = true;
369 mSampleStateDirty = true;
370 mDitherStateDirty = true;
371 mFrontFaceDirty = true;
372 mDxUniformsDirty = true;
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000373}
374
375void Context::markDxUniformsDirty()
376{
377 mDxUniformsDirty = true;
378}
379
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +0000380// NOTE: this function should not assume that this context is current!
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000381void Context::markContextLost()
382{
383 if (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT)
384 mResetStatus = GL_UNKNOWN_CONTEXT_RESET_EXT;
385 mContextLost = true;
386}
387
388bool Context::isContextLost()
389{
390 return mContextLost;
391}
392
393void Context::setClearColor(float red, float green, float blue, float alpha)
394{
395 mState.colorClearValue.red = red;
396 mState.colorClearValue.green = green;
397 mState.colorClearValue.blue = blue;
398 mState.colorClearValue.alpha = alpha;
399}
400
401void Context::setClearDepth(float depth)
402{
403 mState.depthClearValue = depth;
404}
405
406void Context::setClearStencil(int stencil)
407{
408 mState.stencilClearValue = stencil;
409}
410
411void Context::setCullFace(bool enabled)
412{
413 if (mState.cullFace != enabled)
414 {
415 mState.cullFace = enabled;
416 mCullStateDirty = true;
417 }
418}
419
420bool Context::isCullFaceEnabled() const
421{
422 return mState.cullFace;
423}
424
425void Context::setCullMode(GLenum mode)
426{
427 if (mState.cullMode != mode)
428 {
429 mState.cullMode = mode;
430 mCullStateDirty = true;
431 }
432}
433
434void Context::setFrontFace(GLenum front)
435{
436 if (mState.frontFace != front)
437 {
438 mState.frontFace = front;
439 mFrontFaceDirty = true;
440 }
441}
442
443void Context::setDepthTest(bool enabled)
444{
445 if (mState.depthTest != enabled)
446 {
447 mState.depthTest = enabled;
448 mDepthStateDirty = true;
449 }
450}
451
452bool Context::isDepthTestEnabled() const
453{
454 return mState.depthTest;
455}
456
457void Context::setDepthFunc(GLenum depthFunc)
458{
459 if (mState.depthFunc != depthFunc)
460 {
461 mState.depthFunc = depthFunc;
462 mDepthStateDirty = true;
463 }
464}
465
466void Context::setDepthRange(float zNear, float zFar)
467{
468 mState.zNear = zNear;
469 mState.zFar = zFar;
470}
471
472void Context::setBlend(bool enabled)
473{
474 if (mState.blend != enabled)
475 {
476 mState.blend = enabled;
477 mBlendStateDirty = true;
478 }
479}
480
481bool Context::isBlendEnabled() const
482{
483 return mState.blend;
484}
485
486void Context::setBlendFactors(GLenum sourceRGB, GLenum destRGB, GLenum sourceAlpha, GLenum destAlpha)
487{
488 if (mState.sourceBlendRGB != sourceRGB ||
489 mState.sourceBlendAlpha != sourceAlpha ||
490 mState.destBlendRGB != destRGB ||
491 mState.destBlendAlpha != destAlpha)
492 {
493 mState.sourceBlendRGB = sourceRGB;
494 mState.destBlendRGB = destRGB;
495 mState.sourceBlendAlpha = sourceAlpha;
496 mState.destBlendAlpha = destAlpha;
497 mBlendStateDirty = true;
498 }
499}
500
501void Context::setBlendColor(float red, float green, float blue, float alpha)
502{
503 if (mState.blendColor.red != red ||
504 mState.blendColor.green != green ||
505 mState.blendColor.blue != blue ||
506 mState.blendColor.alpha != alpha)
507 {
508 mState.blendColor.red = red;
509 mState.blendColor.green = green;
510 mState.blendColor.blue = blue;
511 mState.blendColor.alpha = alpha;
512 mBlendStateDirty = true;
513 }
514}
515
516void Context::setBlendEquation(GLenum rgbEquation, GLenum alphaEquation)
517{
518 if (mState.blendEquationRGB != rgbEquation ||
519 mState.blendEquationAlpha != alphaEquation)
520 {
521 mState.blendEquationRGB = rgbEquation;
522 mState.blendEquationAlpha = alphaEquation;
523 mBlendStateDirty = true;
524 }
525}
526
527void Context::setStencilTest(bool enabled)
528{
529 if (mState.stencilTest != enabled)
530 {
531 mState.stencilTest = enabled;
532 mStencilStateDirty = true;
533 }
534}
535
536bool Context::isStencilTestEnabled() const
537{
538 return mState.stencilTest;
539}
540
541void Context::setStencilParams(GLenum stencilFunc, GLint stencilRef, GLuint stencilMask)
542{
543 if (mState.stencilFunc != stencilFunc ||
544 mState.stencilRef != stencilRef ||
545 mState.stencilMask != stencilMask)
546 {
547 mState.stencilFunc = stencilFunc;
548 mState.stencilRef = (stencilRef > 0) ? stencilRef : 0;
549 mState.stencilMask = stencilMask;
550 mStencilStateDirty = true;
551 }
552}
553
554void Context::setStencilBackParams(GLenum stencilBackFunc, GLint stencilBackRef, GLuint stencilBackMask)
555{
556 if (mState.stencilBackFunc != stencilBackFunc ||
557 mState.stencilBackRef != stencilBackRef ||
558 mState.stencilBackMask != stencilBackMask)
559 {
560 mState.stencilBackFunc = stencilBackFunc;
561 mState.stencilBackRef = (stencilBackRef > 0) ? stencilBackRef : 0;
562 mState.stencilBackMask = stencilBackMask;
563 mStencilStateDirty = true;
564 }
565}
566
567void Context::setStencilWritemask(GLuint stencilWritemask)
568{
569 if (mState.stencilWritemask != stencilWritemask)
570 {
571 mState.stencilWritemask = stencilWritemask;
572 mStencilStateDirty = true;
573 }
574}
575
576void Context::setStencilBackWritemask(GLuint stencilBackWritemask)
577{
578 if (mState.stencilBackWritemask != stencilBackWritemask)
579 {
580 mState.stencilBackWritemask = stencilBackWritemask;
581 mStencilStateDirty = true;
582 }
583}
584
585void Context::setStencilOperations(GLenum stencilFail, GLenum stencilPassDepthFail, GLenum stencilPassDepthPass)
586{
587 if (mState.stencilFail != stencilFail ||
588 mState.stencilPassDepthFail != stencilPassDepthFail ||
589 mState.stencilPassDepthPass != stencilPassDepthPass)
590 {
591 mState.stencilFail = stencilFail;
592 mState.stencilPassDepthFail = stencilPassDepthFail;
593 mState.stencilPassDepthPass = stencilPassDepthPass;
594 mStencilStateDirty = true;
595 }
596}
597
598void Context::setStencilBackOperations(GLenum stencilBackFail, GLenum stencilBackPassDepthFail, GLenum stencilBackPassDepthPass)
599{
600 if (mState.stencilBackFail != stencilBackFail ||
601 mState.stencilBackPassDepthFail != stencilBackPassDepthFail ||
602 mState.stencilBackPassDepthPass != stencilBackPassDepthPass)
603 {
604 mState.stencilBackFail = stencilBackFail;
605 mState.stencilBackPassDepthFail = stencilBackPassDepthFail;
606 mState.stencilBackPassDepthPass = stencilBackPassDepthPass;
607 mStencilStateDirty = true;
608 }
609}
610
611void Context::setPolygonOffsetFill(bool enabled)
612{
613 if (mState.polygonOffsetFill != enabled)
614 {
615 mState.polygonOffsetFill = enabled;
616 mPolygonOffsetStateDirty = true;
617 }
618}
619
620bool Context::isPolygonOffsetFillEnabled() const
621{
622 return mState.polygonOffsetFill;
623
624}
625
626void Context::setPolygonOffsetParams(GLfloat factor, GLfloat units)
627{
628 if (mState.polygonOffsetFactor != factor ||
629 mState.polygonOffsetUnits != units)
630 {
631 mState.polygonOffsetFactor = factor;
632 mState.polygonOffsetUnits = units;
633 mPolygonOffsetStateDirty = true;
634 }
635}
636
637void Context::setSampleAlphaToCoverage(bool enabled)
638{
639 if (mState.sampleAlphaToCoverage != enabled)
640 {
641 mState.sampleAlphaToCoverage = enabled;
642 mSampleStateDirty = true;
643 }
644}
645
646bool Context::isSampleAlphaToCoverageEnabled() const
647{
648 return mState.sampleAlphaToCoverage;
649}
650
651void Context::setSampleCoverage(bool enabled)
652{
653 if (mState.sampleCoverage != enabled)
654 {
655 mState.sampleCoverage = enabled;
656 mSampleStateDirty = true;
657 }
658}
659
660bool Context::isSampleCoverageEnabled() const
661{
662 return mState.sampleCoverage;
663}
664
665void Context::setSampleCoverageParams(GLclampf value, bool invert)
666{
667 if (mState.sampleCoverageValue != value ||
668 mState.sampleCoverageInvert != invert)
669 {
670 mState.sampleCoverageValue = value;
671 mState.sampleCoverageInvert = invert;
672 mSampleStateDirty = true;
673 }
674}
675
676void Context::setScissorTest(bool enabled)
677{
678 if (mState.scissorTest != enabled)
679 {
680 mState.scissorTest = enabled;
681 mScissorStateDirty = true;
682 }
683}
684
685bool Context::isScissorTestEnabled() const
686{
687 return mState.scissorTest;
688}
689
690void Context::setDither(bool enabled)
691{
692 if (mState.dither != enabled)
693 {
694 mState.dither = enabled;
695 mDitherStateDirty = true;
696 }
697}
698
699bool Context::isDitherEnabled() const
700{
701 return mState.dither;
702}
703
704void Context::setLineWidth(GLfloat width)
705{
706 mState.lineWidth = width;
707}
708
709void Context::setGenerateMipmapHint(GLenum hint)
710{
711 mState.generateMipmapHint = hint;
712}
713
714void Context::setFragmentShaderDerivativeHint(GLenum hint)
715{
716 mState.fragmentShaderDerivativeHint = hint;
717 // TODO: Propagate the hint to shader translator so we can write
718 // ddx, ddx_coarse, or ddx_fine depending on the hint.
719 // Ignore for now. It is valid for implementations to ignore hint.
720}
721
722void Context::setViewportParams(GLint x, GLint y, GLsizei width, GLsizei height)
723{
724 mState.viewportX = x;
725 mState.viewportY = y;
726 mState.viewportWidth = width;
727 mState.viewportHeight = height;
728}
729
730void Context::setScissorParams(GLint x, GLint y, GLsizei width, GLsizei height)
731{
732 if (mState.scissorX != x || mState.scissorY != y ||
733 mState.scissorWidth != width || mState.scissorHeight != height)
734 {
735 mState.scissorX = x;
736 mState.scissorY = y;
737 mState.scissorWidth = width;
738 mState.scissorHeight = height;
739 mScissorStateDirty = true;
740 }
741}
742
743void Context::setColorMask(bool red, bool green, bool blue, bool alpha)
744{
745 if (mState.colorMaskRed != red || mState.colorMaskGreen != green ||
746 mState.colorMaskBlue != blue || mState.colorMaskAlpha != alpha)
747 {
748 mState.colorMaskRed = red;
749 mState.colorMaskGreen = green;
750 mState.colorMaskBlue = blue;
751 mState.colorMaskAlpha = alpha;
752 mMaskStateDirty = true;
753 }
754}
755
756void Context::setDepthMask(bool mask)
757{
758 if (mState.depthMask != mask)
759 {
760 mState.depthMask = mask;
761 mMaskStateDirty = true;
762 }
763}
764
765void Context::setActiveSampler(unsigned int active)
766{
767 mState.activeSampler = active;
768}
769
770GLuint Context::getReadFramebufferHandle() const
771{
772 return mState.readFramebuffer;
773}
774
775GLuint Context::getDrawFramebufferHandle() const
776{
777 return mState.drawFramebuffer;
778}
779
780GLuint Context::getRenderbufferHandle() const
781{
782 return mState.renderbuffer.id();
783}
784
785GLuint Context::getArrayBufferHandle() const
786{
787 return mState.arrayBuffer.id();
788}
789
790GLuint Context::getActiveQuery(GLenum target) const
791{
792 Query *queryObject = NULL;
793
794 switch (target)
795 {
796 case GL_ANY_SAMPLES_PASSED_EXT:
797 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED].get();
798 break;
799 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
800 queryObject = mState.activeQuery[QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE].get();
801 break;
802 default:
803 ASSERT(false);
804 }
805
806 if (queryObject)
807 {
808 return queryObject->id();
809 }
810 else
811 {
812 return 0;
813 }
814}
815
816void Context::setEnableVertexAttribArray(unsigned int attribNum, bool enabled)
817{
818 mState.vertexAttribute[attribNum].mArrayEnabled = enabled;
819}
820
821const VertexAttribute &Context::getVertexAttribState(unsigned int attribNum)
822{
823 return mState.vertexAttribute[attribNum];
824}
825
826void Context::setVertexAttribState(unsigned int attribNum, Buffer *boundBuffer, GLint size, GLenum type, bool normalized,
827 GLsizei stride, const void *pointer)
828{
829 mState.vertexAttribute[attribNum].mBoundBuffer.set(boundBuffer);
830 mState.vertexAttribute[attribNum].mSize = size;
831 mState.vertexAttribute[attribNum].mType = type;
832 mState.vertexAttribute[attribNum].mNormalized = normalized;
833 mState.vertexAttribute[attribNum].mStride = stride;
834 mState.vertexAttribute[attribNum].mPointer = pointer;
835}
836
837const void *Context::getVertexAttribPointer(unsigned int attribNum) const
838{
839 return mState.vertexAttribute[attribNum].mPointer;
840}
841
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000842void Context::setPackAlignment(GLint alignment)
843{
844 mState.packAlignment = alignment;
845}
846
847GLint Context::getPackAlignment() const
848{
849 return mState.packAlignment;
850}
851
852void Context::setUnpackAlignment(GLint alignment)
853{
854 mState.unpackAlignment = alignment;
855}
856
857GLint Context::getUnpackAlignment() const
858{
859 return mState.unpackAlignment;
860}
861
862void Context::setPackReverseRowOrder(bool reverseRowOrder)
863{
864 mState.packReverseRowOrder = reverseRowOrder;
865}
866
867bool Context::getPackReverseRowOrder() const
868{
869 return mState.packReverseRowOrder;
870}
871
872GLuint Context::createBuffer()
873{
874 return mResourceManager->createBuffer();
875}
876
877GLuint Context::createProgram()
878{
879 return mResourceManager->createProgram();
880}
881
882GLuint Context::createShader(GLenum type)
883{
884 return mResourceManager->createShader(type);
885}
886
887GLuint Context::createTexture()
888{
889 return mResourceManager->createTexture();
890}
891
892GLuint Context::createRenderbuffer()
893{
894 return mResourceManager->createRenderbuffer();
895}
896
897// Returns an unused framebuffer name
898GLuint Context::createFramebuffer()
899{
900 GLuint handle = mFramebufferHandleAllocator.allocate();
901
902 mFramebufferMap[handle] = NULL;
903
904 return handle;
905}
906
907GLuint Context::createFence()
908{
909 GLuint handle = mFenceHandleAllocator.allocate();
910
daniel@transgaming.comef21ab22012-10-31 17:52:47 +0000911 mFenceMap[handle] = new Fence(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000912
913 return handle;
914}
915
916// Returns an unused query name
917GLuint Context::createQuery()
918{
919 GLuint handle = mQueryHandleAllocator.allocate();
920
921 mQueryMap[handle] = NULL;
922
923 return handle;
924}
925
926void Context::deleteBuffer(GLuint buffer)
927{
928 if (mResourceManager->getBuffer(buffer))
929 {
930 detachBuffer(buffer);
931 }
932
933 mResourceManager->deleteBuffer(buffer);
934}
935
936void Context::deleteShader(GLuint shader)
937{
938 mResourceManager->deleteShader(shader);
939}
940
941void Context::deleteProgram(GLuint program)
942{
943 mResourceManager->deleteProgram(program);
apatrick@chromium.org144f2802012-07-12 01:42:34 +0000944}
945
946void Context::deleteTexture(GLuint texture)
947{
948 if (mResourceManager->getTexture(texture))
949 {
950 detachTexture(texture);
951 }
952
953 mResourceManager->deleteTexture(texture);
954}
955
956void Context::deleteRenderbuffer(GLuint renderbuffer)
957{
958 if (mResourceManager->getRenderbuffer(renderbuffer))
959 {
960 detachRenderbuffer(renderbuffer);
961 }
962
963 mResourceManager->deleteRenderbuffer(renderbuffer);
964}
965
966void Context::deleteFramebuffer(GLuint framebuffer)
967{
968 FramebufferMap::iterator framebufferObject = mFramebufferMap.find(framebuffer);
969
970 if (framebufferObject != mFramebufferMap.end())
971 {
972 detachFramebuffer(framebuffer);
973
974 mFramebufferHandleAllocator.release(framebufferObject->first);
975 delete framebufferObject->second;
976 mFramebufferMap.erase(framebufferObject);
977 }
978}
979
980void Context::deleteFence(GLuint fence)
981{
982 FenceMap::iterator fenceObject = mFenceMap.find(fence);
983
984 if (fenceObject != mFenceMap.end())
985 {
986 mFenceHandleAllocator.release(fenceObject->first);
987 delete fenceObject->second;
988 mFenceMap.erase(fenceObject);
989 }
990}
991
992void Context::deleteQuery(GLuint query)
993{
994 QueryMap::iterator queryObject = mQueryMap.find(query);
995 if (queryObject != mQueryMap.end())
996 {
997 mQueryHandleAllocator.release(queryObject->first);
998 if (queryObject->second)
999 {
1000 queryObject->second->release();
1001 }
1002 mQueryMap.erase(queryObject);
1003 }
1004}
1005
1006Buffer *Context::getBuffer(GLuint handle)
1007{
1008 return mResourceManager->getBuffer(handle);
1009}
1010
1011Shader *Context::getShader(GLuint handle)
1012{
1013 return mResourceManager->getShader(handle);
1014}
1015
1016Program *Context::getProgram(GLuint handle)
1017{
1018 return mResourceManager->getProgram(handle);
1019}
1020
1021Texture *Context::getTexture(GLuint handle)
1022{
1023 return mResourceManager->getTexture(handle);
1024}
1025
1026Renderbuffer *Context::getRenderbuffer(GLuint handle)
1027{
1028 return mResourceManager->getRenderbuffer(handle);
1029}
1030
1031Framebuffer *Context::getReadFramebuffer()
1032{
1033 return getFramebuffer(mState.readFramebuffer);
1034}
1035
1036Framebuffer *Context::getDrawFramebuffer()
1037{
1038 return mBoundDrawFramebuffer;
1039}
1040
1041void Context::bindArrayBuffer(unsigned int buffer)
1042{
1043 mResourceManager->checkBufferAllocation(buffer);
1044
1045 mState.arrayBuffer.set(getBuffer(buffer));
1046}
1047
1048void Context::bindElementArrayBuffer(unsigned int buffer)
1049{
1050 mResourceManager->checkBufferAllocation(buffer);
1051
1052 mState.elementArrayBuffer.set(getBuffer(buffer));
1053}
1054
1055void Context::bindTexture2D(GLuint texture)
1056{
1057 mResourceManager->checkTextureAllocation(texture, TEXTURE_2D);
1058
1059 mState.samplerTexture[TEXTURE_2D][mState.activeSampler].set(getTexture(texture));
1060}
1061
1062void Context::bindTextureCubeMap(GLuint texture)
1063{
1064 mResourceManager->checkTextureAllocation(texture, TEXTURE_CUBE);
1065
1066 mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].set(getTexture(texture));
1067}
1068
1069void Context::bindReadFramebuffer(GLuint framebuffer)
1070{
1071 if (!getFramebuffer(framebuffer))
1072 {
daniel@transgaming.com16418b12012-11-28 19:32:22 +00001073 mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001074 }
1075
1076 mState.readFramebuffer = framebuffer;
1077}
1078
1079void Context::bindDrawFramebuffer(GLuint framebuffer)
1080{
1081 if (!getFramebuffer(framebuffer))
1082 {
daniel@transgaming.com16418b12012-11-28 19:32:22 +00001083 mFramebufferMap[framebuffer] = new Framebuffer(mRenderer);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001084 }
1085
1086 mState.drawFramebuffer = framebuffer;
1087
1088 mBoundDrawFramebuffer = getFramebuffer(framebuffer);
1089}
1090
1091void Context::bindRenderbuffer(GLuint renderbuffer)
1092{
1093 mResourceManager->checkRenderbufferAllocation(renderbuffer);
1094
1095 mState.renderbuffer.set(getRenderbuffer(renderbuffer));
1096}
1097
1098void Context::useProgram(GLuint program)
1099{
1100 GLuint priorProgram = mState.currentProgram;
1101 mState.currentProgram = program; // Must switch before trying to delete, otherwise it only gets flagged.
1102
1103 if (priorProgram != program)
1104 {
1105 Program *newProgram = mResourceManager->getProgram(program);
1106 Program *oldProgram = mResourceManager->getProgram(priorProgram);
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001107 mCurrentProgramBinary.set(NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001108 mDxUniformsDirty = true;
1109
1110 if (newProgram)
1111 {
1112 newProgram->addRef();
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001113 mCurrentProgramBinary.set(newProgram->getProgramBinary());
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001114 }
1115
1116 if (oldProgram)
1117 {
1118 oldProgram->release();
1119 }
1120 }
1121}
1122
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001123void Context::linkProgram(GLuint program)
1124{
1125 Program *programObject = mResourceManager->getProgram(program);
1126
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001127 bool linked = programObject->link();
1128
1129 // if the current program was relinked successfully we
1130 // need to install the new executables
1131 if (linked && program == mState.currentProgram)
1132 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001133 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001134 mDxUniformsDirty = true;
1135 }
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001136}
1137
1138void Context::setProgramBinary(GLuint program, const void *binary, GLint length)
1139{
1140 Program *programObject = mResourceManager->getProgram(program);
1141
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001142 bool loaded = programObject->setProgramBinary(binary, length);
1143
1144 // if the current program was reloaded successfully we
1145 // need to install the new executables
1146 if (loaded && program == mState.currentProgram)
1147 {
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001148 mCurrentProgramBinary.set(programObject->getProgramBinary());
daniel@transgaming.com12394cf2012-07-24 18:37:59 +00001149 mDxUniformsDirty = true;
1150 }
1151
daniel@transgaming.com95d29422012-07-24 18:36:10 +00001152}
1153
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001154void Context::beginQuery(GLenum target, GLuint query)
1155{
1156 // From EXT_occlusion_query_boolean: If BeginQueryEXT is called with an <id>
1157 // of zero, if the active query object name for <target> is non-zero (for the
1158 // targets ANY_SAMPLES_PASSED_EXT and ANY_SAMPLES_PASSED_CONSERVATIVE_EXT, if
1159 // the active query for either target is non-zero), if <id> is the name of an
1160 // existing query object whose type does not match <target>, or if <id> is the
1161 // active query object name for any query type, the error INVALID_OPERATION is
1162 // generated.
1163
1164 // Ensure no other queries are active
1165 // NOTE: If other queries than occlusion are supported, we will need to check
1166 // separately that:
1167 // a) The query ID passed is not the current active query for any target/type
1168 // b) There are no active queries for the requested target (and in the case
1169 // of GL_ANY_SAMPLES_PASSED_EXT and GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT,
1170 // no query may be active for either if glBeginQuery targets either.
1171 for (int i = 0; i < QUERY_TYPE_COUNT; i++)
1172 {
1173 if (mState.activeQuery[i].get() != NULL)
1174 {
1175 return error(GL_INVALID_OPERATION);
1176 }
1177 }
1178
1179 QueryType qType;
1180 switch (target)
1181 {
1182 case GL_ANY_SAMPLES_PASSED_EXT:
1183 qType = QUERY_ANY_SAMPLES_PASSED;
1184 break;
1185 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1186 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1187 break;
1188 default:
1189 ASSERT(false);
1190 return;
1191 }
1192
1193 Query *queryObject = getQuery(query, true, target);
1194
1195 // check that name was obtained with glGenQueries
1196 if (!queryObject)
1197 {
1198 return error(GL_INVALID_OPERATION);
1199 }
1200
1201 // check for type mismatch
1202 if (queryObject->getType() != target)
1203 {
1204 return error(GL_INVALID_OPERATION);
1205 }
1206
1207 // set query as active for specified target
1208 mState.activeQuery[qType].set(queryObject);
1209
1210 // begin query
1211 queryObject->begin();
1212}
1213
1214void Context::endQuery(GLenum target)
1215{
1216 QueryType qType;
1217
1218 switch (target)
1219 {
1220 case GL_ANY_SAMPLES_PASSED_EXT:
1221 qType = QUERY_ANY_SAMPLES_PASSED;
1222 break;
1223 case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
1224 qType = QUERY_ANY_SAMPLES_PASSED_CONSERVATIVE;
1225 break;
1226 default:
1227 ASSERT(false);
1228 return;
1229 }
1230
1231 Query *queryObject = mState.activeQuery[qType].get();
1232
1233 if (queryObject == NULL)
1234 {
1235 return error(GL_INVALID_OPERATION);
1236 }
1237
1238 queryObject->end();
1239
1240 mState.activeQuery[qType].set(NULL);
1241}
1242
1243void Context::setFramebufferZero(Framebuffer *buffer)
1244{
1245 delete mFramebufferMap[0];
1246 mFramebufferMap[0] = buffer;
1247 if (mState.drawFramebuffer == 0)
1248 {
1249 mBoundDrawFramebuffer = buffer;
1250 }
1251}
1252
daniel@transgaming.com70062c92012-11-28 19:32:30 +00001253void Context::setRenderbufferStorage(GLsizei width, GLsizei height, GLenum internalformat, GLsizei samples)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001254{
daniel@transgaming.com70062c92012-11-28 19:32:30 +00001255 RenderbufferStorage *renderbuffer = NULL;
1256 switch (internalformat)
1257 {
1258 case GL_DEPTH_COMPONENT16:
1259 renderbuffer = new gl::Depthbuffer(mRenderer, width, height, samples);
1260 break;
1261 case GL_RGBA4:
1262 case GL_RGB5_A1:
1263 case GL_RGB565:
1264 case GL_RGB8_OES:
1265 case GL_RGBA8_OES:
1266 renderbuffer = new gl::Colorbuffer(mRenderer,width, height, internalformat, samples);
1267 break;
1268 case GL_STENCIL_INDEX8:
1269 renderbuffer = new gl::Stencilbuffer(mRenderer, width, height, samples);
1270 break;
1271 case GL_DEPTH24_STENCIL8_OES:
1272 renderbuffer = new gl::DepthStencilbuffer(mRenderer, width, height, samples);
1273 break;
1274 default:
1275 UNREACHABLE(); return;
1276 }
1277
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001278 Renderbuffer *renderbufferObject = mState.renderbuffer.get();
1279 renderbufferObject->setStorage(renderbuffer);
1280}
1281
1282Framebuffer *Context::getFramebuffer(unsigned int handle)
1283{
1284 FramebufferMap::iterator framebuffer = mFramebufferMap.find(handle);
1285
1286 if (framebuffer == mFramebufferMap.end())
1287 {
1288 return NULL;
1289 }
1290 else
1291 {
1292 return framebuffer->second;
1293 }
1294}
1295
1296Fence *Context::getFence(unsigned int handle)
1297{
1298 FenceMap::iterator fence = mFenceMap.find(handle);
1299
1300 if (fence == mFenceMap.end())
1301 {
1302 return NULL;
1303 }
1304 else
1305 {
1306 return fence->second;
1307 }
1308}
1309
1310Query *Context::getQuery(unsigned int handle, bool create, GLenum type)
1311{
1312 QueryMap::iterator query = mQueryMap.find(handle);
1313
1314 if (query == mQueryMap.end())
1315 {
1316 return NULL;
1317 }
1318 else
1319 {
1320 if (!query->second && create)
1321 {
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00001322 query->second = new Query(mRenderer, handle, type);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001323 query->second->addRef();
1324 }
1325 return query->second;
1326 }
1327}
1328
1329Buffer *Context::getArrayBuffer()
1330{
1331 return mState.arrayBuffer.get();
1332}
1333
1334Buffer *Context::getElementArrayBuffer()
1335{
1336 return mState.elementArrayBuffer.get();
1337}
1338
daniel@transgaming.com62a28462012-07-24 18:33:59 +00001339ProgramBinary *Context::getCurrentProgramBinary()
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001340{
daniel@transgaming.com989c1c82012-07-24 18:40:38 +00001341 return mCurrentProgramBinary.get();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001342}
1343
1344Texture2D *Context::getTexture2D()
1345{
1346 return static_cast<Texture2D*>(getSamplerTexture(mState.activeSampler, TEXTURE_2D));
1347}
1348
1349TextureCubeMap *Context::getTextureCubeMap()
1350{
1351 return static_cast<TextureCubeMap*>(getSamplerTexture(mState.activeSampler, TEXTURE_CUBE));
1352}
1353
1354Texture *Context::getSamplerTexture(unsigned int sampler, TextureType type)
1355{
1356 GLuint texid = mState.samplerTexture[type][sampler].id();
1357
1358 if (texid == 0) // Special case: 0 refers to different initial textures based on the target
1359 {
1360 switch (type)
1361 {
1362 default: UNREACHABLE();
1363 case TEXTURE_2D: return mTexture2DZero.get();
1364 case TEXTURE_CUBE: return mTextureCubeMapZero.get();
1365 }
1366 }
1367
1368 return mState.samplerTexture[type][sampler].get();
1369}
1370
1371bool Context::getBooleanv(GLenum pname, GLboolean *params)
1372{
1373 switch (pname)
1374 {
1375 case GL_SHADER_COMPILER: *params = GL_TRUE; break;
1376 case GL_SAMPLE_COVERAGE_INVERT: *params = mState.sampleCoverageInvert; break;
1377 case GL_DEPTH_WRITEMASK: *params = mState.depthMask; break;
1378 case GL_COLOR_WRITEMASK:
1379 params[0] = mState.colorMaskRed;
1380 params[1] = mState.colorMaskGreen;
1381 params[2] = mState.colorMaskBlue;
1382 params[3] = mState.colorMaskAlpha;
1383 break;
1384 case GL_CULL_FACE: *params = mState.cullFace; break;
1385 case GL_POLYGON_OFFSET_FILL: *params = mState.polygonOffsetFill; break;
1386 case GL_SAMPLE_ALPHA_TO_COVERAGE: *params = mState.sampleAlphaToCoverage; break;
1387 case GL_SAMPLE_COVERAGE: *params = mState.sampleCoverage; break;
1388 case GL_SCISSOR_TEST: *params = mState.scissorTest; break;
1389 case GL_STENCIL_TEST: *params = mState.stencilTest; break;
1390 case GL_DEPTH_TEST: *params = mState.depthTest; break;
1391 case GL_BLEND: *params = mState.blend; break;
1392 case GL_DITHER: *params = mState.dither; break;
1393 case GL_CONTEXT_ROBUST_ACCESS_EXT: *params = mRobustAccess ? GL_TRUE : GL_FALSE; break;
1394 default:
1395 return false;
1396 }
1397
1398 return true;
1399}
1400
1401bool Context::getFloatv(GLenum pname, GLfloat *params)
1402{
1403 // Please note: DEPTH_CLEAR_VALUE is included in our internal getFloatv implementation
1404 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1405 // GetIntegerv as its native query function. As it would require conversion in any
1406 // case, this should make no difference to the calling application.
1407 switch (pname)
1408 {
1409 case GL_LINE_WIDTH: *params = mState.lineWidth; break;
1410 case GL_SAMPLE_COVERAGE_VALUE: *params = mState.sampleCoverageValue; break;
1411 case GL_DEPTH_CLEAR_VALUE: *params = mState.depthClearValue; break;
1412 case GL_POLYGON_OFFSET_FACTOR: *params = mState.polygonOffsetFactor; break;
1413 case GL_POLYGON_OFFSET_UNITS: *params = mState.polygonOffsetUnits; break;
1414 case GL_ALIASED_LINE_WIDTH_RANGE:
1415 params[0] = gl::ALIASED_LINE_WIDTH_RANGE_MIN;
1416 params[1] = gl::ALIASED_LINE_WIDTH_RANGE_MAX;
1417 break;
1418 case GL_ALIASED_POINT_SIZE_RANGE:
1419 params[0] = gl::ALIASED_POINT_SIZE_RANGE_MIN;
1420 params[1] = getMaximumPointSize();
1421 break;
1422 case GL_DEPTH_RANGE:
1423 params[0] = mState.zNear;
1424 params[1] = mState.zFar;
1425 break;
1426 case GL_COLOR_CLEAR_VALUE:
1427 params[0] = mState.colorClearValue.red;
1428 params[1] = mState.colorClearValue.green;
1429 params[2] = mState.colorClearValue.blue;
1430 params[3] = mState.colorClearValue.alpha;
1431 break;
1432 case GL_BLEND_COLOR:
1433 params[0] = mState.blendColor.red;
1434 params[1] = mState.blendColor.green;
1435 params[2] = mState.blendColor.blue;
1436 params[3] = mState.blendColor.alpha;
1437 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001438 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1439 if (!supportsTextureFilterAnisotropy())
1440 {
1441 return false;
1442 }
1443 *params = mMaxTextureAnisotropy;
1444 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001445 default:
1446 return false;
1447 }
1448
1449 return true;
1450}
1451
1452bool Context::getIntegerv(GLenum pname, GLint *params)
1453{
1454 // Please note: DEPTH_CLEAR_VALUE is not included in our internal getIntegerv implementation
1455 // because it is stored as a float, despite the fact that the GL ES 2.0 spec names
1456 // GetIntegerv as its native query function. As it would require conversion in any
1457 // case, this should make no difference to the calling application. You may find it in
1458 // Context::getFloatv.
1459 switch (pname)
1460 {
1461 case GL_MAX_VERTEX_ATTRIBS: *params = gl::MAX_VERTEX_ATTRIBS; break;
1462 case GL_MAX_VERTEX_UNIFORM_VECTORS: *params = gl::MAX_VERTEX_UNIFORM_VECTORS; break;
1463 case GL_MAX_VARYING_VECTORS: *params = getMaximumVaryingVectors(); break;
1464 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: *params = getMaximumCombinedTextureImageUnits(); break;
1465 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: *params = getMaximumVertexTextureImageUnits(); break;
1466 case GL_MAX_TEXTURE_IMAGE_UNITS: *params = gl::MAX_TEXTURE_IMAGE_UNITS; break;
1467 case GL_MAX_FRAGMENT_UNIFORM_VECTORS: *params = getMaximumFragmentUniformVectors(); break;
1468 case GL_MAX_RENDERBUFFER_SIZE: *params = getMaximumRenderbufferDimension(); break;
1469 case GL_NUM_SHADER_BINARY_FORMATS: *params = 0; break;
1470 case GL_SHADER_BINARY_FORMATS: /* no shader binary formats are supported */ break;
1471 case GL_ARRAY_BUFFER_BINDING: *params = mState.arrayBuffer.id(); break;
1472 case GL_ELEMENT_ARRAY_BUFFER_BINDING: *params = mState.elementArrayBuffer.id(); break;
1473 //case GL_FRAMEBUFFER_BINDING: // now equivalent to GL_DRAW_FRAMEBUFFER_BINDING_ANGLE
1474 case GL_DRAW_FRAMEBUFFER_BINDING_ANGLE: *params = mState.drawFramebuffer; break;
1475 case GL_READ_FRAMEBUFFER_BINDING_ANGLE: *params = mState.readFramebuffer; break;
1476 case GL_RENDERBUFFER_BINDING: *params = mState.renderbuffer.id(); break;
1477 case GL_CURRENT_PROGRAM: *params = mState.currentProgram; break;
1478 case GL_PACK_ALIGNMENT: *params = mState.packAlignment; break;
1479 case GL_PACK_REVERSE_ROW_ORDER_ANGLE: *params = mState.packReverseRowOrder; break;
1480 case GL_UNPACK_ALIGNMENT: *params = mState.unpackAlignment; break;
1481 case GL_GENERATE_MIPMAP_HINT: *params = mState.generateMipmapHint; break;
1482 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES: *params = mState.fragmentShaderDerivativeHint; break;
1483 case GL_ACTIVE_TEXTURE: *params = (mState.activeSampler + GL_TEXTURE0); break;
1484 case GL_STENCIL_FUNC: *params = mState.stencilFunc; break;
1485 case GL_STENCIL_REF: *params = mState.stencilRef; break;
1486 case GL_STENCIL_VALUE_MASK: *params = mState.stencilMask; break;
1487 case GL_STENCIL_BACK_FUNC: *params = mState.stencilBackFunc; break;
1488 case GL_STENCIL_BACK_REF: *params = mState.stencilBackRef; break;
1489 case GL_STENCIL_BACK_VALUE_MASK: *params = mState.stencilBackMask; break;
1490 case GL_STENCIL_FAIL: *params = mState.stencilFail; break;
1491 case GL_STENCIL_PASS_DEPTH_FAIL: *params = mState.stencilPassDepthFail; break;
1492 case GL_STENCIL_PASS_DEPTH_PASS: *params = mState.stencilPassDepthPass; break;
1493 case GL_STENCIL_BACK_FAIL: *params = mState.stencilBackFail; break;
1494 case GL_STENCIL_BACK_PASS_DEPTH_FAIL: *params = mState.stencilBackPassDepthFail; break;
1495 case GL_STENCIL_BACK_PASS_DEPTH_PASS: *params = mState.stencilBackPassDepthPass; break;
1496 case GL_DEPTH_FUNC: *params = mState.depthFunc; break;
1497 case GL_BLEND_SRC_RGB: *params = mState.sourceBlendRGB; break;
1498 case GL_BLEND_SRC_ALPHA: *params = mState.sourceBlendAlpha; break;
1499 case GL_BLEND_DST_RGB: *params = mState.destBlendRGB; break;
1500 case GL_BLEND_DST_ALPHA: *params = mState.destBlendAlpha; break;
1501 case GL_BLEND_EQUATION_RGB: *params = mState.blendEquationRGB; break;
1502 case GL_BLEND_EQUATION_ALPHA: *params = mState.blendEquationAlpha; break;
1503 case GL_STENCIL_WRITEMASK: *params = mState.stencilWritemask; break;
1504 case GL_STENCIL_BACK_WRITEMASK: *params = mState.stencilBackWritemask; break;
1505 case GL_STENCIL_CLEAR_VALUE: *params = mState.stencilClearValue; break;
1506 case GL_SUBPIXEL_BITS: *params = 4; break;
1507 case GL_MAX_TEXTURE_SIZE: *params = getMaximumTextureDimension(); break;
1508 case GL_MAX_CUBE_MAP_TEXTURE_SIZE: *params = getMaximumCubeTextureDimension(); break;
1509 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1510 params[0] = mNumCompressedTextureFormats;
1511 break;
1512 case GL_MAX_SAMPLES_ANGLE:
1513 {
1514 GLsizei maxSamples = getMaxSupportedSamples();
1515 if (maxSamples != 0)
1516 {
1517 *params = maxSamples;
1518 }
1519 else
1520 {
1521 return false;
1522 }
1523
1524 break;
1525 }
1526 case GL_SAMPLE_BUFFERS:
1527 case GL_SAMPLES:
1528 {
1529 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1530 if (framebuffer->completeness() == GL_FRAMEBUFFER_COMPLETE)
1531 {
1532 switch (pname)
1533 {
1534 case GL_SAMPLE_BUFFERS:
1535 if (framebuffer->getSamples() != 0)
1536 {
1537 *params = 1;
1538 }
1539 else
1540 {
1541 *params = 0;
1542 }
1543 break;
1544 case GL_SAMPLES:
1545 *params = framebuffer->getSamples();
1546 break;
1547 }
1548 }
1549 else
1550 {
1551 *params = 0;
1552 }
1553 }
1554 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00001555 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1556 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1557 {
1558 GLenum format, type;
1559 if (getCurrentReadFormatType(&format, &type))
1560 {
1561 if (pname == GL_IMPLEMENTATION_COLOR_READ_FORMAT)
1562 *params = format;
1563 else
1564 *params = type;
1565 }
1566 }
1567 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001568 case GL_MAX_VIEWPORT_DIMS:
1569 {
1570 int maxDimension = std::max(getMaximumRenderbufferDimension(), getMaximumTextureDimension());
1571 params[0] = maxDimension;
1572 params[1] = maxDimension;
1573 }
1574 break;
1575 case GL_COMPRESSED_TEXTURE_FORMATS:
1576 {
1577 if (supportsDXT1Textures())
1578 {
1579 *params++ = GL_COMPRESSED_RGB_S3TC_DXT1_EXT;
1580 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
1581 }
1582 if (supportsDXT3Textures())
1583 {
1584 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE;
1585 }
1586 if (supportsDXT5Textures())
1587 {
1588 *params++ = GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE;
1589 }
1590 }
1591 break;
1592 case GL_VIEWPORT:
1593 params[0] = mState.viewportX;
1594 params[1] = mState.viewportY;
1595 params[2] = mState.viewportWidth;
1596 params[3] = mState.viewportHeight;
1597 break;
1598 case GL_SCISSOR_BOX:
1599 params[0] = mState.scissorX;
1600 params[1] = mState.scissorY;
1601 params[2] = mState.scissorWidth;
1602 params[3] = mState.scissorHeight;
1603 break;
1604 case GL_CULL_FACE_MODE: *params = mState.cullMode; break;
1605 case GL_FRONT_FACE: *params = mState.frontFace; break;
1606 case GL_RED_BITS:
1607 case GL_GREEN_BITS:
1608 case GL_BLUE_BITS:
1609 case GL_ALPHA_BITS:
1610 {
1611 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1612 gl::Renderbuffer *colorbuffer = framebuffer->getColorbuffer();
1613
1614 if (colorbuffer)
1615 {
1616 switch (pname)
1617 {
1618 case GL_RED_BITS: *params = colorbuffer->getRedSize(); break;
1619 case GL_GREEN_BITS: *params = colorbuffer->getGreenSize(); break;
1620 case GL_BLUE_BITS: *params = colorbuffer->getBlueSize(); break;
1621 case GL_ALPHA_BITS: *params = colorbuffer->getAlphaSize(); break;
1622 }
1623 }
1624 else
1625 {
1626 *params = 0;
1627 }
1628 }
1629 break;
1630 case GL_DEPTH_BITS:
1631 {
1632 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1633 gl::Renderbuffer *depthbuffer = framebuffer->getDepthbuffer();
1634
1635 if (depthbuffer)
1636 {
1637 *params = depthbuffer->getDepthSize();
1638 }
1639 else
1640 {
1641 *params = 0;
1642 }
1643 }
1644 break;
1645 case GL_STENCIL_BITS:
1646 {
1647 gl::Framebuffer *framebuffer = getDrawFramebuffer();
1648 gl::Renderbuffer *stencilbuffer = framebuffer->getStencilbuffer();
1649
1650 if (stencilbuffer)
1651 {
1652 *params = stencilbuffer->getStencilSize();
1653 }
1654 else
1655 {
1656 *params = 0;
1657 }
1658 }
1659 break;
1660 case GL_TEXTURE_BINDING_2D:
1661 {
1662 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1663 {
1664 error(GL_INVALID_OPERATION);
1665 return false;
1666 }
1667
1668 *params = mState.samplerTexture[TEXTURE_2D][mState.activeSampler].id();
1669 }
1670 break;
1671 case GL_TEXTURE_BINDING_CUBE_MAP:
1672 {
1673 if (mState.activeSampler < 0 || mState.activeSampler > getMaximumCombinedTextureImageUnits() - 1)
1674 {
1675 error(GL_INVALID_OPERATION);
1676 return false;
1677 }
1678
1679 *params = mState.samplerTexture[TEXTURE_CUBE][mState.activeSampler].id();
1680 }
1681 break;
1682 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1683 *params = mResetStrategy;
1684 break;
1685 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1686 *params = 1;
1687 break;
1688 case GL_PROGRAM_BINARY_FORMATS_OES:
1689 *params = GL_PROGRAM_BINARY_ANGLE;
1690 break;
1691 default:
1692 return false;
1693 }
1694
1695 return true;
1696}
1697
1698bool Context::getQueryParameterInfo(GLenum pname, GLenum *type, unsigned int *numParams)
1699{
1700 // Please note: the query type returned for DEPTH_CLEAR_VALUE in this implementation
1701 // is FLOAT rather than INT, as would be suggested by the GL ES 2.0 spec. This is due
1702 // to the fact that it is stored internally as a float, and so would require conversion
1703 // if returned from Context::getIntegerv. Since this conversion is already implemented
1704 // in the case that one calls glGetIntegerv to retrieve a float-typed state variable, we
1705 // place DEPTH_CLEAR_VALUE with the floats. This should make no difference to the calling
1706 // application.
1707 switch (pname)
1708 {
1709 case GL_COMPRESSED_TEXTURE_FORMATS:
1710 {
1711 *type = GL_INT;
1712 *numParams = mNumCompressedTextureFormats;
1713 }
1714 break;
1715 case GL_SHADER_BINARY_FORMATS:
1716 {
1717 *type = GL_INT;
1718 *numParams = 0;
1719 }
1720 break;
1721 case GL_MAX_VERTEX_ATTRIBS:
1722 case GL_MAX_VERTEX_UNIFORM_VECTORS:
1723 case GL_MAX_VARYING_VECTORS:
1724 case GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS:
1725 case GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS:
1726 case GL_MAX_TEXTURE_IMAGE_UNITS:
1727 case GL_MAX_FRAGMENT_UNIFORM_VECTORS:
1728 case GL_MAX_RENDERBUFFER_SIZE:
1729 case GL_NUM_SHADER_BINARY_FORMATS:
1730 case GL_NUM_COMPRESSED_TEXTURE_FORMATS:
1731 case GL_ARRAY_BUFFER_BINDING:
1732 case GL_FRAMEBUFFER_BINDING:
1733 case GL_RENDERBUFFER_BINDING:
1734 case GL_CURRENT_PROGRAM:
1735 case GL_PACK_ALIGNMENT:
1736 case GL_PACK_REVERSE_ROW_ORDER_ANGLE:
1737 case GL_UNPACK_ALIGNMENT:
1738 case GL_GENERATE_MIPMAP_HINT:
1739 case GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES:
1740 case GL_RED_BITS:
1741 case GL_GREEN_BITS:
1742 case GL_BLUE_BITS:
1743 case GL_ALPHA_BITS:
1744 case GL_DEPTH_BITS:
1745 case GL_STENCIL_BITS:
1746 case GL_ELEMENT_ARRAY_BUFFER_BINDING:
1747 case GL_CULL_FACE_MODE:
1748 case GL_FRONT_FACE:
1749 case GL_ACTIVE_TEXTURE:
1750 case GL_STENCIL_FUNC:
1751 case GL_STENCIL_VALUE_MASK:
1752 case GL_STENCIL_REF:
1753 case GL_STENCIL_FAIL:
1754 case GL_STENCIL_PASS_DEPTH_FAIL:
1755 case GL_STENCIL_PASS_DEPTH_PASS:
1756 case GL_STENCIL_BACK_FUNC:
1757 case GL_STENCIL_BACK_VALUE_MASK:
1758 case GL_STENCIL_BACK_REF:
1759 case GL_STENCIL_BACK_FAIL:
1760 case GL_STENCIL_BACK_PASS_DEPTH_FAIL:
1761 case GL_STENCIL_BACK_PASS_DEPTH_PASS:
1762 case GL_DEPTH_FUNC:
1763 case GL_BLEND_SRC_RGB:
1764 case GL_BLEND_SRC_ALPHA:
1765 case GL_BLEND_DST_RGB:
1766 case GL_BLEND_DST_ALPHA:
1767 case GL_BLEND_EQUATION_RGB:
1768 case GL_BLEND_EQUATION_ALPHA:
1769 case GL_STENCIL_WRITEMASK:
1770 case GL_STENCIL_BACK_WRITEMASK:
1771 case GL_STENCIL_CLEAR_VALUE:
1772 case GL_SUBPIXEL_BITS:
1773 case GL_MAX_TEXTURE_SIZE:
1774 case GL_MAX_CUBE_MAP_TEXTURE_SIZE:
1775 case GL_SAMPLE_BUFFERS:
1776 case GL_SAMPLES:
1777 case GL_IMPLEMENTATION_COLOR_READ_TYPE:
1778 case GL_IMPLEMENTATION_COLOR_READ_FORMAT:
1779 case GL_TEXTURE_BINDING_2D:
1780 case GL_TEXTURE_BINDING_CUBE_MAP:
1781 case GL_RESET_NOTIFICATION_STRATEGY_EXT:
1782 case GL_NUM_PROGRAM_BINARY_FORMATS_OES:
1783 case GL_PROGRAM_BINARY_FORMATS_OES:
1784 {
1785 *type = GL_INT;
1786 *numParams = 1;
1787 }
1788 break;
1789 case GL_MAX_SAMPLES_ANGLE:
1790 {
1791 if (getMaxSupportedSamples() != 0)
1792 {
1793 *type = GL_INT;
1794 *numParams = 1;
1795 }
1796 else
1797 {
1798 return false;
1799 }
1800 }
1801 break;
1802 case GL_MAX_VIEWPORT_DIMS:
1803 {
1804 *type = GL_INT;
1805 *numParams = 2;
1806 }
1807 break;
1808 case GL_VIEWPORT:
1809 case GL_SCISSOR_BOX:
1810 {
1811 *type = GL_INT;
1812 *numParams = 4;
1813 }
1814 break;
1815 case GL_SHADER_COMPILER:
1816 case GL_SAMPLE_COVERAGE_INVERT:
1817 case GL_DEPTH_WRITEMASK:
1818 case GL_CULL_FACE: // CULL_FACE through DITHER are natural to IsEnabled,
1819 case GL_POLYGON_OFFSET_FILL: // but can be retrieved through the Get{Type}v queries.
1820 case GL_SAMPLE_ALPHA_TO_COVERAGE: // For this purpose, they are treated here as bool-natural
1821 case GL_SAMPLE_COVERAGE:
1822 case GL_SCISSOR_TEST:
1823 case GL_STENCIL_TEST:
1824 case GL_DEPTH_TEST:
1825 case GL_BLEND:
1826 case GL_DITHER:
1827 case GL_CONTEXT_ROBUST_ACCESS_EXT:
1828 {
1829 *type = GL_BOOL;
1830 *numParams = 1;
1831 }
1832 break;
1833 case GL_COLOR_WRITEMASK:
1834 {
1835 *type = GL_BOOL;
1836 *numParams = 4;
1837 }
1838 break;
1839 case GL_POLYGON_OFFSET_FACTOR:
1840 case GL_POLYGON_OFFSET_UNITS:
1841 case GL_SAMPLE_COVERAGE_VALUE:
1842 case GL_DEPTH_CLEAR_VALUE:
1843 case GL_LINE_WIDTH:
1844 {
1845 *type = GL_FLOAT;
1846 *numParams = 1;
1847 }
1848 break;
1849 case GL_ALIASED_LINE_WIDTH_RANGE:
1850 case GL_ALIASED_POINT_SIZE_RANGE:
1851 case GL_DEPTH_RANGE:
1852 {
1853 *type = GL_FLOAT;
1854 *numParams = 2;
1855 }
1856 break;
1857 case GL_COLOR_CLEAR_VALUE:
1858 case GL_BLEND_COLOR:
1859 {
1860 *type = GL_FLOAT;
1861 *numParams = 4;
1862 }
1863 break;
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00001864 case GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT:
1865 if (!supportsTextureFilterAnisotropy())
1866 {
1867 return false;
1868 }
1869 *type = GL_FLOAT;
1870 *numParams = 1;
1871 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00001872 default:
1873 return false;
1874 }
1875
1876 return true;
1877}
1878
1879// Applies the render target surface, depth stencil surface, viewport rectangle and
1880// scissor rectangle to the Direct3D 9 device
1881bool Context::applyRenderTarget(bool ignoreViewport)
1882{
1883 Framebuffer *framebufferObject = getDrawFramebuffer();
1884
1885 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
1886 {
1887 return error(GL_INVALID_FRAMEBUFFER_OPERATION, false);
1888 }
1889
1890 // if there is no color attachment we must synthesize a NULL colorattachment
1891 // to keep the D3D runtime happy. This should only be possible if depth texturing.
1892 Renderbuffer *renderbufferObject = NULL;
1893 if (framebufferObject->getColorbufferType() != GL_NONE)
1894 {
1895 renderbufferObject = framebufferObject->getColorbuffer();
1896 }
1897 else
1898 {
1899 renderbufferObject = framebufferObject->getNullColorbuffer();
1900 }
1901 if (!renderbufferObject)
1902 {
1903 ERR("unable to locate renderbuffer for FBO.");
1904 return false;
1905 }
1906
1907 bool renderTargetChanged = false;
1908 unsigned int renderTargetSerial = renderbufferObject->getSerial();
1909 if (renderTargetSerial != mAppliedRenderTargetSerial)
1910 {
1911 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1912 if (!renderTarget)
1913 {
1914 ERR("render target pointer unexpectedly null.");
1915 return false; // Context must be lost
1916 }
1917 mDevice->SetRenderTarget(0, renderTarget);
1918 mAppliedRenderTargetSerial = renderTargetSerial;
1919 mScissorStateDirty = true; // Scissor area must be clamped to render target's size-- this is different for different render targets.
1920 renderTargetChanged = true;
1921 renderTarget->Release();
1922 }
1923
1924 IDirect3DSurface9 *depthStencil = NULL;
1925 unsigned int depthbufferSerial = 0;
1926 unsigned int stencilbufferSerial = 0;
1927 if (framebufferObject->getDepthbufferType() != GL_NONE)
1928 {
1929 Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
1930 depthStencil = depthbuffer->getDepthStencil();
1931 if (!depthStencil)
1932 {
1933 ERR("Depth stencil pointer unexpectedly null.");
1934 return false;
1935 }
1936
1937 depthbufferSerial = depthbuffer->getSerial();
1938 }
1939 else if (framebufferObject->getStencilbufferType() != GL_NONE)
1940 {
1941 Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
1942 depthStencil = stencilbuffer->getDepthStencil();
1943 if (!depthStencil)
1944 {
1945 ERR("Depth stencil pointer unexpectedly null.");
1946 return false;
1947 }
1948
1949 stencilbufferSerial = stencilbuffer->getSerial();
1950 }
1951
1952 if (depthbufferSerial != mAppliedDepthbufferSerial ||
1953 stencilbufferSerial != mAppliedStencilbufferSerial ||
1954 !mDepthStencilInitialized)
1955 {
1956 mDevice->SetDepthStencilSurface(depthStencil);
1957 mAppliedDepthbufferSerial = depthbufferSerial;
1958 mAppliedStencilbufferSerial = stencilbufferSerial;
1959 mDepthStencilInitialized = true;
1960 }
1961
1962 if (depthStencil)
1963 {
1964 depthStencil->Release();
1965 }
1966
1967 if (!mRenderTargetDescInitialized || renderTargetChanged)
1968 {
1969 IDirect3DSurface9 *renderTarget = renderbufferObject->getRenderTarget();
1970 if (!renderTarget)
1971 {
1972 return false; // Context must be lost
1973 }
1974 renderTarget->GetDesc(&mRenderTargetDesc);
1975 mRenderTargetDescInitialized = true;
1976 renderTarget->Release();
1977 }
1978
1979 D3DVIEWPORT9 viewport;
1980
1981 float zNear = clamp01(mState.zNear);
1982 float zFar = clamp01(mState.zFar);
1983
1984 if (ignoreViewport)
1985 {
1986 viewport.X = 0;
1987 viewport.Y = 0;
1988 viewport.Width = mRenderTargetDesc.Width;
1989 viewport.Height = mRenderTargetDesc.Height;
1990 viewport.MinZ = 0.0f;
1991 viewport.MaxZ = 1.0f;
1992 }
1993 else
1994 {
1995 viewport.X = clamp(mState.viewportX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
1996 viewport.Y = clamp(mState.viewportY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
1997 viewport.Width = clamp(mState.viewportWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width) - static_cast<LONG>(viewport.X));
1998 viewport.Height = clamp(mState.viewportHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height) - static_cast<LONG>(viewport.Y));
1999 viewport.MinZ = zNear;
2000 viewport.MaxZ = zFar;
2001 }
2002
2003 if (viewport.Width <= 0 || viewport.Height <= 0)
2004 {
2005 return false; // Nothing to render
2006 }
2007
2008 if (renderTargetChanged || !mViewportInitialized || memcmp(&viewport, &mSetViewport, sizeof mSetViewport) != 0)
2009 {
2010 mDevice->SetViewport(&viewport);
2011 mSetViewport = viewport;
2012 mViewportInitialized = true;
2013 mDxUniformsDirty = true;
2014 }
2015
2016 if (mScissorStateDirty)
2017 {
2018 if (mState.scissorTest)
2019 {
2020 RECT rect;
2021 rect.left = clamp(mState.scissorX, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2022 rect.top = clamp(mState.scissorY, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2023 rect.right = clamp(mState.scissorX + mState.scissorWidth, 0L, static_cast<LONG>(mRenderTargetDesc.Width));
2024 rect.bottom = clamp(mState.scissorY + mState.scissorHeight, 0L, static_cast<LONG>(mRenderTargetDesc.Height));
2025 mDevice->SetScissorRect(&rect);
2026 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, TRUE);
2027 }
2028 else
2029 {
2030 mDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
2031 }
2032
2033 mScissorStateDirty = false;
2034 }
2035
2036 if (mState.currentProgram && mDxUniformsDirty)
2037 {
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002038 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002039
2040 GLint halfPixelSize = programBinary->getDxHalfPixelSizeLocation();
2041 GLfloat xy[2] = {1.0f / viewport.Width, -1.0f / viewport.Height};
2042 programBinary->setUniform2fv(halfPixelSize, 1, xy);
2043
2044 // These values are used for computing gl_FragCoord in Program::linkVaryings().
2045 GLint coord = programBinary->getDxCoordLocation();
2046 GLfloat whxy[4] = {mState.viewportWidth / 2.0f, mState.viewportHeight / 2.0f,
2047 (float)mState.viewportX + mState.viewportWidth / 2.0f,
2048 (float)mState.viewportY + mState.viewportHeight / 2.0f};
2049 programBinary->setUniform4fv(coord, 1, whxy);
2050
2051 GLint depth = programBinary->getDxDepthLocation();
2052 GLfloat dz[2] = {(zFar - zNear) / 2.0f, (zNear + zFar) / 2.0f};
2053 programBinary->setUniform2fv(depth, 1, dz);
2054
2055 GLint depthRange = programBinary->getDxDepthRangeLocation();
2056 GLfloat nearFarDiff[3] = {zNear, zFar, zFar - zNear};
2057 programBinary->setUniform3fv(depthRange, 1, nearFarDiff);
2058 mDxUniformsDirty = false;
2059 }
2060
2061 return true;
2062}
2063
2064// Applies the fixed-function state (culling, depth test, alpha blending, stenciling, etc) to the Direct3D 9 device
2065void Context::applyState(GLenum drawMode)
2066{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002067 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002068
2069 Framebuffer *framebufferObject = getDrawFramebuffer();
2070
2071 GLint frontCCW = programBinary->getDxFrontCCWLocation();
2072 GLint ccw = (mState.frontFace == GL_CCW);
2073 programBinary->setUniform1iv(frontCCW, 1, &ccw);
2074
2075 GLint pointsOrLines = programBinary->getDxPointsOrLinesLocation();
2076 GLint alwaysFront = !isTriangleMode(drawMode);
2077 programBinary->setUniform1iv(pointsOrLines, 1, &alwaysFront);
2078
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00002079 bool zeroColorMaskAllowed = mRenderer->getAdapterVendor() != VENDOR_ID_AMD;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002080 // Apparently some ATI cards have a bug where a draw with a zero color
2081 // write mask can cause later draws to have incorrect results. Instead,
2082 // set a nonzero color write mask but modify the blend state so that no
2083 // drawing is done.
2084 // http://code.google.com/p/angleproject/issues/detail?id=169
2085
2086 if (mCullStateDirty || mFrontFaceDirty)
2087 {
2088 if (mState.cullFace)
2089 {
2090 mDevice->SetRenderState(D3DRS_CULLMODE, es2dx::ConvertCullMode(mState.cullMode, mState.frontFace));
2091 }
2092 else
2093 {
2094 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2095 }
2096
2097 mCullStateDirty = false;
2098 }
2099
2100 if (mDepthStateDirty)
2101 {
2102 if (mState.depthTest)
2103 {
2104 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE);
2105 mDevice->SetRenderState(D3DRS_ZFUNC, es2dx::ConvertComparison(mState.depthFunc));
2106 }
2107 else
2108 {
2109 mDevice->SetRenderState(D3DRS_ZENABLE, D3DZB_FALSE);
2110 }
2111
2112 mDepthStateDirty = false;
2113 }
2114
2115 if (!zeroColorMaskAllowed && (mMaskStateDirty || mBlendStateDirty))
2116 {
2117 mBlendStateDirty = true;
2118 mMaskStateDirty = true;
2119 }
2120
2121 if (mBlendStateDirty)
2122 {
2123 if (mState.blend)
2124 {
2125 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2126
2127 if (mState.sourceBlendRGB != GL_CONSTANT_ALPHA && mState.sourceBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA &&
2128 mState.destBlendRGB != GL_CONSTANT_ALPHA && mState.destBlendRGB != GL_ONE_MINUS_CONSTANT_ALPHA)
2129 {
2130 mDevice->SetRenderState(D3DRS_BLENDFACTOR, es2dx::ConvertColor(mState.blendColor));
2131 }
2132 else
2133 {
2134 mDevice->SetRenderState(D3DRS_BLENDFACTOR, D3DCOLOR_RGBA(unorm<8>(mState.blendColor.alpha),
2135 unorm<8>(mState.blendColor.alpha),
2136 unorm<8>(mState.blendColor.alpha),
2137 unorm<8>(mState.blendColor.alpha)));
2138 }
2139
2140 mDevice->SetRenderState(D3DRS_SRCBLEND, es2dx::ConvertBlendFunc(mState.sourceBlendRGB));
2141 mDevice->SetRenderState(D3DRS_DESTBLEND, es2dx::ConvertBlendFunc(mState.destBlendRGB));
2142 mDevice->SetRenderState(D3DRS_BLENDOP, es2dx::ConvertBlendOp(mState.blendEquationRGB));
2143
2144 if (mState.sourceBlendRGB != mState.sourceBlendAlpha ||
2145 mState.destBlendRGB != mState.destBlendAlpha ||
2146 mState.blendEquationRGB != mState.blendEquationAlpha)
2147 {
2148 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2149
2150 mDevice->SetRenderState(D3DRS_SRCBLENDALPHA, es2dx::ConvertBlendFunc(mState.sourceBlendAlpha));
2151 mDevice->SetRenderState(D3DRS_DESTBLENDALPHA, es2dx::ConvertBlendFunc(mState.destBlendAlpha));
2152 mDevice->SetRenderState(D3DRS_BLENDOPALPHA, es2dx::ConvertBlendOp(mState.blendEquationAlpha));
2153 }
2154 else
2155 {
2156 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, FALSE);
2157 }
2158 }
2159 else
2160 {
2161 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2162 }
2163
2164 mBlendStateDirty = false;
2165 }
2166
2167 if (mStencilStateDirty || mFrontFaceDirty)
2168 {
2169 if (mState.stencilTest && framebufferObject->hasStencil())
2170 {
2171 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2172 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, TRUE);
2173
2174 // FIXME: Unsupported by D3D9
2175 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILREF = D3DRS_STENCILREF;
2176 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILMASK = D3DRS_STENCILMASK;
2177 const D3DRENDERSTATETYPE D3DRS_CCW_STENCILWRITEMASK = D3DRS_STENCILWRITEMASK;
2178 if (mState.stencilWritemask != mState.stencilBackWritemask ||
2179 mState.stencilRef != mState.stencilBackRef ||
2180 mState.stencilMask != mState.stencilBackMask)
2181 {
2182 ERR("Separate front/back stencil writemasks, reference values, or stencil mask values are invalid under WebGL.");
2183 return error(GL_INVALID_OPERATION);
2184 }
2185
2186 // get the maximum size of the stencil ref
2187 gl::Renderbuffer *stencilbuffer = framebufferObject->getStencilbuffer();
2188 GLuint maxStencil = (1 << stencilbuffer->getStencilSize()) - 1;
2189
2190 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilWritemask);
2191 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2192 es2dx::ConvertComparison(mState.stencilFunc));
2193
2194 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilRef < (GLint)maxStencil) ? mState.stencilRef : maxStencil);
2195 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilMask);
2196
2197 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2198 es2dx::ConvertStencilOp(mState.stencilFail));
2199 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2200 es2dx::ConvertStencilOp(mState.stencilPassDepthFail));
2201 mDevice->SetRenderState(mState.frontFace == GL_CCW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2202 es2dx::ConvertStencilOp(mState.stencilPassDepthPass));
2203
2204 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILWRITEMASK : D3DRS_CCW_STENCILWRITEMASK, mState.stencilBackWritemask);
2205 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFUNC : D3DRS_CCW_STENCILFUNC,
2206 es2dx::ConvertComparison(mState.stencilBackFunc));
2207
2208 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILREF : D3DRS_CCW_STENCILREF, (mState.stencilBackRef < (GLint)maxStencil) ? mState.stencilBackRef : maxStencil);
2209 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILMASK : D3DRS_CCW_STENCILMASK, mState.stencilBackMask);
2210
2211 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILFAIL : D3DRS_CCW_STENCILFAIL,
2212 es2dx::ConvertStencilOp(mState.stencilBackFail));
2213 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILZFAIL : D3DRS_CCW_STENCILZFAIL,
2214 es2dx::ConvertStencilOp(mState.stencilBackPassDepthFail));
2215 mDevice->SetRenderState(mState.frontFace == GL_CW ? D3DRS_STENCILPASS : D3DRS_CCW_STENCILPASS,
2216 es2dx::ConvertStencilOp(mState.stencilBackPassDepthPass));
2217 }
2218 else
2219 {
2220 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2221 }
2222
2223 mStencilStateDirty = false;
2224 mFrontFaceDirty = false;
2225 }
2226
2227 if (mMaskStateDirty)
2228 {
2229 int colorMask = es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen,
2230 mState.colorMaskBlue, mState.colorMaskAlpha);
2231 if (colorMask == 0 && !zeroColorMaskAllowed)
2232 {
2233 // Enable green channel, but set blending so nothing will be drawn.
2234 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, D3DCOLORWRITEENABLE_GREEN);
2235 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE);
2236
2237 mDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_ZERO);
2238 mDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_ONE);
2239 mDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);
2240 }
2241 else
2242 {
2243 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, colorMask);
2244 }
2245 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, mState.depthMask ? TRUE : FALSE);
2246
2247 mMaskStateDirty = false;
2248 }
2249
2250 if (mPolygonOffsetStateDirty)
2251 {
2252 if (mState.polygonOffsetFill)
2253 {
2254 gl::Renderbuffer *depthbuffer = framebufferObject->getDepthbuffer();
2255 if (depthbuffer)
2256 {
2257 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *((DWORD*)&mState.polygonOffsetFactor));
2258 float depthBias = ldexp(mState.polygonOffsetUnits, -(int)(depthbuffer->getDepthSize()));
2259 mDevice->SetRenderState(D3DRS_DEPTHBIAS, *((DWORD*)&depthBias));
2260 }
2261 }
2262 else
2263 {
2264 mDevice->SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, 0);
2265 mDevice->SetRenderState(D3DRS_DEPTHBIAS, 0);
2266 }
2267
2268 mPolygonOffsetStateDirty = false;
2269 }
2270
2271 if (mSampleStateDirty)
2272 {
2273 if (mState.sampleAlphaToCoverage)
2274 {
2275 FIXME("Sample alpha to coverage is unimplemented.");
2276 }
2277
2278 mDevice->SetRenderState(D3DRS_MULTISAMPLEANTIALIAS, TRUE);
2279 if (mState.sampleCoverage)
2280 {
2281 unsigned int mask = 0;
2282 if (mState.sampleCoverageValue != 0)
2283 {
2284 float threshold = 0.5f;
2285
2286 for (int i = 0; i < framebufferObject->getSamples(); ++i)
2287 {
2288 mask <<= 1;
2289
2290 if ((i + 1) * mState.sampleCoverageValue >= threshold)
2291 {
2292 threshold += 1.0f;
2293 mask |= 1;
2294 }
2295 }
2296 }
2297
2298 if (mState.sampleCoverageInvert)
2299 {
2300 mask = ~mask;
2301 }
2302
2303 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, mask);
2304 }
2305 else
2306 {
2307 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2308 }
2309
2310 mSampleStateDirty = false;
2311 }
2312
2313 if (mDitherStateDirty)
2314 {
2315 mDevice->SetRenderState(D3DRS_DITHERENABLE, mState.dither ? TRUE : FALSE);
2316
2317 mDitherStateDirty = false;
2318 }
2319}
2320
2321GLenum Context::applyVertexBuffer(GLint first, GLsizei count, GLsizei instances, GLsizei *repeatDraw)
2322{
2323 TranslatedAttribute attributes[MAX_VERTEX_ATTRIBS];
2324
daniel@transgaming.com408caa52012-10-31 18:47:01 +00002325 ProgramBinary *programBinary = getCurrentProgramBinary();
2326 GLenum err = mVertexDataManager->prepareVertexData(mState.vertexAttribute, programBinary, first, count, attributes, instances);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002327 if (err != GL_NO_ERROR)
2328 {
2329 return err;
2330 }
daniel@transgaming.com408caa52012-10-31 18:47:01 +00002331
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00002332 return mVertexDeclarationCache.applyDeclaration(mDevice, attributes, programBinary, instances, repeatDraw);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002333}
2334
2335// Applies the indices and element array bindings to the Direct3D 9 device
2336GLenum Context::applyIndexBuffer(const GLvoid *indices, GLsizei count, GLenum mode, GLenum type, TranslatedIndexData *indexInfo)
2337{
2338 GLenum err = mIndexDataManager->prepareIndexData(type, count, mState.elementArrayBuffer.get(), indices, indexInfo);
2339
2340 if (err == GL_NO_ERROR)
2341 {
2342 if (indexInfo->serial != mAppliedIBSerial)
2343 {
2344 mDevice->SetIndices(indexInfo->indexBuffer);
2345 mAppliedIBSerial = indexInfo->serial;
2346 }
2347 }
2348
2349 return err;
2350}
2351
2352// Applies the shaders and shader constants to the Direct3D 9 device
2353void Context::applyShaders()
2354{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002355 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002356
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002357 if (programBinary->getSerial() != mAppliedProgramBinarySerial)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002358 {
2359 IDirect3DVertexShader9 *vertexShader = programBinary->getVertexShader();
2360 IDirect3DPixelShader9 *pixelShader = programBinary->getPixelShader();
2361
2362 mDevice->SetPixelShader(pixelShader);
2363 mDevice->SetVertexShader(vertexShader);
2364 programBinary->dirtyAllUniforms();
daniel@transgaming.come6af4f92012-07-24 18:31:31 +00002365 mAppliedProgramBinarySerial = programBinary->getSerial();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002366 }
2367
2368 programBinary->applyUniforms();
2369}
2370
2371// Applies the textures and sampler states to the Direct3D 9 device
2372void Context::applyTextures()
2373{
2374 applyTextures(SAMPLER_PIXEL);
2375
2376 if (mSupportsVertexTexture)
2377 {
2378 applyTextures(SAMPLER_VERTEX);
2379 }
2380}
2381
2382// For each Direct3D 9 sampler of either the pixel or vertex stage,
2383// looks up the corresponding OpenGL texture image unit and texture type,
2384// and sets the texture and its addressing/filtering state (or NULL when inactive).
2385void Context::applyTextures(SamplerType type)
2386{
daniel@transgaming.com62a28462012-07-24 18:33:59 +00002387 ProgramBinary *programBinary = getCurrentProgramBinary();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002388
2389 int samplerCount = (type == SAMPLER_PIXEL) ? MAX_TEXTURE_IMAGE_UNITS : MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF; // Range of Direct3D 9 samplers of given sampler type
2390 unsigned int *appliedTextureSerial = (type == SAMPLER_PIXEL) ? mAppliedTextureSerialPS : mAppliedTextureSerialVS;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002391 int samplerRange = programBinary->getUsedSamplerRange(type);
2392
2393 for (int samplerIndex = 0; samplerIndex < samplerRange; samplerIndex++)
2394 {
2395 int textureUnit = programBinary->getSamplerMapping(type, samplerIndex); // OpenGL texture image unit index
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002396
2397 if (textureUnit != -1)
2398 {
2399 TextureType textureType = programBinary->getSamplerTextureType(type, samplerIndex);
2400
2401 Texture *texture = getSamplerTexture(textureUnit, textureType);
2402 unsigned int texSerial = texture->getTextureSerial();
2403
2404 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters() || texture->hasDirtyImages())
2405 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002406 if (texture->isSamplerComplete())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002407 {
2408 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyParameters())
2409 {
daniel@transgaming.comebf139f2012-10-31 18:07:32 +00002410 SamplerState samplerState;
2411 texture->getSamplerState(&samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002412
daniel@transgaming.comba0570e2012-10-31 18:07:39 +00002413 mRenderer->setSamplerState(type, samplerIndex, samplerState);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002414 }
2415
2416 if (appliedTextureSerial[samplerIndex] != texSerial || texture->hasDirtyImages())
2417 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002418 mRenderer->setTexture(type, samplerIndex, texture);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002419 }
2420 }
2421 else
2422 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002423 mRenderer->setTexture(type, samplerIndex, getIncompleteTexture(textureType));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002424 }
2425
2426 appliedTextureSerial[samplerIndex] = texSerial;
2427 texture->resetDirty();
2428 }
2429 }
2430 else
2431 {
2432 if (appliedTextureSerial[samplerIndex] != 0)
2433 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002434 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002435 appliedTextureSerial[samplerIndex] = 0;
2436 }
2437 }
2438 }
2439
2440 for (int samplerIndex = samplerRange; samplerIndex < samplerCount; samplerIndex++)
2441 {
2442 if (appliedTextureSerial[samplerIndex] != 0)
2443 {
daniel@transgaming.coma734f272012-10-31 18:07:48 +00002444 mRenderer->setTexture(type, samplerIndex, NULL);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002445 appliedTextureSerial[samplerIndex] = 0;
2446 }
2447 }
2448}
2449
2450void Context::readPixels(GLint x, GLint y, GLsizei width, GLsizei height,
2451 GLenum format, GLenum type, GLsizei *bufSize, void* pixels)
2452{
2453 Framebuffer *framebuffer = getReadFramebuffer();
2454
2455 if (framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
2456 {
2457 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2458 }
2459
2460 if (getReadFramebufferHandle() != 0 && framebuffer->getSamples() != 0)
2461 {
2462 return error(GL_INVALID_OPERATION);
2463 }
2464
daniel@transgaming.com6452adf2012-10-17 18:22:35 +00002465 GLsizei outputPitch = ComputePitch(width, ConvertSizedInternalFormat(format, type), mState.packAlignment);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002466 // sized query sanity check
2467 if (bufSize)
2468 {
2469 int requiredSize = outputPitch * height;
2470 if (requiredSize > *bufSize)
2471 {
2472 return error(GL_INVALID_OPERATION);
2473 }
2474 }
2475
2476 IDirect3DSurface9 *renderTarget = framebuffer->getRenderTarget();
2477 if (!renderTarget)
2478 {
2479 return; // Context must be lost, return silently
2480 }
2481
2482 D3DSURFACE_DESC desc;
2483 renderTarget->GetDesc(&desc);
2484
2485 if (desc.MultiSampleType != D3DMULTISAMPLE_NONE)
2486 {
2487 UNIMPLEMENTED(); // FIXME: Requires resolve using StretchRect into non-multisampled render target
2488 renderTarget->Release();
2489 return error(GL_OUT_OF_MEMORY);
2490 }
2491
2492 HRESULT result;
2493 IDirect3DSurface9 *systemSurface = NULL;
daniel@transgaming.com7cb796e2012-10-31 18:46:44 +00002494 bool directToPixels = !getPackReverseRowOrder() && getPackAlignment() <= 4 && mRenderer->getShareHandleSupport() &&
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002495 x == 0 && y == 0 && UINT(width) == desc.Width && UINT(height) == desc.Height &&
2496 desc.Format == D3DFMT_A8R8G8B8 && format == GL_BGRA_EXT && type == GL_UNSIGNED_BYTE;
2497 if (directToPixels)
2498 {
2499 // Use the pixels ptr as a shared handle to write directly into client's memory
2500 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2501 D3DPOOL_SYSTEMMEM, &systemSurface, &pixels);
2502 if (FAILED(result))
2503 {
2504 // Try again without the shared handle
2505 directToPixels = false;
2506 }
2507 }
2508
2509 if (!directToPixels)
2510 {
2511 result = mDevice->CreateOffscreenPlainSurface(desc.Width, desc.Height, desc.Format,
2512 D3DPOOL_SYSTEMMEM, &systemSurface, NULL);
2513 if (FAILED(result))
2514 {
2515 ASSERT(result == D3DERR_OUTOFVIDEOMEMORY || result == E_OUTOFMEMORY);
2516 renderTarget->Release();
2517 return error(GL_OUT_OF_MEMORY);
2518 }
2519 }
2520
2521 result = mDevice->GetRenderTargetData(renderTarget, systemSurface);
2522 renderTarget->Release();
2523 renderTarget = NULL;
2524
2525 if (FAILED(result))
2526 {
2527 systemSurface->Release();
2528
2529 // It turns out that D3D will sometimes produce more error
2530 // codes than those documented.
2531 if (checkDeviceLost(result))
2532 return error(GL_OUT_OF_MEMORY);
2533 else
2534 {
2535 UNREACHABLE();
2536 return;
2537 }
2538
2539 }
2540
2541 if (directToPixels)
2542 {
2543 systemSurface->Release();
2544 return;
2545 }
2546
2547 RECT rect;
2548 rect.left = clamp(x, 0L, static_cast<LONG>(desc.Width));
2549 rect.top = clamp(y, 0L, static_cast<LONG>(desc.Height));
2550 rect.right = clamp(x + width, 0L, static_cast<LONG>(desc.Width));
2551 rect.bottom = clamp(y + height, 0L, static_cast<LONG>(desc.Height));
2552
2553 D3DLOCKED_RECT lock;
2554 result = systemSurface->LockRect(&lock, &rect, D3DLOCK_READONLY);
2555
2556 if (FAILED(result))
2557 {
2558 UNREACHABLE();
2559 systemSurface->Release();
2560
2561 return; // No sensible error to generate
2562 }
2563
2564 unsigned char *dest = (unsigned char*)pixels;
2565 unsigned short *dest16 = (unsigned short*)pixels;
2566
2567 unsigned char *source;
2568 int inputPitch;
2569 if (getPackReverseRowOrder())
2570 {
2571 source = ((unsigned char*)lock.pBits) + lock.Pitch * (rect.bottom - rect.top - 1);
2572 inputPitch = -lock.Pitch;
2573 }
2574 else
2575 {
2576 source = (unsigned char*)lock.pBits;
2577 inputPitch = lock.Pitch;
2578 }
2579
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002580 unsigned int fastPixelSize = 0;
2581
2582 if (desc.Format == D3DFMT_A8R8G8B8 &&
2583 format == GL_BGRA_EXT &&
2584 type == GL_UNSIGNED_BYTE)
2585 {
2586 fastPixelSize = 4;
2587 }
2588 else if ((desc.Format == D3DFMT_A4R4G4B4 &&
2589 format == GL_BGRA_EXT &&
2590 type == GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT) ||
2591 (desc.Format == D3DFMT_A1R5G5B5 &&
2592 format == GL_BGRA_EXT &&
2593 type == GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT))
2594 {
2595 fastPixelSize = 2;
2596 }
2597 else if (desc.Format == D3DFMT_A16B16G16R16F &&
2598 format == GL_RGBA &&
2599 type == GL_HALF_FLOAT_OES)
2600 {
2601 fastPixelSize = 8;
2602 }
2603 else if (desc.Format == D3DFMT_A32B32G32R32F &&
2604 format == GL_RGBA &&
2605 type == GL_FLOAT)
2606 {
2607 fastPixelSize = 16;
2608 }
2609
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002610 for (int j = 0; j < rect.bottom - rect.top; j++)
2611 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002612 if (fastPixelSize != 0)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002613 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002614 // Fast path for formats which require no translation:
2615 // D3DFMT_A8R8G8B8 to BGRA/UNSIGNED_BYTE
2616 // D3DFMT_A4R4G4B4 to BGRA/UNSIGNED_SHORT_4_4_4_4_REV_EXT
2617 // D3DFMT_A1R5G5B5 to BGRA/UNSIGNED_SHORT_1_5_5_5_REV_EXT
2618 // D3DFMT_A16B16G16R16F to RGBA/HALF_FLOAT_OES
2619 // D3DFMT_A32B32G32R32F to RGBA/FLOAT
2620 //
2621 // Note that buffers with no alpha go through the slow path below.
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002622 memcpy(dest + j * outputPitch,
2623 source + j * inputPitch,
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002624 (rect.right - rect.left) * fastPixelSize);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002625 continue;
2626 }
2627
2628 for (int i = 0; i < rect.right - rect.left; i++)
2629 {
2630 float r;
2631 float g;
2632 float b;
2633 float a;
2634
2635 switch (desc.Format)
2636 {
2637 case D3DFMT_R5G6B5:
2638 {
2639 unsigned short rgb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2640
2641 a = 1.0f;
2642 b = (rgb & 0x001F) * (1.0f / 0x001F);
2643 g = (rgb & 0x07E0) * (1.0f / 0x07E0);
2644 r = (rgb & 0xF800) * (1.0f / 0xF800);
2645 }
2646 break;
2647 case D3DFMT_A1R5G5B5:
2648 {
2649 unsigned short argb = *(unsigned short*)(source + 2 * i + j * inputPitch);
2650
2651 a = (argb & 0x8000) ? 1.0f : 0.0f;
2652 b = (argb & 0x001F) * (1.0f / 0x001F);
2653 g = (argb & 0x03E0) * (1.0f / 0x03E0);
2654 r = (argb & 0x7C00) * (1.0f / 0x7C00);
2655 }
2656 break;
2657 case D3DFMT_A8R8G8B8:
2658 {
2659 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2660
2661 a = (argb & 0xFF000000) * (1.0f / 0xFF000000);
2662 b = (argb & 0x000000FF) * (1.0f / 0x000000FF);
2663 g = (argb & 0x0000FF00) * (1.0f / 0x0000FF00);
2664 r = (argb & 0x00FF0000) * (1.0f / 0x00FF0000);
2665 }
2666 break;
2667 case D3DFMT_X8R8G8B8:
2668 {
2669 unsigned int xrgb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2670
2671 a = 1.0f;
2672 b = (xrgb & 0x000000FF) * (1.0f / 0x000000FF);
2673 g = (xrgb & 0x0000FF00) * (1.0f / 0x0000FF00);
2674 r = (xrgb & 0x00FF0000) * (1.0f / 0x00FF0000);
2675 }
2676 break;
2677 case D3DFMT_A2R10G10B10:
2678 {
2679 unsigned int argb = *(unsigned int*)(source + 4 * i + j * inputPitch);
2680
2681 a = (argb & 0xC0000000) * (1.0f / 0xC0000000);
2682 b = (argb & 0x000003FF) * (1.0f / 0x000003FF);
2683 g = (argb & 0x000FFC00) * (1.0f / 0x000FFC00);
2684 r = (argb & 0x3FF00000) * (1.0f / 0x3FF00000);
2685 }
2686 break;
2687 case D3DFMT_A32B32G32R32F:
2688 {
2689 // float formats in D3D are stored rgba, rather than the other way round
2690 r = *((float*)(source + 16 * i + j * inputPitch) + 0);
2691 g = *((float*)(source + 16 * i + j * inputPitch) + 1);
2692 b = *((float*)(source + 16 * i + j * inputPitch) + 2);
2693 a = *((float*)(source + 16 * i + j * inputPitch) + 3);
2694 }
2695 break;
2696 case D3DFMT_A16B16G16R16F:
2697 {
2698 // float formats in D3D are stored rgba, rather than the other way round
apatrick@chromium.orgaa480672012-09-05 19:32:38 +00002699 r = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 0));
2700 g = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 1));
2701 b = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 2));
2702 a = float16ToFloat32(*((unsigned short*)(source + 8 * i + j * inputPitch) + 3));
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002703 }
2704 break;
2705 default:
2706 UNIMPLEMENTED(); // FIXME
2707 UNREACHABLE();
2708 return;
2709 }
2710
2711 switch (format)
2712 {
2713 case GL_RGBA:
2714 switch (type)
2715 {
2716 case GL_UNSIGNED_BYTE:
2717 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2718 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2719 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2720 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2721 break;
2722 default: UNREACHABLE();
2723 }
2724 break;
2725 case GL_BGRA_EXT:
2726 switch (type)
2727 {
2728 case GL_UNSIGNED_BYTE:
2729 dest[4 * i + j * outputPitch + 0] = (unsigned char)(255 * b + 0.5f);
2730 dest[4 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2731 dest[4 * i + j * outputPitch + 2] = (unsigned char)(255 * r + 0.5f);
2732 dest[4 * i + j * outputPitch + 3] = (unsigned char)(255 * a + 0.5f);
2733 break;
2734 case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
2735 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2736 // this type is packed as follows:
2737 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2738 // --------------------------------------------------------------------------------
2739 // | 4th | 3rd | 2nd | 1st component |
2740 // --------------------------------------------------------------------------------
2741 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2742 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2743 ((unsigned short)(15 * a + 0.5f) << 12)|
2744 ((unsigned short)(15 * r + 0.5f) << 8) |
2745 ((unsigned short)(15 * g + 0.5f) << 4) |
2746 ((unsigned short)(15 * b + 0.5f) << 0);
2747 break;
2748 case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
2749 // According to the desktop GL spec in the "Transfer of Pixel Rectangles" section
2750 // this type is packed as follows:
2751 // 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
2752 // --------------------------------------------------------------------------------
2753 // | 4th | 3rd | 2nd | 1st component |
2754 // --------------------------------------------------------------------------------
2755 // in the case of BGRA_EXT, B is the first component, G the second, and so forth.
2756 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2757 ((unsigned short)( a + 0.5f) << 15) |
2758 ((unsigned short)(31 * r + 0.5f) << 10) |
2759 ((unsigned short)(31 * g + 0.5f) << 5) |
2760 ((unsigned short)(31 * b + 0.5f) << 0);
2761 break;
2762 default: UNREACHABLE();
2763 }
2764 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002765 case GL_RGB:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002766 switch (type)
2767 {
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002768 case GL_UNSIGNED_SHORT_5_6_5:
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002769 dest16[i + j * outputPitch / sizeof(unsigned short)] =
2770 ((unsigned short)(31 * b + 0.5f) << 0) |
2771 ((unsigned short)(63 * g + 0.5f) << 5) |
2772 ((unsigned short)(31 * r + 0.5f) << 11);
2773 break;
daniel@transgaming.com42944b02012-09-27 17:45:57 +00002774 case GL_UNSIGNED_BYTE:
2775 dest[3 * i + j * outputPitch + 0] = (unsigned char)(255 * r + 0.5f);
2776 dest[3 * i + j * outputPitch + 1] = (unsigned char)(255 * g + 0.5f);
2777 dest[3 * i + j * outputPitch + 2] = (unsigned char)(255 * b + 0.5f);
2778 break;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002779 default: UNREACHABLE();
2780 }
2781 break;
2782 default: UNREACHABLE();
2783 }
2784 }
2785 }
2786
2787 systemSurface->UnlockRect();
2788
2789 systemSurface->Release();
2790}
2791
2792void Context::clear(GLbitfield mask)
2793{
2794 Framebuffer *framebufferObject = getDrawFramebuffer();
2795
2796 if (!framebufferObject || framebufferObject->completeness() != GL_FRAMEBUFFER_COMPLETE)
2797 {
2798 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
2799 }
2800
2801 DWORD flags = 0;
2802
2803 if (mask & GL_COLOR_BUFFER_BIT)
2804 {
2805 mask &= ~GL_COLOR_BUFFER_BIT;
2806
2807 if (framebufferObject->getColorbufferType() != GL_NONE)
2808 {
2809 flags |= D3DCLEAR_TARGET;
2810 }
2811 }
2812
2813 if (mask & GL_DEPTH_BUFFER_BIT)
2814 {
2815 mask &= ~GL_DEPTH_BUFFER_BIT;
2816 if (mState.depthMask && framebufferObject->getDepthbufferType() != GL_NONE)
2817 {
2818 flags |= D3DCLEAR_ZBUFFER;
2819 }
2820 }
2821
2822 GLuint stencilUnmasked = 0x0;
2823
2824 if (mask & GL_STENCIL_BUFFER_BIT)
2825 {
2826 mask &= ~GL_STENCIL_BUFFER_BIT;
2827 if (framebufferObject->getStencilbufferType() != GL_NONE)
2828 {
2829 IDirect3DSurface9 *depthStencil = framebufferObject->getStencilbuffer()->getDepthStencil();
2830 if (!depthStencil)
2831 {
2832 ERR("Depth stencil pointer unexpectedly null.");
2833 return;
2834 }
2835
2836 D3DSURFACE_DESC desc;
2837 depthStencil->GetDesc(&desc);
2838 depthStencil->Release();
2839
2840 unsigned int stencilSize = dx2es::GetStencilSize(desc.Format);
2841 stencilUnmasked = (0x1 << stencilSize) - 1;
2842
2843 if (stencilUnmasked != 0x0)
2844 {
2845 flags |= D3DCLEAR_STENCIL;
2846 }
2847 }
2848 }
2849
2850 if (mask != 0)
2851 {
2852 return error(GL_INVALID_VALUE);
2853 }
2854
2855 if (!applyRenderTarget(true)) // Clips the clear to the scissor rectangle but not the viewport
2856 {
2857 return;
2858 }
2859
2860 D3DCOLOR color = D3DCOLOR_ARGB(unorm<8>(mState.colorClearValue.alpha),
2861 unorm<8>(mState.colorClearValue.red),
2862 unorm<8>(mState.colorClearValue.green),
2863 unorm<8>(mState.colorClearValue.blue));
2864 float depth = clamp01(mState.depthClearValue);
2865 int stencil = mState.stencilClearValue & 0x000000FF;
2866
2867 bool alphaUnmasked = (dx2es::GetAlphaSize(mRenderTargetDesc.Format) == 0) || mState.colorMaskAlpha;
2868
2869 const bool needMaskedStencilClear = (flags & D3DCLEAR_STENCIL) &&
2870 (mState.stencilWritemask & stencilUnmasked) != stencilUnmasked;
2871 const bool needMaskedColorClear = (flags & D3DCLEAR_TARGET) &&
2872 !(mState.colorMaskRed && mState.colorMaskGreen &&
2873 mState.colorMaskBlue && alphaUnmasked);
2874
2875 if (needMaskedColorClear || needMaskedStencilClear)
2876 {
2877 // State which is altered in all paths from this point to the clear call is saved.
2878 // State which is altered in only some paths will be flagged dirty in the case that
2879 // that path is taken.
2880 HRESULT hr;
2881 if (mMaskedClearSavedState == NULL)
2882 {
2883 hr = mDevice->BeginStateBlock();
2884 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2885
2886 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2887 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2888 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2889 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2890 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2891 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2892 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2893 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2894 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2895 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2896 mDevice->SetPixelShader(NULL);
2897 mDevice->SetVertexShader(NULL);
2898 mDevice->SetFVF(D3DFVF_XYZRHW | D3DFVF_DIFFUSE);
2899 mDevice->SetStreamSource(0, NULL, 0, 0);
2900 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2901 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2902 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2903 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2904 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2905 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2906 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2907
2908 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2909 {
2910 mDevice->SetStreamSourceFreq(i, 1);
2911 }
2912
2913 hr = mDevice->EndStateBlock(&mMaskedClearSavedState);
2914 ASSERT(SUCCEEDED(hr) || hr == D3DERR_OUTOFVIDEOMEMORY || hr == E_OUTOFMEMORY);
2915 }
2916
2917 ASSERT(mMaskedClearSavedState != NULL);
2918
2919 if (mMaskedClearSavedState != NULL)
2920 {
2921 hr = mMaskedClearSavedState->Capture();
2922 ASSERT(SUCCEEDED(hr));
2923 }
2924
2925 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, FALSE);
2926 mDevice->SetRenderState(D3DRS_ZFUNC, D3DCMP_ALWAYS);
2927 mDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
2928 mDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
2929 mDevice->SetRenderState(D3DRS_FILLMODE, D3DFILL_SOLID);
2930 mDevice->SetRenderState(D3DRS_ALPHATESTENABLE, FALSE);
2931 mDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
2932 mDevice->SetRenderState(D3DRS_CLIPPLANEENABLE, 0);
2933
2934 if (flags & D3DCLEAR_TARGET)
2935 {
2936 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, es2dx::ConvertColorMask(mState.colorMaskRed, mState.colorMaskGreen, mState.colorMaskBlue, mState.colorMaskAlpha));
2937 }
2938 else
2939 {
2940 mDevice->SetRenderState(D3DRS_COLORWRITEENABLE, 0);
2941 }
2942
2943 if (stencilUnmasked != 0x0 && (flags & D3DCLEAR_STENCIL))
2944 {
2945 mDevice->SetRenderState(D3DRS_STENCILENABLE, TRUE);
2946 mDevice->SetRenderState(D3DRS_TWOSIDEDSTENCILMODE, FALSE);
2947 mDevice->SetRenderState(D3DRS_STENCILFUNC, D3DCMP_ALWAYS);
2948 mDevice->SetRenderState(D3DRS_STENCILREF, stencil);
2949 mDevice->SetRenderState(D3DRS_STENCILWRITEMASK, mState.stencilWritemask);
2950 mDevice->SetRenderState(D3DRS_STENCILFAIL, D3DSTENCILOP_REPLACE);
2951 mDevice->SetRenderState(D3DRS_STENCILZFAIL, D3DSTENCILOP_REPLACE);
2952 mDevice->SetRenderState(D3DRS_STENCILPASS, D3DSTENCILOP_REPLACE);
2953 mStencilStateDirty = true;
2954 }
2955 else
2956 {
2957 mDevice->SetRenderState(D3DRS_STENCILENABLE, FALSE);
2958 }
2959
2960 mDevice->SetPixelShader(NULL);
2961 mDevice->SetVertexShader(NULL);
2962 mDevice->SetFVF(D3DFVF_XYZRHW);
2963 mDevice->SetRenderState(D3DRS_SEPARATEALPHABLENDENABLE, TRUE);
2964 mDevice->SetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1);
2965 mDevice->SetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR);
2966 mDevice->SetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_SELECTARG1);
2967 mDevice->SetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_TFACTOR);
2968 mDevice->SetRenderState(D3DRS_TEXTUREFACTOR, color);
2969 mDevice->SetRenderState(D3DRS_MULTISAMPLEMASK, 0xFFFFFFFF);
2970
2971 for(int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
2972 {
2973 mDevice->SetStreamSourceFreq(i, 1);
2974 }
2975
2976 float quad[4][4]; // A quadrilateral covering the target, aligned to match the edges
2977 quad[0][0] = -0.5f;
2978 quad[0][1] = mRenderTargetDesc.Height - 0.5f;
2979 quad[0][2] = 0.0f;
2980 quad[0][3] = 1.0f;
2981
2982 quad[1][0] = mRenderTargetDesc.Width - 0.5f;
2983 quad[1][1] = mRenderTargetDesc.Height - 0.5f;
2984 quad[1][2] = 0.0f;
2985 quad[1][3] = 1.0f;
2986
2987 quad[2][0] = -0.5f;
2988 quad[2][1] = -0.5f;
2989 quad[2][2] = 0.0f;
2990 quad[2][3] = 1.0f;
2991
2992 quad[3][0] = mRenderTargetDesc.Width - 0.5f;
2993 quad[3][1] = -0.5f;
2994 quad[3][2] = 0.0f;
2995 quad[3][3] = 1.0f;
2996
daniel@transgaming.com621ce052012-10-31 17:52:29 +00002997 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00002998 mDevice->DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, quad, sizeof(float[4]));
2999
3000 if (flags & D3DCLEAR_ZBUFFER)
3001 {
3002 mDevice->SetRenderState(D3DRS_ZENABLE, TRUE);
3003 mDevice->SetRenderState(D3DRS_ZWRITEENABLE, TRUE);
3004 mDevice->Clear(0, NULL, D3DCLEAR_ZBUFFER, color, depth, stencil);
3005 }
3006
3007 if (mMaskedClearSavedState != NULL)
3008 {
3009 mMaskedClearSavedState->Apply();
3010 }
3011 }
3012 else if (flags)
3013 {
3014 mDevice->Clear(0, NULL, flags, color, depth, stencil);
3015 }
3016}
3017
3018void Context::drawArrays(GLenum mode, GLint first, GLsizei count, GLsizei instances)
3019{
3020 if (!mState.currentProgram)
3021 {
3022 return error(GL_INVALID_OPERATION);
3023 }
3024
3025 D3DPRIMITIVETYPE primitiveType;
3026 int primitiveCount;
3027
3028 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3029 return error(GL_INVALID_ENUM);
3030
3031 if (primitiveCount <= 0)
3032 {
3033 return;
3034 }
3035
3036 if (!applyRenderTarget(false))
3037 {
3038 return;
3039 }
3040
3041 applyState(mode);
3042
3043 GLsizei repeatDraw = 1;
3044 GLenum err = applyVertexBuffer(first, count, instances, &repeatDraw);
3045 if (err != GL_NO_ERROR)
3046 {
3047 return error(err);
3048 }
3049
3050 applyShaders();
3051 applyTextures();
3052
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003053 if (!getCurrentProgramBinary()->validateSamplers(NULL))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003054 {
3055 return error(GL_INVALID_OPERATION);
3056 }
3057
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003058 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003059 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003060 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003061
3062 if (mode == GL_LINE_LOOP)
3063 {
3064 drawLineLoop(count, GL_NONE, NULL, 0);
3065 }
3066 else if (instances > 0)
3067 {
3068 StaticIndexBuffer *countingIB = mIndexDataManager->getCountingIndices(count);
3069 if (countingIB)
3070 {
3071 if (mAppliedIBSerial != countingIB->getSerial())
3072 {
3073 mDevice->SetIndices(countingIB->getBuffer());
3074 mAppliedIBSerial = countingIB->getSerial();
3075 }
3076
3077 for (int i = 0; i < repeatDraw; i++)
3078 {
3079 mDevice->DrawIndexedPrimitive(primitiveType, 0, 0, count, 0, primitiveCount);
3080 }
3081 }
3082 else
3083 {
3084 ERR("Could not create a counting index buffer for glDrawArraysInstanced.");
3085 return error(GL_OUT_OF_MEMORY);
3086 }
3087 }
3088 else // Regular case
3089 {
3090 mDevice->DrawPrimitive(primitiveType, 0, primitiveCount);
3091 }
3092 }
3093}
3094
3095void Context::drawElements(GLenum mode, GLsizei count, GLenum type, const GLvoid *indices, GLsizei instances)
3096{
3097 if (!mState.currentProgram)
3098 {
3099 return error(GL_INVALID_OPERATION);
3100 }
3101
3102 if (!indices && !mState.elementArrayBuffer)
3103 {
3104 return error(GL_INVALID_OPERATION);
3105 }
3106
3107 D3DPRIMITIVETYPE primitiveType;
3108 int primitiveCount;
3109
3110 if(!es2dx::ConvertPrimitiveType(mode, count, &primitiveType, &primitiveCount))
3111 return error(GL_INVALID_ENUM);
3112
3113 if (primitiveCount <= 0)
3114 {
3115 return;
3116 }
3117
3118 if (!applyRenderTarget(false))
3119 {
3120 return;
3121 }
3122
3123 applyState(mode);
3124
3125 TranslatedIndexData indexInfo;
3126 GLenum err = applyIndexBuffer(indices, count, mode, type, &indexInfo);
3127 if (err != GL_NO_ERROR)
3128 {
3129 return error(err);
3130 }
3131
3132 GLsizei vertexCount = indexInfo.maxIndex - indexInfo.minIndex + 1;
3133 GLsizei repeatDraw = 1;
3134 err = applyVertexBuffer(indexInfo.minIndex, vertexCount, instances, &repeatDraw);
3135 if (err != GL_NO_ERROR)
3136 {
3137 return error(err);
3138 }
3139
3140 applyShaders();
3141 applyTextures();
3142
daniel@transgaming.com62a28462012-07-24 18:33:59 +00003143 if (!getCurrentProgramBinary()->validateSamplers(false))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003144 {
3145 return error(GL_INVALID_OPERATION);
3146 }
3147
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003148 if (!skipDraw(mode))
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003149 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003150 mRenderer->startScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003151
3152 if (mode == GL_LINE_LOOP)
3153 {
3154 drawLineLoop(count, type, indices, indexInfo.minIndex);
3155 }
3156 else
3157 {
3158 for (int i = 0; i < repeatDraw; i++)
3159 {
3160 mDevice->DrawIndexedPrimitive(primitiveType, -(INT)indexInfo.minIndex, indexInfo.minIndex, vertexCount, indexInfo.startIndex, primitiveCount);
3161 }
3162 }
3163 }
3164}
3165
3166// Implements glFlush when block is false, glFinish when block is true
3167void Context::sync(bool block)
3168{
daniel@transgaming.comef21ab22012-10-31 17:52:47 +00003169 mRenderer->sync(block);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003170}
3171
3172void Context::drawLineLoop(GLsizei count, GLenum type, const GLvoid *indices, int minIndex)
3173{
3174 // Get the raw indices for an indexed draw
3175 if (type != GL_NONE && mState.elementArrayBuffer.get())
3176 {
3177 Buffer *indexBuffer = mState.elementArrayBuffer.get();
3178 intptr_t offset = reinterpret_cast<intptr_t>(indices);
3179 indices = static_cast<const GLubyte*>(indexBuffer->data()) + offset;
3180 }
3181
3182 UINT startIndex = 0;
3183 bool succeeded = false;
3184
3185 if (supports32bitIndices())
3186 {
3187 const int spaceNeeded = (count + 1) * sizeof(unsigned int);
3188
3189 if (!mLineLoopIB)
3190 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003191 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX32);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003192 }
3193
3194 if (mLineLoopIB)
3195 {
3196 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_INT);
3197
3198 UINT offset = 0;
3199 unsigned int *data = static_cast<unsigned int*>(mLineLoopIB->map(spaceNeeded, &offset));
3200 startIndex = offset / 4;
3201
3202 if (data)
3203 {
3204 switch (type)
3205 {
3206 case GL_NONE: // Non-indexed draw
3207 for (int i = 0; i < count; i++)
3208 {
3209 data[i] = i;
3210 }
3211 data[count] = 0;
3212 break;
3213 case GL_UNSIGNED_BYTE:
3214 for (int i = 0; i < count; i++)
3215 {
3216 data[i] = static_cast<const GLubyte*>(indices)[i];
3217 }
3218 data[count] = static_cast<const GLubyte*>(indices)[0];
3219 break;
3220 case GL_UNSIGNED_SHORT:
3221 for (int i = 0; i < count; i++)
3222 {
3223 data[i] = static_cast<const GLushort*>(indices)[i];
3224 }
3225 data[count] = static_cast<const GLushort*>(indices)[0];
3226 break;
3227 case GL_UNSIGNED_INT:
3228 for (int i = 0; i < count; i++)
3229 {
3230 data[i] = static_cast<const GLuint*>(indices)[i];
3231 }
3232 data[count] = static_cast<const GLuint*>(indices)[0];
3233 break;
3234 default: UNREACHABLE();
3235 }
3236
3237 mLineLoopIB->unmap();
3238 succeeded = true;
3239 }
3240 }
3241 }
3242 else
3243 {
3244 const int spaceNeeded = (count + 1) * sizeof(unsigned short);
3245
3246 if (!mLineLoopIB)
3247 {
daniel@transgaming.com6716a272012-10-31 18:31:39 +00003248 mLineLoopIB = new StreamingIndexBuffer(mRenderer, INITIAL_INDEX_BUFFER_SIZE, D3DFMT_INDEX16);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003249 }
3250
3251 if (mLineLoopIB)
3252 {
3253 mLineLoopIB->reserveSpace(spaceNeeded, GL_UNSIGNED_SHORT);
3254
3255 UINT offset = 0;
3256 unsigned short *data = static_cast<unsigned short*>(mLineLoopIB->map(spaceNeeded, &offset));
3257 startIndex = offset / 2;
3258
3259 if (data)
3260 {
3261 switch (type)
3262 {
3263 case GL_NONE: // Non-indexed draw
3264 for (int i = 0; i < count; i++)
3265 {
3266 data[i] = i;
3267 }
3268 data[count] = 0;
3269 break;
3270 case GL_UNSIGNED_BYTE:
3271 for (int i = 0; i < count; i++)
3272 {
3273 data[i] = static_cast<const GLubyte*>(indices)[i];
3274 }
3275 data[count] = static_cast<const GLubyte*>(indices)[0];
3276 break;
3277 case GL_UNSIGNED_SHORT:
3278 for (int i = 0; i < count; i++)
3279 {
3280 data[i] = static_cast<const GLushort*>(indices)[i];
3281 }
3282 data[count] = static_cast<const GLushort*>(indices)[0];
3283 break;
3284 case GL_UNSIGNED_INT:
3285 for (int i = 0; i < count; i++)
3286 {
3287 data[i] = static_cast<const GLuint*>(indices)[i];
3288 }
3289 data[count] = static_cast<const GLuint*>(indices)[0];
3290 break;
3291 default: UNREACHABLE();
3292 }
3293
3294 mLineLoopIB->unmap();
3295 succeeded = true;
3296 }
3297 }
3298 }
3299
3300 if (succeeded)
3301 {
3302 if (mAppliedIBSerial != mLineLoopIB->getSerial())
3303 {
3304 mDevice->SetIndices(mLineLoopIB->getBuffer());
3305 mAppliedIBSerial = mLineLoopIB->getSerial();
3306 }
3307
3308 mDevice->DrawIndexedPrimitive(D3DPT_LINESTRIP, -minIndex, minIndex, count, startIndex, count);
3309 }
3310 else
3311 {
3312 ERR("Could not create a looping index buffer for GL_LINE_LOOP.");
3313 return error(GL_OUT_OF_MEMORY);
3314 }
3315}
3316
3317void Context::recordInvalidEnum()
3318{
3319 mInvalidEnum = true;
3320}
3321
3322void Context::recordInvalidValue()
3323{
3324 mInvalidValue = true;
3325}
3326
3327void Context::recordInvalidOperation()
3328{
3329 mInvalidOperation = true;
3330}
3331
3332void Context::recordOutOfMemory()
3333{
3334 mOutOfMemory = true;
3335}
3336
3337void Context::recordInvalidFramebufferOperation()
3338{
3339 mInvalidFramebufferOperation = true;
3340}
3341
3342// Get one of the recorded errors and clear its flag, if any.
3343// [OpenGL ES 2.0.24] section 2.5 page 13.
3344GLenum Context::getError()
3345{
3346 if (mInvalidEnum)
3347 {
3348 mInvalidEnum = false;
3349
3350 return GL_INVALID_ENUM;
3351 }
3352
3353 if (mInvalidValue)
3354 {
3355 mInvalidValue = false;
3356
3357 return GL_INVALID_VALUE;
3358 }
3359
3360 if (mInvalidOperation)
3361 {
3362 mInvalidOperation = false;
3363
3364 return GL_INVALID_OPERATION;
3365 }
3366
3367 if (mOutOfMemory)
3368 {
3369 mOutOfMemory = false;
3370
3371 return GL_OUT_OF_MEMORY;
3372 }
3373
3374 if (mInvalidFramebufferOperation)
3375 {
3376 mInvalidFramebufferOperation = false;
3377
3378 return GL_INVALID_FRAMEBUFFER_OPERATION;
3379 }
3380
3381 return GL_NO_ERROR;
3382}
3383
3384GLenum Context::getResetStatus()
3385{
3386 if (mResetStatus == GL_NO_ERROR)
3387 {
daniel@transgaming.comf688c0d2012-10-31 17:52:57 +00003388 // mResetStatus will be set by the markContextLost callback
3389 // in the case a notification is sent
3390 mRenderer->testDeviceLost(true);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003391 }
3392
3393 GLenum status = mResetStatus;
3394
3395 if (mResetStatus != GL_NO_ERROR)
3396 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00003397 if (mRenderer->testDeviceResettable())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003398 {
3399 mResetStatus = GL_NO_ERROR;
3400 }
3401 }
3402
3403 return status;
3404}
3405
3406bool Context::isResetNotificationEnabled()
3407{
3408 return (mResetStrategy == GL_LOSE_CONTEXT_ON_RESET_EXT);
3409}
3410
3411bool Context::supportsShaderModel3() const
3412{
3413 return mSupportsShaderModel3;
3414}
3415
3416float Context::getMaximumPointSize() const
3417{
3418 return mSupportsShaderModel3 ? mMaximumPointSize : ALIASED_POINT_SIZE_RANGE_MAX_SM2;
3419}
3420
3421int Context::getMaximumVaryingVectors() const
3422{
3423 return mSupportsShaderModel3 ? MAX_VARYING_VECTORS_SM3 : MAX_VARYING_VECTORS_SM2;
3424}
3425
3426unsigned int Context::getMaximumVertexTextureImageUnits() const
3427{
3428 return mSupportsVertexTexture ? MAX_VERTEX_TEXTURE_IMAGE_UNITS_VTF : 0;
3429}
3430
3431unsigned int Context::getMaximumCombinedTextureImageUnits() const
3432{
3433 return MAX_TEXTURE_IMAGE_UNITS + getMaximumVertexTextureImageUnits();
3434}
3435
3436int Context::getMaximumFragmentUniformVectors() const
3437{
3438 return mSupportsShaderModel3 ? MAX_FRAGMENT_UNIFORM_VECTORS_SM3 : MAX_FRAGMENT_UNIFORM_VECTORS_SM2;
3439}
3440
3441int Context::getMaxSupportedSamples() const
3442{
daniel@transgaming.comb7833982012-10-31 18:31:46 +00003443 return mRenderer->getMaxSupportedSamples();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003444}
3445
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003446bool Context::supportsEventQueries() const
3447{
3448 return mSupportsEventQueries;
3449}
3450
3451bool Context::supportsOcclusionQueries() const
3452{
3453 return mSupportsOcclusionQueries;
3454}
3455
3456bool Context::supportsDXT1Textures() const
3457{
3458 return mSupportsDXT1Textures;
3459}
3460
3461bool Context::supportsDXT3Textures() const
3462{
3463 return mSupportsDXT3Textures;
3464}
3465
3466bool Context::supportsDXT5Textures() const
3467{
3468 return mSupportsDXT5Textures;
3469}
3470
3471bool Context::supportsFloat32Textures() const
3472{
3473 return mSupportsFloat32Textures;
3474}
3475
3476bool Context::supportsFloat32LinearFilter() const
3477{
3478 return mSupportsFloat32LinearFilter;
3479}
3480
3481bool Context::supportsFloat32RenderableTextures() const
3482{
3483 return mSupportsFloat32RenderableTextures;
3484}
3485
3486bool Context::supportsFloat16Textures() const
3487{
3488 return mSupportsFloat16Textures;
3489}
3490
3491bool Context::supportsFloat16LinearFilter() const
3492{
3493 return mSupportsFloat16LinearFilter;
3494}
3495
3496bool Context::supportsFloat16RenderableTextures() const
3497{
3498 return mSupportsFloat16RenderableTextures;
3499}
3500
3501int Context::getMaximumRenderbufferDimension() const
3502{
3503 return mMaxRenderbufferDimension;
3504}
3505
3506int Context::getMaximumTextureDimension() const
3507{
3508 return mMaxTextureDimension;
3509}
3510
3511int Context::getMaximumCubeTextureDimension() const
3512{
3513 return mMaxCubeTextureDimension;
3514}
3515
3516int Context::getMaximumTextureLevel() const
3517{
3518 return mMaxTextureLevel;
3519}
3520
3521bool Context::supportsLuminanceTextures() const
3522{
3523 return mSupportsLuminanceTextures;
3524}
3525
3526bool Context::supportsLuminanceAlphaTextures() const
3527{
3528 return mSupportsLuminanceAlphaTextures;
3529}
3530
3531bool Context::supportsDepthTextures() const
3532{
3533 return mSupportsDepthTextures;
3534}
3535
3536bool Context::supports32bitIndices() const
3537{
3538 return mSupports32bitIndices;
3539}
3540
3541bool Context::supportsNonPower2Texture() const
3542{
3543 return mSupportsNonPower2Texture;
3544}
3545
3546bool Context::supportsInstancing() const
3547{
3548 return mSupportsInstancing;
3549}
3550
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003551bool Context::supportsTextureFilterAnisotropy() const
3552{
3553 return mSupportsTextureFilterAnisotropy;
3554}
3555
3556float Context::getTextureMaxAnisotropy() const
3557{
3558 return mMaxTextureAnisotropy;
3559}
3560
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003561bool Context::getCurrentReadFormatType(GLenum *format, GLenum *type)
3562{
3563 Framebuffer *framebuffer = getReadFramebuffer();
3564 if (!framebuffer || framebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3565 {
3566 return error(GL_INVALID_OPERATION, false);
3567 }
3568
3569 Renderbuffer *renderbuffer = framebuffer->getColorbuffer();
3570 if (!renderbuffer)
3571 {
3572 return error(GL_INVALID_OPERATION, false);
3573 }
3574
daniel@transgaming.com20d36662012-10-31 19:51:43 +00003575 *format = gl::ExtractFormat(renderbuffer->getActualFormat());
3576 *type = gl::ExtractType(renderbuffer->getActualFormat());
daniel@transgaming.com42944b02012-09-27 17:45:57 +00003577
3578 return true;
3579}
3580
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003581void Context::detachBuffer(GLuint buffer)
3582{
3583 // [OpenGL ES 2.0.24] section 2.9 page 22:
3584 // If a buffer object is deleted while it is bound, all bindings to that object in the current context
3585 // (i.e. in the thread that called Delete-Buffers) are reset to zero.
3586
3587 if (mState.arrayBuffer.id() == buffer)
3588 {
3589 mState.arrayBuffer.set(NULL);
3590 }
3591
3592 if (mState.elementArrayBuffer.id() == buffer)
3593 {
3594 mState.elementArrayBuffer.set(NULL);
3595 }
3596
3597 for (int attribute = 0; attribute < MAX_VERTEX_ATTRIBS; attribute++)
3598 {
3599 if (mState.vertexAttribute[attribute].mBoundBuffer.id() == buffer)
3600 {
3601 mState.vertexAttribute[attribute].mBoundBuffer.set(NULL);
3602 }
3603 }
3604}
3605
3606void Context::detachTexture(GLuint texture)
3607{
3608 // [OpenGL ES 2.0.24] section 3.8 page 84:
3609 // If a texture object is deleted, it is as if all texture units which are bound to that texture object are
3610 // rebound to texture object zero
3611
3612 for (int type = 0; type < TEXTURE_TYPE_COUNT; type++)
3613 {
3614 for (int sampler = 0; sampler < MAX_COMBINED_TEXTURE_IMAGE_UNITS_VTF; sampler++)
3615 {
3616 if (mState.samplerTexture[type][sampler].id() == texture)
3617 {
3618 mState.samplerTexture[type][sampler].set(NULL);
3619 }
3620 }
3621 }
3622
3623 // [OpenGL ES 2.0.24] section 4.4 page 112:
3624 // If a texture object is deleted while its image is attached to the currently bound framebuffer, then it is
3625 // as if FramebufferTexture2D had been called, with a texture of 0, for each attachment point to which this
3626 // image was attached in the currently bound framebuffer.
3627
3628 Framebuffer *readFramebuffer = getReadFramebuffer();
3629 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3630
3631 if (readFramebuffer)
3632 {
3633 readFramebuffer->detachTexture(texture);
3634 }
3635
3636 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3637 {
3638 drawFramebuffer->detachTexture(texture);
3639 }
3640}
3641
3642void Context::detachFramebuffer(GLuint framebuffer)
3643{
3644 // [OpenGL ES 2.0.24] section 4.4 page 107:
3645 // If a framebuffer that is currently bound to the target FRAMEBUFFER is deleted, it is as though
3646 // BindFramebuffer had been executed with the target of FRAMEBUFFER and framebuffer of zero.
3647
3648 if (mState.readFramebuffer == framebuffer)
3649 {
3650 bindReadFramebuffer(0);
3651 }
3652
3653 if (mState.drawFramebuffer == framebuffer)
3654 {
3655 bindDrawFramebuffer(0);
3656 }
3657}
3658
3659void Context::detachRenderbuffer(GLuint renderbuffer)
3660{
3661 // [OpenGL ES 2.0.24] section 4.4 page 109:
3662 // If a renderbuffer that is currently bound to RENDERBUFFER is deleted, it is as though BindRenderbuffer
3663 // had been executed with the target RENDERBUFFER and name of zero.
3664
3665 if (mState.renderbuffer.id() == renderbuffer)
3666 {
3667 bindRenderbuffer(0);
3668 }
3669
3670 // [OpenGL ES 2.0.24] section 4.4 page 111:
3671 // If a renderbuffer object is deleted while its image is attached to the currently bound framebuffer,
3672 // then it is as if FramebufferRenderbuffer had been called, with a renderbuffer of 0, for each attachment
3673 // point to which this image was attached in the currently bound framebuffer.
3674
3675 Framebuffer *readFramebuffer = getReadFramebuffer();
3676 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3677
3678 if (readFramebuffer)
3679 {
3680 readFramebuffer->detachRenderbuffer(renderbuffer);
3681 }
3682
3683 if (drawFramebuffer && drawFramebuffer != readFramebuffer)
3684 {
3685 drawFramebuffer->detachRenderbuffer(renderbuffer);
3686 }
3687}
3688
3689Texture *Context::getIncompleteTexture(TextureType type)
3690{
3691 Texture *t = mIncompleteTextures[type].get();
3692
3693 if (t == NULL)
3694 {
3695 static const GLubyte color[] = { 0, 0, 0, 255 };
3696
3697 switch (type)
3698 {
3699 default:
3700 UNREACHABLE();
3701 // default falls through to TEXTURE_2D
3702
3703 case TEXTURE_2D:
3704 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +00003705 Texture2D *incomplete2d = new Texture2D(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003706 incomplete2d->setImage(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3707 t = incomplete2d;
3708 }
3709 break;
3710
3711 case TEXTURE_CUBE:
3712 {
daniel@transgaming.com370482e2012-11-28 19:32:13 +00003713 TextureCubeMap *incompleteCube = new TextureCubeMap(mRenderer, Texture::INCOMPLETE_TEXTURE_ID);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003714
3715 incompleteCube->setImagePosX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3716 incompleteCube->setImageNegX(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3717 incompleteCube->setImagePosY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3718 incompleteCube->setImageNegY(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3719 incompleteCube->setImagePosZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3720 incompleteCube->setImageNegZ(0, 1, 1, GL_RGBA, GL_UNSIGNED_BYTE, 1, color);
3721
3722 t = incompleteCube;
3723 }
3724 break;
3725 }
3726
3727 mIncompleteTextures[type].set(t);
3728 }
3729
3730 return t;
3731}
3732
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003733bool Context::skipDraw(GLenum drawMode)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003734{
daniel@transgaming.com087e5782012-09-17 21:28:47 +00003735 if (drawMode == GL_POINTS)
3736 {
3737 // ProgramBinary assumes non-point rendering if gl_PointSize isn't written,
3738 // which affects varying interpolation. Since the value of gl_PointSize is
3739 // undefined when not written, just skip drawing to avoid unexpected results.
3740 if (!getCurrentProgramBinary()->usesPointSize())
3741 {
3742 // This is stictly speaking not an error, but developers should be
3743 // notified of risking undefined behavior.
3744 ERR("Point rendering without writing to gl_PointSize.");
3745
3746 return true;
3747 }
3748 }
3749 else if (isTriangleMode(drawMode))
3750 {
3751 if (mState.cullFace && mState.cullMode == GL_FRONT_AND_BACK)
3752 {
3753 return true;
3754 }
3755 }
3756
3757 return false;
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003758}
3759
3760bool Context::isTriangleMode(GLenum drawMode)
3761{
3762 switch (drawMode)
3763 {
3764 case GL_TRIANGLES:
3765 case GL_TRIANGLE_FAN:
3766 case GL_TRIANGLE_STRIP:
3767 return true;
3768 case GL_POINTS:
3769 case GL_LINES:
3770 case GL_LINE_LOOP:
3771 case GL_LINE_STRIP:
3772 return false;
3773 default: UNREACHABLE();
3774 }
3775
3776 return false;
3777}
3778
3779void Context::setVertexAttrib(GLuint index, const GLfloat *values)
3780{
3781 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3782
3783 mState.vertexAttribute[index].mCurrentValue[0] = values[0];
3784 mState.vertexAttribute[index].mCurrentValue[1] = values[1];
3785 mState.vertexAttribute[index].mCurrentValue[2] = values[2];
3786 mState.vertexAttribute[index].mCurrentValue[3] = values[3];
3787
3788 mVertexDataManager->dirtyCurrentValue(index);
3789}
3790
3791void Context::setVertexAttribDivisor(GLuint index, GLuint divisor)
3792{
3793 ASSERT(index < gl::MAX_VERTEX_ATTRIBS);
3794
3795 mState.vertexAttribute[index].mDivisor = divisor;
3796}
3797
3798// keep list sorted in following order
3799// OES extensions
3800// EXT extensions
3801// Vendor extensions
3802void Context::initExtensionString()
3803{
3804 mExtensionString = "";
3805
3806 // OES extensions
3807 if (supports32bitIndices())
3808 {
3809 mExtensionString += "GL_OES_element_index_uint ";
3810 }
3811
3812 mExtensionString += "GL_OES_packed_depth_stencil ";
3813 mExtensionString += "GL_OES_get_program_binary ";
3814 mExtensionString += "GL_OES_rgb8_rgba8 ";
3815 mExtensionString += "GL_OES_standard_derivatives ";
3816
3817 if (supportsFloat16Textures())
3818 {
3819 mExtensionString += "GL_OES_texture_half_float ";
3820 }
3821 if (supportsFloat16LinearFilter())
3822 {
3823 mExtensionString += "GL_OES_texture_half_float_linear ";
3824 }
3825 if (supportsFloat32Textures())
3826 {
3827 mExtensionString += "GL_OES_texture_float ";
3828 }
3829 if (supportsFloat32LinearFilter())
3830 {
3831 mExtensionString += "GL_OES_texture_float_linear ";
3832 }
3833
3834 if (supportsNonPower2Texture())
3835 {
3836 mExtensionString += "GL_OES_texture_npot ";
3837 }
3838
3839 // Multi-vendor (EXT) extensions
3840 if (supportsOcclusionQueries())
3841 {
3842 mExtensionString += "GL_EXT_occlusion_query_boolean ";
3843 }
3844
3845 mExtensionString += "GL_EXT_read_format_bgra ";
3846 mExtensionString += "GL_EXT_robustness ";
3847
3848 if (supportsDXT1Textures())
3849 {
3850 mExtensionString += "GL_EXT_texture_compression_dxt1 ";
3851 }
3852
daniel@transgaming.com07ab8412012-07-12 15:17:09 +00003853 if (supportsTextureFilterAnisotropy())
3854 {
3855 mExtensionString += "GL_EXT_texture_filter_anisotropic ";
3856 }
3857
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003858 mExtensionString += "GL_EXT_texture_format_BGRA8888 ";
3859 mExtensionString += "GL_EXT_texture_storage ";
3860
3861 // ANGLE-specific extensions
3862 if (supportsDepthTextures())
3863 {
3864 mExtensionString += "GL_ANGLE_depth_texture ";
3865 }
3866
3867 mExtensionString += "GL_ANGLE_framebuffer_blit ";
3868 if (getMaxSupportedSamples() != 0)
3869 {
3870 mExtensionString += "GL_ANGLE_framebuffer_multisample ";
3871 }
3872
3873 if (supportsInstancing())
3874 {
3875 mExtensionString += "GL_ANGLE_instanced_arrays ";
3876 }
3877
3878 mExtensionString += "GL_ANGLE_pack_reverse_row_order ";
3879
3880 if (supportsDXT3Textures())
3881 {
3882 mExtensionString += "GL_ANGLE_texture_compression_dxt3 ";
3883 }
3884 if (supportsDXT5Textures())
3885 {
3886 mExtensionString += "GL_ANGLE_texture_compression_dxt5 ";
3887 }
3888
3889 mExtensionString += "GL_ANGLE_texture_usage ";
3890 mExtensionString += "GL_ANGLE_translated_shader_source ";
3891
3892 // Other vendor-specific extensions
3893 if (supportsEventQueries())
3894 {
3895 mExtensionString += "GL_NV_fence ";
3896 }
3897
3898 std::string::size_type end = mExtensionString.find_last_not_of(' ');
3899 if (end != std::string::npos)
3900 {
3901 mExtensionString.resize(end+1);
3902 }
3903}
3904
3905const char *Context::getExtensionString() const
3906{
3907 return mExtensionString.c_str();
3908}
3909
3910void Context::initRendererString()
3911{
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003912 mRendererString = "ANGLE (";
daniel@transgaming.com4ca789e2012-10-31 18:46:40 +00003913 mRendererString += mRenderer->getAdapterDescription();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00003914 mRendererString += ")";
3915}
3916
3917const char *Context::getRendererString() const
3918{
3919 return mRendererString.c_str();
3920}
3921
3922void Context::blitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1,
3923 GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1,
3924 GLbitfield mask)
3925{
3926 Framebuffer *readFramebuffer = getReadFramebuffer();
3927 Framebuffer *drawFramebuffer = getDrawFramebuffer();
3928
3929 if (!readFramebuffer || readFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE ||
3930 !drawFramebuffer || drawFramebuffer->completeness() != GL_FRAMEBUFFER_COMPLETE)
3931 {
3932 return error(GL_INVALID_FRAMEBUFFER_OPERATION);
3933 }
3934
3935 if (drawFramebuffer->getSamples() != 0)
3936 {
3937 return error(GL_INVALID_OPERATION);
3938 }
3939
3940 int readBufferWidth = readFramebuffer->getColorbuffer()->getWidth();
3941 int readBufferHeight = readFramebuffer->getColorbuffer()->getHeight();
3942 int drawBufferWidth = drawFramebuffer->getColorbuffer()->getWidth();
3943 int drawBufferHeight = drawFramebuffer->getColorbuffer()->getHeight();
3944
3945 RECT sourceRect;
3946 RECT destRect;
3947
3948 if (srcX0 < srcX1)
3949 {
3950 sourceRect.left = srcX0;
3951 sourceRect.right = srcX1;
3952 destRect.left = dstX0;
3953 destRect.right = dstX1;
3954 }
3955 else
3956 {
3957 sourceRect.left = srcX1;
3958 destRect.left = dstX1;
3959 sourceRect.right = srcX0;
3960 destRect.right = dstX0;
3961 }
3962
3963 if (srcY0 < srcY1)
3964 {
3965 sourceRect.bottom = srcY1;
3966 destRect.bottom = dstY1;
3967 sourceRect.top = srcY0;
3968 destRect.top = dstY0;
3969 }
3970 else
3971 {
3972 sourceRect.bottom = srcY0;
3973 destRect.bottom = dstY0;
3974 sourceRect.top = srcY1;
3975 destRect.top = dstY1;
3976 }
3977
3978 RECT sourceScissoredRect = sourceRect;
3979 RECT destScissoredRect = destRect;
3980
3981 if (mState.scissorTest)
3982 {
3983 // Only write to parts of the destination framebuffer which pass the scissor test
3984 // Please note: the destRect is now in D3D-style coordinates, so the *top* of the
3985 // rect will be checked against scissorY, rather than the bottom.
3986 if (destRect.left < mState.scissorX)
3987 {
3988 int xDiff = mState.scissorX - destRect.left;
3989 destScissoredRect.left = mState.scissorX;
3990 sourceScissoredRect.left += xDiff;
3991 }
3992
3993 if (destRect.right > mState.scissorX + mState.scissorWidth)
3994 {
3995 int xDiff = destRect.right - (mState.scissorX + mState.scissorWidth);
3996 destScissoredRect.right = mState.scissorX + mState.scissorWidth;
3997 sourceScissoredRect.right -= xDiff;
3998 }
3999
4000 if (destRect.top < mState.scissorY)
4001 {
4002 int yDiff = mState.scissorY - destRect.top;
4003 destScissoredRect.top = mState.scissorY;
4004 sourceScissoredRect.top += yDiff;
4005 }
4006
4007 if (destRect.bottom > mState.scissorY + mState.scissorHeight)
4008 {
4009 int yDiff = destRect.bottom - (mState.scissorY + mState.scissorHeight);
4010 destScissoredRect.bottom = mState.scissorY + mState.scissorHeight;
4011 sourceScissoredRect.bottom -= yDiff;
4012 }
4013 }
4014
4015 bool blitRenderTarget = false;
4016 bool blitDepthStencil = false;
4017
4018 RECT sourceTrimmedRect = sourceScissoredRect;
4019 RECT destTrimmedRect = destScissoredRect;
4020
4021 // The source & destination rectangles also may need to be trimmed if they fall out of the bounds of
4022 // the actual draw and read surfaces.
4023 if (sourceTrimmedRect.left < 0)
4024 {
4025 int xDiff = 0 - sourceTrimmedRect.left;
4026 sourceTrimmedRect.left = 0;
4027 destTrimmedRect.left += xDiff;
4028 }
4029
4030 if (sourceTrimmedRect.right > readBufferWidth)
4031 {
4032 int xDiff = sourceTrimmedRect.right - readBufferWidth;
4033 sourceTrimmedRect.right = readBufferWidth;
4034 destTrimmedRect.right -= xDiff;
4035 }
4036
4037 if (sourceTrimmedRect.top < 0)
4038 {
4039 int yDiff = 0 - sourceTrimmedRect.top;
4040 sourceTrimmedRect.top = 0;
4041 destTrimmedRect.top += yDiff;
4042 }
4043
4044 if (sourceTrimmedRect.bottom > readBufferHeight)
4045 {
4046 int yDiff = sourceTrimmedRect.bottom - readBufferHeight;
4047 sourceTrimmedRect.bottom = readBufferHeight;
4048 destTrimmedRect.bottom -= yDiff;
4049 }
4050
4051 if (destTrimmedRect.left < 0)
4052 {
4053 int xDiff = 0 - destTrimmedRect.left;
4054 destTrimmedRect.left = 0;
4055 sourceTrimmedRect.left += xDiff;
4056 }
4057
4058 if (destTrimmedRect.right > drawBufferWidth)
4059 {
4060 int xDiff = destTrimmedRect.right - drawBufferWidth;
4061 destTrimmedRect.right = drawBufferWidth;
4062 sourceTrimmedRect.right -= xDiff;
4063 }
4064
4065 if (destTrimmedRect.top < 0)
4066 {
4067 int yDiff = 0 - destTrimmedRect.top;
4068 destTrimmedRect.top = 0;
4069 sourceTrimmedRect.top += yDiff;
4070 }
4071
4072 if (destTrimmedRect.bottom > drawBufferHeight)
4073 {
4074 int yDiff = destTrimmedRect.bottom - drawBufferHeight;
4075 destTrimmedRect.bottom = drawBufferHeight;
4076 sourceTrimmedRect.bottom -= yDiff;
4077 }
4078
4079 bool partialBufferCopy = false;
4080 if (sourceTrimmedRect.bottom - sourceTrimmedRect.top < readBufferHeight ||
4081 sourceTrimmedRect.right - sourceTrimmedRect.left < readBufferWidth ||
4082 destTrimmedRect.bottom - destTrimmedRect.top < drawBufferHeight ||
4083 destTrimmedRect.right - destTrimmedRect.left < drawBufferWidth ||
4084 sourceTrimmedRect.top != 0 || destTrimmedRect.top != 0 || sourceTrimmedRect.left != 0 || destTrimmedRect.left != 0)
4085 {
4086 partialBufferCopy = true;
4087 }
4088
4089 if (mask & GL_COLOR_BUFFER_BIT)
4090 {
4091 const bool validReadType = readFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4092 readFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4093 const bool validDrawType = drawFramebuffer->getColorbufferType() == GL_TEXTURE_2D ||
4094 drawFramebuffer->getColorbufferType() == GL_RENDERBUFFER;
4095 if (!validReadType || !validDrawType ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004096 readFramebuffer->getColorbuffer()->getActualFormat() != drawFramebuffer->getColorbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004097 {
4098 ERR("Color buffer format conversion in BlitFramebufferANGLE not supported by this implementation");
4099 return error(GL_INVALID_OPERATION);
4100 }
4101
4102 if (partialBufferCopy && readFramebuffer->getSamples() != 0)
4103 {
4104 return error(GL_INVALID_OPERATION);
4105 }
4106
4107 blitRenderTarget = true;
4108
4109 }
4110
4111 if (mask & (GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT))
4112 {
4113 Renderbuffer *readDSBuffer = NULL;
4114 Renderbuffer *drawDSBuffer = NULL;
4115
4116 // We support OES_packed_depth_stencil, and do not support a separately attached depth and stencil buffer, so if we have
4117 // both a depth and stencil buffer, it will be the same buffer.
4118
4119 if (mask & GL_DEPTH_BUFFER_BIT)
4120 {
4121 if (readFramebuffer->getDepthbuffer() && drawFramebuffer->getDepthbuffer())
4122 {
4123 if (readFramebuffer->getDepthbufferType() != drawFramebuffer->getDepthbufferType() ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004124 readFramebuffer->getDepthbuffer()->getActualFormat() != drawFramebuffer->getDepthbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004125 {
4126 return error(GL_INVALID_OPERATION);
4127 }
4128
4129 blitDepthStencil = true;
4130 readDSBuffer = readFramebuffer->getDepthbuffer();
4131 drawDSBuffer = drawFramebuffer->getDepthbuffer();
4132 }
4133 }
4134
4135 if (mask & GL_STENCIL_BUFFER_BIT)
4136 {
4137 if (readFramebuffer->getStencilbuffer() && drawFramebuffer->getStencilbuffer())
4138 {
4139 if (readFramebuffer->getStencilbufferType() != drawFramebuffer->getStencilbufferType() ||
daniel@transgaming.com20d36662012-10-31 19:51:43 +00004140 readFramebuffer->getStencilbuffer()->getActualFormat() != drawFramebuffer->getStencilbuffer()->getActualFormat())
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004141 {
4142 return error(GL_INVALID_OPERATION);
4143 }
4144
4145 blitDepthStencil = true;
4146 readDSBuffer = readFramebuffer->getStencilbuffer();
4147 drawDSBuffer = drawFramebuffer->getStencilbuffer();
4148 }
4149 }
4150
4151 if (partialBufferCopy)
4152 {
4153 ERR("Only whole-buffer depth and stencil blits are supported by this implementation.");
4154 return error(GL_INVALID_OPERATION); // only whole-buffer copies are permitted
4155 }
4156
4157 if ((drawDSBuffer && drawDSBuffer->getSamples() != 0) ||
4158 (readDSBuffer && readDSBuffer->getSamples() != 0))
4159 {
4160 return error(GL_INVALID_OPERATION);
4161 }
4162 }
4163
4164 if (blitRenderTarget || blitDepthStencil)
4165 {
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004166 mRenderer->endScene();
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004167
4168 if (blitRenderTarget)
4169 {
4170 IDirect3DSurface9* readRenderTarget = readFramebuffer->getRenderTarget();
4171 IDirect3DSurface9* drawRenderTarget = drawFramebuffer->getRenderTarget();
4172
4173 HRESULT result = mDevice->StretchRect(readRenderTarget, &sourceTrimmedRect,
4174 drawRenderTarget, &destTrimmedRect, D3DTEXF_NONE);
4175
4176 readRenderTarget->Release();
4177 drawRenderTarget->Release();
4178
4179 if (FAILED(result))
4180 {
4181 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4182 return;
4183 }
4184 }
4185
4186 if (blitDepthStencil)
4187 {
4188 IDirect3DSurface9* readDepthStencil = readFramebuffer->getDepthStencil();
4189 IDirect3DSurface9* drawDepthStencil = drawFramebuffer->getDepthStencil();
4190
4191 HRESULT result = mDevice->StretchRect(readDepthStencil, NULL, drawDepthStencil, NULL, D3DTEXF_NONE);
4192
4193 readDepthStencil->Release();
4194 drawDepthStencil->Release();
4195
4196 if (FAILED(result))
4197 {
4198 ERR("BlitFramebufferANGLE failed: StretchRect returned %x.", result);
4199 return;
4200 }
4201 }
4202 }
4203}
4204
4205VertexDeclarationCache::VertexDeclarationCache() : mMaxLru(0)
4206{
4207 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4208 {
4209 mVertexDeclCache[i].vertexDeclaration = NULL;
4210 mVertexDeclCache[i].lruCount = 0;
4211 }
4212}
4213
4214VertexDeclarationCache::~VertexDeclarationCache()
4215{
4216 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4217 {
4218 if (mVertexDeclCache[i].vertexDeclaration)
4219 {
4220 mVertexDeclCache[i].vertexDeclaration->Release();
4221 }
4222 }
4223}
4224
daniel@transgaming.com5ae3ccc2012-07-24 18:29:38 +00004225GLenum VertexDeclarationCache::applyDeclaration(IDirect3DDevice9 *device, TranslatedAttribute attributes[], ProgramBinary *programBinary, GLsizei instances, GLsizei *repeatDraw)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004226{
4227 *repeatDraw = 1;
4228
4229 int indexedAttribute = MAX_VERTEX_ATTRIBS;
4230 int instancedAttribute = MAX_VERTEX_ATTRIBS;
4231
4232 if (instances > 0)
4233 {
4234 // Find an indexed attribute to be mapped to D3D stream 0
4235 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4236 {
4237 if (attributes[i].active)
4238 {
4239 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4240 {
4241 if (attributes[i].divisor == 0)
4242 {
4243 indexedAttribute = i;
4244 }
4245 }
4246 else if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4247 {
4248 if (attributes[i].divisor != 0)
4249 {
4250 instancedAttribute = i;
4251 }
4252 }
4253 else break; // Found both an indexed and instanced attribute
4254 }
4255 }
4256
4257 if (indexedAttribute == MAX_VERTEX_ATTRIBS)
4258 {
4259 return GL_INVALID_OPERATION;
4260 }
4261 }
4262
4263 D3DVERTEXELEMENT9 elements[MAX_VERTEX_ATTRIBS + 1];
4264 D3DVERTEXELEMENT9 *element = &elements[0];
4265
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004266 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4267 {
4268 if (attributes[i].active)
4269 {
4270 int stream = i;
4271
4272 if (instances > 0)
4273 {
4274 // Due to a bug on ATI cards we can't enable instancing when none of the attributes are instanced.
4275 if (instancedAttribute == MAX_VERTEX_ATTRIBS)
4276 {
4277 *repeatDraw = instances;
4278 }
4279 else
4280 {
4281 if (i == indexedAttribute)
4282 {
4283 stream = 0;
4284 }
4285 else if (i == 0)
4286 {
4287 stream = indexedAttribute;
4288 }
4289
4290 UINT frequency = 1;
4291
4292 if (attributes[i].divisor == 0)
4293 {
4294 frequency = D3DSTREAMSOURCE_INDEXEDDATA | instances;
4295 }
4296 else
4297 {
4298 frequency = D3DSTREAMSOURCE_INSTANCEDATA | attributes[i].divisor;
4299 }
4300
4301 device->SetStreamSourceFreq(stream, frequency);
4302 mInstancingEnabled = true;
4303 }
4304 }
4305
4306 if (mAppliedVBs[stream].serial != attributes[i].serial ||
4307 mAppliedVBs[stream].stride != attributes[i].stride ||
4308 mAppliedVBs[stream].offset != attributes[i].offset)
4309 {
4310 device->SetStreamSource(stream, attributes[i].vertexBuffer, attributes[i].offset, attributes[i].stride);
4311 mAppliedVBs[stream].serial = attributes[i].serial;
4312 mAppliedVBs[stream].stride = attributes[i].stride;
4313 mAppliedVBs[stream].offset = attributes[i].offset;
4314 }
4315
4316 element->Stream = stream;
4317 element->Offset = 0;
4318 element->Type = attributes[i].type;
4319 element->Method = D3DDECLMETHOD_DEFAULT;
4320 element->Usage = D3DDECLUSAGE_TEXCOORD;
4321 element->UsageIndex = programBinary->getSemanticIndex(i);
4322 element++;
4323 }
4324 }
4325
4326 if (instances == 0 || instancedAttribute == MAX_VERTEX_ATTRIBS)
4327 {
4328 if (mInstancingEnabled)
4329 {
4330 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4331 {
4332 device->SetStreamSourceFreq(i, 1);
4333 }
4334
4335 mInstancingEnabled = false;
4336 }
4337 }
4338
4339 static const D3DVERTEXELEMENT9 end = D3DDECL_END();
4340 *(element++) = end;
4341
4342 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4343 {
4344 VertexDeclCacheEntry *entry = &mVertexDeclCache[i];
4345 if (memcmp(entry->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9)) == 0 && entry->vertexDeclaration)
4346 {
4347 entry->lruCount = ++mMaxLru;
4348 if(entry->vertexDeclaration != mLastSetVDecl)
4349 {
4350 device->SetVertexDeclaration(entry->vertexDeclaration);
4351 mLastSetVDecl = entry->vertexDeclaration;
4352 }
4353
4354 return GL_NO_ERROR;
4355 }
4356 }
4357
4358 VertexDeclCacheEntry *lastCache = mVertexDeclCache;
4359
4360 for (int i = 0; i < NUM_VERTEX_DECL_CACHE_ENTRIES; i++)
4361 {
4362 if (mVertexDeclCache[i].lruCount < lastCache->lruCount)
4363 {
4364 lastCache = &mVertexDeclCache[i];
4365 }
4366 }
4367
4368 if (lastCache->vertexDeclaration != NULL)
4369 {
4370 lastCache->vertexDeclaration->Release();
4371 lastCache->vertexDeclaration = NULL;
4372 // mLastSetVDecl is set to the replacement, so we don't have to worry
4373 // about it.
4374 }
4375
4376 memcpy(lastCache->cachedElements, elements, (element - elements) * sizeof(D3DVERTEXELEMENT9));
4377 device->CreateVertexDeclaration(elements, &lastCache->vertexDeclaration);
4378 device->SetVertexDeclaration(lastCache->vertexDeclaration);
4379 mLastSetVDecl = lastCache->vertexDeclaration;
4380 lastCache->lruCount = ++mMaxLru;
4381
4382 return GL_NO_ERROR;
4383}
4384
4385void VertexDeclarationCache::markStateDirty()
4386{
4387 for (int i = 0; i < MAX_VERTEX_ATTRIBS; i++)
4388 {
4389 mAppliedVBs[i].serial = 0;
4390 }
4391
4392 mLastSetVDecl = NULL;
4393 mInstancingEnabled = true; // Forces it to be disabled when not used
4394}
4395
4396}
4397
4398extern "C"
4399{
daniel@transgaming.com03d39092012-11-28 19:31:59 +00004400gl::Context *glCreateContext(const gl::Context *shareContext, rx::Renderer *renderer, bool notifyResets, bool robustAccess)
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004401{
daniel@transgaming.com03d39092012-11-28 19:31:59 +00004402 return new gl::Context(shareContext, renderer, notifyResets, robustAccess);
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004403}
4404
4405void glDestroyContext(gl::Context *context)
4406{
4407 delete context;
4408
4409 if (context == gl::getContext())
4410 {
4411 gl::makeCurrent(NULL, NULL, NULL);
4412 }
4413}
4414
4415void glMakeCurrent(gl::Context *context, egl::Display *display, egl::Surface *surface)
4416{
4417 gl::makeCurrent(context, display, surface);
4418}
4419
4420gl::Context *glGetCurrentContext()
4421{
4422 return gl::getContext();
4423}
daniel@transgaming.com621ce052012-10-31 17:52:29 +00004424
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004425rx::SwapChain *glCreateSwapChain(rx::Renderer9 *renderer, HWND window, HANDLE shareHandle,
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004426 GLenum backBufferFormat, GLenum depthBufferFormat)
4427{
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004428 return new rx::SwapChain(renderer, window, shareHandle, backBufferFormat, depthBufferFormat);
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004429}
4430
daniel@transgaming.com76d3e6e2012-10-31 19:55:33 +00004431void glDestroySwapChain(rx::SwapChain *swapChain)
daniel@transgaming.com3c720782012-10-31 18:42:34 +00004432{
4433 delete swapChain;
4434}
4435
4436
apatrick@chromium.org144f2802012-07-12 01:42:34 +00004437}