CmGLRenderSystem.cpp 67 KB

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