CmGLRenderSystem.cpp 67 KB

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