CmGLRenderSystem.cpp 63 KB

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