gfxGLDevice.cpp 37 KB

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