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