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