gfxGLDevice.cpp 32 KB

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