BsGLRenderSystem.cpp 57 KB

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