BsGLRenderAPI.cpp 63 KB

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