BsGLRenderAPI.cpp 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsGLRenderAPI.h"
  4. #include "BsRenderAPI.h"
  5. #include "BsGLTextureManager.h"
  6. #include "BsGLIndexBuffer.h"
  7. #include "BsGLUtil.h"
  8. #include "BsGLSLGpuProgram.h"
  9. #include "BsException.h"
  10. #include "BsGLContext.h"
  11. #include "BsGLSupport.h"
  12. #include "BsBlendState.h"
  13. #include "BsRasterizerState.h"
  14. #include "BsDepthStencilState.h"
  15. #include "BsGLRenderTexture.h"
  16. #include "BsGLRenderWindowManager.h"
  17. #include "BsGLSLProgramPipelineManager.h"
  18. #include "BsGLVertexArrayObjectManager.h"
  19. #include "BsRenderStateManager.h"
  20. #include "BsGpuParams.h"
  21. #include "BsGLGpuParamBlockBuffer.h"
  22. #include "BsCoreThread.h"
  23. #include "BsGLQueryManager.h"
  24. #include "BsDebug.h"
  25. #include "BsRenderStats.h"
  26. #include "BsGpuParamDesc.h"
  27. namespace BansheeEngine
  28. {
  29. const char* MODULE_NAME = "BansheeGLRenderAPI.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. GLRenderAPI::GLRenderAPI()
  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. mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  61. {
  62. // Get our GLSupport
  63. mGLSupport = BansheeEngine::getGLSupport();
  64. mViewMatrix = Matrix4::IDENTITY;
  65. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  66. mCurrentContext = 0;
  67. mMainContext = 0;
  68. mGLInitialised = false;
  69. mMinFilter = FO_LINEAR;
  70. mMipFilter = FO_POINT;
  71. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  72. }
  73. GLRenderAPI::~GLRenderAPI()
  74. {
  75. }
  76. const StringID& GLRenderAPI::getName() const
  77. {
  78. static StringID strName("GLRenderAPI");
  79. return strName;
  80. }
  81. const String& GLRenderAPI::getShadingLanguageName() const
  82. {
  83. static String strName("glsl");
  84. return strName;
  85. }
  86. void GLRenderAPI::initializePrepare()
  87. {
  88. THROW_IF_NOT_CORE_THREAD;
  89. mGLSupport->start();
  90. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  91. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  92. RenderWindowCoreManager::startUp<GLRenderWindowCoreManager>(this);
  93. RenderStateCoreManager::startUp();
  94. QueryManager::startUp<GLQueryManager>();
  95. RenderAPICore::initializePrepare();
  96. }
  97. void GLRenderAPI::initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow)
  98. {
  99. // Get the context from the window and finish initialization
  100. SPtr<GLContext> context;
  101. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  102. // Set main and current context
  103. mMainContext = context;
  104. mCurrentContext = mMainContext;
  105. // Set primary context as active
  106. if (mCurrentContext)
  107. mCurrentContext->setCurrent();
  108. checkForErrors();
  109. // Setup GLSupport
  110. mGLSupport->initializeExtensions();
  111. checkForErrors();
  112. Vector<BansheeEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  113. if (!tokens.empty())
  114. {
  115. mDriverVersion.major = parseINT32(tokens[0]);
  116. if (tokens.size() > 1)
  117. mDriverVersion.minor = parseINT32(tokens[1]);
  118. if (tokens.size() > 2)
  119. mDriverVersion.release = parseINT32(tokens[2]);
  120. }
  121. mDriverVersion.build = 0;
  122. mCurrentCapabilities = createRenderSystemCapabilities();
  123. initFromCaps(mCurrentCapabilities);
  124. GLVertexArrayObjectManager::startUp();
  125. mGLInitialised = true;
  126. RenderAPICore::initializeFinalize(primaryWindow);
  127. }
  128. void GLRenderAPI::destroyCore()
  129. {
  130. RenderAPICore::destroyCore();
  131. // Deleting the GLSL program factory
  132. if (mGLSLProgramFactory)
  133. {
  134. // Remove from manager safely
  135. GpuProgramCoreManager::instance().removeFactory(mGLSLProgramFactory);
  136. bs_delete(mGLSLProgramFactory);
  137. mGLSLProgramFactory = nullptr;
  138. }
  139. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  140. HardwareBufferCoreManager::shutDown();
  141. HardwareBufferManager::shutDown();
  142. GLRTTManager::shutDown();
  143. mBoundVertexBuffers.clear();
  144. mBoundVertexDeclaration = nullptr;
  145. mBoundIndexBuffer = nullptr;
  146. mCurrentVertexProgram = nullptr;
  147. mCurrentFragmentProgram = nullptr;
  148. mCurrentGeometryProgram = nullptr;
  149. mCurrentHullProgram = nullptr;
  150. mCurrentDomainProgram = nullptr;
  151. mGLSupport->stop();
  152. TextureCoreManager::shutDown();
  153. TextureManager::shutDown();
  154. QueryManager::shutDown();
  155. RenderWindowCoreManager::shutDown();
  156. RenderWindowManager::shutDown();
  157. RenderStateCoreManager::shutDown();
  158. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  159. mGLInitialised = false;
  160. if(mProgramPipelineManager != nullptr)
  161. bs_delete(mProgramPipelineManager);
  162. if(mGLSupport)
  163. bs_delete(mGLSupport);
  164. if(mTextureTypes != nullptr)
  165. bs_deleteN(mTextureTypes, mNumTextureTypes);
  166. }
  167. void GLRenderAPI::bindGpuProgram(const SPtr<GpuProgramCore>& prg)
  168. {
  169. THROW_IF_NOT_CORE_THREAD;
  170. SPtr<GLSLGpuProgramCore> glprg = std::static_pointer_cast<GLSLGpuProgramCore>(prg);
  171. switch (glprg->getProperties().getType())
  172. {
  173. case GPT_VERTEX_PROGRAM:
  174. mCurrentVertexProgram = glprg;
  175. break;
  176. case GPT_FRAGMENT_PROGRAM:
  177. mCurrentFragmentProgram = glprg;
  178. break;
  179. case GPT_GEOMETRY_PROGRAM:
  180. mCurrentGeometryProgram = glprg;
  181. break;
  182. case GPT_DOMAIN_PROGRAM:
  183. mCurrentDomainProgram = glprg;
  184. break;
  185. case GPT_HULL_PROGRAM:
  186. mCurrentHullProgram = glprg;
  187. break;
  188. }
  189. RenderAPICore::bindGpuProgram(prg);
  190. }
  191. void GLRenderAPI::unbindGpuProgram(GpuProgramType gptype)
  192. {
  193. THROW_IF_NOT_CORE_THREAD;
  194. setActiveProgram(gptype, nullptr);
  195. RenderAPICore::unbindGpuProgram(gptype);
  196. }
  197. void GLRenderAPI::setConstantBuffers(GpuProgramType gptype, const SPtr<GpuParamsCore>& bindableParams)
  198. {
  199. THROW_IF_NOT_CORE_THREAD;
  200. bindableParams->updateHardwareBuffers();
  201. const GpuParamDesc& paramDesc = bindableParams->getParamDesc();
  202. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  203. GLuint glProgram = activeProgram->getGLHandle();
  204. UINT8* uniformBufferData = nullptr;
  205. UINT32 blockBinding = 0;
  206. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  207. {
  208. SPtr<GpuParamBlockBufferCore> paramBlockBuffer = bindableParams->getParamBlockBuffer(iter->second.slot);
  209. if(paramBlockBuffer == nullptr)
  210. continue;
  211. if(iter->second.slot == 0)
  212. {
  213. // 0 means uniforms are not in block, in which case we handle it specially
  214. if (uniformBufferData == nullptr && paramBlockBuffer->getSize() > 0)
  215. {
  216. uniformBufferData = (UINT8*)bs_alloc(paramBlockBuffer->getSize());
  217. paramBlockBuffer->readFromGPU(uniformBufferData); // TODO - Don't read from GPU!? Just read the cached version
  218. }
  219. continue;
  220. }
  221. const GLGpuParamBlockBufferCore* glParamBlockBuffer = static_cast<const GLGpuParamBlockBufferCore*>(paramBlockBuffer.get());
  222. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  223. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  224. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  225. blockBinding++;
  226. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  227. }
  228. bool hasBoundAtLeastOne = false;
  229. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  230. {
  231. const GpuParamDataDesc& paramDesc = iter->second;
  232. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  233. continue;
  234. const UINT8* ptrData = uniformBufferData + paramDesc.cpuMemOffset * sizeof(UINT32);
  235. hasBoundAtLeastOne = true;
  236. // Note: We don't transpose matrices here even though we don't use column major format
  237. // because they are assumed to be pre-transposed in the GpuParams buffer
  238. switch(paramDesc.type)
  239. {
  240. case GPDT_FLOAT1:
  241. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  242. break;
  243. case GPDT_FLOAT2:
  244. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  245. break;
  246. case GPDT_FLOAT3:
  247. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  248. break;
  249. case GPDT_FLOAT4:
  250. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  251. break;
  252. case GPDT_MATRIX_2X2:
  253. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  254. GL_FALSE, (GLfloat*)ptrData);
  255. break;
  256. case GPDT_MATRIX_2X3:
  257. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  258. GL_FALSE, (GLfloat*)ptrData);
  259. break;
  260. case GPDT_MATRIX_2X4:
  261. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  262. GL_FALSE, (GLfloat*)ptrData);
  263. break;
  264. case GPDT_MATRIX_3X2:
  265. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  266. GL_FALSE, (GLfloat*)ptrData);
  267. break;
  268. case GPDT_MATRIX_3X3:
  269. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  270. GL_FALSE, (GLfloat*)ptrData);
  271. break;
  272. case GPDT_MATRIX_3X4:
  273. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  274. GL_FALSE, (GLfloat*)ptrData);
  275. break;
  276. case GPDT_MATRIX_4X2:
  277. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  278. GL_FALSE, (GLfloat*)ptrData);
  279. break;
  280. case GPDT_MATRIX_4X3:
  281. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  282. GL_FALSE, (GLfloat*)ptrData);
  283. break;
  284. case GPDT_MATRIX_4X4:
  285. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  286. GL_FALSE, (GLfloat*)ptrData);
  287. break;
  288. case GPDT_INT1:
  289. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  290. break;
  291. case GPDT_INT2:
  292. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  293. break;
  294. case GPDT_INT3:
  295. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  296. break;
  297. case GPDT_INT4:
  298. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  299. break;
  300. case GPDT_BOOL:
  301. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  302. break;
  303. case GPDT_UNKNOWN:
  304. break;
  305. }
  306. }
  307. if (hasBoundAtLeastOne)
  308. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  309. if(uniformBufferData != nullptr)
  310. {
  311. bs_free(uniformBufferData);
  312. }
  313. }
  314. void GLRenderAPI::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr)
  315. {
  316. THROW_IF_NOT_CORE_THREAD;
  317. unit = getGLTextureUnit(gptype, unit);
  318. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  319. GLenum lastTextureType = mTextureTypes[unit];
  320. if (!activateGLTextureUnit(unit))
  321. return;
  322. if (enabled && tex)
  323. {
  324. mTextureTypes[unit] = tex->getGLTextureTarget();
  325. glBindTexture(mTextureTypes[unit], tex->getGLID());
  326. }
  327. else
  328. {
  329. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  330. // - If a non-2D sampler is used, the texture will still be displayed
  331. glBindTexture(GL_TEXTURE_2D, 0);
  332. }
  333. activateGLTextureUnit(0);
  334. BS_INC_RENDER_STAT(NumTextureBinds);
  335. }
  336. void GLRenderAPI::setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state)
  337. {
  338. THROW_IF_NOT_CORE_THREAD;
  339. const SamplerProperties& stateProps = state->getProperties();
  340. unit = getGLTextureUnit(gptype, unit);
  341. // Set texture layer filtering
  342. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  343. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  344. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  345. // Set texture anisotropy
  346. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  347. // Set mipmap biasing
  348. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  349. // Texture addressing mode
  350. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  351. setTextureAddressingMode(unit, uvw);
  352. // Set border color
  353. setTextureBorderColor(unit, stateProps.getBorderColor());
  354. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  355. GLuint glProgram = activeProgram->getGLHandle();
  356. glProgramUniform1i(glProgram, unit, getGLTextureUnit(gptype, unit));
  357. BS_INC_RENDER_STAT(NumSamplerBinds);
  358. }
  359. void GLRenderAPI::setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  360. const TextureSurface& surface)
  361. {
  362. THROW_IF_NOT_CORE_THREAD;
  363. // TODO - OpenGL can't bind a certain subset of faces like DX11, only zero, one or all, so I'm ignoring numSlices parameter
  364. if (texPtr != nullptr)
  365. {
  366. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  367. glBindImageTexture(unit, tex->getGLID(), surface.mipLevel, surface.numArraySlices > 1,
  368. surface.arraySlice, tex->getGLFormat(), GL_READ_WRITE);
  369. }
  370. else
  371. glBindImageTexture(unit, 0, 0, false, 0, 0, GL_READ_WRITE);
  372. BS_INC_RENDER_STAT(NumTextureBinds);
  373. }
  374. void GLRenderAPI::setBlendState(const SPtr<BlendStateCore>& blendState)
  375. {
  376. THROW_IF_NOT_CORE_THREAD;
  377. const BlendProperties& stateProps = blendState->getProperties();
  378. // Alpha to coverage
  379. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  380. // Blend states
  381. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  382. if (stateProps.getBlendEnabled(0))
  383. {
  384. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  385. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  386. }
  387. else
  388. {
  389. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  390. }
  391. // Color write mask
  392. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  393. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  394. BS_INC_RENDER_STAT(NumBlendStateChanges);
  395. }
  396. void GLRenderAPI::setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState)
  397. {
  398. THROW_IF_NOT_CORE_THREAD;
  399. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  400. setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  401. setCullingMode(stateProps.getCullMode());
  402. setPolygonMode(stateProps.getPolygonMode());
  403. setScissorTestEnable(stateProps.getScissorEnable());
  404. setMultisamplingEnable(stateProps.getMultisampleEnable());
  405. setDepthClipEnable(stateProps.getDepthClipEnable());
  406. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  407. BS_INC_RENDER_STAT(NumRasterizerStateChanges);
  408. }
  409. void GLRenderAPI::setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue)
  410. {
  411. THROW_IF_NOT_CORE_THREAD;
  412. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  413. // Set stencil buffer options
  414. setStencilCheckEnabled(stateProps.getStencilEnable());
  415. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  416. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  417. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  418. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  419. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  420. // Set depth buffer options
  421. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  422. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  423. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  424. // Set stencil ref value
  425. setStencilRefValue(stencilRefValue);
  426. BS_INC_RENDER_STAT(NumDepthStencilStateChanges);
  427. }
  428. void GLRenderAPI::setViewport(const Rect2& area)
  429. {
  430. THROW_IF_NOT_CORE_THREAD;
  431. mViewportNorm = area;
  432. applyViewport();
  433. }
  434. void GLRenderAPI::setRenderTarget(const SPtr<RenderTargetCore>& target, bool readOnlyDepthStencil)
  435. {
  436. THROW_IF_NOT_CORE_THREAD;
  437. // Switch context if different from current one
  438. SPtr<GLContext> newContext;
  439. target->getCustomAttribute("GLCONTEXT", &newContext);
  440. if(newContext && mCurrentContext != newContext)
  441. {
  442. switchContext(newContext);
  443. }
  444. // This must happen after context switch to ensure previous context is still alive
  445. mActiveRenderTarget = target;
  446. GLFrameBufferObject* fbo = nullptr;
  447. target->getCustomAttribute("FBO", &fbo);
  448. if(fbo)
  449. fbo->bind();
  450. else
  451. // Old style context (window/pbuffer) or copying render texture
  452. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  453. if (GLEW_EXT_framebuffer_sRGB)
  454. {
  455. // Enable / disable sRGB states
  456. if (target->getProperties().isHwGammaEnabled())
  457. {
  458. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  459. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  460. // enabling, but GL spec says incapable surfaces ignore the setting
  461. // anyway. We test the capability to enable isHardwareGammaEnabled.
  462. }
  463. else
  464. {
  465. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  466. }
  467. }
  468. applyViewport();
  469. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  470. }
  471. void GLRenderAPI::beginFrame()
  472. {
  473. THROW_IF_NOT_CORE_THREAD;
  474. // Activate the viewport clipping
  475. glEnable(GL_SCISSOR_TEST);
  476. }
  477. void GLRenderAPI::endFrame()
  478. {
  479. THROW_IF_NOT_CORE_THREAD;
  480. // Deactivate the viewport clipping.
  481. glDisable(GL_SCISSOR_TEST);
  482. }
  483. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers)
  484. {
  485. THROW_IF_NOT_CORE_THREAD;
  486. if ((index + numBuffers) > (UINT32)mBoundVertexBuffers.size())
  487. mBoundVertexBuffers.resize(index + numBuffers);
  488. for(UINT32 i = 0; i < numBuffers; i++)
  489. {
  490. mBoundVertexBuffers[index + i] = buffers[i];
  491. }
  492. }
  493. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration)
  494. {
  495. THROW_IF_NOT_CORE_THREAD;
  496. mBoundVertexDeclaration = vertexDeclaration;
  497. }
  498. void GLRenderAPI::setDrawOperation(DrawOperationType op)
  499. {
  500. THROW_IF_NOT_CORE_THREAD;
  501. mCurrentDrawOperation = op;
  502. }
  503. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBufferCore>& buffer)
  504. {
  505. THROW_IF_NOT_CORE_THREAD;
  506. mBoundIndexBuffer = buffer;
  507. }
  508. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount)
  509. {
  510. // Find the correct type to render
  511. GLint primType = getGLDrawMode();
  512. beginDraw();
  513. glDrawArrays(primType, vertexOffset, vertexCount);
  514. endDraw();
  515. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  516. BS_INC_RENDER_STAT(NumDrawCalls);
  517. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  518. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  519. }
  520. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  521. {
  522. if(mBoundIndexBuffer == nullptr)
  523. {
  524. LOGWRN("Cannot draw indexed because index buffer is not set.");
  525. return;
  526. }
  527. // Find the correct type to render
  528. GLint primType = getGLDrawMode();
  529. beginDraw();
  530. SPtr<GLIndexBufferCore> indexBuffer = std::static_pointer_cast<GLIndexBufferCore>(mBoundIndexBuffer);
  531. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  532. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  533. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  534. glDrawElementsBaseVertex(primType, indexCount, indexType, (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex), vertexOffset);
  535. endDraw();
  536. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  537. BS_INC_RENDER_STAT(NumDrawCalls);
  538. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  539. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  540. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  541. }
  542. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  543. {
  544. THROW_IF_NOT_CORE_THREAD;
  545. mScissorTop = top;
  546. mScissorBottom = bottom;
  547. mScissorLeft = left;
  548. mScissorRight = right;
  549. }
  550. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  551. {
  552. if(mActiveRenderTarget == nullptr)
  553. return;
  554. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  555. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  556. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  557. }
  558. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  559. {
  560. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  561. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  562. }
  563. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
  564. UINT8 targetMask)
  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. // Disable scissor test as we want to clear the entire render surface
  572. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  573. UINT32 oldScissorTop = mScissorTop;
  574. UINT32 oldScissorBottom = mScissorBottom;
  575. UINT32 oldScissorLeft = mScissorLeft;
  576. UINT32 oldScissorRight = mScissorRight;
  577. if (scissorTestEnabled)
  578. {
  579. glDisable(GL_SCISSOR_TEST);
  580. }
  581. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  582. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  583. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  584. if (!clearEntireTarget)
  585. {
  586. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  587. setScissorTestEnable(true);
  588. }
  589. if (buffers & FBT_COLOR)
  590. {
  591. // Enable buffer for writing if it isn't
  592. if (colorMask)
  593. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  594. }
  595. if (buffers & FBT_DEPTH)
  596. {
  597. // Enable buffer for writing if it isn't
  598. if (!mDepthWrite)
  599. glDepthMask(GL_TRUE);
  600. }
  601. if (buffers & FBT_STENCIL)
  602. {
  603. // Enable buffer for writing if it isn't
  604. glStencilMask(0xFFFFFFFF);
  605. }
  606. if (targetMask == 0xFF)
  607. {
  608. GLbitfield flags = 0;
  609. if (buffers & FBT_COLOR)
  610. {
  611. flags |= GL_COLOR_BUFFER_BIT;
  612. glClearColor(color.r, color.g, color.b, color.a);
  613. }
  614. if (buffers & FBT_DEPTH)
  615. {
  616. flags |= GL_DEPTH_BUFFER_BIT;
  617. glClearDepth(depth);
  618. }
  619. if (buffers & FBT_STENCIL)
  620. {
  621. flags |= GL_STENCIL_BUFFER_BIT;
  622. glClearStencil(stencil);
  623. }
  624. // Clear buffers
  625. glClear(flags);
  626. }
  627. else
  628. {
  629. GLFrameBufferObject* fbo = nullptr;
  630. mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
  631. if (buffers & FBT_COLOR)
  632. {
  633. for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
  634. {
  635. if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
  636. glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
  637. }
  638. }
  639. if (buffers & FBT_DEPTH)
  640. {
  641. if (buffers & FBT_STENCIL)
  642. {
  643. glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
  644. }
  645. else
  646. {
  647. glClearBufferfv(GL_DEPTH, 0, &depth);
  648. }
  649. }
  650. else if (buffers & FBT_STENCIL)
  651. {
  652. INT32 stencilClear = (INT32)stencil;
  653. glClearBufferiv(GL_STENCIL, 0, &stencilClear);
  654. }
  655. }
  656. if (!clearEntireTarget)
  657. {
  658. setScissorTestEnable(false);
  659. }
  660. // Restore scissor test
  661. if (scissorTestEnabled)
  662. {
  663. glEnable(GL_SCISSOR_TEST);
  664. mScissorTop = oldScissorTop;
  665. mScissorBottom = oldScissorBottom;
  666. mScissorLeft = oldScissorLeft;
  667. mScissorRight = oldScissorRight;
  668. }
  669. // Reset buffer write state
  670. if (!mDepthWrite && (buffers & FBT_DEPTH))
  671. {
  672. glDepthMask(GL_FALSE);
  673. }
  674. if (colorMask && (buffers & FBT_COLOR))
  675. {
  676. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  677. }
  678. if (buffers & FBT_STENCIL)
  679. {
  680. glStencilMask(mStencilWriteMask);
  681. }
  682. BS_INC_RENDER_STAT(NumClears);
  683. }
  684. /************************************************************************/
  685. /* PRIVATE */
  686. /************************************************************************/
  687. void GLRenderAPI::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  688. {
  689. if (!activateGLTextureUnit(stage))
  690. return;
  691. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  692. getTextureAddressingMode(uvw.u));
  693. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  694. getTextureAddressingMode(uvw.v));
  695. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  696. getTextureAddressingMode(uvw.w));
  697. activateGLTextureUnit(0);
  698. }
  699. void GLRenderAPI::setTextureBorderColor(UINT16 stage, const Color& colour)
  700. {
  701. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  702. if (activateGLTextureUnit(stage))
  703. {
  704. glTexParameterfv(mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  705. activateGLTextureUnit(0);
  706. }
  707. }
  708. void GLRenderAPI::setTextureMipmapBias(UINT16 stage, float bias)
  709. {
  710. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  711. {
  712. if (activateGLTextureUnit(stage))
  713. {
  714. glTexParameterf(mTextureTypes[stage], GL_TEXTURE_LOD_BIAS, bias);
  715. activateGLTextureUnit(0);
  716. }
  717. }
  718. }
  719. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  720. {
  721. GLint sourceBlend = getBlendMode(sourceFactor);
  722. GLint destBlend = getBlendMode(destFactor);
  723. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  724. {
  725. glDisable(GL_BLEND);
  726. }
  727. else
  728. {
  729. glEnable(GL_BLEND);
  730. glBlendFunc(sourceBlend, destBlend);
  731. }
  732. GLint func = GL_FUNC_ADD;
  733. switch(op)
  734. {
  735. case BO_ADD:
  736. func = GL_FUNC_ADD;
  737. break;
  738. case BO_SUBTRACT:
  739. func = GL_FUNC_SUBTRACT;
  740. break;
  741. case BO_REVERSE_SUBTRACT:
  742. func = GL_FUNC_REVERSE_SUBTRACT;
  743. break;
  744. case BO_MIN:
  745. func = GL_MIN;
  746. break;
  747. case BO_MAX:
  748. func = GL_MAX;
  749. break;
  750. }
  751. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  752. {
  753. glBlendEquation(func);
  754. }
  755. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  756. {
  757. glBlendEquationEXT(func);
  758. }
  759. }
  760. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  761. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  762. {
  763. GLint sourceBlend = getBlendMode(sourceFactor);
  764. GLint destBlend = getBlendMode(destFactor);
  765. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  766. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  767. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  768. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  769. {
  770. glDisable(GL_BLEND);
  771. }
  772. else
  773. {
  774. glEnable(GL_BLEND);
  775. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  776. }
  777. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  778. switch(op)
  779. {
  780. case BO_ADD:
  781. func = GL_FUNC_ADD;
  782. break;
  783. case BO_SUBTRACT:
  784. func = GL_FUNC_SUBTRACT;
  785. break;
  786. case BO_REVERSE_SUBTRACT:
  787. func = GL_FUNC_REVERSE_SUBTRACT;
  788. break;
  789. case BO_MIN:
  790. func = GL_MIN;
  791. break;
  792. case BO_MAX:
  793. func = GL_MAX;
  794. break;
  795. }
  796. switch(alphaOp)
  797. {
  798. case BO_ADD:
  799. alphaFunc = GL_FUNC_ADD;
  800. break;
  801. case BO_SUBTRACT:
  802. alphaFunc = GL_FUNC_SUBTRACT;
  803. break;
  804. case BO_REVERSE_SUBTRACT:
  805. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  806. break;
  807. case BO_MIN:
  808. alphaFunc = GL_MIN;
  809. break;
  810. case BO_MAX:
  811. alphaFunc = GL_MAX;
  812. break;
  813. }
  814. if(GLEW_VERSION_2_0) {
  815. glBlendEquationSeparate(func, alphaFunc);
  816. }
  817. else if(GLEW_EXT_blend_equation_separate) {
  818. glBlendEquationSeparateEXT(func, alphaFunc);
  819. }
  820. }
  821. void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
  822. {
  823. if(func == CMPF_ALWAYS_PASS)
  824. {
  825. glDisable(GL_ALPHA_TEST);
  826. }
  827. else
  828. {
  829. glEnable(GL_ALPHA_TEST);
  830. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  831. }
  832. }
  833. void GLRenderAPI::setAlphaToCoverage(bool enable)
  834. {
  835. static bool lasta2c = false;
  836. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  837. {
  838. if (enable)
  839. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  840. else
  841. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  842. lasta2c = enable;
  843. }
  844. }
  845. void GLRenderAPI::setScissorTestEnable(bool enable)
  846. {
  847. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  848. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  849. bool flipping = rtProps.requiresTextureFlipping();
  850. // GL measures from the bottom, not the top
  851. UINT32 targetHeight = rtProps.getHeight();
  852. // Calculate the "lower-left" corner of the viewport
  853. GLsizei x = 0, y = 0, w = 0, h = 0;
  854. if (enable)
  855. {
  856. glEnable(GL_SCISSOR_TEST);
  857. // GL uses width / height rather than right / bottom
  858. x = mScissorLeft;
  859. if (flipping)
  860. y = targetHeight - mScissorBottom - 1;
  861. else
  862. y = mScissorTop;
  863. w = mScissorRight - mScissorLeft;
  864. h = mScissorBottom - mScissorTop;
  865. glScissor(x, y, w, h);
  866. }
  867. else
  868. {
  869. glDisable(GL_SCISSOR_TEST);
  870. // GL requires you to reset the scissor when disabling
  871. w = mViewportWidth;
  872. h = mViewportHeight;
  873. x = mViewportLeft;
  874. y = mViewportTop;
  875. glScissor(x, y, w, h);
  876. }
  877. }
  878. void GLRenderAPI::setMultisamplingEnable(bool enable)
  879. {
  880. if (enable)
  881. glEnable(GL_MULTISAMPLE);
  882. else
  883. glDisable(GL_MULTISAMPLE);
  884. }
  885. void GLRenderAPI::setDepthClipEnable(bool enable)
  886. {
  887. if (enable)
  888. glEnable(GL_DEPTH_CLAMP);
  889. else
  890. glDisable(GL_DEPTH_CLAMP);
  891. }
  892. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  893. {
  894. if (enable)
  895. glEnable(GL_LINE_SMOOTH);
  896. else
  897. glDisable(GL_LINE_SMOOTH);
  898. }
  899. void GLRenderAPI::setCullingMode(CullingMode mode)
  900. {
  901. mCullingMode = mode;
  902. GLenum cullMode;
  903. switch( mode )
  904. {
  905. case CULL_NONE:
  906. glDisable(GL_CULL_FACE);
  907. return;
  908. default:
  909. case CULL_CLOCKWISE:
  910. cullMode = GL_BACK;
  911. break;
  912. case CULL_COUNTERCLOCKWISE:
  913. cullMode = GL_FRONT;
  914. break;
  915. }
  916. glEnable(GL_CULL_FACE);
  917. glCullFace(cullMode);
  918. }
  919. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  920. {
  921. if (enabled)
  922. {
  923. glClearDepth(1.0f);
  924. glEnable(GL_DEPTH_TEST);
  925. }
  926. else
  927. {
  928. glDisable(GL_DEPTH_TEST);
  929. }
  930. }
  931. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  932. {
  933. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  934. glDepthMask(flag);
  935. mDepthWrite = enabled;
  936. }
  937. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  938. {
  939. glDepthFunc(convertCompareFunction(func));
  940. }
  941. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  942. {
  943. if (constantBias != 0 || slopeScaleBias != 0)
  944. {
  945. glEnable(GL_POLYGON_OFFSET_FILL);
  946. glEnable(GL_POLYGON_OFFSET_POINT);
  947. glEnable(GL_POLYGON_OFFSET_LINE);
  948. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  949. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  950. }
  951. else
  952. {
  953. glDisable(GL_POLYGON_OFFSET_FILL);
  954. glDisable(GL_POLYGON_OFFSET_POINT);
  955. glDisable(GL_POLYGON_OFFSET_LINE);
  956. }
  957. }
  958. void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  959. {
  960. glColorMask(red, green, blue, alpha);
  961. // record this
  962. mColorWrite[0] = red;
  963. mColorWrite[1] = blue;
  964. mColorWrite[2] = green;
  965. mColorWrite[3] = alpha;
  966. }
  967. void GLRenderAPI::setPolygonMode(PolygonMode level)
  968. {
  969. GLenum glmode;
  970. switch(level)
  971. {
  972. case PM_WIREFRAME:
  973. glmode = GL_LINE;
  974. break;
  975. default:
  976. case PM_SOLID:
  977. glmode = GL_FILL;
  978. break;
  979. }
  980. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  981. }
  982. void GLRenderAPI::setStencilCheckEnabled(bool enabled)
  983. {
  984. if (enabled)
  985. glEnable(GL_STENCIL_TEST);
  986. else
  987. glDisable(GL_STENCIL_TEST);
  988. }
  989. void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
  990. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  991. {
  992. if (front)
  993. {
  994. glStencilOpSeparate(GL_FRONT,
  995. convertStencilOp(stencilFailOp),
  996. convertStencilOp(depthFailOp),
  997. convertStencilOp(passOp));
  998. }
  999. else
  1000. {
  1001. glStencilOpSeparate(GL_BACK,
  1002. convertStencilOp(stencilFailOp, true),
  1003. convertStencilOp(depthFailOp, true),
  1004. convertStencilOp(passOp, true));
  1005. }
  1006. }
  1007. void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1008. {
  1009. mStencilReadMask = mask;
  1010. if(front)
  1011. {
  1012. mStencilCompareFront = func;
  1013. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1014. }
  1015. else
  1016. {
  1017. mStencilCompareBack = func;
  1018. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1019. }
  1020. }
  1021. void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1022. {
  1023. mStencilWriteMask = mask;
  1024. glStencilMask(mask);
  1025. }
  1026. void GLRenderAPI::setStencilRefValue(UINT32 refValue)
  1027. {
  1028. THROW_IF_NOT_CORE_THREAD;
  1029. mStencilRefValue = refValue;
  1030. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1031. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1032. }
  1033. void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1034. {
  1035. if (!activateGLTextureUnit(unit))
  1036. return;
  1037. switch(ftype)
  1038. {
  1039. case FT_MIN:
  1040. mMinFilter = fo;
  1041. // Combine with existing mip filter
  1042. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1043. break;
  1044. case FT_MAG:
  1045. switch (fo)
  1046. {
  1047. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1048. case FO_LINEAR:
  1049. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1050. break;
  1051. case FO_POINT:
  1052. case FO_NONE:
  1053. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1054. break;
  1055. }
  1056. break;
  1057. case FT_MIP:
  1058. mMipFilter = fo;
  1059. // Combine with existing min filter
  1060. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1061. break;
  1062. }
  1063. activateGLTextureUnit(0);
  1064. }
  1065. void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1066. {
  1067. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1068. return;
  1069. if (!activateGLTextureUnit(unit))
  1070. return;
  1071. GLfloat largest_supported_anisotropy = 0;
  1072. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1073. if (maxAnisotropy > largest_supported_anisotropy)
  1074. maxAnisotropy = largest_supported_anisotropy ?
  1075. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1076. if(maxAnisotropy < 1)
  1077. maxAnisotropy = 1;
  1078. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1079. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1080. activateGLTextureUnit(0);
  1081. }
  1082. void GLRenderAPI::setClipPlanesImpl(const PlaneList& clipPlanes)
  1083. {
  1084. size_t i = 0;
  1085. size_t numClipPlanes;
  1086. GLdouble clipPlane[4];
  1087. numClipPlanes = clipPlanes.size();
  1088. for (i = 0; i < numClipPlanes; ++i)
  1089. {
  1090. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1091. const Plane& plane = clipPlanes[i];
  1092. if (i >= 6)
  1093. {
  1094. BS_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1095. }
  1096. clipPlane[0] = plane.normal.x;
  1097. clipPlane[1] = plane.normal.y;
  1098. clipPlane[2] = plane.normal.z;
  1099. clipPlane[3] = plane.d;
  1100. glClipPlane(clipPlaneId, clipPlane);
  1101. glEnable(clipPlaneId);
  1102. }
  1103. // Disable remaining clip planes
  1104. for (; i < 6; ++i)
  1105. {
  1106. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1107. }
  1108. }
  1109. bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
  1110. {
  1111. if (mActiveTextureUnit != unit)
  1112. {
  1113. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1114. {
  1115. glActiveTexture(GL_TEXTURE0 + unit);
  1116. mActiveTextureUnit = unit;
  1117. return true;
  1118. }
  1119. else if (!unit)
  1120. {
  1121. // always ok to use the first unit
  1122. return true;
  1123. }
  1124. else
  1125. {
  1126. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1127. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1128. return false;
  1129. }
  1130. }
  1131. else
  1132. {
  1133. return true;
  1134. }
  1135. }
  1136. void GLRenderAPI::beginDraw()
  1137. {
  1138. if(mDrawCallInProgress)
  1139. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1140. mDrawCallInProgress = true;
  1141. if(mCurrentVertexProgram == nullptr)
  1142. {
  1143. LOGWRN("Cannot render without a set vertex shader.");
  1144. return;
  1145. }
  1146. if(mBoundVertexDeclaration == nullptr)
  1147. {
  1148. LOGWRN("Cannot render without a set vertex declaration.");
  1149. return;
  1150. }
  1151. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1152. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1153. if(mActivePipeline != pipeline)
  1154. {
  1155. glBindProgramPipeline(pipeline->glHandle);
  1156. mActivePipeline = pipeline;
  1157. }
  1158. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(mCurrentVertexProgram, mBoundVertexDeclaration, mBoundVertexBuffers);
  1159. glBindVertexArray(vao.getGLHandle());
  1160. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1161. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  1162. }
  1163. void GLRenderAPI::endDraw()
  1164. {
  1165. if(!mDrawCallInProgress)
  1166. return;
  1167. mDrawCallInProgress = false;
  1168. }
  1169. GLfloat GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  1334. {
  1335. if (gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  1336. {
  1337. BS_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. BS_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. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1355. }
  1356. }
  1357. UINT32 GLRenderAPI::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  1358. {
  1359. UINT32 maxNumBindings = mCurrentCapabilities->getNumGpuParamBlockBuffers(gptype);
  1360. if (binding < 0 || binding >= maxNumBindings)
  1361. {
  1362. BS_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. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1381. }
  1382. }
  1383. void GLRenderAPI::setActiveProgram(GpuProgramType gptype, const SPtr<GLSLGpuProgramCore>& 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. SPtr<GLSLGpuProgramCore> GLRenderAPI::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. BS_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  1425. }
  1426. }
  1427. void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  1428. {
  1429. if(caps->getRenderAPIName() != getName())
  1430. {
  1431. BS_EXCEPT(InvalidParametersException,
  1432. "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
  1433. }
  1434. #if BS_DEBUG_MODE
  1435. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  1436. {
  1437. glDebugMessageCallback(&openGlErrorCallback, 0);
  1438. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1439. }
  1440. #endif
  1441. HardwareBufferManager::startUp();
  1442. HardwareBufferCoreManager::startUp<GLHardwareBufferCoreManager>();
  1443. // GPU Program Manager setup
  1444. if(caps->isShaderProfileSupported("glsl"))
  1445. {
  1446. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  1447. GpuProgramCoreManager::instance().addFactory(mGLSLProgramFactory);
  1448. }
  1449. // Check for framebuffer object extension
  1450. if(caps->hasCapability(RSC_FBO))
  1451. {
  1452. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1453. {
  1454. // Create FBO manager
  1455. GLRTTManager::startUp<GLRTTManager>();
  1456. }
  1457. }
  1458. else
  1459. {
  1460. BS_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1461. }
  1462. mFragmentTexOffset = 0;
  1463. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1464. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1465. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1466. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1467. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1468. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1469. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1470. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1471. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1472. if(totalNumTexUnits > numCombinedTexUnits)
  1473. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1474. mNumTextureTypes = numCombinedTexUnits;
  1475. mTextureTypes = bs_newN<GLenum>(mNumTextureTypes);
  1476. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1477. mTextureTypes[i] = GL_TEXTURE_2D;
  1478. mVertexUBOffset = 0;
  1479. UINT32 totalNumUniformBlocks = caps->getNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM);
  1480. mFragmentUBOffset = totalNumUniformBlocks;
  1481. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1482. mGeometryUBOffset = totalNumUniformBlocks;
  1483. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1484. mHullUBOffset = totalNumUniformBlocks;
  1485. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_HULL_PROGRAM);
  1486. mDomainUBOffset = totalNumUniformBlocks;
  1487. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM);
  1488. mComputeUBOffset = totalNumUniformBlocks;
  1489. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM);
  1490. UINT16 numCombinedUniformBlocks = caps->getNumCombinedGpuParamBlockBuffers();
  1491. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1492. BS_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1493. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  1494. TextureCoreManager::startUp<GLTextureCoreManager>(std::ref(*mGLSupport));
  1495. }
  1496. void GLRenderAPI::switchContext(const SPtr<GLContext>& context)
  1497. {
  1498. // Unbind GPU programs and rebind to new context later, because
  1499. // scene manager treat render system as ONE 'context' ONLY, and it
  1500. // cached the GPU programs using state.
  1501. unbindGpuProgram(GPT_VERTEX_PROGRAM);
  1502. unbindGpuProgram(GPT_FRAGMENT_PROGRAM);
  1503. unbindGpuProgram(GPT_GEOMETRY_PROGRAM);
  1504. unbindGpuProgram(GPT_HULL_PROGRAM);
  1505. unbindGpuProgram(GPT_DOMAIN_PROGRAM);
  1506. // It's ready for switching
  1507. if (mCurrentContext)
  1508. mCurrentContext->endCurrent();
  1509. mCurrentContext = context;
  1510. mCurrentContext->setCurrent();
  1511. // Must reset depth/colour write mask to according with user desired, otherwise,
  1512. // clearFrameBuffer would be wrong because the value we are recorded may be
  1513. // difference with the really state stored in GL context.
  1514. glDepthMask(mDepthWrite);
  1515. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1516. glStencilMask(mStencilWriteMask);
  1517. }
  1518. RenderAPICapabilities* GLRenderAPI::createRenderSystemCapabilities() const
  1519. {
  1520. RenderAPICapabilities* rsc = bs_new<RenderAPICapabilities>();
  1521. rsc->setDriverVersion(mDriverVersion);
  1522. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  1523. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  1524. rsc->setDeviceName(deviceName);
  1525. rsc->setRenderAPIName(getName());
  1526. // determine vendor
  1527. if (strstr(vendorName, "NVIDIA"))
  1528. rsc->setVendor(GPU_NVIDIA);
  1529. else if (strstr(vendorName, "ATI"))
  1530. rsc->setVendor(GPU_AMD);
  1531. else if (strstr(vendorName, "AMD"))
  1532. rsc->setVendor(GPU_AMD);
  1533. else if (strstr(vendorName, "Intel"))
  1534. rsc->setVendor(GPU_INTEL);
  1535. else
  1536. rsc->setVendor(GPU_UNKNOWN);
  1537. // Check for hardware mipmapping support.
  1538. if(GLEW_VERSION_1_4)
  1539. {
  1540. rsc->setCapability(RSC_AUTOMIPMAP);
  1541. }
  1542. // Check for Anisotropy support
  1543. if (getGLSupport()->checkExtension("GL_EXT_texture_filter_anisotropic"))
  1544. {
  1545. rsc->setCapability(RSC_ANISOTROPY);
  1546. }
  1547. // Check for cube mapping
  1548. if(GLEW_VERSION_1_3 ||
  1549. getGLSupport()->checkExtension("GL_ARB_texture_cube_map") ||
  1550. getGLSupport()->checkExtension("GL_EXT_texture_cube_map"))
  1551. {
  1552. rsc->setCapability(RSC_CUBEMAPPING);
  1553. }
  1554. // Point sprites
  1555. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_point_sprite"))
  1556. {
  1557. rsc->setCapability(RSC_POINT_SPRITES);
  1558. }
  1559. // Check for hardware stencil support and set bit depth
  1560. GLint stencil;
  1561. glGetIntegerv(GL_STENCIL_BITS, &stencil);
  1562. if(stencil)
  1563. {
  1564. rsc->setStencilBufferBitDepth(stencil);
  1565. }
  1566. if (GLEW_VERSION_2_0 ||
  1567. (getGLSupport()->checkExtension("GL_ARB_shading_language_100") &&
  1568. getGLSupport()->checkExtension("GL_ARB_shader_objects") &&
  1569. getGLSupport()->checkExtension("GL_ARB_fragment_shader") &&
  1570. getGLSupport()->checkExtension("GL_ARB_vertex_shader")))
  1571. {
  1572. rsc->addShaderProfile("glsl");
  1573. }
  1574. // Check if geometry shaders are supported
  1575. if (GLEW_VERSION_2_0 &&
  1576. getGLSupport()->checkExtension("GL_EXT_geometry_shader4"))
  1577. {
  1578. rsc->setCapability(RSC_GEOMETRY_PROGRAM);
  1579. rsc->setGeometryProgramConstantBoolCount(0);
  1580. rsc->setGeometryProgramConstantIntCount(0);
  1581. GLint floatConstantCount = 0;
  1582. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT, &floatConstantCount);
  1583. rsc->setGeometryProgramConstantFloatCount(floatConstantCount);
  1584. GLint maxOutputVertices;
  1585. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  1586. rsc->setGeometryProgramNumOutputVertices(maxOutputVertices);
  1587. }
  1588. //Check if render to vertex buffer (transform feedback in OpenGL)
  1589. if (GLEW_VERSION_2_0 && getGLSupport()->checkExtension("GL_EXT_transform_feedback"))
  1590. {
  1591. rsc->setCapability(RSC_HWRENDER_TO_VERTEX_BUFFER);
  1592. }
  1593. // Check for texture compression
  1594. if (GLEW_VERSION_1_3 || getGLSupport()->checkExtension("GL_ARB_texture_compression"))
  1595. {
  1596. rsc->setCapability(RSC_TEXTURE_COMPRESSION);
  1597. // Check for dxt compression
  1598. if (getGLSupport()->checkExtension("GL_EXT_texture_compression_s3tc"))
  1599. {
  1600. rsc->setCapability(RSC_TEXTURE_COMPRESSION_DXT);
  1601. }
  1602. // Check for vtc compression
  1603. if (getGLSupport()->checkExtension("GL_NV_texture_compression_vtc"))
  1604. {
  1605. rsc->setCapability(RSC_TEXTURE_COMPRESSION_VTC);
  1606. }
  1607. }
  1608. // As are user clipping planes
  1609. rsc->setCapability(RSC_USER_CLIP_PLANES);
  1610. // 2-sided stencil?
  1611. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_EXT_stencil_two_side"))
  1612. {
  1613. rsc->setCapability(RSC_TWO_SIDED_STENCIL);
  1614. }
  1615. // stencil wrapping?
  1616. if (GLEW_VERSION_1_4 || getGLSupport()->checkExtension("GL_EXT_stencil_wrap"))
  1617. {
  1618. rsc->setCapability(RSC_STENCIL_WRAP);
  1619. }
  1620. // Check for hardware occlusion support
  1621. if (GLEW_VERSION_1_5 || getGLSupport()->checkExtension("GL_ARB_occlusion_query"))
  1622. {
  1623. rsc->setCapability(RSC_HWOCCLUSION);
  1624. }
  1625. // UBYTE4 always supported
  1626. rsc->setCapability(RSC_VERTEX_FORMAT_UBYTE4);
  1627. // Infinite far plane always supported
  1628. rsc->setCapability(RSC_INFINITE_FAR_PLANE);
  1629. // Check for non-power-of-2 texture support
  1630. if (getGLSupport()->checkExtension("GL_ARB_texture_non_power_of_two"))
  1631. {
  1632. rsc->setCapability(RSC_NON_POWER_OF_2_TEXTURES);
  1633. }
  1634. // Check for Float textures
  1635. if (getGLSupport()->checkExtension("GL_ATI_texture_float") || getGLSupport()->checkExtension("GL_ARB_texture_float"))
  1636. {
  1637. rsc->setCapability(RSC_TEXTURE_FLOAT);
  1638. }
  1639. // 3D textures should always be supported
  1640. rsc->setCapability(RSC_TEXTURE_3D);
  1641. // Check for framebuffer object extension
  1642. if (getGLSupport()->checkExtension("GL_ARB_framebuffer_object"))
  1643. {
  1644. // Probe number of draw buffers
  1645. // Only makes sense with FBO support, so probe here
  1646. if (GLEW_VERSION_2_0 || getGLSupport()->checkExtension("GL_ARB_draw_buffers") || getGLSupport()->checkExtension("GL_ATI_draw_buffers"))
  1647. {
  1648. GLint buffers;
  1649. glGetIntegerv(GL_MAX_DRAW_BUFFERS_ARB, &buffers);
  1650. rsc->setNumMultiRenderTargets(std::min<int>(buffers, (GLint)BS_MAX_MULTIPLE_RENDER_TARGETS));
  1651. rsc->setCapability(RSC_MRT_DIFFERENT_BIT_DEPTHS);
  1652. rsc->setCapability(RSC_FBO);
  1653. }
  1654. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1655. }
  1656. rsc->setCapability(RSC_HWRENDER_TO_TEXTURE);
  1657. rsc->setCapability(RSC_PBUFFER);
  1658. // Point size
  1659. float ps;
  1660. glGetFloatv(GL_POINT_SIZE_MAX, &ps);
  1661. rsc->setMaxPointSize(ps);
  1662. // Max number of fragment shader textures
  1663. GLint units;
  1664. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  1665. rsc->setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  1666. // Max number of vertex shader textures
  1667. GLint vUnits;
  1668. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  1669. rsc->setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  1670. if (vUnits > 0)
  1671. {
  1672. rsc->setCapability(RSC_VERTEX_TEXTURE_FETCH);
  1673. }
  1674. GLint numUniformBlocks;
  1675. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  1676. rsc->setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  1677. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  1678. rsc->setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  1679. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  1680. {
  1681. GLint geomUnits;
  1682. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  1683. rsc->setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  1684. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  1685. rsc->setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  1686. }
  1687. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  1688. {
  1689. rsc->setCapability(RSC_TESSELLATION_PROGRAM);
  1690. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  1691. rsc->setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  1692. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  1693. rsc->setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  1694. }
  1695. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  1696. {
  1697. rsc->setCapability(RSC_COMPUTE_PROGRAM);
  1698. GLint computeUnits;
  1699. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  1700. rsc->setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  1701. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  1702. rsc->setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  1703. }
  1704. GLint combinedTexUnits;
  1705. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  1706. rsc->setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  1707. GLint combinedUniformBlockUnits;
  1708. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  1709. rsc->setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  1710. // Mipmap LOD biasing
  1711. if (mGLSupport->checkExtension("GL_EXT_texture_lod_bias"))
  1712. rsc->setCapability(RSC_MIPMAP_LOD_BIAS);
  1713. // Alpha to coverage?
  1714. if (mGLSupport->checkExtension("GL_ARB_multisample"))
  1715. {
  1716. // Alpha to coverage always 'supported' when MSAA is available
  1717. // although card may ignore it if it doesn't specifically support A2C
  1718. rsc->setCapability(RSC_ALPHA_TO_COVERAGE);
  1719. }
  1720. // Advanced blending operations
  1721. if(GLEW_VERSION_2_0)
  1722. {
  1723. rsc->setCapability(RSC_ADVANCED_BLEND_OPERATIONS);
  1724. }
  1725. return rsc;
  1726. }
  1727. bool GLRenderAPI::checkForErrors() const
  1728. {
  1729. GLenum glErr = glGetError();
  1730. bool errorsFound = false;
  1731. String msg;
  1732. while (glErr != GL_NO_ERROR)
  1733. {
  1734. const char* glerrStr = (const char*)gluErrorString(glErr);
  1735. if (glerrStr)
  1736. {
  1737. msg += String(glerrStr);
  1738. }
  1739. glErr = glGetError();
  1740. errorsFound = true;
  1741. }
  1742. if (errorsFound)
  1743. LOGWRN("OpenGL error: " + msg);
  1744. return errorsFound;
  1745. }
  1746. void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  1747. {
  1748. UINT32 x = 0;
  1749. for (UINT32 i = 0; i < 4; i++)
  1750. {
  1751. for (UINT32 j = 0; j < 4; j++)
  1752. {
  1753. gl_matrix[x] = m[j][i];
  1754. x++;
  1755. }
  1756. }
  1757. }
  1758. void GLRenderAPI::applyViewport()
  1759. {
  1760. if (mActiveRenderTarget == nullptr)
  1761. return;
  1762. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1763. // Calculate the "lower-left" corner of the viewport
  1764. mViewportLeft = (UINT32)(rtProps.getWidth() * mViewportNorm.x);
  1765. mViewportTop = (UINT32)(rtProps.getHeight() * mViewportNorm.y);
  1766. mViewportWidth = (UINT32)(rtProps.getWidth() * mViewportNorm.width);
  1767. mViewportHeight = (UINT32)(rtProps.getHeight() * mViewportNorm.height);
  1768. if (rtProps.requiresTextureFlipping())
  1769. {
  1770. // Convert "upper-left" corner to "lower-left"
  1771. mViewportTop = rtProps.getHeight() - (mViewportTop + mViewportHeight) - 1;
  1772. }
  1773. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1774. // Configure the viewport clipping
  1775. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1776. }
  1777. /************************************************************************/
  1778. /* UTILITY */
  1779. /************************************************************************/
  1780. float GLRenderAPI::getMinimumDepthInputValue()
  1781. {
  1782. return -1.0f;
  1783. }
  1784. float GLRenderAPI::getMaximumDepthInputValue()
  1785. {
  1786. return 1.0f;
  1787. }
  1788. float GLRenderAPI::getHorizontalTexelOffset()
  1789. {
  1790. return 0.0f;
  1791. }
  1792. float GLRenderAPI::getVerticalTexelOffset()
  1793. {
  1794. return 0.0f;
  1795. }
  1796. VertexElementType GLRenderAPI::getColorVertexElementType() const
  1797. {
  1798. return VET_COLOR_ABGR;
  1799. }
  1800. void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  1801. {
  1802. dest = matrix;
  1803. }
  1804. bool GLRenderAPI::getGpuProgramHasColumnMajorMatrices() const
  1805. {
  1806. return true;
  1807. }
  1808. GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
  1809. {
  1810. GpuParamBlockDesc block;
  1811. block.blockSize = 0;
  1812. block.isShareable = true;
  1813. block.name = name;
  1814. block.slot = 0;
  1815. for (auto& param : params)
  1816. {
  1817. const GpuParamDataTypeInfo& typeInfo = GpuParams::PARAM_SIZES.lookup[param.type];
  1818. UINT32 size = typeInfo.size / 4;
  1819. UINT32 alignment = typeInfo.alignment / 4;
  1820. // Fix alignment if needed
  1821. UINT32 alignOffset = block.blockSize % alignment;
  1822. if (alignOffset != 0)
  1823. {
  1824. UINT32 padding = (alignment - alignOffset);
  1825. block.blockSize += padding;
  1826. }
  1827. if (param.arraySize > 1)
  1828. {
  1829. // Array elements are always padded and aligned to vec4
  1830. alignOffset = size % typeInfo.baseTypeSize;
  1831. if (alignOffset != 0)
  1832. {
  1833. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  1834. size += padding;
  1835. }
  1836. alignOffset = block.blockSize % typeInfo.baseTypeSize;
  1837. if (alignOffset != 0)
  1838. {
  1839. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  1840. block.blockSize += padding;
  1841. }
  1842. param.elementSize = size;
  1843. param.arrayElementStride = size;
  1844. param.cpuMemOffset = block.blockSize;
  1845. param.gpuMemOffset = 0;
  1846. block.blockSize += size * param.arraySize;
  1847. }
  1848. else
  1849. {
  1850. param.elementSize = size;
  1851. param.arrayElementStride = size;
  1852. param.cpuMemOffset = block.blockSize;
  1853. param.gpuMemOffset = 0;
  1854. block.blockSize += size;
  1855. }
  1856. param.paramBlockSlot = 0;
  1857. }
  1858. // Constant buffer size must always be a multiple of 16
  1859. if (block.blockSize % 4 != 0)
  1860. block.blockSize += (4 - (block.blockSize % 4));
  1861. return block;
  1862. }
  1863. void __stdcall openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam)
  1864. {
  1865. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  1866. {
  1867. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  1868. }
  1869. }
  1870. }