CmGLRenderSystem.cpp 74 KB

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