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