gfxGLDevice.cpp 33 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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.textureStorage = mCardProfiler->queryProfile("GL_ARB_texture_storage");
  119. mCapabilities.copyImage = mCardProfiler->queryProfile("GL_ARB_copy_image");
  120. mCapabilities.vertexAttributeBinding = mCardProfiler->queryProfile("GL_ARB_vertex_attrib_binding");
  121. mCapabilities.khrDebug = mCardProfiler->queryProfile("GL_KHR_debug");
  122. mCapabilities.extDebugMarker = mCardProfiler->queryProfile("GL_EXT_debug_marker");
  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. GFXCubemapArray *GFXGLDevice::createCubemapArray()
  382. {
  383. GFXGLCubemapArray* cubeArray = new GFXGLCubemapArray();
  384. cubeArray->registerResourceWithDevice(this);
  385. return cubeArray;
  386. }
  387. void GFXGLDevice::endSceneInternal()
  388. {
  389. // nothing to do for opengl
  390. mCanCurrentlyRender = false;
  391. }
  392. void GFXGLDevice::clear(U32 flags, const LinearColorF& color, F32 z, U32 stencil)
  393. {
  394. // Make sure we have flushed our render target state.
  395. _updateRenderTargets();
  396. bool writeAllColors = true;
  397. bool zwrite = true;
  398. bool writeAllStencil = true;
  399. const GFXStateBlockDesc *desc = NULL;
  400. if (mCurrentGLStateBlock)
  401. {
  402. desc = &mCurrentGLStateBlock->getDesc();
  403. zwrite = desc->zWriteEnable;
  404. writeAllColors = desc->colorWriteRed && desc->colorWriteGreen && desc->colorWriteBlue && desc->colorWriteAlpha;
  405. writeAllStencil = desc->stencilWriteMask == 0xFFFFFFFF;
  406. }
  407. glColorMask(true, true, true, true);
  408. glDepthMask(true);
  409. glStencilMask(0xFFFFFFFF);
  410. glClearColor(color.red, color.green, color.blue, color.alpha);
  411. glClearDepth(z);
  412. glClearStencil(stencil);
  413. GLbitfield clearflags = 0;
  414. clearflags |= (flags & GFXClearTarget) ? GL_COLOR_BUFFER_BIT : 0;
  415. clearflags |= (flags & GFXClearZBuffer) ? GL_DEPTH_BUFFER_BIT : 0;
  416. clearflags |= (flags & GFXClearStencil) ? GL_STENCIL_BUFFER_BIT : 0;
  417. glClear(clearflags);
  418. if(!writeAllColors)
  419. glColorMask(desc->colorWriteRed, desc->colorWriteGreen, desc->colorWriteBlue, desc->colorWriteAlpha);
  420. if(!zwrite)
  421. glDepthMask(false);
  422. if(!writeAllStencil)
  423. glStencilMask(desc->stencilWriteMask);
  424. }
  425. void GFXGLDevice::clearColorAttachment(const U32 attachment, const LinearColorF& color)
  426. {
  427. const GLfloat clearColor[4] = { color.red, color.green, color.blue, color.alpha };
  428. glClearBufferfv(GL_COLOR, attachment, clearColor);
  429. }
  430. // Given a primitive type and a number of primitives, return the number of indexes/vertexes used.
  431. inline GLsizei GFXGLDevice::primCountToIndexCount(GFXPrimitiveType primType, U32 primitiveCount)
  432. {
  433. switch (primType)
  434. {
  435. case GFXPointList :
  436. return primitiveCount;
  437. break;
  438. case GFXLineList :
  439. return primitiveCount * 2;
  440. break;
  441. case GFXLineStrip :
  442. return primitiveCount + 1;
  443. break;
  444. case GFXTriangleList :
  445. return primitiveCount * 3;
  446. break;
  447. case GFXTriangleStrip :
  448. return 2 + primitiveCount;
  449. break;
  450. default:
  451. AssertFatal(false, "GFXGLDevice::primCountToIndexCount - unrecognized prim type");
  452. break;
  453. }
  454. return 0;
  455. }
  456. GFXVertexDecl* GFXGLDevice::allocVertexDecl( const GFXVertexFormat *vertexFormat )
  457. {
  458. PROFILE_SCOPE(GFXGLDevice_allocVertexDecl);
  459. typedef Map<void*, GFXGLVertexDecl> GFXGLVertexDeclMap;
  460. static GFXGLVertexDeclMap declMap;
  461. GFXGLVertexDeclMap::Iterator itr = declMap.find( (void*)vertexFormat->getDescription().c_str() ); // description string are interned, safe to use c_str()
  462. if(itr != declMap.end())
  463. return &itr->value;
  464. GFXGLVertexDecl &decl = declMap[(void*)vertexFormat->getDescription().c_str()];
  465. decl.init(vertexFormat);
  466. return &decl;
  467. }
  468. void GFXGLDevice::setVertexDecl( const GFXVertexDecl *decl )
  469. {
  470. static_cast<const GFXGLVertexDecl*>(decl)->prepareVertexFormat();
  471. }
  472. inline void GFXGLDevice::preDrawPrimitive()
  473. {
  474. if( mStateDirty )
  475. {
  476. updateStates();
  477. }
  478. if(mCurrentShaderConstBuffer)
  479. setShaderConstBufferInternal(mCurrentShaderConstBuffer);
  480. if( mNeedUpdateVertexAttrib )
  481. {
  482. AssertFatal(mCurrVertexDecl, "");
  483. const GFXGLVertexDecl* decl = static_cast<const GFXGLVertexDecl*>(mCurrVertexDecl);
  484. for(int i = 0; i < getNumVertexStreams(); ++i)
  485. {
  486. if(mCurrentVB[i])
  487. {
  488. mCurrentVB[i]->prepare(i, mCurrentVB_Divisor[i]); // GL_ARB_vertex_attrib_binding
  489. decl->prepareBuffer_old( i, mCurrentVB[i]->mBuffer, mCurrentVB_Divisor[i] ); // old vertex buffer/format
  490. }
  491. }
  492. decl->updateActiveVertexAttrib( GFXGL->getOpenglCache()->getCacheVertexAttribActive() );
  493. }
  494. mNeedUpdateVertexAttrib = false;
  495. }
  496. inline void GFXGLDevice::postDrawPrimitive(U32 primitiveCount)
  497. {
  498. mDeviceStatistics.mDrawCalls++;
  499. mDeviceStatistics.mPolyCount += primitiveCount;
  500. }
  501. void GFXGLDevice::drawPrimitive( GFXPrimitiveType primType, U32 vertexStart, U32 primitiveCount )
  502. {
  503. preDrawPrimitive();
  504. if(mCurrentVB[0])
  505. vertexStart += mCurrentVB[0]->mBufferVertexOffset;
  506. if(mDrawInstancesCount)
  507. glDrawArraysInstanced(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount), mDrawInstancesCount);
  508. else
  509. glDrawArrays(GFXGLPrimType[primType], vertexStart, primCountToIndexCount(primType, primitiveCount));
  510. postDrawPrimitive(primitiveCount);
  511. }
  512. void GFXGLDevice::drawIndexedPrimitive( GFXPrimitiveType primType,
  513. U32 startVertex,
  514. U32 minIndex,
  515. U32 numVerts,
  516. U32 startIndex,
  517. U32 primitiveCount )
  518. {
  519. preDrawPrimitive();
  520. U16* buf = (U16*)static_cast<GFXGLPrimitiveBuffer*>(mCurrentPrimitiveBuffer.getPointer())->getBuffer() + startIndex + mCurrentPrimitiveBuffer->mVolatileStart;
  521. const U32 baseVertex = mCurrentVB[0]->mBufferVertexOffset + startVertex;
  522. if(mDrawInstancesCount)
  523. glDrawElementsInstancedBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, mDrawInstancesCount, baseVertex);
  524. else
  525. glDrawElementsBaseVertex(GFXGLPrimType[primType], primCountToIndexCount(primType, primitiveCount), GL_UNSIGNED_SHORT, buf, baseVertex);
  526. postDrawPrimitive(primitiveCount);
  527. }
  528. void GFXGLDevice::setPB(GFXGLPrimitiveBuffer* pb)
  529. {
  530. if(mCurrentPB)
  531. mCurrentPB->finish();
  532. mCurrentPB = pb;
  533. }
  534. void GFXGLDevice::setLightInternal(U32 lightStage, const GFXLightInfo light, bool lightEnable)
  535. {
  536. // ONLY NEEDED ON FFP
  537. }
  538. void GFXGLDevice::setLightMaterialInternal(const GFXLightMaterial mat)
  539. {
  540. // ONLY NEEDED ON FFP
  541. }
  542. void GFXGLDevice::setGlobalAmbientInternal(LinearColorF color)
  543. {
  544. // ONLY NEEDED ON FFP
  545. }
  546. void GFXGLDevice::setTextureInternal(U32 textureUnit, const GFXTextureObject*texture)
  547. {
  548. GFXGLTextureObject *tex = static_cast<GFXGLTextureObject*>(const_cast<GFXTextureObject*>(texture));
  549. if (tex)
  550. {
  551. mActiveTextureType[textureUnit] = tex->getBinding();
  552. tex->bind(textureUnit);
  553. }
  554. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  555. {
  556. glActiveTexture(GL_TEXTURE0 + textureUnit);
  557. glBindTexture(mActiveTextureType[textureUnit], 0);
  558. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  559. mActiveTextureType[textureUnit] = GL_ZERO;
  560. }
  561. }
  562. void GFXGLDevice::setCubemapInternal(U32 textureUnit, const GFXGLCubemap* texture)
  563. {
  564. if(texture)
  565. {
  566. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP;
  567. texture->bind(textureUnit);
  568. }
  569. else if(mActiveTextureType[textureUnit] != GL_ZERO)
  570. {
  571. glActiveTexture(GL_TEXTURE0 + textureUnit);
  572. glBindTexture(mActiveTextureType[textureUnit], 0);
  573. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  574. mActiveTextureType[textureUnit] = GL_ZERO;
  575. }
  576. }
  577. void GFXGLDevice::setCubemapArrayInternal(U32 textureUnit, const GFXGLCubemapArray* texture)
  578. {
  579. if (texture)
  580. {
  581. mActiveTextureType[textureUnit] = GL_TEXTURE_CUBE_MAP_ARRAY_ARB;
  582. texture->bind(textureUnit);
  583. }
  584. else if (mActiveTextureType[textureUnit] != GL_ZERO)
  585. {
  586. glActiveTexture(GL_TEXTURE0 + textureUnit);
  587. glBindTexture(mActiveTextureType[textureUnit], 0);
  588. getOpenglCache()->setCacheBindedTex(textureUnit, mActiveTextureType[textureUnit], 0);
  589. mActiveTextureType[textureUnit] = GL_ZERO;
  590. }
  591. }
  592. void GFXGLDevice::setMatrix( GFXMatrixType mtype, const MatrixF &mat )
  593. {
  594. // ONLY NEEDED ON FFP
  595. }
  596. void GFXGLDevice::setClipRect( const RectI &inRect )
  597. {
  598. AssertFatal(mCurrentRT.isValid(), "GFXGLDevice::setClipRect - must have a render target set to do any rendering operations!");
  599. // Clip the rect against the renderable size.
  600. Point2I size = mCurrentRT->getSize();
  601. RectI maxRect(Point2I(0,0), size);
  602. mClip = inRect;
  603. mClip.intersect(maxRect);
  604. // Create projection matrix. See http://www.opengl.org/documentation/specs/man_pages/hardcopy/GL/html/gl/ortho.html
  605. const F32 left = mClip.point.x;
  606. const F32 right = mClip.point.x + mClip.extent.x;
  607. const F32 bottom = mClip.extent.y;
  608. const F32 top = 0.0f;
  609. const F32 nearPlane = 0.0f;
  610. const F32 farPlane = 1.0f;
  611. const F32 tx = -(right + left)/(right - left);
  612. const F32 ty = -(top + bottom)/(top - bottom);
  613. const F32 tz = -(farPlane + nearPlane)/(farPlane - nearPlane);
  614. static Point4F pt;
  615. pt.set(2.0f / (right - left), 0.0f, 0.0f, 0.0f);
  616. mProjectionMatrix.setColumn(0, pt);
  617. pt.set(0.0f, 2.0f/(top - bottom), 0.0f, 0.0f);
  618. mProjectionMatrix.setColumn(1, pt);
  619. pt.set(0.0f, 0.0f, -2.0f/(farPlane - nearPlane), 0.0f);
  620. mProjectionMatrix.setColumn(2, pt);
  621. pt.set(tx, ty, tz, 1.0f);
  622. mProjectionMatrix.setColumn(3, pt);
  623. // Translate projection matrix.
  624. static MatrixF translate(true);
  625. pt.set(0.0f, -mClip.point.y, 0.0f, 1.0f);
  626. translate.setColumn(3, pt);
  627. mProjectionMatrix *= translate;
  628. setMatrix(GFXMatrixProjection, mProjectionMatrix);
  629. MatrixF mTempMatrix(true);
  630. setViewMatrix( mTempMatrix );
  631. setWorldMatrix( mTempMatrix );
  632. // Set the viewport to the clip rect
  633. RectI viewport(mClip.point.x, mClip.point.y, mClip.extent.x, mClip.extent.y);
  634. setViewport(viewport);
  635. }
  636. /// Creates a state block object based on the desc passed in. This object
  637. /// represents an immutable state.
  638. GFXStateBlockRef GFXGLDevice::createStateBlockInternal(const GFXStateBlockDesc& desc)
  639. {
  640. return GFXStateBlockRef(new GFXGLStateBlock(desc));
  641. }
  642. /// Activates a stateblock
  643. void GFXGLDevice::setStateBlockInternal(GFXStateBlock* block, bool force)
  644. {
  645. AssertFatal(dynamic_cast<GFXGLStateBlock*>(block), "GFXGLDevice::setStateBlockInternal - Incorrect stateblock type for this device!");
  646. GFXGLStateBlock* glBlock = static_cast<GFXGLStateBlock*>(block);
  647. GFXGLStateBlock* glCurrent = static_cast<GFXGLStateBlock*>(mCurrentStateBlock.getPointer());
  648. if (force)
  649. glCurrent = NULL;
  650. glBlock->activate(glCurrent); // Doesn't use current yet.
  651. mCurrentGLStateBlock = glBlock;
  652. }
  653. //------------------------------------------------------------------------------
  654. GFXTextureTarget * GFXGLDevice::allocRenderToTextureTarget(bool genMips)
  655. {
  656. GFXGLTextureTarget *targ = new GFXGLTextureTarget(genMips);
  657. targ->registerResourceWithDevice(this);
  658. return targ;
  659. }
  660. GFXFence * GFXGLDevice::createFence()
  661. {
  662. GFXFence* fence = _createPlatformSpecificFence();
  663. if(!fence)
  664. fence = new GFXGeneralFence( this );
  665. fence->registerResourceWithDevice(this);
  666. return fence;
  667. }
  668. GFXOcclusionQuery* GFXGLDevice::createOcclusionQuery()
  669. {
  670. GFXOcclusionQuery *query = new GFXGLOcclusionQuery( this );
  671. query->registerResourceWithDevice(this);
  672. return query;
  673. }
  674. void GFXGLDevice::setupGenericShaders( GenericShaderType type )
  675. {
  676. AssertFatal(type != GSTargetRestore, "");
  677. if( mGenericShader[GSColor] == NULL )
  678. {
  679. ShaderData *shaderData;
  680. shaderData = new ShaderData();
  681. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorV.glsl"));
  682. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/colorP.glsl"));
  683. shaderData->setField("pixVersion", "2.0");
  684. shaderData->registerObject();
  685. mGenericShader[GSColor] = shaderData->getShader();
  686. mGenericShaderBuffer[GSColor] = mGenericShader[GSColor]->allocConstBuffer();
  687. mModelViewProjSC[GSColor] = mGenericShader[GSColor]->getShaderConstHandle( "$modelView" );
  688. Sim::getRootGroup()->addObject(shaderData);
  689. shaderData = new ShaderData();
  690. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureV.glsl"));
  691. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/modColorTextureP.glsl"));
  692. shaderData->setSamplerName("$diffuseMap", 0);
  693. shaderData->setField("pixVersion", "2.0");
  694. shaderData->registerObject();
  695. mGenericShader[GSModColorTexture] = shaderData->getShader();
  696. mGenericShaderBuffer[GSModColorTexture] = mGenericShader[GSModColorTexture]->allocConstBuffer();
  697. mModelViewProjSC[GSModColorTexture] = mGenericShader[GSModColorTexture]->getShaderConstHandle( "$modelView" );
  698. Sim::getRootGroup()->addObject(shaderData);
  699. shaderData = new ShaderData();
  700. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureV.glsl"));
  701. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/addColorTextureP.glsl"));
  702. shaderData->setSamplerName("$diffuseMap", 0);
  703. shaderData->setField("pixVersion", "2.0");
  704. shaderData->registerObject();
  705. mGenericShader[GSAddColorTexture] = shaderData->getShader();
  706. mGenericShaderBuffer[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->allocConstBuffer();
  707. mModelViewProjSC[GSAddColorTexture] = mGenericShader[GSAddColorTexture]->getShaderConstHandle( "$modelView" );
  708. Sim::getRootGroup()->addObject(shaderData);
  709. shaderData = new ShaderData();
  710. shaderData->setField("OGLVertexShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureV.glsl"));
  711. shaderData->setField("OGLPixelShaderFile", ShaderGen::smCommonShaderPath + String("/fixedFunction/gl/textureP.glsl"));
  712. shaderData->setSamplerName("$diffuseMap", 0);
  713. shaderData->setField("pixVersion", "2.0");
  714. shaderData->registerObject();
  715. mGenericShader[GSTexture] = shaderData->getShader();
  716. mGenericShaderBuffer[GSTexture] = mGenericShader[GSTexture]->allocConstBuffer();
  717. mModelViewProjSC[GSTexture] = mGenericShader[GSTexture]->getShaderConstHandle( "$modelView" );
  718. Sim::getRootGroup()->addObject(shaderData);
  719. }
  720. MatrixF tempMatrix = mProjectionMatrix * mViewMatrix * mWorldMatrix[mWorldStackSize];
  721. mGenericShaderBuffer[type]->setSafe(mModelViewProjSC[type], tempMatrix);
  722. setShader( mGenericShader[type] );
  723. setShaderConstBuffer( mGenericShaderBuffer[type] );
  724. }
  725. GFXShader* GFXGLDevice::createShader()
  726. {
  727. GFXGLShader* shader = new GFXGLShader();
  728. shader->registerResourceWithDevice( this );
  729. return shader;
  730. }
  731. void GFXGLDevice::setShader(GFXShader *shader, bool force)
  732. {
  733. if(mCurrentShader == shader && !force)
  734. return;
  735. if ( shader )
  736. {
  737. GFXGLShader *glShader = static_cast<GFXGLShader*>( shader );
  738. glShader->useProgram();
  739. mCurrentShader = shader;
  740. }
  741. else
  742. {
  743. setupGenericShaders();
  744. }
  745. }
  746. void GFXGLDevice::setShaderConstBufferInternal(GFXShaderConstBuffer* buffer)
  747. {
  748. PROFILE_SCOPE(GFXGLDevice_setShaderConstBufferInternal);
  749. static_cast<GFXGLShaderConstBuffer*>(buffer)->activate();
  750. }
  751. U32 GFXGLDevice::getNumSamplers() const
  752. {
  753. return getMin((U32)TEXTURE_STAGE_COUNT,mPixelShaderVersion > 0.001f ? mMaxShaderTextures : mMaxFFTextures);
  754. }
  755. GFXTextureObject* GFXGLDevice::getDefaultDepthTex() const
  756. {
  757. if(mWindowRT && mWindowRT->getPointer())
  758. return static_cast<GFXGLWindowTarget*>( mWindowRT->getPointer() )->mBackBufferDepthTex.getPointer();
  759. return NULL;
  760. }
  761. U32 GFXGLDevice::getNumRenderTargets() const
  762. {
  763. return mMaxTRColors;
  764. }
  765. void GFXGLDevice::_updateRenderTargets()
  766. {
  767. if ( mRTDirty || mCurrentRT->isPendingState() )
  768. {
  769. if ( mRTDeactivate )
  770. {
  771. mRTDeactivate->deactivate();
  772. mRTDeactivate = NULL;
  773. }
  774. // NOTE: The render target changes is not really accurate
  775. // as the GFXTextureTarget supports MRT internally. So when
  776. // we activate a GFXTarget it could result in multiple calls
  777. // to SetRenderTarget on the actual device.
  778. mDeviceStatistics.mRenderTargetChanges++;
  779. GFXGLTextureTarget *tex = dynamic_cast<GFXGLTextureTarget*>( mCurrentRT.getPointer() );
  780. if ( tex )
  781. {
  782. tex->applyState();
  783. tex->makeActive();
  784. }
  785. else
  786. {
  787. GFXGLWindowTarget *win = dynamic_cast<GFXGLWindowTarget*>( mCurrentRT.getPointer() );
  788. AssertFatal( win != NULL,
  789. "GFXGLDevice::_updateRenderTargets() - invalid target subclass passed!" );
  790. win->makeActive();
  791. if( win->mContext != static_cast<GFXGLDevice*>(GFX)->mContext )
  792. {
  793. mRTDirty = false;
  794. GFX->updateStates(true);
  795. }
  796. }
  797. mRTDirty = false;
  798. }
  799. if ( mViewportDirty )
  800. {
  801. glViewport( mViewport.point.x, mViewport.point.y, mViewport.extent.x, mViewport.extent.y );
  802. mViewportDirty = false;
  803. }
  804. }
  805. GFXFormat GFXGLDevice::selectSupportedFormat( GFXTextureProfile* profile,
  806. const Vector<GFXFormat>& formats,
  807. bool texture,
  808. bool mustblend,
  809. bool mustfilter )
  810. {
  811. for(U32 i = 0; i < formats.size(); i++)
  812. {
  813. // Single channel textures are not supported by FBOs.
  814. if(profile->testFlag(GFXTextureProfile::RenderTarget) && (formats[i] == GFXFormatA8 || formats[i] == GFXFormatL8 || formats[i] == GFXFormatL16))
  815. continue;
  816. if(GFXGLTextureInternalFormat[formats[i]] == GL_ZERO)
  817. continue;
  818. return formats[i];
  819. }
  820. return GFXFormatR8G8B8A8;
  821. }
  822. U32 GFXGLDevice::getTotalVideoMemory_GL_EXT()
  823. {
  824. // Source: http://www.opengl.org/registry/specs/ATI/meminfo.txt
  825. if( gglHasExtension(ATI_meminfo) )
  826. {
  827. GLint mem[4] = {0};
  828. glGetIntegerv(GL_TEXTURE_FREE_MEMORY_ATI, mem); // Retrieve the texture pool
  829. /* With mem[0] i get only the total memory free in the pool in KB
  830. *
  831. * mem[0] - total memory free in the pool
  832. * mem[1] - largest available free block in the pool
  833. * mem[2] - total auxiliary memory free
  834. * mem[3] - largest auxiliary free block
  835. */
  836. return mem[0] / 1024;
  837. }
  838. //source http://www.opengl.org/registry/specs/NVX/gpu_memory_info.txt
  839. else if( gglHasExtension(NVX_gpu_memory_info) )
  840. {
  841. GLint mem = 0;
  842. glGetIntegerv(GL_GPU_MEMORY_INFO_TOTAL_AVAILABLE_MEMORY_NVX, &mem);
  843. return mem / 1024;
  844. }
  845. // TODO OPENGL, add supprt for INTEL cards.
  846. return 0;
  847. }
  848. //
  849. // Register this device with GFXInit
  850. //
  851. class GFXGLRegisterDevice
  852. {
  853. public:
  854. GFXGLRegisterDevice()
  855. {
  856. GFXInit::getRegisterDeviceSignal().notify(&GFXGLDevice::enumerateAdapters);
  857. }
  858. };
  859. static GFXGLRegisterDevice pGLRegisterDevice;
  860. DefineEngineFunction(cycleResources, void, (),, "")
  861. {
  862. static_cast<GFXGLDevice*>(GFX)->zombify();
  863. static_cast<GFXGLDevice*>(GFX)->resurrect();
  864. }