2
0

BsGLRenderSystem.cpp 58 KB

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