gfxGLDevice.cpp 36 KB

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