gfxGLDevice.cpp 31 KB

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