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