gfxGLDevice.cpp 30 KB

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