gfxGLDevice.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "gfx/gl/gfxGLDevice.h"
  24. #include "platform/platformGL.h"
  25. #include "gfx/gfxCubemap.h"
  26. #include "gfx/screenshot.h"
  27. #include "gfx/gfxDrawUtil.h"
  28. #include "gfx/gl/gfxGLEnumTranslate.h"
  29. #include "gfx/gl/gfxGLVertexBuffer.h"
  30. #include "gfx/gl/gfxGLPrimitiveBuffer.h"
  31. #include "gfx/gl/gfxGLTextureTarget.h"
  32. #include "gfx/gl/gfxGLTextureManager.h"
  33. #include "gfx/gl/gfxGLTextureObject.h"
  34. #include "gfx/gl/gfxGLCubemap.h"
  35. #include "gfx/gl/gfxGLCardProfiler.h"
  36. #include "gfx/gl/gfxGLWindowTarget.h"
  37. #include "platform/platformDlibrary.h"
  38. #include "gfx/gl/gfxGLShader.h"
  39. #include "gfx/primBuilder.h"
  40. #include "console/console.h"
  41. #include "gfx/gl/gfxGLOcclusionQuery.h"
  42. #include "materials/shaderData.h"
  43. #include "gfx/gl/gfxGLStateCache.h"
  44. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  45. #include "gfx/gl/gfxGLVertexDecl.h"
  46. GFXAdapter::CreateDeviceInstanceDelegate GFXGLDevice::mCreateDeviceInstance(GFXGLDevice::createInstance);
  47. GFXDevice *GFXGLDevice::createInstance( U32 adapterIndex )
  48. {
  49. return new GFXGLDevice(adapterIndex);
  50. }
  51. namespace GL
  52. {
  53. extern void gglPerformBinds();
  54. extern void gglPerformExtensionBinds(void *context);
  55. }
  56. void loadGLCore()
  57. {
  58. static bool coreLoaded = false; // Guess what this is for.
  59. if(coreLoaded)
  60. return;
  61. coreLoaded = true;
  62. // Make sure we've got our GL bindings.
  63. GL::gglPerformBinds();
  64. }
  65. void loadGLExtensions(void *context)
  66. {
  67. static bool extensionsLoaded = false;
  68. if(extensionsLoaded)
  69. return;
  70. extensionsLoaded = true;
  71. GL::gglPerformExtensionBinds(context);
  72. }
  73. void STDCALL glDebugCallback(GLenum source, GLenum type, GLuint id,
  74. GLenum severity, GLsizei length, const GLchar* message, void* userParam)
  75. {
  76. #if defined(TORQUE_DEBUG) && !defined(TORQUE_DEBUG_GFX)
  77. if( type == GL_DEBUG_TYPE_OTHER_ARB )
  78. return;
  79. #endif
  80. Con::errorf("OPENGL: %s", message);
  81. }
  82. void STDCALL glAmdDebugCallback(GLuint id, GLenum category, GLenum severity, GLsizei length,
  83. const GLchar* message,GLvoid* userParam)
  84. {
  85. Con::errorf("OPENGL: %s",message);
  86. }
  87. void GFXGLDevice::initGLState()
  88. {
  89. // We don't currently need to sync device state with a known good place because we are
  90. // going to set everything in GFXGLStateBlock, but if we change our GFXGLStateBlock strategy, this may
  91. // need to happen.
  92. // Deal with the card profiler here when we know we have a valid context.
  93. mCardProfiler = new GFXGLCardProfiler();
  94. mCardProfiler->init();
  95. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint*)&mMaxShaderTextures);
  96. glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&mMaxFFTextures);
  97. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, (GLint*)&mMaxTRColors);
  98. mMaxTRColors = getMin( mMaxTRColors, (U32)(GFXTextureTarget::MaxRenderSlotId-1) );
  99. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  100. // Setting mPixelShaderVersion to 3.0 will allow Advanced Lighting to run.
  101. mPixelShaderVersion = 3.0;
  102. mSupportsAnisotropic = mCardProfiler->queryProfile( "GL::suppAnisotropic" );
  103. String vendorStr = (const char*)glGetString( GL_VENDOR );
  104. if( vendorStr.find("NVIDIA") != String::NPos)
  105. mUseGlMap = false;
  106. #if TORQUE_DEBUG
  107. if( gglHasExtension(ARB_debug_output) )
  108. {
  109. glEnable(GL_DEBUG_OUTPUT);
  110. glDebugMessageCallbackARB(glDebugCallback, NULL);
  111. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  112. GLuint unusedIds = 0;
  113. glDebugMessageControlARB(GL_DONT_CARE,
  114. GL_DONT_CARE,
  115. GL_DONT_CARE,
  116. 0,
  117. &unusedIds,
  118. GL_TRUE);
  119. }
  120. else if(gglHasExtension(AMD_debug_output))
  121. {
  122. glEnable(GL_DEBUG_OUTPUT);
  123. glDebugMessageCallbackAMD(glAmdDebugCallback, NULL);
  124. //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  125. GLuint unusedIds = 0;
  126. glDebugMessageEnableAMD(GL_DONT_CARE, GL_DONT_CARE, 0,&unusedIds, GL_TRUE);
  127. }
  128. #endif
  129. PlatformGL::setVSync(0);
  130. //OpenGL 3 need a binded VAO for render
  131. GLuint vao;
  132. glGenVertexArrays(1, &vao);
  133. glBindVertexArray(vao);
  134. }
  135. GFXGLDevice::GFXGLDevice(U32 adapterIndex) :
  136. mAdapterIndex(adapterIndex),
  137. mCurrentPB(NULL),
  138. mDrawInstancesCount(0),
  139. m_mCurrentWorld(true),
  140. m_mCurrentView(true),
  141. mContext(NULL),
  142. mPixelFormat(NULL),
  143. mPixelShaderVersion(0.0f),
  144. mMaxShaderTextures(2),
  145. mMaxFFTextures(2),
  146. mMaxTRColors(1),
  147. mClip(0, 0, 0, 0),
  148. mCurrentShader( NULL ),
  149. mNeedUpdateVertexAttrib(false),
  150. mWindowRT(NULL),
  151. mUseGlMap(true)
  152. {
  153. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  154. {
  155. mCurrentVB[i] = NULL;
  156. mCurrentVB_Divisor[i] = 0;
  157. }
  158. loadGLCore();
  159. GFXGLEnumTranslate::init();
  160. GFXVertexColor::setSwizzle( &Swizzles::rgba );
  161. // OpenGL have native RGB, no need swizzle
  162. mDeviceSwizzle32 = &Swizzles::rgba;
  163. mDeviceSwizzle24 = &Swizzles::rgb;
  164. mTextureManager = new GFXGLTextureManager();
  165. gScreenShot = new ScreenShot();
  166. for(U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  167. mActiveTextureType[i] = GL_ZERO;
  168. mNumVertexStream = 2;
  169. for(int i = 0; i < GS_COUNT; ++i)
  170. mModelViewProjSC[i] = NULL;
  171. mOpenglStateCache = new GFXGLStateCache;
  172. }
  173. GFXGLDevice::~GFXGLDevice()
  174. {
  175. mCurrentStateBlock = NULL;
  176. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  177. mCurrentVB[i] = NULL;
  178. mCurrentPB = NULL;
  179. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  180. mVolatileVBs[i] = NULL;
  181. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  182. mVolatilePBs[i] = NULL;
  183. // Clear out our current texture references
  184. for (U32 i = 0; i < TEXTURE_STAGE_COUNT; i++)
  185. {
  186. mCurrentTexture[i] = NULL;
  187. mNewTexture[i] = NULL;
  188. mCurrentCubemap[i] = NULL;
  189. mNewCubemap[i] = NULL;
  190. }
  191. mRTStack.clear();
  192. mCurrentRT = NULL;
  193. if( mTextureManager )
  194. {
  195. mTextureManager->zombify();
  196. mTextureManager->kill();
  197. }
  198. GFXResource* walk = mResourceListHead;
  199. while(walk)
  200. {
  201. walk->zombify();
  202. walk = walk->getNextResource();
  203. }
  204. if( mCardProfiler )
  205. SAFE_DELETE( mCardProfiler );
  206. SAFE_DELETE( gScreenShot );
  207. SAFE_DELETE( mOpenglStateCache );
  208. }
  209. void GFXGLDevice::zombify()
  210. {
  211. mTextureManager->zombify();
  212. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  213. if(mCurrentVB[i])
  214. mCurrentVB[i]->finish();
  215. if(mCurrentPB)
  216. mCurrentPB->finish();
  217. //mVolatileVBs.clear();
  218. //mVolatilePBs.clear();
  219. GFXResource* walk = mResourceListHead;
  220. while(walk)
  221. {
  222. walk->zombify();
  223. walk = walk->getNextResource();
  224. }
  225. }
  226. void GFXGLDevice::resurrect()
  227. {
  228. GFXResource* walk = mResourceListHead;
  229. while(walk)
  230. {
  231. walk->resurrect();
  232. walk = walk->getNextResource();
  233. }
  234. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  235. if(mCurrentVB[i])
  236. mCurrentVB[i]->prepare();
  237. if(mCurrentPB)
  238. mCurrentPB->prepare();
  239. mTextureManager->resurrect();
  240. }
  241. GFXVertexBuffer* GFXGLDevice::findVolatileVBO(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize)
  242. {
  243. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  244. if ( mVolatileVBs[i]->mNumVerts >= numVerts &&
  245. mVolatileVBs[i]->mVertexFormat.isEqual( *vertexFormat ) &&
  246. mVolatileVBs[i]->mVertexSize == vertSize &&
  247. mVolatileVBs[i]->getRefCount() == 1 )
  248. return mVolatileVBs[i];
  249. // No existing VB, so create one
  250. StrongRefPtr<GFXGLVertexBuffer> buf(new GFXGLVertexBuffer(GFX, numVerts, vertexFormat, vertSize, GFXBufferTypeVolatile));
  251. buf->registerResourceWithDevice(this);
  252. mVolatileVBs.push_back(buf);
  253. return buf.getPointer();
  254. }
  255. GFXPrimitiveBuffer* GFXGLDevice::findVolatilePBO(U32 numIndices, U32 numPrimitives)
  256. {
  257. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  258. if((mVolatilePBs[i]->mIndexCount >= numIndices) && (mVolatilePBs[i]->getRefCount() == 1))
  259. return mVolatilePBs[i];
  260. // No existing PB, so create one
  261. StrongRefPtr<GFXGLPrimitiveBuffer> buf(new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, GFXBufferTypeVolatile));
  262. buf->registerResourceWithDevice(this);
  263. mVolatilePBs.push_back(buf);
  264. return buf.getPointer();
  265. }
  266. GFXVertexBuffer *GFXGLDevice::allocVertexBuffer( U32 numVerts,
  267. const GFXVertexFormat *vertexFormat,
  268. U32 vertSize,
  269. GFXBufferType bufferType )
  270. {
  271. if(bufferType == GFXBufferTypeVolatile)
  272. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  273. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  274. buf->registerResourceWithDevice(this);
  275. return buf;
  276. }
  277. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType )
  278. {
  279. if(bufferType == GFXBufferTypeVolatile)
  280. return findVolatilePBO(numIndices, numPrimitives);
  281. GFXGLPrimitiveBuffer* buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  282. buf->registerResourceWithDevice(this);
  283. return buf;
  284. }
  285. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  286. {
  287. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  288. //if(mCurrentVB[stream] != buffer)
  289. {
  290. // Reset the state the old VB required, then set the state the new VB requires.
  291. if( mCurrentVB[stream] )
  292. {
  293. mCurrentVB[stream]->finish();
  294. }
  295. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  296. mNeedUpdateVertexAttrib = true;
  297. }
  298. }
  299. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  300. {
  301. if( stream == 0 )
  302. {
  303. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  304. mDrawInstancesCount = frequency; // instances count
  305. }
  306. else
  307. {
  308. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  309. if( stream == 1 && frequency == 1 )
  310. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  311. else
  312. mCurrentVB_Divisor[stream] = 0;
  313. }
  314. mNeedUpdateVertexAttrib = true;
  315. }
  316. GFXCubemap* GFXGLDevice::createCubemap()
  317. {
  318. GFXGLCubemap* cube = new GFXGLCubemap();
  319. cube->registerResourceWithDevice(this);
  320. return cube;
  321. };
  322. void GFXGLDevice::endSceneInternal()
  323. {
  324. // nothing to do for opengl
  325. mCanCurrentlyRender = false;
  326. }
  327. void GFXGLDevice::clear(U32 flags, ColorI color, F32 z, U32 stencil)
  328. {
  329. // Make sure we have flushed our render target state.
  330. _updateRenderTargets();
  331. bool writeAllColors = true;
  332. bool zwrite = true;
  333. bool writeAllStencil = true;
  334. const GFXStateBlockDesc *desc = NULL;
  335. if (mCurrentGLStateBlock)
  336. {
  337. desc = &mCurrentGLStateBlock->getDesc();
  338. zwrite = desc->zWriteEnable;
  339. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  340. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  341. }
  342. glColorMask(true, true, true, true);
  343. glDepthMask(true);
  344. glStencilMask(0xFFFFFFFF);
  345. ColorF c = color;
  346. glClearColor(c.red, c.green, c.blue, c.alpha);
  347. glClearDepth(z);
  348. glClearStencil(stencil);
  349. GLbitfield clearflags = 0;
  350. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  351. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  352. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  353. glClear(clearflags);
  354. if(!writeAllColors)
  355. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  356. if(!zwrite)
  357. glDepthMask(false);
  358. if(!writeAllStencil)
  359. glStencilMask(desc->stencilWriteMask);
  360. }
  361. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  362. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  363. {
  364. switch (primType)
  365. {
  366. case GFXPointList :
  367. return primitiveCount;
  368. break;
  369. case GFXLineList :
  370. return primitiveCount * 2;
  371. break;
  372. case GFXLineStrip :
  373. return primitiveCount + 1;
  374. break;
  375. case GFXTriangleList :
  376. return primitiveCount * 3;
  377. break;
  378. case GFXTriangleStrip :
  379. return 2 + primitiveCount;
  380. break;
  381. case GFXTriangleFan :
  382. return 2 + primitiveCount;
  383. break;
  384. default:
  385. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  386. break;
  387. }
  388. return 0;
  389. }
  390. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  391. {
  392. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  393. static GFXGLVertexDeclMap declMap;
  394. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  395. if(itr != declMap.end())
  396. return &itr->value;
  397. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  398. decl.init(vertexFormat);
  399. return &decl;
  400. }
  401. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  402. {
  403. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  404. }
  405. inline void GFXGLDevice::preDrawPrimitive()
  406. {
  407. if( mStateDirty )
  408. {
  409. updateStates();
  410. }
  411. if(mCurrentShaderConstBuffer)
  412. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  413. if( mNeedUpdateVertexAttrib )
  414. {
  415. AssertFatal(mCurrVertexDecl, "");
  416. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  417. for(int i = 0; i < getNumVertexStreams(); ++i)
  418. {
  419. if(mCurrentVB[i])
  420. {
  421. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  422. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  423. }
  424. }
  425. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  426. }
  427. mNeedUpdateVertexAttrib = false;
  428. }
  429. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  430. {
  431. mDeviceStatistics.mDrawCalls++;
  432. mDeviceStatistics.mPolyCount += primitiveCount;
  433. }
  434. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  435. {
  436. preDrawPrimitive();
  437. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  438. if(mDrawInstancesCount)
  439. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  440. else
  441. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  442. postDrawPrimitive(primitiveCount);
  443. }
  444. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  445. U32 startVertex,
  446. U32 minIndex,
  447. U32 numVerts,
  448. U32 startIndex,
  449. U32 primitiveCount )
  450. {
  451. AssertFatal( startVertex == 0, "GFXGLDevice::drawIndexedPrimitive() - Non-zero startVertex unsupported!" );
  452. preDrawPrimitive();
  453. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex;
  454. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset;
  455. if(mDrawInstancesCount)
  456. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  457. else
  458. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  459. postDrawPrimitive(primitiveCount);
  460. }
  461. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  462. {
  463. if(mCurrentPB)
  464. mCurrentPB->finish();
  465. mCurrentPB = pb;
  466. }
  467. void GFXGLDevice::setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable)
  468. {
  469. // ONLY NEEDED ON FFP
  470. }
  471. void GFXGLDevice::setLightMaterialInternal(const GFXLightMaterial mat)
  472. {
  473. // ONLY NEEDED ON FFP
  474. }
  475. void GFXGLDevice::setGlobalAmbientInternal(ColorF color)
  476. {
  477. glLightModelfv(GL_LIGHT_MODEL_AMBIENT, (GLfloat*)&color);
  478. }
  479. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  480. {
  481. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  482. if (tex)
  483. {
  484. mActiveTextureType[textureUnit] = tex->getBinding();
  485. tex->bind(textureUnit);
  486. }
  487. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  488. {
  489. glActiveTexture(GL_TEXTURE0 + textureUnit);
  490. glBindTexture(mActiveTextureType[textureUnit], 0);
  491. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  492. mActiveTextureType[textureUnit] = GL_ZERO;
  493. }
  494. }
  495. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  496. {
  497. if(texture)
  498. {
  499. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  500. texture->bind(textureUnit);
  501. }
  502. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  503. {
  504. glActiveTexture(GL_TEXTURE0 + textureUnit);
  505. glBindTexture(mActiveTextureType[textureUnit], 0);
  506. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  507. mActiveTextureType[textureUnit] = GL_ZERO;
  508. }
  509. }
  510. void GFXGLDevice::setMatrix( GFXMatrixType mtype, const MatrixF &mat )
  511. {
  512. // ONLY NEEDED ON FFP
  513. }
  514. void GFXGLDevice::setClipRect( const RectI &inRect )
  515. {
  516. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  517. // Clip the rect against the renderable size.
  518. Point2I size = mCurrentRT->getSize();
  519. RectI maxRect(Point2I(0,0), size);
  520. mClip = inRect;
  521. mClip.intersect(maxRect);
  522. // Create projection matrix. See http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html
  523. const F32 left = mClip.point.x;
  524. const F32 right = mClip.point.x + mClip.extent.x;
  525. const F32 bottom = mClip.extent.y;
  526. const F32 top = 0.0f;
  527. const F32 near = 0.0f;
  528. const F32 far = 1.0f;
  529. const F32 tx = -(right + left)/(right - left);
  530. const F32 ty = -(top + bottom)/(top - bottom);
  531. const F32 tz = -(far + near)/(far - near);
  532. static Point4F pt;
  533. pt.set(2.0f / (right - left), 0.0f, 0.0f, 0.0f);
  534. mProjectionMatrix.setColumn(0, pt);
  535. pt.set(0.0f, 2.0f/(top - bottom), 0.0f, 0.0f);
  536. mProjectionMatrix.setColumn(1, pt);
  537. pt.set(0.0f, 0.0f, -2.0f/(far - near), 0.0f);
  538. mProjectionMatrix.setColumn(2, pt);
  539. pt.set(tx, ty, tz, 1.0f);
  540. mProjectionMatrix.setColumn(3, pt);
  541. // Translate projection matrix.
  542. static MatrixF translate(true);
  543. pt.set(0.0f, -mClip.point.y, 0.0f, 1.0f);
  544. translate.setColumn(3, pt);
  545. mProjectionMatrix *= translate;
  546. setMatrix(GFXMatrixProjection, mProjectionMatrix);
  547. MatrixF mTempMatrix(true);
  548. setViewMatrix( mTempMatrix );
  549. setWorldMatrix( mTempMatrix );
  550. // Set the viewport to the clip rect
  551. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  552. setViewport(viewport);
  553. }
  554. /// Creates a state block object based on the desc passed in. This object
  555. /// represents an immutable state.
  556. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  557. {
  558. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  559. }
  560. /// Activates a stateblock
  561. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  562. {
  563. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  564. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  565. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  566. if (force)
  567. glCurrent = NULL;
  568. glBlock->activate(glCurrent); // Doesn't use current yet.
  569. mCurrentGLStateBlock = glBlock;
  570. }
  571. //------------------------------------------------------------------------------
  572. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget()
  573. {
  574. GFXGLTextureTarget *targ = new GFXGLTextureTarget();
  575. targ->registerResourceWithDevice(this);
  576. return targ;
  577. }
  578. GFXFence * GFXGLDevice::createFence()
  579. {
  580. GFXFence* fence = _createPlatformSpecificFence();
  581. if(!fence)
  582. fence = new GFXGeneralFence( this );
  583. fence->registerResourceWithDevice(this);
  584. return fence;
  585. }
  586. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  587. {
  588. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  589. query->registerResourceWithDevice(this);
  590. return query;
  591. }
  592. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  593. {
  594. AssertFatal(type != GSTargetRestore, "");
  595. if( mGenericShader[GSColor] == NULL )
  596. {
  597. ShaderData *shaderData;
  598. shaderData = new ShaderData();
  599. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/colorV.glsl");
  600. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/colorP.glsl");
  601. shaderData->setField("pixVersion", "2.0");
  602. shaderData->registerObject();
  603. mGenericShader[GSColor] = shaderData->getShader();
  604. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  605. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  606. shaderData = new ShaderData();
  607. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/modColorTextureV.glsl");
  608. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/modColorTextureP.glsl");
  609. shaderData->setSamplerName("$diffuseMap", 0);
  610. shaderData->setField("pixVersion", "2.0");
  611. shaderData->registerObject();
  612. mGenericShader[GSModColorTexture] = shaderData->getShader();
  613. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  614. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  615. shaderData = new ShaderData();
  616. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/addColorTextureV.glsl");
  617. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/addColorTextureP.glsl");
  618. shaderData->setSamplerName("$diffuseMap", 0);
  619. shaderData->setField("pixVersion", "2.0");
  620. shaderData->registerObject();
  621. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  622. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  623. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  624. shaderData = new ShaderData();
  625. shaderData->setField("OGLVertexShaderFile", "shaders/common/fixedFunction/gl/textureV.glsl");
  626. shaderData->setField("OGLPixelShaderFile", "shaders/common/fixedFunction/gl/textureP.glsl");
  627. shaderData->setSamplerName("$diffuseMap", 0);
  628. shaderData->setField("pixVersion", "2.0");
  629. shaderData->registerObject();
  630. mGenericShader[GSTexture] = shaderData->getShader();
  631. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  632. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  633. }
  634. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  635. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  636. setShader( mGenericShader[type] );
  637. setShaderConstBuffer( mGenericShaderBuffer[type] );
  638. }
  639. GFXShader* GFXGLDevice::createShader()
  640. {
  641. GFXGLShader* shader = new GFXGLShader();
  642. shader->registerResourceWithDevice( this );
  643. return shader;
  644. }
  645. void GFXGLDevice::setShader( GFXShader *shader )
  646. {
  647. if(mCurrentShader == shader)
  648. return;
  649. if ( shader )
  650. {
  651. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  652. glShader->useProgram();
  653. mCurrentShader = shader;
  654. }
  655. else
  656. {
  657. setupGenericShaders();
  658. }
  659. }
  660. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  661. {
  662. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  663. }
  664. U32 GFXGLDevice::getNumSamplers() const
  665. {
  666. return getMin((U32)TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  667. }
  668. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  669. {
  670. if(mWindowRT && mWindowRT->getPointer())
  671. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  672. return NULL;
  673. }
  674. U32 GFXGLDevice::getNumRenderTargets() const
  675. {
  676. return mMaxTRColors;
  677. }
  678. void GFXGLDevice::_updateRenderTargets()
  679. {
  680. if ( mRTDirty || mCurrentRT->isPendingState() )
  681. {
  682. if ( mRTDeactivate )
  683. {
  684. mRTDeactivate->deactivate();
  685. mRTDeactivate = NULL;
  686. }
  687. // NOTE: The render target changes is not really accurate
  688. // as the GFXTextureTarget supports MRT internally. So when
  689. // we activate a GFXTarget it could result in multiple calls
  690. // to SetRenderTarget on the actual device.
  691. mDeviceStatistics.mRenderTargetChanges++;
  692. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  693. if ( tex )
  694. {
  695. tex->applyState();
  696. tex->makeActive();
  697. }
  698. else
  699. {
  700. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  701. AssertFatal( win != NULL,
  702. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  703. win->makeActive();
  704. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  705. {
  706. mRTDirty = false;
  707. GFX->updateStates(true);
  708. }
  709. }
  710. mRTDirty = false;
  711. }
  712. if ( mViewportDirty )
  713. {
  714. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  715. mViewportDirty = false;
  716. }
  717. }
  718. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  719. const Vector<GFXFormat>& formats,
  720. bool texture,
  721. bool mustblend,
  722. bool mustfilter )
  723. {
  724. for(U32 i = 0; i < formats.size(); i++)
  725. {
  726. // Single channel textures are not supported by FBOs.
  727. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  728. continue;
  729. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  730. continue;
  731. return formats[i];
  732. }
  733. return GFXFormatR8G8B8A8;
  734. }
  735. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  736. {
  737. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  738. if( gglHasExtension(ATI_meminfo) )
  739. {
  740. GLint mem[4] = {0};
  741. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  742. /* With mem[0] i get only the total memory free in the pool in KB
  743. *
  744. * mem[0] - total memory free in the pool
  745. * mem[1] - largest available free block in the pool
  746. * mem[2] - total auxiliary memory free
  747. * mem[3] - largest auxiliary free block
  748. */
  749. return mem[0] / 1024;
  750. }
  751. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  752. else if( gglHasExtension(NVX_gpu_memory_info) )
  753. {
  754. GLint mem = 0;
  755. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  756. return mem / 1024;
  757. }
  758. // TODO OPENGL, add supprt for INTEL cards.
  759. return 0;
  760. }
  761. //
  762. // Register this device with GFXInit
  763. //
  764. class GFXGLRegisterDevice
  765. {
  766. public:
  767. GFXGLRegisterDevice()
  768. {
  769. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  770. }
  771. };
  772. static GFXGLRegisterDevice pGLRegisterDevice;
  773. ConsoleFunction(cycleResources, void, 1, 1, "")
  774. {
  775. static_cast<GFXGLDevice*>(GFX)->zombify();
  776. static_cast<GFXGLDevice*>(GFX)->resurrect();
  777. }