gfxGLDevice.cpp 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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 "gfxGLTextureArray.h"
  25. #include "platform/platformGL.h"
  26. #include "gfx/gfxCubemap.h"
  27. #include "gfx/gl/screenshotGL.h"
  28. #include "gfx/gfxDrawUtil.h"
  29. #include "gfx/gl/gfxGLEnumTranslate.h"
  30. #include "gfx/gl/gfxGLVertexBuffer.h"
  31. #include "gfx/gl/gfxGLPrimitiveBuffer.h"
  32. #include "gfx/gl/gfxGLTextureTarget.h"
  33. #include "gfx/gl/gfxGLTextureManager.h"
  34. #include "gfx/gl/gfxGLTextureObject.h"
  35. #include "gfx/gl/gfxGLCubemap.h"
  36. #include "gfx/gl/gfxGLCardProfiler.h"
  37. #include "gfx/gl/gfxGLWindowTarget.h"
  38. #include "platform/platformDlibrary.h"
  39. #include "gfx/gl/gfxGLShader.h"
  40. #include "gfx/primBuilder.h"
  41. #include "console/console.h"
  42. #include "gfx/gl/gfxGLOcclusionQuery.h"
  43. #include "materials/shaderData.h"
  44. #include "gfx/gl/gfxGLStateCache.h"
  45. #include "gfx/gl/gfxGLVertexAttribLocation.h"
  46. #include "gfx/gl/gfxGLVertexDecl.h"
  47. #include "shaderGen/shaderGen.h"
  48. #include "gfxGLUtils.h"
  49. #if defined(TORQUE_OS_WIN)
  50. #include "gfx/gl/tGL/tWGL.h"
  51. #elif defined(TORQUE_OS_LINUX)
  52. #include "gfx/gl/tGL/tXGL.h"
  53. #endif
  54. GFXAdapter::CreateDeviceInstanceDelegate GFXGLDevice::mCreateDeviceInstance(GFXGLDevice::createInstance);
  55. GFXDevice *GFXGLDevice::createInstance( U32 adapterIndex )
  56. {
  57. return new GFXGLDevice(adapterIndex);
  58. }
  59. namespace GL
  60. {
  61. extern void gglPerformBinds();
  62. extern void gglPerformExtensionBinds(void *context);
  63. }
  64. void loadGLCore()
  65. {
  66. static bool coreLoaded = false; // Guess what this is for.
  67. if(coreLoaded)
  68. return;
  69. coreLoaded = true;
  70. // Make sure we've got our GL bindings.
  71. GL::gglPerformBinds();
  72. }
  73. void loadGLExtensions(void *context)
  74. {
  75. static bool extensionsLoaded = false;
  76. if(extensionsLoaded)
  77. return;
  78. extensionsLoaded = true;
  79. GL::gglPerformExtensionBinds(context);
  80. }
  81. void STDCALL glDebugCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  82. const GLchar *message, const void *userParam)
  83. {
  84. // JTH [11/24/2016]: This is a temporary fix so that we do not get spammed for redundant fbo changes.
  85. // This only happens on Intel cards. This should be looked into sometime in the near future.
  86. if (dStrStartsWith(message, "API_ID_REDUNDANT_FBO"))
  87. return;
  88. if (severity == GL_DEBUG_SEVERITY_HIGH)
  89. Con::errorf("OPENGL: %s", message);
  90. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  91. Con::warnf("OPENGL: %s", message);
  92. else if (severity == GL_DEBUG_SEVERITY_LOW)
  93. Con::printf("OPENGL: %s", message);
  94. }
  95. void STDCALL glAmdDebugCallback(GLuint id, GLenum category, GLenum severity, GLsizei length,
  96. const GLchar* message, GLvoid* userParam)
  97. {
  98. if (severity == GL_DEBUG_SEVERITY_HIGH)
  99. Con::errorf("AMDOPENGL: %s", message);
  100. else if (severity == GL_DEBUG_SEVERITY_MEDIUM)
  101. Con::warnf("AMDOPENGL: %s", message);
  102. else if (severity == GL_DEBUG_SEVERITY_LOW)
  103. Con::printf("AMDOPENGL: %s", message);
  104. }
  105. void GFXGLDevice::initGLState()
  106. {
  107. // We don't currently need to sync device state with a known good place because we are
  108. // going to set everything in GFXGLStateBlock, but if we change our GFXGLStateBlock strategy, this may
  109. // need to happen.
  110. // Deal with the card profiler here when we know we have a valid context.
  111. mCardProfiler = new GFXGLCardProfiler();
  112. mCardProfiler->init();
  113. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, (GLint*)&mMaxShaderTextures);
  114. // JTH: Needs removed, ffp
  115. //glGetIntegerv(GL_MAX_TEXTURE_UNITS, (GLint*)&mMaxFFTextures);
  116. glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, (GLint*)&mMaxTRColors);
  117. mMaxTRColors = getMin( mMaxTRColors, (U32)(GFXTextureTarget::MaxRenderSlotId-1) );
  118. glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
  119. // [JTH 5/6/2016] GLSL 1.50 is really SM 4.0
  120. // Setting mPixelShaderVersion to 3.0 will allow Advanced Lighting to run.
  121. mPixelShaderVersion = 3.0;
  122. // Set capability extensions.
  123. mCapabilities.anisotropicFiltering = mCardProfiler->queryProfile("GL_EXT_texture_filter_anisotropic");
  124. mCapabilities.bufferStorage = mCardProfiler->queryProfile("GL_ARB_buffer_storage");
  125. mCapabilities.textureStorage = mCardProfiler->queryProfile("GL_ARB_texture_storage");
  126. mCapabilities.copyImage = mCardProfiler->queryProfile("GL_ARB_copy_image");
  127. mCapabilities.vertexAttributeBinding = mCardProfiler->queryProfile("GL_ARB_vertex_attrib_binding");
  128. mCapabilities.khrDebug = mCardProfiler->queryProfile("GL_KHR_debug");
  129. mCapabilities.extDebugMarker = mCardProfiler->queryProfile("GL_EXT_debug_marker");
  130. String vendorStr = (const char*)glGetString( GL_VENDOR );
  131. if( vendorStr.find("NVIDIA", 0, String::NoCase | String::Left) != String::NPos)
  132. mUseGlMap = false;
  133. // Workaround for all Mac's, has a problem using glMap* with volatile buffers
  134. #ifdef TORQUE_OS_MAC
  135. mUseGlMap = false;
  136. #endif
  137. #if TORQUE_DEBUG
  138. if( gglHasExtension(ARB_debug_output) )
  139. {
  140. glEnable(GL_DEBUG_OUTPUT);
  141. glDebugMessageCallbackARB(glDebugCallback, NULL);
  142. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  143. GLuint unusedIds = 0;
  144. glDebugMessageControlARB(GL_DONT_CARE,
  145. GL_DONT_CARE,
  146. GL_DONT_CARE,
  147. 0,
  148. &unusedIds,
  149. GL_TRUE);
  150. }
  151. else if(gglHasExtension(AMD_debug_output))
  152. {
  153. glEnable(GL_DEBUG_OUTPUT);
  154. glDebugMessageCallbackAMD(glAmdDebugCallback, NULL);
  155. //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  156. GLuint unusedIds = 0;
  157. glDebugMessageEnableAMD(GL_DONT_CARE, GL_DONT_CARE, 0,&unusedIds, GL_TRUE);
  158. }
  159. #endif
  160. PlatformGL::setVSync(smEnableVSync);
  161. //install vsync callback
  162. Con::NotifyDelegate clbk(this, &GFXGLDevice::vsyncCallback);
  163. Con::addVariableNotify("$pref::Video::enableVerticalSync", clbk);
  164. //OpenGL 3 need a binded VAO for render
  165. GLuint vao;
  166. glGenVertexArrays(1, &vao);
  167. glBindVertexArray(vao);
  168. //enable sRGB
  169. glEnable(GL_FRAMEBUFFER_SRGB);
  170. //enable seamless cubemapping
  171. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  172. }
  173. void GFXGLDevice::vsyncCallback()
  174. {
  175. PlatformGL::setVSync(smEnableVSync);
  176. }
  177. GFXGLDevice::GFXGLDevice(U32 adapterIndex) :
  178. mAdapterIndex(adapterIndex),
  179. mNeedUpdateVertexAttrib(false),
  180. mCurrentPB(NULL),
  181. mDrawInstancesCount(0),
  182. mCurrentShader( NULL ),
  183. m_mCurrentWorld(true),
  184. m_mCurrentView(true),
  185. mContext(NULL),
  186. mPixelFormat(NULL),
  187. mPixelShaderVersion(0.0f),
  188. mMaxShaderTextures(2),
  189. mMaxFFTextures(2),
  190. mMaxTRColors(1),
  191. mClip(0, 0, 0, 0),
  192. mWindowRT(NULL),
  193. mUseGlMap(true)
  194. {
  195. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  196. {
  197. mCurrentVB[i] = NULL;
  198. mCurrentVB_Divisor[i] = 0;
  199. }
  200. // Initiailize capabilities to false.
  201. memset(&mCapabilities, 0, sizeof(GLCapabilities));
  202. loadGLCore();
  203. GFXGLEnumTranslate::init();
  204. GFXVertexColor::setSwizzle( &Swizzles::rgba );
  205. // OpenGL have native RGB, no need swizzle
  206. mDeviceSwizzle32 = &Swizzles::rgba;
  207. mDeviceSwizzle24 = &Swizzles::rgb;
  208. mTextureManager = new GFXGLTextureManager();
  209. gScreenShot = new ScreenShotGL();
  210. for(U32 i = 0; i < GFX_TEXTURE_STAGE_COUNT; i++)
  211. mActiveTextureType[i] = GL_ZERO;
  212. mNumVertexStream = 2;
  213. for(int i = 0; i < GS_COUNT; ++i)
  214. mModelViewProjSC[i] = NULL;
  215. mOpenglStateCache = new GFXGLStateCache;
  216. }
  217. GFXGLDevice::~GFXGLDevice()
  218. {
  219. mCurrentStateBlock = NULL;
  220. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  221. mCurrentVB[i] = NULL;
  222. mCurrentPB = NULL;
  223. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  224. mVolatileVBs[i] = NULL;
  225. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  226. mVolatilePBs[i] = NULL;
  227. // Clear out our current texture references
  228. for (U32 i = 0; i < GFX_TEXTURE_STAGE_COUNT; i++)
  229. {
  230. mCurrentTexture[i] = NULL;
  231. mNewTexture[i] = NULL;
  232. mCurrentCubemap[i] = NULL;
  233. mNewCubemap[i] = NULL;
  234. }
  235. mRTStack.clear();
  236. mCurrentRT = NULL;
  237. if( mTextureManager )
  238. {
  239. mTextureManager->zombify();
  240. mTextureManager->kill();
  241. }
  242. GFXResource* walk = mResourceListHead;
  243. while(walk)
  244. {
  245. walk->zombify();
  246. walk = walk->getNextResource();
  247. }
  248. if( mCardProfiler )
  249. SAFE_DELETE( mCardProfiler );
  250. SAFE_DELETE( gScreenShot );
  251. SAFE_DELETE( mOpenglStateCache );
  252. }
  253. void GFXGLDevice::zombify()
  254. {
  255. mTextureManager->zombify();
  256. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  257. if(mCurrentVB[i])
  258. mCurrentVB[i]->finish();
  259. if(mCurrentPB)
  260. mCurrentPB->finish();
  261. //mVolatileVBs.clear();
  262. //mVolatilePBs.clear();
  263. GFXResource* walk = mResourceListHead;
  264. while(walk)
  265. {
  266. walk->zombify();
  267. walk = walk->getNextResource();
  268. }
  269. }
  270. void GFXGLDevice::resurrect()
  271. {
  272. GFXResource* walk = mResourceListHead;
  273. while(walk)
  274. {
  275. walk->resurrect();
  276. walk = walk->getNextResource();
  277. }
  278. for(int i = 0; i < VERTEX_STREAM_COUNT; ++i)
  279. if(mCurrentVB[i])
  280. mCurrentVB[i]->prepare();
  281. if(mCurrentPB)
  282. mCurrentPB->prepare();
  283. mTextureManager->resurrect();
  284. }
  285. GFXVertexBuffer* GFXGLDevice::findVolatileVBO(U32 numVerts, const GFXVertexFormat *vertexFormat, U32 vertSize)
  286. {
  287. PROFILE_SCOPE(GFXGLDevice_findVBPool);
  288. for(U32 i = 0; i < mVolatileVBs.size(); i++)
  289. if ( mVolatileVBs[i]->mNumVerts >= numVerts &&
  290. mVolatileVBs[i]->mVertexFormat.isEqual( *vertexFormat ) &&
  291. mVolatileVBs[i]->mVertexSize == vertSize &&
  292. mVolatileVBs[i]->getRefCount() == 1 )
  293. return mVolatileVBs[i];
  294. // No existing VB, so create one
  295. PROFILE_SCOPE(GFXGLDevice_createVBPool);
  296. StrongRefPtr<GFXGLVertexBuffer> buf(new GFXGLVertexBuffer(GFX, numVerts, vertexFormat, vertSize, GFXBufferTypeVolatile));
  297. buf->registerResourceWithDevice(this);
  298. mVolatileVBs.push_back(buf);
  299. return buf.getPointer();
  300. }
  301. GFXPrimitiveBuffer* GFXGLDevice::findVolatilePBO(U32 numIndices, U32 numPrimitives)
  302. {
  303. for(U32 i = 0; i < mVolatilePBs.size(); i++)
  304. if((mVolatilePBs[i]->mIndexCount >= numIndices) && (mVolatilePBs[i]->getRefCount() == 1))
  305. return mVolatilePBs[i];
  306. // No existing PB, so create one
  307. StrongRefPtr<GFXGLPrimitiveBuffer> buf(new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, GFXBufferTypeVolatile));
  308. buf->registerResourceWithDevice(this);
  309. mVolatilePBs.push_back(buf);
  310. return buf.getPointer();
  311. }
  312. GFXVertexBuffer *GFXGLDevice::allocVertexBuffer( U32 numVerts,
  313. const GFXVertexFormat *vertexFormat,
  314. U32 vertSize,
  315. GFXBufferType bufferType,
  316. void* data )
  317. {
  318. PROFILE_SCOPE(GFXGLDevice_allocVertexBuffer);
  319. if(bufferType == GFXBufferTypeVolatile)
  320. return findVolatileVBO(numVerts, vertexFormat, vertSize);
  321. GFXGLVertexBuffer* buf = new GFXGLVertexBuffer( GFX, numVerts, vertexFormat, vertSize, bufferType );
  322. buf->registerResourceWithDevice(this);
  323. if(data)
  324. {
  325. void* dest;
  326. buf->lock(0, numVerts, &dest);
  327. dMemcpy(dest, data, vertSize * numVerts);
  328. buf->unlock();
  329. }
  330. return buf;
  331. }
  332. GFXPrimitiveBuffer *GFXGLDevice::allocPrimitiveBuffer( U32 numIndices, U32 numPrimitives, GFXBufferType bufferType, void* data )
  333. {
  334. GFXPrimitiveBuffer* buf;
  335. if(bufferType == GFXBufferTypeVolatile)
  336. {
  337. buf = findVolatilePBO(numIndices, numPrimitives);
  338. }
  339. else
  340. {
  341. buf = new GFXGLPrimitiveBuffer(GFX, numIndices, numPrimitives, bufferType);
  342. buf->registerResourceWithDevice(this);
  343. }
  344. if(data)
  345. {
  346. void* dest;
  347. buf->lock(0, numIndices, &dest);
  348. dMemcpy(dest, data, sizeof(U16) * numIndices);
  349. buf->unlock();
  350. }
  351. return buf;
  352. }
  353. void GFXGLDevice::setVertexStream( U32 stream, GFXVertexBuffer *buffer )
  354. {
  355. AssertFatal(stream <= 1, "GFXGLDevice::setVertexStream only support 2 stream (0: data, 1: instancing)");
  356. //if(mCurrentVB[stream] != buffer)
  357. {
  358. // Reset the state the old VB required, then set the state the new VB requires.
  359. if( mCurrentVB[stream] )
  360. {
  361. mCurrentVB[stream]->finish();
  362. }
  363. mCurrentVB[stream] = static_cast<GFXGLVertexBuffer*>( buffer );
  364. mNeedUpdateVertexAttrib = true;
  365. }
  366. }
  367. void GFXGLDevice::setVertexStreamFrequency( U32 stream, U32 frequency )
  368. {
  369. if( stream == 0 )
  370. {
  371. mCurrentVB_Divisor[stream] = 0; // non instanced, is vertex buffer
  372. mDrawInstancesCount = frequency; // instances count
  373. }
  374. else
  375. {
  376. AssertFatal(frequency <= 1, "GFXGLDevice::setVertexStreamFrequency only support 0/1 for this stream" );
  377. if( stream == 1 && frequency == 1 )
  378. mCurrentVB_Divisor[stream] = 1; // instances data need a frequency of 1
  379. else
  380. mCurrentVB_Divisor[stream] = 0;
  381. }
  382. mNeedUpdateVertexAttrib = true;
  383. }
  384. GFXCubemap* GFXGLDevice::createCubemap()
  385. {
  386. GFXGLCubemap* cube = new GFXGLCubemap();
  387. cube->registerResourceWithDevice(this);
  388. return cube;
  389. };
  390. GFXCubemapArray *GFXGLDevice::createCubemapArray()
  391. {
  392. GFXGLCubemapArray* cubeArray = new GFXGLCubemapArray();
  393. cubeArray->registerResourceWithDevice(this);
  394. return cubeArray;
  395. }
  396. GFXTextureArray* GFXGLDevice::createTextureArray()
  397. {
  398. GFXGLTextureArray* textureArray = new GFXGLTextureArray();
  399. textureArray->registerResourceWithDevice(this);
  400. return textureArray;
  401. }
  402. void GFXGLDevice::endSceneInternal()
  403. {
  404. // nothing to do for opengl
  405. mCanCurrentlyRender = false;
  406. }
  407. void GFXGLDevice::copyResource(GFXTextureObject* pDst, GFXCubemap* pSrc, const U32 face)
  408. {
  409. AssertFatal(pDst, "GFXGLDevice::copyResource: Destination texture is null");
  410. AssertFatal(pSrc, "GFXGLDevice::copyResource: Source cubemap is null");
  411. GFXGLTextureObject* gGLDst = static_cast<GFXGLTextureObject*>(pDst);
  412. GFXGLCubemap* pGLSrc = static_cast<GFXGLCubemap*>(pSrc);
  413. const GFXFormat format = pGLSrc->getFormat();
  414. const bool isCompressed = ImageUtil::isCompressedFormat(format);
  415. const U32 mipLevels = pGLSrc->getMipMapLevels();
  416. const U32 texSize = pGLSrc->getSize();
  417. //set up pbo if we don't have copyImage support
  418. if (!GFXGL->mCapabilities.copyImage)
  419. {
  420. const GLuint pbo = gGLDst->getBuffer();
  421. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  422. //allocate data
  423. glBufferData(GL_PIXEL_PACK_BUFFER, texSize * texSize * GFXFormat_getByteSize(format), NULL, GL_STREAM_COPY);
  424. }
  425. for (U32 mip = 0; mip < mipLevels; mip++)
  426. {
  427. const U32 mipSize = texSize >> mip;
  428. if (GFXGL->mCapabilities.copyImage)
  429. {
  430. glCopyImageSubData(pGLSrc->mCubemap, GL_TEXTURE_CUBE_MAP, mip, 0, 0, face, gGLDst->getHandle(), GL_TEXTURE_2D, mip, 0, 0, 0, mipSize, mipSize, 1);
  431. }
  432. else
  433. {
  434. //pbo id
  435. const GLuint pbo = gGLDst->getBuffer();
  436. //copy source texture data to pbo
  437. glBindTexture(GL_TEXTURE_CUBE_MAP, pGLSrc->mCubemap);
  438. glBindBuffer(GL_PIXEL_PACK_BUFFER, pbo);
  439. if (isCompressed)
  440. glGetCompressedTexImage(GFXGLFaceType[face], mip, NULL);
  441. else
  442. glGetTexImage(GFXGLFaceType[face], mip, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  443. glBindBuffer(GL_PIXEL_PACK_BUFFER, 0);
  444. glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
  445. //copy data from pbo to destination
  446. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, pbo);
  447. glBindTexture(gGLDst->getBinding(), gGLDst->getHandle());
  448. if (isCompressed)
  449. {
  450. const U32 mipDataSize = getCompressedSurfaceSize(format, pGLSrc->getSize(), pGLSrc->getSize(), 0);
  451. glCompressedTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], mipDataSize, NULL);
  452. }
  453. else
  454. {
  455. glTexSubImage2D(gGLDst->getBinding(), mip, 0, 0, mipSize, mipSize, GFXGLTextureFormat[format], GFXGLTextureType[format], NULL);
  456. }
  457. glBindBuffer(GL_PIXEL_UNPACK_BUFFER, 0);
  458. glBindTexture(gGLDst->getBinding(), 0);
  459. }
  460. }
  461. }
  462. void GFXGLDevice::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  463. {
  464. // Make sure we have flushed our render target state.
  465. _updateRenderTargets();
  466. bool writeAllColors = true;
  467. bool zwrite = true;
  468. bool writeAllStencil = true;
  469. const GFXStateBlockDesc *desc = NULL;
  470. if (mCurrentGLStateBlock)
  471. {
  472. desc = &mCurrentGLStateBlock->getDesc();
  473. zwrite = desc->zWriteEnable;
  474. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  475. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  476. }
  477. glColorMask(true, true, true, true);
  478. glDepthMask(true);
  479. glStencilMask(0xFFFFFFFF);
  480. glClearColor(color.red, color.green, color.blue, color.alpha);
  481. glClearDepth(z);
  482. glClearStencil(stencil);
  483. GLbitfield clearflags = 0;
  484. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  485. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  486. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  487. glClear(clearflags);
  488. if(!writeAllColors)
  489. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  490. if(!zwrite)
  491. glDepthMask(false);
  492. if(!writeAllStencil)
  493. glStencilMask(desc->stencilWriteMask);
  494. }
  495. void GFXGLDevice::clearColorAttachment(const U32 attachment, const LinearColorF& color)
  496. {
  497. const GLfloat clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  498. glClearBufferfv(GL_COLOR, attachment, clearColor);
  499. }
  500. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  501. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  502. {
  503. switch (primType)
  504. {
  505. case GFXPointList :
  506. return primitiveCount;
  507. break;
  508. case GFXLineList :
  509. return primitiveCount * 2;
  510. break;
  511. case GFXLineStrip :
  512. return primitiveCount + 1;
  513. break;
  514. case GFXTriangleList :
  515. return primitiveCount * 3;
  516. break;
  517. case GFXTriangleStrip :
  518. return 2 + primitiveCount;
  519. break;
  520. default:
  521. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  522. break;
  523. }
  524. return 0;
  525. }
  526. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  527. {
  528. PROFILE_SCOPE(GFXGLDevice_allocVertexDecl);
  529. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  530. static GFXGLVertexDeclMap declMap;
  531. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  532. if(itr != declMap.end())
  533. return &itr->value;
  534. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  535. decl.init(vertexFormat);
  536. return &decl;
  537. }
  538. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  539. {
  540. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  541. }
  542. inline void GFXGLDevice::preDrawPrimitive()
  543. {
  544. if( mStateDirty )
  545. {
  546. updateStates();
  547. }
  548. if(mCurrentShaderConstBuffer)
  549. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  550. if( mNeedUpdateVertexAttrib )
  551. {
  552. AssertFatal(mCurrVertexDecl, "");
  553. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  554. for(int i = 0; i < getNumVertexStreams(); ++i)
  555. {
  556. if(mCurrentVB[i])
  557. {
  558. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  559. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  560. }
  561. }
  562. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  563. }
  564. mNeedUpdateVertexAttrib = false;
  565. }
  566. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  567. {
  568. mDeviceStatistics.mDrawCalls++;
  569. mDeviceStatistics.mPolyCount += primitiveCount;
  570. }
  571. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  572. {
  573. preDrawPrimitive();
  574. if(mCurrentVB[0])
  575. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  576. if(mDrawInstancesCount)
  577. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  578. else
  579. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  580. postDrawPrimitive(primitiveCount);
  581. }
  582. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  583. U32 startVertex,
  584. U32 minIndex,
  585. U32 numVerts,
  586. U32 startIndex,
  587. U32 primitiveCount )
  588. {
  589. preDrawPrimitive();
  590. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex + mCurrentPrimitiveBuffer->mVolatileStart;
  591. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset + startVertex;
  592. if(mDrawInstancesCount)
  593. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  594. else
  595. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  596. postDrawPrimitive(primitiveCount);
  597. }
  598. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  599. {
  600. if(mCurrentPB)
  601. mCurrentPB->finish();
  602. mCurrentPB = pb;
  603. }
  604. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  605. {
  606. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  607. if (tex)
  608. {
  609. mActiveTextureType[textureUnit] = tex->getBinding();
  610. tex->bind(textureUnit);
  611. }
  612. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  613. {
  614. glActiveTexture(GL_TEXTURE0 + textureUnit);
  615. glBindTexture(mActiveTextureType[textureUnit], 0);
  616. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  617. mActiveTextureType[textureUnit] = GL_ZERO;
  618. }
  619. }
  620. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  621. {
  622. if(texture)
  623. {
  624. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  625. texture->bind(textureUnit);
  626. }
  627. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  628. {
  629. glActiveTexture(GL_TEXTURE0 + textureUnit);
  630. glBindTexture(mActiveTextureType[textureUnit], 0);
  631. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  632. mActiveTextureType[textureUnit] = GL_ZERO;
  633. }
  634. }
  635. void GFXGLDevice::setCubemapArrayInternal(U32 textureUnit, const GFXGLCubemapArray* texture)
  636. {
  637. if (texture)
  638. {
  639. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP_ARRAY_ARB;
  640. texture->bind(textureUnit);
  641. }
  642. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  643. {
  644. glActiveTexture(GL_TEXTURE0 + textureUnit);
  645. glBindTexture(mActiveTextureType[textureUnit], 0);
  646. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  647. mActiveTextureType[textureUnit] = GL_ZERO;
  648. }
  649. }
  650. void GFXGLDevice::setTextureArrayInternal(U32 textureUnit, const GFXGLTextureArray* texture)
  651. {
  652. if (texture)
  653. {
  654. mActiveTextureType[textureUnit] = GL_TEXTURE_2D_ARRAY;
  655. texture->bind(textureUnit);
  656. }
  657. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  658. {
  659. glActiveTexture(GL_TEXTURE0 + textureUnit);
  660. glBindTexture(mActiveTextureType[textureUnit], 0);
  661. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  662. mActiveTextureType[textureUnit] = GL_ZERO;
  663. }
  664. }
  665. void GFXGLDevice::setClipRect( const RectI &inRect )
  666. {
  667. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  668. // Clip the rect against the renderable size.
  669. Point2I size = mCurrentRT->getSize();
  670. RectI maxRect(Point2I(0,0), size);
  671. mClip = inRect;
  672. mClip.intersect(maxRect);
  673. // Create projection matrix. See http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html
  674. const F32 left = mClip.point.x;
  675. const F32 right = mClip.point.x + mClip.extent.x;
  676. const F32 bottom = mClip.extent.y;
  677. const F32 top = 0.0f;
  678. const F32 nearPlane = 0.0f;
  679. const F32 farPlane = 1.0f;
  680. const F32 tx = -(right + left)/(right - left);
  681. const F32 ty = -(top + bottom)/(top - bottom);
  682. const F32 tz = -(farPlane + nearPlane)/(farPlane - nearPlane);
  683. static Point4F pt;
  684. pt.set(2.0f / (right - left), 0.0f, 0.0f, 0.0f);
  685. mProjectionMatrix.setColumn(0, pt);
  686. pt.set(0.0f, 2.0f/(top - bottom), 0.0f, 0.0f);
  687. mProjectionMatrix.setColumn(1, pt);
  688. pt.set(0.0f, 0.0f, -2.0f/(farPlane - nearPlane), 0.0f);
  689. mProjectionMatrix.setColumn(2, pt);
  690. pt.set(tx, ty, tz, 1.0f);
  691. mProjectionMatrix.setColumn(3, pt);
  692. // Translate projection matrix.
  693. static MatrixF translate(true);
  694. pt.set(0.0f, -mClip.point.y, 0.0f, 1.0f);
  695. translate.setColumn(3, pt);
  696. mProjectionMatrix *= translate;
  697. MatrixF mTempMatrix(true);
  698. setViewMatrix( mTempMatrix );
  699. setWorldMatrix( mTempMatrix );
  700. // Set the viewport to the clip rect
  701. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  702. setViewport(viewport);
  703. }
  704. /// Creates a state block object based on the desc passed in. This object
  705. /// represents an immutable state.
  706. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  707. {
  708. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  709. }
  710. /// Activates a stateblock
  711. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  712. {
  713. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  714. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  715. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  716. if (force)
  717. glCurrent = NULL;
  718. glBlock->activate(glCurrent); // Doesn't use current yet.
  719. mCurrentGLStateBlock = glBlock;
  720. }
  721. //------------------------------------------------------------------------------
  722. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget(bool genMips)
  723. {
  724. GFXGLTextureTarget *targ = new GFXGLTextureTarget(genMips);
  725. targ->registerResourceWithDevice(this);
  726. return targ;
  727. }
  728. GFXFence * GFXGLDevice::createFence()
  729. {
  730. GFXFence* fence = _createPlatformSpecificFence();
  731. if(!fence)
  732. fence = new GFXGeneralFence( this );
  733. fence->registerResourceWithDevice(this);
  734. return fence;
  735. }
  736. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  737. {
  738. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  739. query->registerResourceWithDevice(this);
  740. return query;
  741. }
  742. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  743. {
  744. AssertFatal(type != GSTargetRestore, "");
  745. if( mGenericShader[GSColor] == NULL )
  746. {
  747. ShaderData *shaderData;
  748. shaderData = new ShaderData();
  749. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorV.glsl"));
  750. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorP.glsl"));
  751. shaderData->setField("pixVersion", "2.0");
  752. shaderData->registerObject();
  753. mGenericShader[GSColor] = shaderData->getShader();
  754. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  755. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  756. Sim::getRootGroup()->addObject(shaderData);
  757. shaderData = new ShaderData();
  758. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureV.glsl"));
  759. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureP.glsl"));
  760. shaderData->setSamplerName("$diffuseMap", 0);
  761. shaderData->setField("pixVersion", "2.0");
  762. shaderData->registerObject();
  763. mGenericShader[GSModColorTexture] = shaderData->getShader();
  764. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  765. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  766. Sim::getRootGroup()->addObject(shaderData);
  767. shaderData = new ShaderData();
  768. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureV.glsl"));
  769. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureP.glsl"));
  770. shaderData->setSamplerName("$diffuseMap", 0);
  771. shaderData->setField("pixVersion", "2.0");
  772. shaderData->registerObject();
  773. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  774. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  775. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  776. Sim::getRootGroup()->addObject(shaderData);
  777. shaderData = new ShaderData();
  778. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureV.glsl"));
  779. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureP.glsl"));
  780. shaderData->setSamplerName("$diffuseMap", 0);
  781. shaderData->setField("pixVersion", "2.0");
  782. shaderData->registerObject();
  783. mGenericShader[GSTexture] = shaderData->getShader();
  784. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  785. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  786. Sim::getRootGroup()->addObject(shaderData);
  787. }
  788. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  789. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  790. setShader( mGenericShader[type] );
  791. setShaderConstBuffer( mGenericShaderBuffer[type] );
  792. }
  793. GFXShader* GFXGLDevice::createShader()
  794. {
  795. GFXGLShader* shader = new GFXGLShader(this);
  796. shader->registerResourceWithDevice( this );
  797. return shader;
  798. }
  799. void GFXGLDevice::setShader(GFXShader *shader, bool force)
  800. {
  801. if(mCurrentShader == shader && !force)
  802. return;
  803. if ( shader )
  804. {
  805. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  806. glShader->useProgram();
  807. mCurrentShader = shader;
  808. }
  809. else
  810. {
  811. setupGenericShaders();
  812. }
  813. }
  814. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  815. {
  816. PROFILE_SCOPE(GFXGLDevice_setShaderConstBufferInternal);
  817. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  818. }
  819. U32 GFXGLDevice::getNumSamplers() const
  820. {
  821. return getMin((U32)GFX_TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  822. }
  823. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  824. {
  825. if(mWindowRT && mWindowRT->getPointer())
  826. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  827. return NULL;
  828. }
  829. U32 GFXGLDevice::getNumRenderTargets() const
  830. {
  831. return mMaxTRColors;
  832. }
  833. void GFXGLDevice::_updateRenderTargets()
  834. {
  835. if ( mRTDirty || mCurrentRT->isPendingState() )
  836. {
  837. if ( mRTDeactivate )
  838. {
  839. mRTDeactivate->deactivate();
  840. mRTDeactivate = NULL;
  841. }
  842. // NOTE: The render target changes is not really accurate
  843. // as the GFXTextureTarget supports MRT internally. So when
  844. // we activate a GFXTarget it could result in multiple calls
  845. // to SetRenderTarget on the actual device.
  846. mDeviceStatistics.mRenderTargetChanges++;
  847. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  848. if ( tex )
  849. {
  850. tex->applyState();
  851. tex->makeActive();
  852. }
  853. else
  854. {
  855. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  856. AssertFatal( win != NULL,
  857. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  858. win->makeActive();
  859. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  860. {
  861. mRTDirty = false;
  862. GFX->updateStates(true);
  863. }
  864. }
  865. mRTDirty = false;
  866. }
  867. if ( mViewportDirty )
  868. {
  869. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  870. mViewportDirty = false;
  871. }
  872. }
  873. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  874. const Vector<GFXFormat>& formats,
  875. bool texture,
  876. bool mustblend,
  877. bool mustfilter )
  878. {
  879. for(U32 i = 0; i < formats.size(); i++)
  880. {
  881. // Single channel textures are not supported by FBOs.
  882. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  883. continue;
  884. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  885. continue;
  886. return formats[i];
  887. }
  888. return GFXFormatR8G8B8A8;
  889. }
  890. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  891. {
  892. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  893. if( gglHasExtension(ATI_meminfo) )
  894. {
  895. GLint mem[4] = {0};
  896. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  897. /* With mem[0] i get only the total memory free in the pool in KB
  898. *
  899. * mem[0] - total memory free in the pool
  900. * mem[1] - largest available free block in the pool
  901. * mem[2] - total auxiliary memory free
  902. * mem[3] - largest auxiliary free block
  903. */
  904. return mem[0] / 1024;
  905. }
  906. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  907. else if( gglHasExtension(NVX_gpu_memory_info) )
  908. {
  909. GLint mem = 0;
  910. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  911. return mem / 1024;
  912. }
  913. #if defined(TORQUE_OS_WIN)
  914. else if( (gglHasWExtension(AMD_gpu_association)) )
  915. {
  916. // Just assume 1 AMD gpu. Who uses crossfire anyways now? And, crossfire doesn't double
  917. // vram anyways, so does it really matter?
  918. UINT id;
  919. if (wglGetGPUIDsAMD(1, &id) != 0)
  920. {
  921. S32 memorySize;
  922. if (wglGetGPUInfoAMD(id, WGL_GPU_RAM_AMD, GL_INT, 1, &memorySize) != -1)
  923. {
  924. // memory size is returned in MB
  925. return memorySize;
  926. }
  927. }
  928. }
  929. #endif
  930. #if defined(TORQUE_OS_LINUX)
  931. else if ( (gglHasXExtension(NULL, NULL, MESA_query_renderer)) )
  932. {
  933. // memory size is in mb
  934. U32 memorySize;
  935. glXQueryCurrentRendererIntegerMESA(GLX_RENDERER_VIDEO_MEMORY_MESA, &memorySize);
  936. return memorySize;
  937. }
  938. #endif
  939. // No other way, sad. Probably windows Intel.
  940. return 0;
  941. }
  942. //
  943. // Register this device with GFXInit
  944. //
  945. class GFXGLRegisterDevice
  946. {
  947. public:
  948. GFXGLRegisterDevice()
  949. {
  950. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  951. }
  952. };
  953. static GFXGLRegisterDevice pGLRegisterDevice;
  954. DefineEngineFunction(cycleResources, void, (),, "")
  955. {
  956. static_cast<GFXGLDevice*>(GFX)->zombify();
  957. static_cast<GFXGLDevice*>(GFX)->resurrect();
  958. }