BsGLRenderSystem.cpp 59 KB

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