CmGLRenderSystem.cpp 73 KB

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