gfxGLDevice.cpp 34 KB

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