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