CmGLRenderSystem.cpp 73 KB

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