gfxGLDevice.cpp 32 KB

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