CmGLRenderSystem.cpp 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in*
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.s
  22. -----------------------------------------------------------------------------
  23. */
  24. #include "CmGLRenderSystem.h"
  25. #include "CmRenderSystem.h"
  26. #include "CmGLTextureManager.h"
  27. #include "CmGLVertexBuffer.h"
  28. #include "CmGLIndexBuffer.h"
  29. #include "CmGLUtil.h"
  30. #include "CmGLSLGpuProgram.h"
  31. #include "CmGLSLProgram.h"
  32. #include "CmGLGpuProgramManager.h"
  33. #include "CmException.h"
  34. #include "CmGLSLExtSupport.h"
  35. #include "CmGLOcclusionQuery.h"
  36. #include "CmGLContext.h"
  37. #include "CmGLSupport.h"
  38. #include "CmAsyncOp.h"
  39. #include "CmBlendState.h"
  40. #include "CmRasterizerState.h"
  41. #include "CmDepthStencilState.h"
  42. #include "CmGLRenderTexture.h"
  43. #include "CmGLRenderWindowManager.h"
  44. #include "CmGLSLProgramPipelineManager.h"
  45. #include "CmRenderStateManager.h"
  46. #include "CmGpuParams.h"
  47. #include "CmGLGpuParamBlockBuffer.h"
  48. #include "CmCoreThread.h"
  49. #include "CmGLQueryManager.h"
  50. #include "CmDebug.h"
  51. // Convenience macro from ARB_vertex_buffer_object spec
  52. #define VBO_BUFFER_OFFSET(i) ((char *)NULL + (i))
  53. #if CM_THREAD_SUPPORT != 1
  54. GLenum __stdcall glewContextInit (CamelotFramework::GLSupport *glSupport);
  55. #endif
  56. namespace CamelotFramework
  57. {
  58. /************************************************************************/
  59. /* PUBLIC INTERFACE */
  60. /************************************************************************/
  61. GLRenderSystem::GLRenderSystem()
  62. : mDepthWrite(true),
  63. mGLSLProgramFactory(nullptr),
  64. mCgProgramFactory(nullptr),
  65. mProgramPipelineManager(nullptr),
  66. mActivePipeline(nullptr),
  67. mActiveTextureUnit(0),
  68. mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280),
  69. mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0),
  70. mStencilReadMask(0xFFFFFFFF),
  71. mStencilWriteMask(0xFFFFFFFF),
  72. mStencilCompareFront(CMPF_ALWAYS_PASS),
  73. mStencilCompareBack(CMPF_ALWAYS_PASS),
  74. mStencilRefValue(0),
  75. mFragmentTexOffset(0),
  76. mVertexTexOffset(0),
  77. mGeometryTexOffset(0),
  78. mTextureTypes(nullptr),
  79. mNumTextureTypes(0),
  80. mFragmentUBOffset(0),
  81. mVertexUBOffset(0),
  82. mGeometryUBOffset(0),
  83. mHullUBOffset(0),
  84. mDomainUBOffset(0),
  85. mComputeUBOffset(0),
  86. mDrawCallInProgress(false),
  87. mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  88. {
  89. // Get our GLSupport
  90. mGLSupport = CamelotFramework::getGLSupport();
  91. mViewMatrix = Matrix4::IDENTITY;
  92. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  93. mCurrentContext = 0;
  94. mMainContext = 0;
  95. mGLInitialised = false;
  96. mMinFilter = FO_LINEAR;
  97. mMipFilter = FO_POINT;
  98. mProgramPipelineManager = cm_new<GLSLProgramPipelineManager>();
  99. }
  100. GLRenderSystem::~GLRenderSystem()
  101. {
  102. }
  103. const String& GLRenderSystem::getName(void) const
  104. {
  105. static String strName("GLRenderSystem");
  106. return strName;
  107. }
  108. const String& GLRenderSystem::getShadingLanguageName() const
  109. {
  110. static String strName("glsl");
  111. return strName;
  112. }
  113. void GLRenderSystem::initialize_internal(AsyncOp& asyncOp)
  114. {
  115. THROW_IF_NOT_CORE_THREAD;
  116. mGLSupport->start();
  117. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  118. RenderStateManager::startUp<RenderStateManager>();
  119. QueryManager::startUp<GLQueryManager>();
  120. // Initialize a window so we have something to create a GL context with
  121. RenderWindowPtr primaryWindow = RenderWindow::create(mPrimaryWindowDesc);
  122. // Get the context from the window and finish initialization
  123. GLContext *context = nullptr;
  124. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  125. initializeContext(context);
  126. checkForErrors();
  127. Vector<CamelotFramework::String>::type tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  128. if (!tokens.empty())
  129. {
  130. mDriverVersion.major = parseInt(tokens[0]);
  131. if (tokens.size() > 1)
  132. mDriverVersion.minor = parseInt(tokens[1]);
  133. if (tokens.size() > 2)
  134. mDriverVersion.release = parseInt(tokens[2]);
  135. }
  136. mDriverVersion.build = 0;
  137. // Initialise GL after the first window has been created
  138. // TODO: fire this from emulation options, and don't duplicate float and Current capabilities
  139. mCurrentCapabilities = createRenderSystemCapabilities();
  140. checkForErrors();
  141. initialiseFromRenderSystemCapabilities(mCurrentCapabilities);
  142. checkForErrors();
  143. // Initialise the main context
  144. oneTimeContextInitialization();
  145. checkForErrors();
  146. mGLInitialised = true;
  147. RenderSystem::initialize_internal(asyncOp);
  148. asyncOp.completeOperation(primaryWindow);
  149. }
  150. void GLRenderSystem::destroy_internal()
  151. {
  152. RenderSystem::destroy_internal();
  153. // Deleting the GLSL program factory
  154. if (mGLSLProgramFactory)
  155. {
  156. // Remove from manager safely
  157. HighLevelGpuProgramManager::instance().removeFactory(mGLSLProgramFactory);
  158. cm_delete(mGLSLProgramFactory);
  159. mGLSLProgramFactory = nullptr;
  160. }
  161. // Deleting Cg GLSL program factory
  162. if (mCgProgramFactory)
  163. {
  164. // Remove from manager safely
  165. HighLevelGpuProgramManager::instance().removeFactory(mCgProgramFactory);
  166. cm_delete(mCgProgramFactory);
  167. mCgProgramFactory = nullptr;
  168. }
  169. // Deleting the GPU program manager and hardware buffer manager. Has to be done before the mGLSupport->stop().
  170. GpuProgramManager::shutDown();
  171. HardwareBufferManager::shutDown();
  172. GLRTTManager::shutDown();
  173. mBoundVertexBuffers.clear();
  174. mBoundVertexDeclaration = nullptr;
  175. mBoundIndexBuffer = nullptr;
  176. mCurrentVertexProgram = nullptr;
  177. mCurrentFragmentProgram = nullptr;
  178. mCurrentGeometryProgram = nullptr;
  179. mCurrentHullProgram = nullptr;
  180. mCurrentDomainProgram = nullptr;
  181. mGLSupport->stop();
  182. TextureManager::shutDown();
  183. QueryManager::shutDown();
  184. RenderWindowManager::shutDown();
  185. RenderStateManager::shutDown();
  186. // There will be a new initial window and so forth, thus any call to test
  187. // some params will access an invalid pointer, so it is best to reset
  188. // the whole state.
  189. mGLInitialised = 0;
  190. if(mProgramPipelineManager != nullptr)
  191. cm_delete(mProgramPipelineManager);
  192. if(mGLSupport)
  193. cm_delete(mGLSupport);
  194. if(mTextureTypes != nullptr)
  195. cm_deleteN(mTextureTypes, mNumTextureTypes);
  196. }
  197. //---------------------------------------------------------------------
  198. void GLRenderSystem::bindGpuProgram(HGpuProgram prg)
  199. {
  200. THROW_IF_NOT_CORE_THREAD;
  201. GpuProgramPtr bindingPrg = prg->getBindingDelegate();
  202. GLSLGpuProgramPtr glprg = std::static_pointer_cast<GLSLGpuProgram>(bindingPrg);
  203. switch (glprg->getType())
  204. {
  205. case GPT_VERTEX_PROGRAM:
  206. if (mCurrentVertexProgram != glprg)
  207. {
  208. unbindGpuProgram(glprg->getType());
  209. mCurrentVertexProgram = glprg;
  210. }
  211. break;
  212. case GPT_FRAGMENT_PROGRAM:
  213. if (mCurrentFragmentProgram != glprg)
  214. {
  215. unbindGpuProgram(glprg->getType());
  216. mCurrentFragmentProgram = glprg;
  217. }
  218. break;
  219. case GPT_GEOMETRY_PROGRAM:
  220. if (mCurrentGeometryProgram != glprg)
  221. {
  222. unbindGpuProgram(glprg->getType());
  223. mCurrentGeometryProgram = glprg;
  224. }
  225. break;
  226. case GPT_DOMAIN_PROGRAM:
  227. if (mCurrentDomainProgram != glprg)
  228. {
  229. unbindGpuProgram(glprg->getType());
  230. mCurrentDomainProgram = glprg;
  231. }
  232. break;
  233. case GPT_HULL_PROGRAM:
  234. if (mCurrentHullProgram != glprg)
  235. {
  236. unbindGpuProgram(glprg->getType());
  237. mCurrentHullProgram = glprg;
  238. }
  239. break;
  240. }
  241. RenderSystem::bindGpuProgram(prg);
  242. }
  243. //---------------------------------------------------------------------
  244. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  245. {
  246. THROW_IF_NOT_CORE_THREAD;
  247. setActiveProgram(gptype, nullptr);
  248. RenderSystem::unbindGpuProgram(gptype);
  249. }
  250. //-----------------------------------------------------------------------------
  251. void GLRenderSystem::bindGpuParams(GpuProgramType gptype, BindableGpuParams& bindableParams)
  252. {
  253. THROW_IF_NOT_CORE_THREAD;
  254. bindableParams.updateHardwareBuffers();
  255. const GpuParamDesc& paramDesc = bindableParams.getParamDesc();
  256. GLSLGpuProgramPtr activeProgram = getActiveProgram(gptype);
  257. GLuint glProgram = activeProgram->getGLSLProgram()->getGLHandle();
  258. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  259. {
  260. HTexture texture = bindableParams.getTexture(iter->second.slot);
  261. if(!texture.isLoaded())
  262. setTexture(gptype, iter->second.slot, false, nullptr);
  263. else
  264. setTexture(gptype, iter->second.slot, true, texture.getInternalPtr());
  265. }
  266. UINT32 texUnit = 0;
  267. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  268. {
  269. HSamplerState& samplerState = bindableParams.getSamplerState(iter->second.slot);
  270. if(samplerState == nullptr)
  271. setSamplerState(gptype, iter->second.slot, SamplerState::getDefault());
  272. else
  273. setSamplerState(gptype, iter->second.slot, samplerState.getInternalPtr());
  274. glProgramUniform1i(glProgram, iter->second.slot, getGLTextureUnit(gptype, texUnit));
  275. texUnit++;
  276. }
  277. UINT8* uniformBufferData = nullptr;
  278. UINT32 blockBinding = 0;
  279. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  280. {
  281. GpuParamBlockBufferPtr paramBlockBuffer = bindableParams.getParamBlockBuffer(iter->second.slot);
  282. if(paramBlockBuffer == nullptr)
  283. continue;
  284. if(iter->second.slot == 0)
  285. {
  286. // 0 means uniforms are not in block, in which case we handle it specially
  287. if(uniformBufferData == nullptr)
  288. {
  289. uniformBufferData = (UINT8*)cm_alloc<ScratchAlloc>(paramBlockBuffer->getSize());
  290. paramBlockBuffer->readData(uniformBufferData);
  291. }
  292. continue;
  293. }
  294. const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(paramBlockBuffer.get());
  295. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  296. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  297. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  298. blockBinding++;
  299. }
  300. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  301. {
  302. const GpuParamDataDesc& paramDesc = iter->second;
  303. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  304. continue;
  305. const UINT8* ptrData = uniformBufferData + paramDesc.cpuMemOffset * sizeof(UINT32);
  306. switch(paramDesc.type)
  307. {
  308. case GCT_FLOAT1:
  309. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  310. break;
  311. case GCT_FLOAT2:
  312. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  313. break;
  314. case GCT_FLOAT3:
  315. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  316. break;
  317. case GCT_FLOAT4:
  318. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  319. break;
  320. case GCT_MATRIX_2X2:
  321. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  322. GL_FALSE, (GLfloat*)ptrData);
  323. break;
  324. case GCT_MATRIX_2X3:
  325. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  326. GL_FALSE, (GLfloat*)ptrData);
  327. break;
  328. case GCT_MATRIX_2X4:
  329. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  330. GL_FALSE, (GLfloat*)ptrData);
  331. break;
  332. case GCT_MATRIX_3X2:
  333. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  334. GL_FALSE, (GLfloat*)ptrData);
  335. break;
  336. case GCT_MATRIX_3X3:
  337. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  338. GL_FALSE, (GLfloat*)ptrData);
  339. break;
  340. case GCT_MATRIX_3X4:
  341. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  342. GL_FALSE, (GLfloat*)ptrData);
  343. break;
  344. case GCT_MATRIX_4X2:
  345. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  346. GL_FALSE, (GLfloat*)ptrData);
  347. break;
  348. case GCT_MATRIX_4X3:
  349. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  350. GL_FALSE, (GLfloat*)ptrData);
  351. break;
  352. case GCT_MATRIX_4X4:
  353. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  354. GL_FALSE, (GLfloat*)ptrData);
  355. break;
  356. case GCT_INT1:
  357. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  358. break;
  359. case GCT_INT2:
  360. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  361. break;
  362. case GCT_INT3:
  363. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  364. break;
  365. case GCT_INT4:
  366. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  367. break;
  368. case GPDT_BOOL:
  369. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  370. break;
  371. case GCT_UNKNOWN:
  372. break;
  373. }
  374. }
  375. if(uniformBufferData != nullptr)
  376. {
  377. cm_free<ScratchAlloc>(uniformBufferData);
  378. }
  379. }
  380. //-----------------------------------------------------------------------------
  381. void GLRenderSystem::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const TexturePtr &texPtr)
  382. {
  383. THROW_IF_NOT_CORE_THREAD;
  384. unit = getGLTextureUnit(gptype, unit);
  385. GLTexturePtr tex = std::static_pointer_cast<GLTexture>(texPtr);
  386. GLenum lastTextureType = mTextureTypes[unit];
  387. if (!activateGLTextureUnit(unit))
  388. return;
  389. if (enabled && tex)
  390. {
  391. mTextureTypes[unit] = tex->getGLTextureTarget();
  392. glBindTexture(mTextureTypes[unit], tex->getGLID());
  393. }
  394. else
  395. {
  396. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  397. // - If a non-2D sampler is used, the texture will still be displayed
  398. // bind zero texture
  399. glBindTexture(GL_TEXTURE_2D, 0);
  400. }
  401. activateGLTextureUnit(0);
  402. }
  403. //-----------------------------------------------------------------------
  404. void GLRenderSystem::setSamplerState(GpuProgramType gptype, UINT16 unit, const SamplerStatePtr& state)
  405. {
  406. THROW_IF_NOT_CORE_THREAD;
  407. unit = getGLTextureUnit(gptype, unit);
  408. // Set texture layer filtering
  409. setTextureFiltering(unit, FT_MIN, state->getTextureFiltering(FT_MIN));
  410. setTextureFiltering(unit, FT_MAG, state->getTextureFiltering(FT_MAG));
  411. setTextureFiltering(unit, FT_MIP, state->getTextureFiltering(FT_MIP));
  412. // Set texture anisotropy
  413. setTextureAnisotropy(unit, state->getTextureAnisotropy());
  414. // Set mipmap biasing
  415. setTextureMipmapBias(unit, state->getTextureMipmapBias());
  416. // Texture addressing mode
  417. const UVWAddressingMode& uvw = state->getTextureAddressingMode();
  418. setTextureAddressingMode(unit, uvw);
  419. // Set border color
  420. setTextureBorderColor(unit, state->getBorderColor());
  421. }
  422. //-----------------------------------------------------------------------------
  423. void GLRenderSystem::setBlendState(const BlendStatePtr& blendState)
  424. {
  425. THROW_IF_NOT_CORE_THREAD;
  426. // Alpha to coverage
  427. setAlphaToCoverage(blendState->getAlphaToCoverageEnabled());
  428. // Blend states
  429. // DirectX 9 doesn't allow us to specify blend state per render target, so we just use the first one.
  430. if(blendState->getBlendEnabled(0))
  431. {
  432. setSceneBlending(blendState->getSrcBlend(0), blendState->getDstBlend(0), blendState->getAlphaSrcBlend(0), blendState->getAlphaDstBlend(0)
  433. , blendState->getBlendOperation(0), blendState->getAlphaBlendOperation(0));
  434. }
  435. else
  436. {
  437. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  438. }
  439. // Color write mask
  440. UINT8 writeMask = blendState->getRenderTargetWriteMask(0);
  441. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  442. }
  443. //----------------------------------------------------------------------
  444. void GLRenderSystem::setRasterizerState(const RasterizerStatePtr& rasterizerState)
  445. {
  446. THROW_IF_NOT_CORE_THREAD;
  447. setDepthBias((float)rasterizerState->getDepthBias(), rasterizerState->getSlopeScaledDepthBias());
  448. setCullingMode(rasterizerState->getCullMode());
  449. setPolygonMode(rasterizerState->getPolygonMode());
  450. setScissorTestEnable(rasterizerState->getScissorEnable());
  451. }
  452. //---------------------------------------------------------------------
  453. void GLRenderSystem::setDepthStencilState(const DepthStencilStatePtr& depthStencilState, UINT32 stencilRefValue)
  454. {
  455. THROW_IF_NOT_CORE_THREAD;
  456. // Set stencil buffer options
  457. setStencilCheckEnabled(depthStencilState->getStencilEnable());
  458. setStencilBufferOperations(depthStencilState->getStencilFrontFailOp(), depthStencilState->getStencilFrontZFailOp(), depthStencilState->getStencilFrontPassOp(), true);
  459. setStencilBufferFunc(depthStencilState->getStencilFrontCompFunc(), depthStencilState->getStencilReadMask(), true);
  460. setStencilBufferOperations(depthStencilState->getStencilBackFailOp(), depthStencilState->getStencilBackZFailOp(), depthStencilState->getStencilBackPassOp(), false);
  461. setStencilBufferFunc(depthStencilState->getStencilBackCompFunc(), depthStencilState->getStencilReadMask(), false);
  462. setStencilBufferWriteMask(depthStencilState->getStencilWriteMask());
  463. // Set depth buffer options
  464. setDepthBufferCheckEnabled(depthStencilState->getDepthReadEnable());
  465. setDepthBufferWriteEnabled(depthStencilState->getDepthWriteEnable());
  466. setDepthBufferFunction(depthStencilState->getDepthComparisonFunc());
  467. // Set stencil ref value
  468. setStencilRefValue(stencilRefValue);
  469. }
  470. //-----------------------------------------------------------------------------
  471. void GLRenderSystem::setViewport(const ViewportPtr& vp)
  472. {
  473. THROW_IF_NOT_CORE_THREAD;
  474. assert(vp != nullptr);
  475. RenderTargetPtr target;
  476. target = vp->getTarget();
  477. setRenderTarget(target);
  478. // Calculate the "lower-left" corner of the viewport
  479. mViewportWidth = vp->getWidth();
  480. mViewportHeight = vp->getHeight();
  481. mViewportLeft = vp->getX();
  482. mViewportTop = vp->getY();
  483. if (!target->requiresTextureFlipping())
  484. {
  485. // Convert "upper-left" corner to "lower-left"
  486. mViewportTop = target->getHeight() - mViewportHeight - mViewportTop;
  487. }
  488. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  489. // Configure the viewport clipping
  490. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  491. }
  492. //---------------------------------------------------------------------
  493. void GLRenderSystem::setRenderTarget(RenderTargetPtr target)
  494. {
  495. THROW_IF_NOT_CORE_THREAD;
  496. mActiveRenderTarget = target;
  497. // Switch context if different from current one
  498. GLContext *newContext = 0;
  499. target->getCustomAttribute("GLCONTEXT", &newContext);
  500. if(newContext && mCurrentContext != newContext)
  501. {
  502. switchContext(newContext);
  503. }
  504. GLFrameBufferObject *fbo = 0;
  505. target->getCustomAttribute("FBO", &fbo);
  506. if(fbo)
  507. fbo->bind();
  508. else
  509. // Old style context (window/pbuffer) or copying render texture
  510. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  511. if (GLEW_EXT_framebuffer_sRGB)
  512. {
  513. // Enable / disable sRGB states
  514. if (target->isHwGammaEnabled())
  515. {
  516. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  517. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  518. // enabling, but GL spec says incapable surfaces ignore the setting
  519. // anyway. We test the capability to enable isHardwareGammaEnabled.
  520. }
  521. else
  522. {
  523. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  524. }
  525. }
  526. }
  527. //-----------------------------------------------------------------------------
  528. void GLRenderSystem::beginFrame(void)
  529. {
  530. THROW_IF_NOT_CORE_THREAD;
  531. // Activate the viewport clipping
  532. glEnable(GL_SCISSOR_TEST);
  533. }
  534. //-----------------------------------------------------------------------------
  535. void GLRenderSystem::endFrame(void)
  536. {
  537. THROW_IF_NOT_CORE_THREAD;
  538. // Deactivate the viewport clipping.
  539. glDisable(GL_SCISSOR_TEST);
  540. // unbind GPU programs at end of frame
  541. // this is mostly to avoid holding bound programs that might get deleted
  542. // outside via the resource manager
  543. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  544. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  545. }
  546. //---------------------------------------------------------------------
  547. void GLRenderSystem::setVertexBuffers(UINT32 index, VertexBufferPtr* buffers, UINT32 numBuffers)
  548. {
  549. THROW_IF_NOT_CORE_THREAD;
  550. for(UINT32 i = 0; i < numBuffers; i++)
  551. {
  552. mBoundVertexBuffers[index + i] = buffers[i];
  553. }
  554. }
  555. //---------------------------------------------------------------------
  556. void GLRenderSystem::setVertexDeclaration(VertexDeclarationPtr vertexDeclaration)
  557. {
  558. THROW_IF_NOT_CORE_THREAD;
  559. mBoundVertexDeclaration = vertexDeclaration;
  560. }
  561. //---------------------------------------------------------------------
  562. void GLRenderSystem::setDrawOperation(DrawOperationType op)
  563. {
  564. THROW_IF_NOT_CORE_THREAD;
  565. mCurrentDrawOperation = op;
  566. }
  567. //---------------------------------------------------------------------
  568. void GLRenderSystem::setIndexBuffer(const IndexBufferPtr& buffer)
  569. {
  570. THROW_IF_NOT_CORE_THREAD;
  571. mBoundIndexBuffer = buffer;
  572. }
  573. //---------------------------------------------------------------------
  574. void GLRenderSystem::draw(UINT32 vertexOffset, UINT32 vertexCount)
  575. {
  576. // Find the correct type to render
  577. GLint primType = getGLDrawMode();
  578. beginDraw();
  579. glDrawArrays(primType, vertexOffset, vertexCount);
  580. endDraw();
  581. }
  582. //---------------------------------------------------------------------
  583. void GLRenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  584. {
  585. if(mBoundIndexBuffer == nullptr)
  586. {
  587. LOGWRN("Cannot draw indexed because index buffer is not set.");
  588. return;
  589. }
  590. // Find the correct type to render
  591. GLint primType = getGLDrawMode();
  592. beginDraw();
  593. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER,
  594. static_cast<GLIndexBuffer*>(mBoundIndexBuffer.get())->getGLBufferId());
  595. GLenum indexType = (mBoundIndexBuffer->getType() == IndexBuffer::IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  596. glDrawElementsBaseVertex(primType, indexCount, indexType, (GLvoid*)(mBoundIndexBuffer->getIndexSize() * startIndex), vertexOffset);
  597. endDraw();
  598. }
  599. void GLRenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  600. {
  601. THROW_IF_NOT_CORE_THREAD;
  602. mScissorTop = top;
  603. mScissorBottom = bottom;
  604. mScissorLeft = left;
  605. mScissorRight = right;
  606. }
  607. void GLRenderSystem::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  608. {
  609. if(mActiveRenderTarget == nullptr)
  610. return;
  611. RectI clearRect(0, 0, mActiveRenderTarget->getWidth(), mActiveRenderTarget->getHeight());
  612. clearArea(buffers, color, depth, stencil, clearRect);
  613. }
  614. void GLRenderSystem::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  615. {
  616. RectI clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  617. clearArea(buffers, color, depth, stencil, clearRect);
  618. }
  619. void GLRenderSystem::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const RectI& clearRect)
  620. {
  621. THROW_IF_NOT_CORE_THREAD;
  622. if(mActiveRenderTarget == nullptr)
  623. return;
  624. bool colorMask = !mColorWrite[0] || !mColorWrite[1]
  625. || !mColorWrite[2] || !mColorWrite[3];
  626. GLbitfield flags = 0;
  627. if (buffers & FBT_COLOR)
  628. {
  629. flags |= GL_COLOR_BUFFER_BIT;
  630. // Enable buffer for writing if it isn't
  631. if (colorMask)
  632. {
  633. glColorMask(true, true, true, true);
  634. }
  635. glClearColor(color.r, color.g, color.b, color.a);
  636. }
  637. if (buffers & FBT_DEPTH)
  638. {
  639. flags |= GL_DEPTH_BUFFER_BIT;
  640. // Enable buffer for writing if it isn't
  641. if (!mDepthWrite)
  642. {
  643. glDepthMask( GL_TRUE );
  644. }
  645. glClearDepth(depth);
  646. }
  647. if (buffers & FBT_STENCIL)
  648. {
  649. flags |= GL_STENCIL_BUFFER_BIT;
  650. // Enable buffer for writing if it isn't
  651. glStencilMask(0xFFFFFFFF);
  652. glClearStencil(stencil);
  653. }
  654. // Disable scissor test as we want to clear the entire render surface
  655. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  656. UINT32 oldScissorTop = mScissorTop;
  657. UINT32 oldScissorBottom = mScissorBottom;
  658. UINT32 oldScissorLeft = mScissorLeft;
  659. UINT32 oldScissorRight = mScissorRight;
  660. if (scissorTestEnabled)
  661. {
  662. glDisable(GL_SCISSOR_TEST);
  663. }
  664. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  665. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == mActiveRenderTarget->getWidth() && clearRect.height == mActiveRenderTarget->getHeight());
  666. if(!clearEntireTarget)
  667. {
  668. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  669. setScissorTestEnable(true);
  670. }
  671. // Clear buffers
  672. glClear(flags);
  673. if(!clearEntireTarget)
  674. {
  675. setScissorTestEnable(false);
  676. }
  677. // Restore scissor test
  678. if (scissorTestEnabled)
  679. {
  680. glEnable(GL_SCISSOR_TEST);
  681. mScissorTop = oldScissorTop;
  682. mScissorBottom = oldScissorBottom;
  683. mScissorLeft = oldScissorLeft;
  684. mScissorRight = oldScissorRight;
  685. }
  686. // Reset buffer write state
  687. if (!mDepthWrite && (buffers & FBT_DEPTH))
  688. {
  689. glDepthMask( GL_FALSE );
  690. }
  691. if (colorMask && (buffers & FBT_COLOR))
  692. {
  693. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  694. }
  695. if (buffers & FBT_STENCIL)
  696. {
  697. glStencilMask(mStencilWriteMask);
  698. }
  699. }
  700. /************************************************************************/
  701. /* PRIVATE */
  702. /************************************************************************/
  703. //-----------------------------------------------------------------------------
  704. void GLRenderSystem::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  705. {
  706. if (!activateGLTextureUnit(stage))
  707. return;
  708. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  709. getTextureAddressingMode(uvw.u));
  710. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  711. getTextureAddressingMode(uvw.v));
  712. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  713. getTextureAddressingMode(uvw.w));
  714. activateGLTextureUnit(0);
  715. }
  716. //-----------------------------------------------------------------------------
  717. void GLRenderSystem::setTextureBorderColor(UINT16 stage, const Color& colour)
  718. {
  719. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  720. if (activateGLTextureUnit(stage))
  721. {
  722. glTexParameterfv( mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  723. activateGLTextureUnit(0);
  724. }
  725. }
  726. //-----------------------------------------------------------------------------
  727. void GLRenderSystem::setTextureMipmapBias(UINT16 stage, float bias)
  728. {
  729. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  730. {
  731. if (activateGLTextureUnit(stage))
  732. {
  733. glTexEnvf(GL_TEXTURE_FILTER_CONTROL_EXT, GL_TEXTURE_LOD_BIAS_EXT, bias);
  734. activateGLTextureUnit(0);
  735. }
  736. }
  737. }
  738. void GLRenderSystem::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  739. {
  740. GLint sourceBlend = getBlendMode(sourceFactor);
  741. GLint destBlend = getBlendMode(destFactor);
  742. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  743. {
  744. glDisable(GL_BLEND);
  745. }
  746. else
  747. {
  748. glEnable(GL_BLEND);
  749. glBlendFunc(sourceBlend, destBlend);
  750. }
  751. GLint func = GL_FUNC_ADD;
  752. switch(op)
  753. {
  754. case BO_ADD:
  755. func = GL_FUNC_ADD;
  756. break;
  757. case BO_SUBTRACT:
  758. func = GL_FUNC_SUBTRACT;
  759. break;
  760. case BO_REVERSE_SUBTRACT:
  761. func = GL_FUNC_REVERSE_SUBTRACT;
  762. break;
  763. case BO_MIN:
  764. func = GL_MIN;
  765. break;
  766. case BO_MAX:
  767. func = GL_MAX;
  768. break;
  769. }
  770. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  771. {
  772. glBlendEquation(func);
  773. }
  774. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  775. {
  776. glBlendEquationEXT(func);
  777. }
  778. }
  779. //-----------------------------------------------------------------------------
  780. void GLRenderSystem::setSceneBlending(
  781. BlendFactor sourceFactor, BlendFactor destFactor,
  782. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha,
  783. BlendOperation op, BlendOperation alphaOp )
  784. {
  785. GLint sourceBlend = getBlendMode(sourceFactor);
  786. GLint destBlend = getBlendMode(destFactor);
  787. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  788. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  789. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  790. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  791. {
  792. glDisable(GL_BLEND);
  793. }
  794. else
  795. {
  796. glEnable(GL_BLEND);
  797. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  798. }
  799. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  800. switch(op)
  801. {
  802. case BO_ADD:
  803. func = GL_FUNC_ADD;
  804. break;
  805. case BO_SUBTRACT:
  806. func = GL_FUNC_SUBTRACT;
  807. break;
  808. case BO_REVERSE_SUBTRACT:
  809. func = GL_FUNC_REVERSE_SUBTRACT;
  810. break;
  811. case BO_MIN:
  812. func = GL_MIN;
  813. break;
  814. case BO_MAX:
  815. func = GL_MAX;
  816. break;
  817. }
  818. switch(alphaOp)
  819. {
  820. case BO_ADD:
  821. alphaFunc = GL_FUNC_ADD;
  822. break;
  823. case BO_SUBTRACT:
  824. alphaFunc = GL_FUNC_SUBTRACT;
  825. break;
  826. case BO_REVERSE_SUBTRACT:
  827. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  828. break;
  829. case BO_MIN:
  830. alphaFunc = GL_MIN;
  831. break;
  832. case BO_MAX:
  833. alphaFunc = GL_MAX;
  834. break;
  835. }
  836. if(GLEW_VERSION_2_0) {
  837. glBlendEquationSeparate(func, alphaFunc);
  838. }
  839. else if(GLEW_EXT_blend_equation_separate) {
  840. glBlendEquationSeparateEXT(func, alphaFunc);
  841. }
  842. }
  843. //-----------------------------------------------------------------------------
  844. void GLRenderSystem::setAlphaTest(CompareFunction func, unsigned char value)
  845. {
  846. if(func == CMPF_ALWAYS_PASS)
  847. {
  848. glDisable(GL_ALPHA_TEST);
  849. }
  850. else
  851. {
  852. glEnable(GL_ALPHA_TEST);
  853. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  854. }
  855. }
  856. //-----------------------------------------------------------------------------
  857. void GLRenderSystem::setAlphaToCoverage(bool enable)
  858. {
  859. static bool lasta2c = false;
  860. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  861. {
  862. if (enable)
  863. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  864. else
  865. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  866. lasta2c = enable;
  867. }
  868. }
  869. //---------------------------------------------------------------------
  870. void GLRenderSystem::setScissorTestEnable(bool enable)
  871. {
  872. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  873. bool flipping = mActiveRenderTarget->requiresTextureFlipping();
  874. // GL measures from the bottom, not the top
  875. UINT32 targetHeight = mActiveRenderTarget->getHeight();
  876. // Calculate the "lower-left" corner of the viewport
  877. GLsizei x = 0, y = 0, w = 0, h = 0;
  878. if (enable)
  879. {
  880. glEnable(GL_SCISSOR_TEST);
  881. // GL uses width / height rather than right / bottom
  882. x = mScissorLeft;
  883. if (flipping)
  884. y = mScissorTop;
  885. else
  886. y = targetHeight - mScissorBottom;
  887. w = mScissorRight - mScissorLeft;
  888. h = mScissorBottom - mScissorTop;
  889. glScissor(x, y, w, h);
  890. }
  891. else
  892. {
  893. glDisable(GL_SCISSOR_TEST);
  894. // GL requires you to reset the scissor when disabling
  895. w = mViewportWidth;
  896. h = mViewportHeight;
  897. x = mViewportLeft;
  898. if (flipping)
  899. y = mViewportTop;
  900. else
  901. y = targetHeight - mViewportTop - h;
  902. glScissor(x, y, w, h);
  903. }
  904. }
  905. //-----------------------------------------------------------------------------
  906. void GLRenderSystem::setCullingMode(CullingMode mode)
  907. {
  908. mCullingMode = mode;
  909. GLenum cullMode;
  910. switch( mode )
  911. {
  912. case CULL_NONE:
  913. glDisable( GL_CULL_FACE );
  914. return;
  915. default:
  916. case CULL_CLOCKWISE:
  917. cullMode = GL_BACK;
  918. break;
  919. case CULL_COUNTERCLOCKWISE:
  920. cullMode = GL_FRONT;
  921. break;
  922. }
  923. glEnable( GL_CULL_FACE );
  924. glCullFace( cullMode );
  925. }
  926. //-----------------------------------------------------------------------------
  927. void GLRenderSystem::setDepthBufferParams(bool depthTest, bool depthWrite, CompareFunction depthFunction)
  928. {
  929. setDepthBufferCheckEnabled(depthTest);
  930. setDepthBufferWriteEnabled(depthWrite);
  931. setDepthBufferFunction(depthFunction);
  932. }
  933. //-----------------------------------------------------------------------------
  934. void GLRenderSystem::setDepthBufferCheckEnabled(bool enabled)
  935. {
  936. if (enabled)
  937. {
  938. glClearDepth(1.0f);
  939. glEnable(GL_DEPTH_TEST);
  940. }
  941. else
  942. {
  943. glDisable(GL_DEPTH_TEST);
  944. }
  945. }
  946. //-----------------------------------------------------------------------------
  947. void GLRenderSystem::setDepthBufferWriteEnabled(bool enabled)
  948. {
  949. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  950. glDepthMask( flag );
  951. // Store for reference in _beginFrame
  952. mDepthWrite = enabled;
  953. }
  954. //-----------------------------------------------------------------------------
  955. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  956. {
  957. glDepthFunc(convertCompareFunction(func));
  958. }
  959. //-----------------------------------------------------------------------------
  960. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  961. {
  962. if (constantBias != 0 || slopeScaleBias != 0)
  963. {
  964. glEnable(GL_POLYGON_OFFSET_FILL);
  965. glEnable(GL_POLYGON_OFFSET_POINT);
  966. glEnable(GL_POLYGON_OFFSET_LINE);
  967. glPolygonOffset(-slopeScaleBias, -constantBias);
  968. }
  969. else
  970. {
  971. glDisable(GL_POLYGON_OFFSET_FILL);
  972. glDisable(GL_POLYGON_OFFSET_POINT);
  973. glDisable(GL_POLYGON_OFFSET_LINE);
  974. }
  975. }
  976. //-----------------------------------------------------------------------------
  977. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  978. {
  979. glColorMask(red, green, blue, alpha);
  980. // record this
  981. mColorWrite[0] = red;
  982. mColorWrite[1] = blue;
  983. mColorWrite[2] = green;
  984. mColorWrite[3] = alpha;
  985. }
  986. //---------------------------------------------------------------------
  987. void GLRenderSystem::setPolygonMode(PolygonMode level)
  988. {
  989. GLenum glmode;
  990. switch(level)
  991. {
  992. case PM_WIREFRAME:
  993. glmode = GL_LINE;
  994. break;
  995. default:
  996. case PM_SOLID:
  997. glmode = GL_FILL;
  998. break;
  999. }
  1000. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1001. }
  1002. //---------------------------------------------------------------------
  1003. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  1004. {
  1005. if (enabled)
  1006. glEnable(GL_STENCIL_TEST);
  1007. else
  1008. glDisable(GL_STENCIL_TEST);
  1009. }
  1010. //---------------------------------------------------------------------
  1011. void GLRenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp,
  1012. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  1013. {
  1014. if (front)
  1015. {
  1016. glStencilOpSeparate(GL_FRONT,
  1017. convertStencilOp(stencilFailOp),
  1018. convertStencilOp(depthFailOp),
  1019. convertStencilOp(passOp));
  1020. }
  1021. else
  1022. {
  1023. glStencilOpSeparate(GL_BACK,
  1024. convertStencilOp(stencilFailOp, true),
  1025. convertStencilOp(depthFailOp, true),
  1026. convertStencilOp(passOp, true));
  1027. }
  1028. }
  1029. //---------------------------------------------------------------------
  1030. void GLRenderSystem::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1031. {
  1032. mStencilReadMask = mask;
  1033. if(front)
  1034. {
  1035. mStencilCompareFront = func;
  1036. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1037. }
  1038. else
  1039. {
  1040. mStencilCompareBack = func;
  1041. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1042. }
  1043. }
  1044. //---------------------------------------------------------------------
  1045. void GLRenderSystem::setStencilBufferWriteMask(UINT32 mask)
  1046. {
  1047. mStencilWriteMask = mask;
  1048. glStencilMask(mask);
  1049. }
  1050. //---------------------------------------------------------------------
  1051. void GLRenderSystem::setStencilRefValue(UINT32 refValue)
  1052. {
  1053. THROW_IF_NOT_CORE_THREAD;
  1054. mStencilRefValue = refValue;
  1055. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1056. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1057. }
  1058. //---------------------------------------------------------------------
  1059. void GLRenderSystem::setTextureFiltering(UINT16 unit,
  1060. FilterType ftype, FilterOptions fo)
  1061. {
  1062. if (!activateGLTextureUnit(unit))
  1063. return;
  1064. switch(ftype)
  1065. {
  1066. case FT_MIN:
  1067. mMinFilter = fo;
  1068. // Combine with existing mip filter
  1069. glTexParameteri(
  1070. mTextureTypes[unit],
  1071. GL_TEXTURE_MIN_FILTER,
  1072. getCombinedMinMipFilter());
  1073. break;
  1074. case FT_MAG:
  1075. switch (fo)
  1076. {
  1077. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1078. case FO_LINEAR:
  1079. glTexParameteri(
  1080. mTextureTypes[unit],
  1081. GL_TEXTURE_MAG_FILTER,
  1082. GL_LINEAR);
  1083. break;
  1084. case FO_POINT:
  1085. case FO_NONE:
  1086. glTexParameteri(
  1087. mTextureTypes[unit],
  1088. GL_TEXTURE_MAG_FILTER,
  1089. GL_NEAREST);
  1090. break;
  1091. }
  1092. break;
  1093. case FT_MIP:
  1094. mMipFilter = fo;
  1095. // Combine with existing min filter
  1096. glTexParameteri(
  1097. mTextureTypes[unit],
  1098. GL_TEXTURE_MIN_FILTER,
  1099. getCombinedMinMipFilter());
  1100. break;
  1101. }
  1102. activateGLTextureUnit(0);
  1103. }
  1104. //---------------------------------------------------------------------
  1105. void GLRenderSystem::setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy)
  1106. {
  1107. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1108. return;
  1109. if (!activateGLTextureUnit(unit))
  1110. return;
  1111. GLfloat largest_supported_anisotropy = 0;
  1112. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1113. if (maxAnisotropy > largest_supported_anisotropy)
  1114. maxAnisotropy = largest_supported_anisotropy ?
  1115. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1116. if(maxAnisotropy < 1)
  1117. maxAnisotropy = 1;
  1118. if (_getCurrentAnisotropy(unit) != maxAnisotropy)
  1119. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1120. activateGLTextureUnit(0);
  1121. }
  1122. //-----------------------------------------------------------------------------
  1123. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1124. {
  1125. // A note on GL user clipping:
  1126. // When an ARB vertex program is enabled in GL, user clipping is completely
  1127. // disabled. There is no way around this, it's just turned off.
  1128. // When using GLSL, user clipping can work but you have to include a
  1129. // glClipVertex command in your vertex shader.
  1130. // Thus the planes set here may not actually be respected.
  1131. size_t i = 0;
  1132. size_t numClipPlanes;
  1133. GLdouble clipPlane[4];
  1134. // Save previous modelview
  1135. glMatrixMode(GL_MODELVIEW);
  1136. glPushMatrix();
  1137. // just load view matrix (identity world)
  1138. GLfloat mat[16];
  1139. makeGLMatrix(mat, mViewMatrix);
  1140. glLoadMatrixf(mat);
  1141. numClipPlanes = clipPlanes.size();
  1142. for (i = 0; i < numClipPlanes; ++i)
  1143. {
  1144. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1145. const Plane& plane = clipPlanes[i];
  1146. if (i >= 6/*GL_MAX_CLIP_PLANES*/)
  1147. {
  1148. CM_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1149. }
  1150. clipPlane[0] = plane.normal.x;
  1151. clipPlane[1] = plane.normal.y;
  1152. clipPlane[2] = plane.normal.z;
  1153. clipPlane[3] = plane.d;
  1154. glClipPlane(clipPlaneId, clipPlane);
  1155. glEnable(clipPlaneId);
  1156. }
  1157. // disable remaining clip planes
  1158. for ( ; i < 6/*GL_MAX_CLIP_PLANES*/; ++i)
  1159. {
  1160. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1161. }
  1162. // restore matrices
  1163. glPopMatrix();
  1164. }
  1165. //---------------------------------------------------------------------
  1166. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam)
  1167. {
  1168. // TODO - Actually hook this up to Log or something
  1169. }
  1170. //---------------------------------------------------------------------
  1171. void GLRenderSystem::oneTimeContextInitialization()
  1172. {
  1173. // Check for FSAA
  1174. // Enable the extension if it was enabled by the GLSupport
  1175. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1176. {
  1177. int fsaa_active = false;
  1178. glGetIntegerv(GL_SAMPLE_BUFFERS_ARB,(GLint*)&fsaa_active);
  1179. if(fsaa_active)
  1180. {
  1181. glEnable(GL_MULTISAMPLE_ARB);
  1182. }
  1183. }
  1184. // TODO - Replace with OpenGL 4.3 built-in functionality (GL_DEBUG_OUTPUT_SYNCHRONOUS)
  1185. #if CM_DEBUG_MODE
  1186. //if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  1187. //{
  1188. // glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
  1189. // glDebugMessageCallbackARB(&openGlErrorCallback, 0);
  1190. //}
  1191. #endif
  1192. }
  1193. //---------------------------------------------------------------------
  1194. void GLRenderSystem::switchContext(GLContext *context)
  1195. {
  1196. // Unbind GPU programs and rebind to new context later, because
  1197. // scene manager treat render system as ONE 'context' ONLY, and it
  1198. // cached the GPU programs using state.
  1199. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1200. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1201. unbindGpuProgram(GPT_GEOMETRY_PROGRAM);
  1202. unbindGpuProgram(GPT_HULL_PROGRAM);
  1203. unbindGpuProgram(GPT_DOMAIN_PROGRAM);
  1204. // It's ready for switching
  1205. if (mCurrentContext)
  1206. mCurrentContext->endCurrent();
  1207. mCurrentContext = context;
  1208. mCurrentContext->setCurrent();
  1209. // Must reset depth/colour write mask to according with user desired, otherwise,
  1210. // clearFrameBuffer would be wrong because the value we are recorded may be
  1211. // difference with the really state stored in GL context.
  1212. glDepthMask(mDepthWrite);
  1213. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1214. glStencilMask(mStencilWriteMask);
  1215. }
  1216. //---------------------------------------------------------------------
  1217. bool GLRenderSystem::activateGLTextureUnit(UINT16 unit)
  1218. {
  1219. if (mActiveTextureUnit != unit)
  1220. {
  1221. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1222. {
  1223. glActiveTexture(GL_TEXTURE0 + unit);
  1224. mActiveTextureUnit = unit;
  1225. return true;
  1226. }
  1227. else if (!unit)
  1228. {
  1229. // always ok to use the first unit
  1230. return true;
  1231. }
  1232. else
  1233. {
  1234. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1235. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1236. return false;
  1237. }
  1238. }
  1239. else
  1240. {
  1241. return true;
  1242. }
  1243. }
  1244. //---------------------------------------------------------------------
  1245. GLfloat GLRenderSystem::_getCurrentAnisotropy(UINT16 unit)
  1246. {
  1247. GLfloat curAniso = 0;
  1248. glGetTexParameterfv(mTextureTypes[unit],
  1249. GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1250. return curAniso ? curAniso : 1;
  1251. }
  1252. //---------------------------------------------------------------------
  1253. GLuint GLRenderSystem::getCombinedMinMipFilter(void) const
  1254. {
  1255. switch(mMinFilter)
  1256. {
  1257. case FO_ANISOTROPIC:
  1258. case FO_LINEAR:
  1259. switch(mMipFilter)
  1260. {
  1261. case FO_ANISOTROPIC:
  1262. case FO_LINEAR:
  1263. // linear min, linear mip
  1264. return GL_LINEAR_MIPMAP_LINEAR;
  1265. case FO_POINT:
  1266. // linear min, point mip
  1267. return GL_LINEAR_MIPMAP_NEAREST;
  1268. case FO_NONE:
  1269. // linear min, no mip
  1270. return GL_LINEAR;
  1271. }
  1272. break;
  1273. case FO_POINT:
  1274. case FO_NONE:
  1275. switch(mMipFilter)
  1276. {
  1277. case FO_ANISOTROPIC:
  1278. case FO_LINEAR:
  1279. // nearest min, linear mip
  1280. return GL_NEAREST_MIPMAP_LINEAR;
  1281. case FO_POINT:
  1282. // nearest min, point mip
  1283. return GL_NEAREST_MIPMAP_NEAREST;
  1284. case FO_NONE:
  1285. // nearest min, no mip
  1286. return GL_NEAREST;
  1287. }
  1288. break;
  1289. }
  1290. // should never get here
  1291. return 0;
  1292. }
  1293. //---------------------------------------------------------------------
  1294. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1295. {
  1296. switch(op)
  1297. {
  1298. case SOP_KEEP:
  1299. return GL_KEEP;
  1300. case SOP_ZERO:
  1301. return GL_ZERO;
  1302. case SOP_REPLACE:
  1303. return GL_REPLACE;
  1304. case SOP_INCREMENT:
  1305. return invert ? GL_DECR : GL_INCR;
  1306. case SOP_DECREMENT:
  1307. return invert ? GL_INCR : GL_DECR;
  1308. case SOP_INCREMENT_WRAP:
  1309. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1310. case SOP_DECREMENT_WRAP:
  1311. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1312. case SOP_INVERT:
  1313. return GL_INVERT;
  1314. };
  1315. // to keep compiler happy
  1316. return SOP_KEEP;
  1317. }
  1318. //---------------------------------------------------------------------
  1319. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1320. {
  1321. switch(func)
  1322. {
  1323. case CMPF_ALWAYS_FAIL:
  1324. return GL_NEVER;
  1325. case CMPF_ALWAYS_PASS:
  1326. return GL_ALWAYS;
  1327. case CMPF_LESS:
  1328. return GL_LESS;
  1329. case CMPF_LESS_EQUAL:
  1330. return GL_LEQUAL;
  1331. case CMPF_EQUAL:
  1332. return GL_EQUAL;
  1333. case CMPF_NOT_EQUAL:
  1334. return GL_NOTEQUAL;
  1335. case CMPF_GREATER_EQUAL:
  1336. return GL_GEQUAL;
  1337. case CMPF_GREATER:
  1338. return GL_GREATER;
  1339. };
  1340. // to keep compiler happy
  1341. return GL_ALWAYS;
  1342. }
  1343. //-----------------------------------------------------------------------------
  1344. String GLRenderSystem::getErrorDescription(long errCode) const
  1345. {
  1346. const GLubyte *errString = gluErrorString (errCode);
  1347. return (errString != 0) ? String((const char*) errString) : StringUtil::BLANK;
  1348. }
  1349. //-----------------------------------------------------------------------------
  1350. GLint GLRenderSystem::getBlendMode(BlendFactor blendMode) const
  1351. {
  1352. switch(blendMode)
  1353. {
  1354. case BF_ONE:
  1355. return GL_ONE;
  1356. case BF_ZERO:
  1357. return GL_ZERO;
  1358. case BF_DEST_COLOR:
  1359. return GL_DST_COLOR;
  1360. case BF_SOURCE_COLOR:
  1361. return GL_SRC_COLOR;
  1362. case BF_INV_DEST_COLOR:
  1363. return GL_ONE_MINUS_DST_COLOR;
  1364. case BF_INV_SOURCE_COLOR:
  1365. return GL_ONE_MINUS_SRC_COLOR;
  1366. case BF_DEST_ALPHA:
  1367. return GL_DST_ALPHA;
  1368. case BF_SOURCE_ALPHA:
  1369. return GL_SRC_ALPHA;
  1370. case BF_INV_DEST_ALPHA:
  1371. return GL_ONE_MINUS_DST_ALPHA;
  1372. case BF_INV_SOURCE_ALPHA:
  1373. return GL_ONE_MINUS_SRC_ALPHA;
  1374. };
  1375. // to keep compiler happy
  1376. return GL_ONE;
  1377. }
  1378. //-----------------------------------------------------------------------------
  1379. GLint GLRenderSystem::getTextureAddressingMode(
  1380. TextureAddressingMode tam) const
  1381. {
  1382. switch(tam)
  1383. {
  1384. default:
  1385. case TAM_WRAP:
  1386. return GL_REPEAT;
  1387. case TAM_MIRROR:
  1388. return GL_MIRRORED_REPEAT;
  1389. case TAM_CLAMP:
  1390. return GL_CLAMP_TO_EDGE;
  1391. case TAM_BORDER:
  1392. return GL_CLAMP_TO_BORDER;
  1393. }
  1394. }
  1395. //-----------------------------------------------------------------------------
  1396. void GLRenderSystem::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  1397. {
  1398. size_t x = 0;
  1399. for (size_t i = 0; i < 4; i++)
  1400. {
  1401. for (size_t j = 0; j < 4; j++)
  1402. {
  1403. gl_matrix[x] = m[j][i];
  1404. x++;
  1405. }
  1406. }
  1407. }
  1408. //-----------------------------------------------------------------------
  1409. void GLRenderSystem::beginDraw()
  1410. {
  1411. if(mDrawCallInProgress)
  1412. CM_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1413. mDrawCallInProgress = true;
  1414. if(mCurrentVertexProgram == nullptr)
  1415. {
  1416. LOGWRN("Cannot render without a set vertex shader.");
  1417. return;
  1418. }
  1419. if(mBoundVertexDeclaration == nullptr)
  1420. {
  1421. LOGWRN("Cannot render without a set vertex declaration.");
  1422. return;
  1423. }
  1424. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1425. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1426. if(mActivePipeline != pipeline)
  1427. {
  1428. glBindProgramPipeline(pipeline->glHandle);
  1429. mActivePipeline = pipeline;
  1430. }
  1431. void* pBufferData = 0;
  1432. const VertexDeclaration::VertexElementList& decl = mBoundVertexDeclaration->getElements();
  1433. VertexDeclaration::VertexElementList::const_iterator elem, elemEnd;
  1434. elemEnd = decl.end();
  1435. const VertexDeclaration::VertexElementList& inputAttributes = mCurrentVertexProgram->getGLSLProgram()->getInputAttributes().getElements();
  1436. for (elem = decl.begin(); elem != elemEnd; ++elem)
  1437. {
  1438. auto iterFind = mBoundVertexBuffers.find(elem->getStreamIdx());
  1439. if(iterFind == mBoundVertexBuffers.end() || iterFind->second == nullptr)
  1440. continue; // skip unbound elements
  1441. VertexBufferPtr vertexBuffer = iterFind->second;
  1442. bool foundSemantic = false;
  1443. GLint attribLocation = 0;
  1444. for(auto iter = inputAttributes.begin(); iter != inputAttributes.end(); ++iter)
  1445. {
  1446. if(iter->getSemantic() == elem->getSemantic() && iter->getSemanticIdx() == elem->getSemanticIdx())
  1447. {
  1448. foundSemantic = true;
  1449. attribLocation = iter->getOffset();
  1450. break;
  1451. }
  1452. }
  1453. if(!foundSemantic) // Shader needs to have a matching input attribute, otherwise we skip it
  1454. continue;
  1455. // TODO - We might also want to check the size of input and buffer, and make sure they match? Or does OpenGL handle that internally?
  1456. glBindBuffer(GL_ARRAY_BUFFER, static_cast<const GLVertexBuffer*>(vertexBuffer.get())->getGLBufferId());
  1457. pBufferData = VBO_BUFFER_OFFSET(elem->getOffset());
  1458. unsigned int i = 0;
  1459. VertexElementSemantic sem = elem->getSemantic();
  1460. unsigned short typeCount = VertexElement::getTypeCount(elem->getType());
  1461. GLboolean normalised = GL_FALSE;
  1462. switch(elem->getType())
  1463. {
  1464. case VET_COLOR:
  1465. case VET_COLOR_ABGR:
  1466. case VET_COLOR_ARGB:
  1467. normalised = GL_TRUE;
  1468. break;
  1469. default:
  1470. break;
  1471. };
  1472. glVertexAttribPointerARB(
  1473. attribLocation,
  1474. typeCount,
  1475. GLHardwareBufferManager::getGLType(elem->getType()),
  1476. normalised,
  1477. static_cast<GLsizei>(vertexBuffer->getVertexSize()),
  1478. pBufferData);
  1479. glEnableVertexAttribArray(attribLocation);
  1480. mBoundAttributes.push_back(attribLocation);
  1481. }
  1482. }
  1483. //-----------------------------------------------------------------------
  1484. void GLRenderSystem::endDraw()
  1485. {
  1486. if(!mDrawCallInProgress)
  1487. return;
  1488. mDrawCallInProgress = false;
  1489. // unbind any custom attributes
  1490. for (auto ai = mBoundAttributes.begin(); ai != mBoundAttributes.end(); ++ai)
  1491. {
  1492. glDisableVertexAttribArray(*ai);
  1493. }
  1494. glColor4f(1,1,1,1);
  1495. mBoundAttributes.clear();
  1496. }
  1497. //-----------------------------------------------------------------------
  1498. bool GLRenderSystem::checkForErrors() const
  1499. {
  1500. GLenum glErr = glGetError();
  1501. bool errorsFound = false;
  1502. String msg;
  1503. while (glErr != GL_NO_ERROR)
  1504. {
  1505. const char* glerrStr = (const char*)gluErrorString(glErr);
  1506. if (glerrStr)
  1507. {
  1508. msg += String(glerrStr);
  1509. }
  1510. glErr = glGetError();
  1511. errorsFound = true;
  1512. }
  1513. if(errorsFound)
  1514. LOGWRN("OpenGL error: " + msg);
  1515. return errorsFound;
  1516. }
  1517. //-----------------------------------------------------------------------
  1518. GLint GLRenderSystem::getGLDrawMode() const
  1519. {
  1520. GLint primType;
  1521. //Use adjacency if there is a geometry program and it requested adjacency info
  1522. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1523. switch (mCurrentDrawOperation)
  1524. {
  1525. case DOT_POINT_LIST:
  1526. primType = GL_POINTS;
  1527. break;
  1528. case DOT_LINE_LIST:
  1529. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1530. break;
  1531. case DOT_LINE_STRIP:
  1532. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1533. break;
  1534. default:
  1535. case DOT_TRIANGLE_LIST:
  1536. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1537. break;
  1538. case DOT_TRIANGLE_STRIP:
  1539. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1540. break;
  1541. case DOT_TRIANGLE_FAN:
  1542. primType = GL_TRIANGLE_FAN;
  1543. break;
  1544. }
  1545. return primType;
  1546. }
  1547. //-----------------------------------------------------------------------
  1548. void GLRenderSystem::initializeContext(GLContext* primary)
  1549. {
  1550. // Set main and current context
  1551. mMainContext = primary;
  1552. mCurrentContext = mMainContext;
  1553. // Set primary context as active
  1554. if(mCurrentContext)
  1555. mCurrentContext->setCurrent();
  1556. // Setup GLSupport
  1557. mGLSupport->initialiseExtensions();
  1558. // Get extension function pointers
  1559. #if CM_THREAD_SUPPORT != 1
  1560. glewContextInit(mGLSupport);
  1561. #endif
  1562. }
  1563. void GLRenderSystem::initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps)
  1564. {
  1565. if(caps->getRenderSystemName() != getName())
  1566. {
  1567. CM_EXCEPT(InvalidParametersException,
  1568. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  1569. }
  1570. if(caps->hasCapability(RSC_GL1_5_NOVBO))
  1571. {
  1572. // Assign ARB functions same to GL 1.5 version since
  1573. // interface identical
  1574. glBindBufferARB = glBindBuffer;
  1575. glBufferDataARB = glBufferData;
  1576. glBufferSubDataARB = glBufferSubData;
  1577. glDeleteBuffersARB = glDeleteBuffers;
  1578. glGenBuffersARB = glGenBuffers;
  1579. glGetBufferParameterivARB = glGetBufferParameteriv;
  1580. glGetBufferPointervARB = glGetBufferPointerv;
  1581. glGetBufferSubDataARB = glGetBufferSubData;
  1582. glIsBufferARB = glIsBuffer;
  1583. glMapBufferARB = glMapBuffer;
  1584. glUnmapBufferARB = glUnmapBuffer;
  1585. }
  1586. HardwareBufferManager::startUp<GLHardwareBufferManager>();
  1587. checkForErrors();
  1588. // GPU Program Manager setup
  1589. GpuProgramManager::startUp<GLGpuProgramManager>();
  1590. checkForErrors();
  1591. if(caps->isShaderProfileSupported("glsl"))
  1592. {
  1593. mGLSLProgramFactory = cm_new<GLSLProgramFactory>();
  1594. HighLevelGpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  1595. checkForErrors();
  1596. }
  1597. if(caps->isShaderProfileSupported("cg"))
  1598. {
  1599. mCgProgramFactory = cm_new<CgProgramFactory>();
  1600. HighLevelGpuProgramManager::instance().addFactory(mCgProgramFactory);
  1601. checkForErrors();
  1602. }
  1603. if(caps->hasCapability(RSC_HWOCCLUSION))
  1604. {
  1605. if(caps->hasCapability(RSC_GL1_5_NOHWOCCLUSION))
  1606. {
  1607. // Assign ARB functions same to GL 1.5 version since
  1608. // interface identical
  1609. glBeginQueryARB = glBeginQuery;
  1610. glDeleteQueriesARB = glDeleteQueries;
  1611. glEndQueryARB = glEndQuery;
  1612. glGenQueriesARB = glGenQueries;
  1613. glGetQueryObjectivARB = glGetQueryObjectiv;
  1614. glGetQueryObjectuivARB = glGetQueryObjectuiv;
  1615. glGetQueryivARB = glGetQueryiv;
  1616. glIsQueryARB = glIsQuery;
  1617. }
  1618. }
  1619. // Check for framebuffer object extension
  1620. if(caps->hasCapability(RSC_FBO))
  1621. {
  1622. // Before GL version 2.0, we need to get one of the extensions
  1623. if(caps->hasCapability(RSC_FBO_ARB))
  1624. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersARB;
  1625. else if(caps->hasCapability(RSC_FBO_ATI))
  1626. GLEW_GET_FUN(__glewDrawBuffers) = glDrawBuffersATI;
  1627. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1628. {
  1629. // Create FBO manager
  1630. GLRTTManager::startUp();
  1631. checkForErrors();
  1632. }
  1633. }
  1634. else
  1635. {
  1636. CM_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1637. }
  1638. mFragmentTexOffset = 0;
  1639. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1640. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1641. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1642. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1643. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1644. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1645. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1646. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1647. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1648. if(totalNumTexUnits > numCombinedTexUnits)
  1649. CM_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1650. mNumTextureTypes = numCombinedTexUnits;
  1651. mTextureTypes = cm_newN<GLenum>(mNumTextureTypes);
  1652. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1653. mTextureTypes[i] = 0;
  1654. mVertexUBOffset = 0;
  1655. UINT32 totalNumUniformBlocks = caps->getNumUniformBlockBuffers(GPT_VERTEX_PROGRAM);
  1656. mFragmentUBOffset = totalNumUniformBlocks;
  1657. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1658. mGeometryUBOffset = totalNumUniformBlocks;
  1659. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1660. mHullUBOffset = totalNumUniformBlocks;
  1661. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_HULL_PROGRAM);
  1662. mDomainUBOffset = totalNumUniformBlocks;
  1663. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_DOMAIN_PROGRAM);
  1664. mComputeUBOffset = totalNumUniformBlocks;
  1665. totalNumUniformBlocks += caps->getNumUniformBlockBuffers(GPT_COMPUTE_PROGRAM);
  1666. UINT16 numCombinedUniformBlocks = caps->getNumCombinedUniformBlockBuffers();
  1667. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1668. CM_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1669. /// Create the texture manager
  1670. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  1671. checkForErrors();
  1672. }
  1673. RenderSystemCapabilities* GLRenderSystem::createRenderSystemCapabilities() const
  1674. {
  1675. RenderSystemCapabilities* rsc = cm_new<RenderSystemCapabilities>();
  1676. rsc->setCategoryRelevant(CAPS_CATEGORY_GL, true);
  1677. rsc->setDriverVersion(mDriverVersion);
  1678. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  1679. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  1680. rsc->setDeviceName(deviceName);
  1681. rsc->setRenderSystemName(getName());
  1682. // determine vendor
  1683. if (strstr(vendorName, "NVIDIA"))
  1684. rsc->setVendor(GPU_NVIDIA);
  1685. else if (strstr(vendorName, "ATI"))
  1686. rsc->setVendor(GPU_ATI);
  1687. else if (strstr(vendorName, "Intel"))
  1688. rsc->setVendor(GPU_INTEL);
  1689. else if (strstr(vendorName, "S3"))
  1690. rsc->setVendor(GPU_S3);
  1691. else if (strstr(vendorName, "Matrox"))
  1692. rsc->setVendor(GPU_MATROX);
  1693. else if (strstr(vendorName, "3DLabs"))
  1694. rsc->setVendor(GPU_3DLABS);
  1695. else if (strstr(vendorName, "SiS"))
  1696. rsc->setVendor(GPU_SIS);
  1697. else
  1698. rsc->setVendor(GPU_UNKNOWN);
  1699. // Supports fixed-function
  1700. rsc->setCapability(RSC_FIXED_FUNCTION);
  1701. // Check for hardware mipmapping support.
  1702. if(GLEW_VERSION_1_4 || GLEW_SGIS_generate_mipmap)
  1703. {
  1704. bool disableAutoMip = false;
  1705. #if CM_PLATFORM == CM_PLATFORM_APPLE || CM_PLATFORM == CM_PLATFORM_LINUX
  1706. // Apple & Linux ATI drivers have faults in hardware mipmap generation
  1707. if (rsc->getVendor() == GPU_ATI)
  1708. disableAutoMip = true;
  1709. #endif
  1710. // The Intel 915G frequently corrupts textures when using hardware mip generation
  1711. // I'm not currently sure how many generations of hardware this affects,
  1712. // so for now, be safe.
  1713. if (rsc->getVendor() == GPU_INTEL)
  1714. disableAutoMip = true;
  1715. // SiS chipsets also seem to have problems with this
  1716. if (rsc->getVendor() == GPU_SIS)
  1717. disableAutoMip = true;
  1718. if (!disableAutoMip)
  1719. rsc->setCapability(RSC_AUTOMIPMAP);
  1720. }
  1721. // Check for blending support
  1722. if(GLEW_VERSION_1_3 ||
  1723. GLEW_ARB_texture_env_combine ||
  1724. GLEW_EXT_texture_env_combine)
  1725. {
  1726. rsc->setCapability(RSC_BLENDING);
  1727. }
  1728. // Check for Anisotropy support
  1729. if(GLEW_EXT_texture_filter_anisotropic)
  1730. {
  1731. rsc->setCapability(RSC_ANISOTROPY);
  1732. }
  1733. // Check for DOT3 support
  1734. if(GLEW_VERSION_1_3 ||
  1735. GLEW_ARB_texture_env_dot3 ||
  1736. GLEW_EXT_texture_env_dot3)
  1737. {
  1738. rsc->setCapability(RSC_DOT3);
  1739. }
  1740. // Check for cube mapping
  1741. if(GLEW_VERSION_1_3 ||
  1742. GLEW_ARB_texture_cube_map ||
  1743. GLEW_EXT_texture_cube_map)
  1744. {
  1745. rsc->setCapability(RSC_CUBEMAPPING);
  1746. }
  1747. // Point sprites
  1748. if (GLEW_VERSION_2_0 || GLEW_ARB_point_sprite)
  1749. {
  1750. rsc->setCapability(RSC_POINT_SPRITES);
  1751. }
  1752. // Check for point parameters
  1753. if (GLEW_VERSION_1_4)
  1754. {
  1755. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS);
  1756. }
  1757. if (GLEW_ARB_point_parameters)
  1758. {
  1759. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_ARB);
  1760. }
  1761. if (GLEW_EXT_point_parameters)
  1762. {
  1763. rsc->setCapability(RSC_POINT_EXTENDED_PARAMETERS_EXT);
  1764. }
  1765. // Check for hardware stencil support and set bit depth
  1766. GLint stencil;
  1767. glGetIntegerv(GL_STENCIL_BITS,&stencil);
  1768. if(stencil)
  1769. {
  1770. rsc->setCapability(RSC_HWSTENCIL);
  1771. rsc->setStencilBufferBitDepth(stencil);
  1772. }
  1773. if(GLEW_VERSION_1_5 || GLEW_ARB_vertex_buffer_object)
  1774. {
  1775. if (!GLEW_ARB_vertex_buffer_object)
  1776. {
  1777. rsc->setCapability(RSC_GL1_5_NOVBO);
  1778. }
  1779. rsc->setCapability(RSC_VBO);
  1780. }
  1781. rsc->setCapability(RSC_VERTEX_PROGRAM);
  1782. rsc->setCapability(RSC_FRAGMENT_PROGRAM);
  1783. rsc->addShaderProfile("cg");
  1784. // NFZ - Check if GLSL is supported
  1785. if ( GLEW_VERSION_2_0 ||
  1786. (GLEW_ARB_shading_language_100 &&
  1787. GLEW_ARB_shader_objects &&
  1788. GLEW_ARB_fragment_shader &&
  1789. GLEW_ARB_vertex_shader) )
  1790. {
  1791. rsc->addShaderProfile("glsl");
  1792. }
  1793. // Check if geometry shaders are supported
  1794. if (GLEW_VERSION_2_0 &&
  1795. GLEW_EXT_geometry_shader4)
  1796. {
  1797. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  1798. rsc->setGeometryProgramConstantBoolCount(0);
  1799. rsc->setGeometryProgramConstantIntCount(0);
  1800. GLint floatConstantCount = 0;
  1801. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  1802. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  1803. GLint maxOutputVertices;
  1804. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  1805. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  1806. }
  1807. //Check if render to vertex buffer (transform feedback in OpenGL)
  1808. if (GLEW_VERSION_2_0 &&
  1809. GLEW_NV_transform_feedback)
  1810. {
  1811. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  1812. }
  1813. // Check for texture compression
  1814. if(GLEW_VERSION_1_3 || GLEW_ARB_texture_compression)
  1815. {
  1816. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1817. // Check for dxt compression
  1818. if(GLEW_EXT_texture_compression_s3tc)
  1819. {
  1820. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1821. }
  1822. // Check for vtc compression
  1823. if(GLEW_NV_texture_compression_vtc)
  1824. {
  1825. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  1826. }
  1827. }
  1828. // Scissor test is standard in GL 1.2 (is it emulated on some cards though?)
  1829. rsc->setCapability(RSC_SCISSOR_TEST);
  1830. // As are user clipping planes
  1831. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1832. // 2-sided stencil?
  1833. if (GLEW_VERSION_2_0 || GLEW_EXT_stencil_two_side)
  1834. {
  1835. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1836. }
  1837. // stencil wrapping?
  1838. if (GLEW_VERSION_1_4 || GLEW_EXT_stencil_wrap)
  1839. {
  1840. rsc->setCapability(RSC_STENCIL_WRAP);
  1841. }
  1842. // Check for hardware occlusion support
  1843. if(GLEW_VERSION_1_5 || GLEW_ARB_occlusion_query)
  1844. {
  1845. // Some buggy driver claim that it is GL 1.5 compliant and
  1846. // not support ARB_occlusion_query
  1847. if (!GLEW_ARB_occlusion_query)
  1848. {
  1849. rsc->setCapability(RSC_GL1_5_NOHWOCCLUSION);
  1850. }
  1851. rsc->setCapability(RSC_HWOCCLUSION);
  1852. }
  1853. else if (GLEW_NV_occlusion_query)
  1854. {
  1855. // Support NV extension too for old hardware
  1856. rsc->setCapability(RSC_HWOCCLUSION);
  1857. }
  1858. // UBYTE4 always supported
  1859. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1860. // Infinite far plane always supported
  1861. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1862. // Check for non-power-of-2 texture support
  1863. if(GLEW_ARB_texture_non_power_of_two)
  1864. {
  1865. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1866. }
  1867. // Check for Float textures
  1868. if(GLEW_ATI_texture_float || GLEW_ARB_texture_float)
  1869. {
  1870. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1871. }
  1872. // 3D textures should always be supported
  1873. rsc->setCapability(RSC_TEXTURE_3D);
  1874. // Check for framebuffer object extension
  1875. if(GLEW_EXT_framebuffer_object)
  1876. {
  1877. // Probe number of draw buffers
  1878. // Only makes sense with FBO support, so probe here
  1879. if(GLEW_VERSION_2_0 ||
  1880. GLEW_ARB_draw_buffers ||
  1881. GLEW_ATI_draw_buffers)
  1882. {
  1883. GLint buffers;
  1884. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  1885. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)CM_MAX_MULTIPLE_RENDER_TARGETS));
  1886. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1887. if(!GLEW_VERSION_2_0)
  1888. {
  1889. // Before GL version 2.0, we need to get one of the extensions
  1890. if(GLEW_ARB_draw_buffers)
  1891. rsc->setCapability(RSC_FBO_ARB);
  1892. if(GLEW_ATI_draw_buffers)
  1893. rsc->setCapability(RSC_FBO_ATI);
  1894. }
  1895. // Set FBO flag for all 3 'subtypes'
  1896. rsc->setCapability(RSC_FBO);
  1897. }
  1898. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1899. }
  1900. // Check GLSupport for PBuffer support
  1901. if(mGLSupport->supportsPBuffers())
  1902. {
  1903. // Use PBuffers
  1904. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1905. rsc->setCapability(RSC_PBUFFER);
  1906. }
  1907. // Point size
  1908. float ps;
  1909. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  1910. rsc->setMaxPointSize(ps);
  1911. // Max number of fragment shader textures
  1912. GLint units;
  1913. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  1914. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  1915. // Max number of vertex shader textures
  1916. GLint vUnits;
  1917. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  1918. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  1919. if (vUnits > 0)
  1920. {
  1921. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1922. }
  1923. GLint numUniformBlocks;
  1924. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  1925. rsc->setNumUniformBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  1926. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  1927. rsc->setNumUniformBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  1928. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  1929. {
  1930. GLint geomUnits;
  1931. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  1932. rsc->setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  1933. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  1934. rsc->setNumUniformBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  1935. }
  1936. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  1937. {
  1938. rsc->setCapability(RSC_TESSELLATION_PROGRAM);
  1939. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  1940. rsc->setNumUniformBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  1941. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  1942. rsc->setNumUniformBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  1943. }
  1944. if (mGLSupport->checkExtension("GL_ARB_compute_shader")) // Enable once I include GL 4.3
  1945. {
  1946. //rsc->setCapability(RSC_COMPUTE_PROGRAM);
  1947. //GLint computeUnits;
  1948. //glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  1949. //rsc->setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  1950. //glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  1951. //rsc->setNumUniformBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  1952. }
  1953. GLint combinedTexUnits;
  1954. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  1955. rsc->setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  1956. GLint combinedUniformBlockUnits;
  1957. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  1958. rsc->setNumCombinedUniformBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  1959. // Mipmap LOD biasing
  1960. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1961. // These are Cg supported profiles, not really used in OpenGL itself in any way
  1962. rsc->addShaderProfile("glslf");
  1963. rsc->addShaderProfile("glslv");
  1964. rsc->addShaderProfile("glslg");
  1965. rsc->addGpuProgramProfile(GPP_PS_1_1, "glslf");
  1966. rsc->addGpuProgramProfile(GPP_PS_1_2, "glslf");
  1967. rsc->addGpuProgramProfile(GPP_PS_1_3, "glslf");
  1968. rsc->addGpuProgramProfile(GPP_PS_1_4, "glslf");
  1969. rsc->addGpuProgramProfile(GPP_PS_2_0, "glslf");
  1970. rsc->addGpuProgramProfile(GPP_PS_2_x, "glslf");
  1971. rsc->addGpuProgramProfile(GPP_PS_2_a, "glslf");
  1972. rsc->addGpuProgramProfile(GPP_PS_2_b, "glslf");
  1973. rsc->addGpuProgramProfile(GPP_PS_3_0, "glslf");
  1974. rsc->addGpuProgramProfile(GPP_PS_3_x, "glslf");
  1975. rsc->addGpuProgramProfile(GPP_VS_1_1, "glslv");
  1976. rsc->addGpuProgramProfile(GPP_VS_2_0, "glslv");
  1977. rsc->addGpuProgramProfile(GPP_VS_2_x, "glslv");
  1978. rsc->addGpuProgramProfile(GPP_VS_2_a, "glslv");
  1979. rsc->addGpuProgramProfile(GPP_VS_3_0, "glslv");
  1980. rsc->addGpuProgramProfile(GPP_PS_4_0, "glslf");
  1981. rsc->addGpuProgramProfile(GPP_VS_4_0, "glslv");
  1982. rsc->addGpuProgramProfile(GPP_GS_4_0, "glslg");
  1983. rsc->addGpuProgramProfile(GPP_PS_4_0, "glslf");
  1984. rsc->addGpuProgramProfile(GPP_VS_4_0, "glslv");
  1985. rsc->addGpuProgramProfile(GPP_GS_4_0, "glslg");
  1986. rsc->addGpuProgramProfile(GPP_PS_4_1, "glslf");
  1987. rsc->addGpuProgramProfile(GPP_VS_4_1, "glslv");
  1988. rsc->addGpuProgramProfile(GPP_GS_4_1, "glslg");
  1989. // No SM5 support for Cg as right now it only supports NV extensions, which isn't very useful
  1990. // Alpha to coverage?
  1991. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1992. {
  1993. // Alpha to coverage always 'supported' when MSAA is available
  1994. // although card may ignore it if it doesn't specifically support A2C
  1995. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1996. }
  1997. // Advanced blending operations
  1998. if(GLEW_VERSION_2_0)
  1999. {
  2000. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  2001. }
  2002. return rsc;
  2003. }
  2004. //---------------------------------------------------------------------
  2005. UINT32 GLRenderSystem::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  2006. {
  2007. if(gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  2008. {
  2009. CM_EXCEPT(InvalidParametersException, "OpenGL cannot assign textures to this gpu program type: " + toString(gptype));
  2010. }
  2011. UINT32 numSupportedUnits = mCurrentCapabilities->getNumTextureUnits(gptype);
  2012. if(unit < 0 || unit >= numSupportedUnits)
  2013. {
  2014. CM_EXCEPT(InvalidParametersException, "Invalid texture unit index for the provided stage. Unit index: " + toString(unit) + ". Stage: " +
  2015. toString(gptype) + ". Supported range is 0 .. " + toString(numSupportedUnits - 1));
  2016. }
  2017. switch(gptype)
  2018. {
  2019. case GPT_FRAGMENT_PROGRAM:
  2020. return mFragmentTexOffset + unit;
  2021. case GPT_VERTEX_PROGRAM:
  2022. return mVertexTexOffset + unit;
  2023. case GPT_GEOMETRY_PROGRAM:
  2024. return mGeometryTexOffset + unit;
  2025. default:
  2026. CM_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  2027. }
  2028. }
  2029. //---------------------------------------------------------------------
  2030. UINT32 GLRenderSystem::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  2031. {
  2032. UINT32 maxNumBindings = mCurrentCapabilities->getNumUniformBlockBuffers(gptype);
  2033. if(binding < 0 || binding >= maxNumBindings)
  2034. {
  2035. CM_EXCEPT(InvalidParametersException, "Invalid buffer binding for the provided stage. Buffer binding: " + toString(binding) + ". Stage: " +
  2036. toString(gptype) + ". Supported range is 0 .. " + toString(maxNumBindings - 1));
  2037. }
  2038. switch(gptype)
  2039. {
  2040. case GPT_FRAGMENT_PROGRAM:
  2041. return mFragmentUBOffset + binding;
  2042. case GPT_VERTEX_PROGRAM:
  2043. return mVertexUBOffset + binding;
  2044. case GPT_GEOMETRY_PROGRAM:
  2045. return mGeometryUBOffset + binding;
  2046. case GPT_HULL_PROGRAM:
  2047. return mHullUBOffset + binding;
  2048. case GPT_DOMAIN_PROGRAM:
  2049. return mDomainUBOffset + binding;
  2050. case GPT_COMPUTE_PROGRAM:
  2051. return mComputeUBOffset + binding;
  2052. default:
  2053. CM_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  2054. }
  2055. }
  2056. void GLRenderSystem::setActiveProgram(GpuProgramType gptype, GLSLGpuProgramPtr program)
  2057. {
  2058. switch (gptype)
  2059. {
  2060. case GPT_VERTEX_PROGRAM:
  2061. mCurrentVertexProgram = program;
  2062. break;
  2063. case GPT_FRAGMENT_PROGRAM:
  2064. mCurrentFragmentProgram = program;
  2065. break;
  2066. case GPT_GEOMETRY_PROGRAM:
  2067. mCurrentGeometryProgram = program;
  2068. break;
  2069. case GPT_DOMAIN_PROGRAM:
  2070. mCurrentDomainProgram = program;
  2071. break;
  2072. case GPT_HULL_PROGRAM:
  2073. mCurrentHullProgram = program;
  2074. break;
  2075. }
  2076. }
  2077. GLSLGpuProgramPtr GLRenderSystem::getActiveProgram(GpuProgramType gptype) const
  2078. {
  2079. switch (gptype)
  2080. {
  2081. case GPT_VERTEX_PROGRAM:
  2082. return mCurrentVertexProgram;
  2083. break;
  2084. case GPT_FRAGMENT_PROGRAM:
  2085. return mCurrentFragmentProgram;
  2086. break;
  2087. case GPT_GEOMETRY_PROGRAM:
  2088. return mCurrentGeometryProgram;
  2089. break;
  2090. case GPT_DOMAIN_PROGRAM:
  2091. return mCurrentDomainProgram;
  2092. break;
  2093. case GPT_HULL_PROGRAM:
  2094. return mCurrentHullProgram;
  2095. break;
  2096. default:
  2097. CM_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  2098. }
  2099. }
  2100. /************************************************************************/
  2101. /* UTILITY */
  2102. /************************************************************************/
  2103. float GLRenderSystem::getMinimumDepthInputValue(void)
  2104. {
  2105. // Range [-1.0f, 1.0f]
  2106. return -1.0f;
  2107. }
  2108. //---------------------------------------------------------------------
  2109. float GLRenderSystem::getMaximumDepthInputValue(void)
  2110. {
  2111. // Range [-1.0f, 1.0f]
  2112. return 1.0f;
  2113. }
  2114. //---------------------------------------------------------------------
  2115. float GLRenderSystem::getHorizontalTexelOffset(void)
  2116. {
  2117. // No offset in GL
  2118. return 0.0f;
  2119. }
  2120. //---------------------------------------------------------------------
  2121. float GLRenderSystem::getVerticalTexelOffset(void)
  2122. {
  2123. // No offset in GL
  2124. return 0.0f;
  2125. }
  2126. VertexElementType GLRenderSystem::getColorVertexElementType(void) const
  2127. {
  2128. return VET_COLOR_ABGR;
  2129. }
  2130. //---------------------------------------------------------------------
  2131. void GLRenderSystem::convertProjectionMatrix(const Matrix4& matrix,
  2132. Matrix4& dest, bool forGpuProgram)
  2133. {
  2134. // no any conversion request for OpenGL
  2135. dest = matrix;
  2136. }
  2137. }