CmGLRenderSystem.cpp 72 KB

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