CmGLRenderSystem.cpp 75 KB

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