BsGLRenderAPI.cpp 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsGLRenderAPI.h"
  4. #include "RenderAPI/BsRenderAPI.h"
  5. #include "BsGLTextureManager.h"
  6. #include "BsGLIndexBuffer.h"
  7. #include "BsGLUtil.h"
  8. #include "GLSL/BsGLSLGpuProgram.h"
  9. #include "Error/BsException.h"
  10. #include "BsGLContext.h"
  11. #include "BsGLSupport.h"
  12. #include "RenderAPI/BsBlendState.h"
  13. #include "RenderAPI/BsRasterizerState.h"
  14. #include "RenderAPI/BsDepthStencilState.h"
  15. #include "BsGLRenderTexture.h"
  16. #include "BsGLRenderWindowManager.h"
  17. #include "GLSL/BsGLSLProgramPipelineManager.h"
  18. #include "BsGLVertexArrayObjectManager.h"
  19. #include "Managers/BsRenderStateManager.h"
  20. #include "RenderAPI/BsGpuParams.h"
  21. #include "BsGLGpuParamBlockBuffer.h"
  22. #include "CoreThread/BsCoreThread.h"
  23. #include "BsGLQueryManager.h"
  24. #include "Debug/BsDebug.h"
  25. #include "Profiling/BsRenderStats.h"
  26. #include "RenderAPI/BsGpuParamDesc.h"
  27. #include "BsGLGpuBuffer.h"
  28. #include "BsGLCommandBuffer.h"
  29. #include "BsGLCommandBufferManager.h"
  30. #include "BsGLTextureView.h"
  31. #include "GLSL/BsGLSLParamParser.h"
  32. namespace bs { namespace ct
  33. {
  34. const char* MODULE_NAME = "BansheeGLRenderAPI.dll";
  35. const char* bs_get_gl_error_string(GLenum errorCode)
  36. {
  37. switch (errorCode)
  38. {
  39. case GL_INVALID_OPERATION: return "INVALID_OPERATION";
  40. case GL_INVALID_ENUM: return "INVALID_ENUM";
  41. case GL_INVALID_VALUE: return "INVALID_VALUE";
  42. case GL_OUT_OF_MEMORY: return "OUT_OF_MEMORY";
  43. case GL_INVALID_FRAMEBUFFER_OPERATION: return "INVALID_FRAMEBUFFER_OPERATION";
  44. }
  45. return nullptr;
  46. }
  47. void bs_check_gl_error(const char* function, const char* file, INT32 line)
  48. {
  49. GLenum errorCode = glGetError();
  50. if (errorCode != GL_NO_ERROR)
  51. {
  52. StringStream errorOutput;
  53. errorOutput << "OpenGL error in " << function << " [" << file << ":" << toString(line) << "]:\n";
  54. while (errorCode != GL_NO_ERROR)
  55. {
  56. const char* errorString = bs_get_gl_error_string(errorCode);
  57. if (errorString)
  58. errorOutput << "\t - " << errorString;
  59. errorCode = glGetError();
  60. }
  61. gDebug().logWarning(errorOutput.str());
  62. }
  63. }
  64. #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
  65. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar
  66. *message, GLvoid *userParam);
  67. #endif
  68. /************************************************************************/
  69. /* PUBLIC INTERFACE */
  70. /************************************************************************/
  71. GLRenderAPI::GLRenderAPI()
  72. : mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  73. , mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280)
  74. , mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0)
  75. , mScissorEnabled(false)
  76. , mStencilReadMask(0xFFFFFFFF)
  77. , mStencilWriteMask(0xFFFFFFFF)
  78. , mStencilRefValue(0)
  79. , mStencilCompareFront(CMPF_ALWAYS_PASS)
  80. , mStencilCompareBack(CMPF_ALWAYS_PASS)
  81. , mNumTextureUnits(0)
  82. , mTextureInfos(nullptr)
  83. , mDepthWrite(true)
  84. , mGLSLProgramFactory(nullptr)
  85. , mProgramPipelineManager(nullptr)
  86. , mActivePipeline(nullptr)
  87. , mCurrentDrawOperation(DOT_TRIANGLE_LIST)
  88. , mDrawCallInProgress(false)
  89. , mActiveTextureUnit(-1)
  90. {
  91. // Get our GLSupport
  92. mGLSupport = ct::getGLSupport();
  93. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  94. mCurrentContext = 0;
  95. mMainContext = 0;
  96. mGLInitialised = false;
  97. mMinFilter = FO_LINEAR;
  98. mMipFilter = FO_POINT;
  99. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  100. }
  101. GLRenderAPI::~GLRenderAPI()
  102. {
  103. }
  104. const StringID& GLRenderAPI::getName() const
  105. {
  106. static StringID strName("GLRenderAPI");
  107. return strName;
  108. }
  109. void GLRenderAPI::initialize()
  110. {
  111. THROW_IF_NOT_CORE_THREAD;
  112. mGLSupport->start();
  113. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  114. CommandBufferManager::startUp<GLCommandBufferManager>();
  115. bs::RenderWindowManager::startUp<bs::GLRenderWindowManager>(this);
  116. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  117. RenderStateManager::startUp();
  118. QueryManager::startUp<GLQueryManager>();
  119. RenderAPI::initialize();
  120. }
  121. void GLRenderAPI::initializeWithWindow(const SPtr<RenderWindow>& primaryWindow)
  122. {
  123. // Get the context from the window and finish initialization
  124. SPtr<GLContext> context;
  125. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  126. // Set main and current context
  127. mMainContext = context;
  128. mCurrentContext = mMainContext;
  129. // Set primary context as active
  130. if (mCurrentContext)
  131. mCurrentContext->setCurrent(*primaryWindow);
  132. // Setup GLSupport
  133. mGLSupport->initializeExtensions();
  134. mNumDevices = 1;
  135. mCurrentCapabilities = bs_newN<RenderAPICapabilities>(mNumDevices);
  136. initCapabilities(mCurrentCapabilities[0]);
  137. initFromCaps(mCurrentCapabilities);
  138. GLVertexArrayObjectManager::startUp();
  139. glFrontFace(GL_CW);
  140. BS_CHECK_GL_ERROR();
  141. // Ensure cubemaps are filtered across seams
  142. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
  143. BS_CHECK_GL_ERROR();
  144. GPUInfo gpuInfo;
  145. gpuInfo.numGPUs = 1;
  146. const char* vendor = (const char*)glGetString(GL_VENDOR);
  147. BS_CHECK_GL_ERROR();
  148. const char* renderer = (const char*)glGetString(GL_RENDERER);
  149. BS_CHECK_GL_ERROR();
  150. gpuInfo.names[0] = String(vendor) + " " + String(renderer);
  151. PlatformUtility::_setGPUInfo(gpuInfo);
  152. mGLInitialised = true;
  153. RenderAPI::initializeWithWindow(primaryWindow);
  154. }
  155. void GLRenderAPI::destroyCore()
  156. {
  157. RenderAPI::destroyCore();
  158. // Deleting the GLSL program factory
  159. if (mGLSLProgramFactory)
  160. {
  161. // Remove from manager safely
  162. GpuProgramManager::instance().removeFactory("glsl");
  163. GpuProgramManager::instance().removeFactory("glsl4_1");
  164. bs_delete(mGLSLProgramFactory);
  165. mGLSLProgramFactory = nullptr;
  166. }
  167. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  168. HardwareBufferManager::shutDown();
  169. bs::HardwareBufferManager::shutDown();
  170. GLRTTManager::shutDown();
  171. for (UINT32 i = 0; i < MAX_VB_COUNT; i++)
  172. mBoundVertexBuffers[i] = nullptr;
  173. mBoundVertexDeclaration = nullptr;
  174. mBoundIndexBuffer = nullptr;
  175. mCurrentVertexProgram = nullptr;
  176. mCurrentFragmentProgram = nullptr;
  177. mCurrentGeometryProgram = nullptr;
  178. mCurrentHullProgram = nullptr;
  179. mCurrentDomainProgram = nullptr;
  180. mCurrentComputeProgram = nullptr;
  181. mGLSupport->stop();
  182. TextureManager::shutDown();
  183. bs::TextureManager::shutDown();
  184. QueryManager::shutDown();
  185. RenderWindowManager::shutDown();
  186. bs::RenderWindowManager::shutDown();
  187. RenderStateManager::shutDown();
  188. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  189. CommandBufferManager::shutDown();
  190. mGLInitialised = false;
  191. if(mProgramPipelineManager != nullptr)
  192. bs_delete(mProgramPipelineManager);
  193. if(mCurrentContext)
  194. mCurrentContext->endCurrent();
  195. mCurrentContext = nullptr;
  196. mMainContext = nullptr;
  197. if(mGLSupport)
  198. bs_delete(mGLSupport);
  199. if (mTextureInfos != nullptr)
  200. bs_deleteN(mTextureInfos, mNumTextureUnits);
  201. }
  202. void GLRenderAPI::setGraphicsPipeline(const SPtr<GraphicsPipelineState>& pipelineState,
  203. const SPtr<CommandBuffer>& commandBuffer)
  204. {
  205. auto executeRef = [&](const SPtr<GraphicsPipelineState>& pipelineState)
  206. {
  207. THROW_IF_NOT_CORE_THREAD;
  208. BlendState* blendState;
  209. RasterizerState* rasterizerState;
  210. DepthStencilState* depthStencilState;
  211. if (pipelineState != nullptr)
  212. {
  213. mCurrentVertexProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getVertexProgram());
  214. mCurrentFragmentProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getFragmentProgram());
  215. mCurrentGeometryProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getGeometryProgram());
  216. mCurrentDomainProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getDomainProgram());
  217. mCurrentHullProgram = std::static_pointer_cast<GLSLGpuProgram>(pipelineState->getHullProgram());
  218. blendState = pipelineState->getBlendState().get();
  219. rasterizerState = pipelineState->getRasterizerState().get();
  220. depthStencilState = pipelineState->getDepthStencilState().get();
  221. if (blendState == nullptr)
  222. blendState = BlendState::getDefault().get();
  223. if (rasterizerState == nullptr)
  224. rasterizerState = RasterizerState::getDefault().get();
  225. if(depthStencilState == nullptr)
  226. depthStencilState = DepthStencilState::getDefault().get();
  227. }
  228. else
  229. {
  230. mCurrentVertexProgram = nullptr;
  231. mCurrentFragmentProgram = nullptr;
  232. mCurrentGeometryProgram = nullptr;
  233. mCurrentDomainProgram = nullptr;
  234. mCurrentHullProgram = nullptr;
  235. blendState = BlendState::getDefault().get();
  236. rasterizerState = RasterizerState::getDefault().get();
  237. depthStencilState = DepthStencilState::getDefault().get();
  238. }
  239. // Blend state
  240. {
  241. const BlendProperties& stateProps = blendState->getProperties();
  242. // Alpha to coverage
  243. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  244. // Blend states
  245. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  246. if (stateProps.getBlendEnabled(0))
  247. {
  248. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  249. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  250. }
  251. else
  252. {
  253. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  254. }
  255. // Color write mask
  256. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  257. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  258. }
  259. // Rasterizer state
  260. {
  261. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  262. setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  263. setCullingMode(stateProps.getCullMode());
  264. setPolygonMode(stateProps.getPolygonMode());
  265. setScissorTestEnable(stateProps.getScissorEnable());
  266. setMultisamplingEnable(stateProps.getMultisampleEnable());
  267. setDepthClipEnable(stateProps.getDepthClipEnable());
  268. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  269. }
  270. // Depth stencil state
  271. {
  272. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  273. // Set stencil buffer options
  274. setStencilCheckEnabled(stateProps.getStencilEnable());
  275. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  276. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  277. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  278. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  279. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  280. // Set depth buffer options
  281. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  282. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  283. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  284. }
  285. };
  286. if (commandBuffer == nullptr)
  287. executeRef(pipelineState);
  288. else
  289. {
  290. auto execute = [=]() { executeRef(pipelineState); };
  291. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  292. cb->queueCommand(execute);
  293. }
  294. BS_INC_RENDER_STAT(NumPipelineStateChanges);
  295. }
  296. void GLRenderAPI::setComputePipeline(const SPtr<ComputePipelineState>& pipelineState,
  297. const SPtr<CommandBuffer>& commandBuffer)
  298. {
  299. auto executeRef = [&](const SPtr<ComputePipelineState>& pipelineState)
  300. {
  301. THROW_IF_NOT_CORE_THREAD;
  302. SPtr<GpuProgram> program;
  303. if (pipelineState != nullptr)
  304. program = pipelineState->getProgram();
  305. if (program != nullptr && program->getProperties().getType() == GPT_COMPUTE_PROGRAM)
  306. mCurrentComputeProgram = std::static_pointer_cast<GLSLGpuProgram>(program);
  307. else
  308. mCurrentComputeProgram = nullptr;
  309. };
  310. if (commandBuffer == nullptr)
  311. executeRef(pipelineState);
  312. else
  313. {
  314. auto execute = [=]() { executeRef(pipelineState); };
  315. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  316. cb->queueCommand(execute);
  317. }
  318. BS_INC_RENDER_STAT(NumPipelineStateChanges);
  319. }
  320. void GLRenderAPI::setGpuParams(const SPtr<GpuParams>& gpuParams, const SPtr<CommandBuffer>& commandBuffer)
  321. {
  322. auto executeRef = [&](const SPtr<GpuParams>& gpuParams)
  323. {
  324. THROW_IF_NOT_CORE_THREAD;
  325. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  326. for (UINT32 i = 0; i < 8; i++)
  327. {
  328. glBindImageTexture(i, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  329. BS_CHECK_GL_ERROR();
  330. }
  331. #endif
  332. bs_frame_mark();
  333. {
  334. UINT32 textureUnitCount = 0;
  335. FrameVector<UINT32> textureUnits(12);
  336. auto getTexUnit = [&](UINT32 binding)
  337. {
  338. for(UINT32 i = 0; i < (UINT32)textureUnits.size(); i++)
  339. {
  340. if (textureUnits[i] == binding)
  341. return i;
  342. }
  343. UINT32 unit = textureUnitCount++;
  344. textureUnits.push_back(binding);
  345. return unit;
  346. };
  347. UINT32 imageUnitCount = 0;
  348. FrameVector<UINT32> imageUnits(6);
  349. auto getImageUnit = [&](UINT32 binding)
  350. {
  351. for (UINT32 i = 0; i < (UINT32)imageUnits.size(); i++)
  352. {
  353. if (imageUnits[i] == binding)
  354. return i;
  355. }
  356. UINT32 unit = imageUnitCount++;
  357. imageUnits.push_back(binding);
  358. return unit;
  359. };
  360. UINT32 uniformUnitCount = 0;
  361. FrameVector<UINT32> uniformUnits(6);
  362. auto getUniformUnit = [&](UINT32 binding)
  363. {
  364. for (UINT32 i = 0; i < (UINT32)uniformUnits.size(); i++)
  365. {
  366. if (uniformUnits[i] == binding)
  367. return i;
  368. }
  369. UINT32 unit = uniformUnitCount++;
  370. uniformUnits.push_back(binding);
  371. return unit;
  372. };
  373. UINT32 sharedStorageUnitCount = 0;
  374. FrameVector<UINT32> sharedStorageUnits(6);
  375. auto getSharedStorageUnit = [&](UINT32 binding)
  376. {
  377. for (UINT32 i = 0; i < (UINT32)sharedStorageUnits.size(); i++)
  378. {
  379. if (sharedStorageUnits[i] == binding)
  380. return i;
  381. }
  382. UINT32 unit = sharedStorageUnitCount++;
  383. sharedStorageUnits.push_back(binding);
  384. return unit;
  385. };
  386. const UINT32 numStages = 6;
  387. for(UINT32 i = 0; i < numStages; i++)
  388. {
  389. textureUnits.clear();
  390. imageUnits.clear();
  391. uniformUnits.clear();
  392. sharedStorageUnits.clear();
  393. GpuProgramType type = (GpuProgramType)i;
  394. SPtr<GpuParamDesc> paramDesc = gpuParams->getParamDesc(type);
  395. if (paramDesc == nullptr)
  396. continue;
  397. for (auto& entry : paramDesc->textures)
  398. {
  399. UINT32 binding = entry.second.slot;
  400. SPtr<Texture> texture = gpuParams->getTexture(entry.second.set, binding);
  401. const TextureSurface& surface = gpuParams->getTextureSurface(entry.second.set, binding);
  402. UINT32 unit = getTexUnit(binding);
  403. if (!activateGLTextureUnit(unit))
  404. continue;
  405. GLTexture* glTex = static_cast<GLTexture*>(texture.get());
  406. if (glTex != nullptr)
  407. {
  408. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  409. SPtr<TextureView> texView = glTex->requestView(
  410. surface.mipLevel,
  411. surface.numMipLevels,
  412. surface.face,
  413. surface.numFaces,
  414. GVU_DEFAULT);
  415. GLTextureView* glTexView = static_cast<GLTextureView*>(texView.get());
  416. GLenum newTextureType = glTexView->getGLTextureTarget();
  417. GLuint texId = glTexView->getGLID();
  418. #else
  419. // Texture views are not supported, so if user requested a part of the texture surface report
  420. // a warning
  421. auto& props = texture->getProperties();
  422. if (surface.mipLevel != 0 || surface.face != 0 ||
  423. (surface.numMipLevels != 0 && surface.numMipLevels != props.getNumMipmaps()) ||
  424. (surface.numFaces != 0 && surface.numFaces != props.getNumFaces()))
  425. {
  426. LOGWRN("Attempting to bind only a part of a texture, but texture views are not supported. "
  427. "Entire texture will be bound instead.");
  428. }
  429. GLenum newTextureType = glTex->getGLTextureTarget();
  430. GLuint texId = glTex->getGLID();
  431. #endif
  432. if (mTextureInfos[unit].type != newTextureType)
  433. {
  434. glBindTexture(mTextureInfos[unit].type, 0);
  435. BS_CHECK_GL_ERROR();
  436. }
  437. glBindTexture(newTextureType, texId);
  438. BS_CHECK_GL_ERROR();
  439. mTextureInfos[unit].type = newTextureType;
  440. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  441. if (activeProgram != nullptr)
  442. {
  443. GLuint glProgram = activeProgram->getGLHandle();
  444. glProgramUniform1i(glProgram, binding, unit);
  445. BS_CHECK_GL_ERROR();
  446. }
  447. }
  448. else
  449. {
  450. glBindTexture(mTextureInfos[unit].type, 0);
  451. BS_CHECK_GL_ERROR();
  452. }
  453. }
  454. for(auto& entry : paramDesc->samplers)
  455. {
  456. UINT32 binding = entry.second.slot;
  457. SPtr<SamplerState> samplerState = gpuParams->getSamplerState(entry.second.set, binding);
  458. if (samplerState == nullptr)
  459. samplerState = SamplerState::getDefault();
  460. UINT32 unit = getTexUnit(binding);
  461. if (!activateGLTextureUnit(unit))
  462. continue;
  463. bool isMultisample = mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE ||
  464. mTextureInfos[unit].type == GL_TEXTURE_2D_MULTISAMPLE_ARRAY;
  465. // No sampler options for multisampled textures
  466. if (!isMultisample)
  467. {
  468. const SamplerProperties& stateProps = samplerState->getProperties();
  469. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  470. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  471. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  472. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  473. setTextureCompareMode(unit, stateProps.getComparisonFunction());
  474. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  475. setTextureMipmapRange(unit, stateProps.getMinimumMip(), stateProps.getMaximumMip());
  476. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  477. setTextureAddressingMode(unit, uvw);
  478. setTextureBorderColor(unit, stateProps.getBorderColor());
  479. }
  480. }
  481. for(auto& entry : paramDesc->buffers)
  482. {
  483. UINT32 binding = entry.second.slot;
  484. SPtr<GpuBuffer> buffer = gpuParams->getBuffer(entry.second.set, binding);
  485. GLGpuBuffer* glBuffer = static_cast<GLGpuBuffer*>(buffer.get());
  486. switch(entry.second.type)
  487. {
  488. case GPOT_BYTE_BUFFER: // Texture buffer (read-only, unstructured)
  489. {
  490. UINT32 unit = getTexUnit(binding);
  491. if (!activateGLTextureUnit(unit))
  492. continue;
  493. if (glBuffer != nullptr)
  494. {
  495. if (mTextureInfos[unit].type != GL_TEXTURE_BUFFER)
  496. {
  497. glBindTexture(mTextureInfos[unit].type, 0);
  498. BS_CHECK_GL_ERROR();
  499. }
  500. mTextureInfos[unit].type = GL_TEXTURE_BUFFER;
  501. glBindTexture(GL_TEXTURE_BUFFER, glBuffer->getGLTextureId());
  502. BS_CHECK_GL_ERROR();
  503. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  504. if (activeProgram != nullptr)
  505. {
  506. GLuint glProgram = activeProgram->getGLHandle();
  507. glProgramUniform1i(glProgram, binding, unit);
  508. BS_CHECK_GL_ERROR();
  509. }
  510. }
  511. else
  512. {
  513. glBindTexture(mTextureInfos[unit].type, 0);
  514. BS_CHECK_GL_ERROR();
  515. }
  516. }
  517. break;
  518. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  519. case GPOT_RWBYTE_BUFFER: // Storage buffer (read/write, unstructured)
  520. {
  521. UINT32 unit = getImageUnit(binding);
  522. if (glBuffer != nullptr)
  523. {
  524. glBindImageTexture(
  525. unit,
  526. glBuffer->getGLTextureId(),
  527. 0,
  528. false,
  529. 0,
  530. GL_READ_WRITE,
  531. glBuffer->getGLFormat());
  532. BS_CHECK_GL_ERROR();
  533. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  534. if (activeProgram != nullptr)
  535. {
  536. GLuint glProgram = activeProgram->getGLHandle();
  537. glProgramUniform1i(glProgram, binding, unit);
  538. BS_CHECK_GL_ERROR();
  539. }
  540. }
  541. else
  542. {
  543. glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  544. BS_CHECK_GL_ERROR();
  545. }
  546. }
  547. break;
  548. #endif
  549. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  550. case GPOT_RWSTRUCTURED_BUFFER: // Shared storage block (read/write, structured)
  551. {
  552. UINT32 unit = getSharedStorageUnit(binding);
  553. if (glBuffer != nullptr)
  554. {
  555. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, glBuffer->getGLBufferId());
  556. BS_CHECK_GL_ERROR();
  557. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  558. if (activeProgram != nullptr)
  559. {
  560. GLuint glProgram = activeProgram->getGLHandle();
  561. glShaderStorageBlockBinding(glProgram, binding, unit);
  562. BS_CHECK_GL_ERROR();
  563. }
  564. }
  565. else
  566. {
  567. glBindBufferBase(GL_SHADER_STORAGE_BUFFER, unit, 0);
  568. BS_CHECK_GL_ERROR();
  569. }
  570. }
  571. break;
  572. #endif
  573. default:
  574. break;
  575. }
  576. }
  577. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  578. for(auto& entry : paramDesc->loadStoreTextures)
  579. {
  580. UINT32 binding = entry.second.slot;
  581. SPtr<Texture> texture = gpuParams->getLoadStoreTexture(entry.second.set, binding);
  582. const TextureSurface& surface = gpuParams->getLoadStoreSurface(entry.second.set, binding);
  583. UINT32 unit = getImageUnit(binding);
  584. if (texture != nullptr)
  585. {
  586. GLTexture* tex = static_cast<GLTexture*>(texture.get());
  587. auto& texProps = tex->getProperties();
  588. GLboolean bindAllLayers =
  589. texProps.getNumFaces() == surface.numFaces ||
  590. surface.numFaces == 0;
  591. if(!bindAllLayers && surface.numFaces > 1)
  592. {
  593. LOGWRN("Attempting to bind multiple faces of a load-store texture. You are allowed to bind \
  594. either a single face, or all the faces of the texture. Only the first face will \
  595. be bound instead.");
  596. }
  597. if(surface.numMipLevels > 1)
  598. {
  599. LOGWRN("Attempting to bind multiple mip levels of a load-store texture. This is not \
  600. supported and only the first provided level will be bound.");
  601. }
  602. glBindImageTexture(
  603. unit,
  604. tex->getGLID(),
  605. surface.mipLevel,
  606. bindAllLayers,
  607. surface.face,
  608. GL_READ_WRITE,
  609. tex->getGLFormat());
  610. BS_CHECK_GL_ERROR();
  611. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  612. if (activeProgram != nullptr)
  613. {
  614. GLuint glProgram = activeProgram->getGLHandle();
  615. glProgramUniform1i(glProgram, binding, unit);
  616. BS_CHECK_GL_ERROR();
  617. }
  618. }
  619. else
  620. {
  621. glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  622. BS_CHECK_GL_ERROR();
  623. }
  624. }
  625. #endif
  626. for (auto& entry : paramDesc->paramBlocks)
  627. {
  628. UINT32 binding = entry.second.slot;
  629. SPtr<GpuParamBlockBuffer> buffer = gpuParams->getParamBlockBuffer(entry.second.set, binding);
  630. if (buffer == nullptr)
  631. continue;
  632. buffer->flushToGPU();
  633. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  634. GLuint glProgram = activeProgram->getGLHandle();
  635. // 0 means uniforms are not in block, in which case we handle it specially
  636. if (binding == 0)
  637. {
  638. UINT8* uniformBufferData = (UINT8*)bs_stack_alloc(buffer->getSize());
  639. buffer->read(0, uniformBufferData, buffer->getSize());
  640. for (auto iter = paramDesc->params.begin(); iter != paramDesc->params.end(); ++iter)
  641. {
  642. const GpuParamDataDesc& param = iter->second;
  643. if (param.paramBlockSlot != 0) // 0 means uniforms are not in a block
  644. continue;
  645. const UINT8* ptrData = uniformBufferData + param.cpuMemOffset * sizeof(UINT32);
  646. // Note: We don't transpose matrices here even though we don't use column major format
  647. // because they are assumed to be pre-transposed in the GpuParams buffer
  648. switch (param.type)
  649. {
  650. case GPDT_FLOAT1:
  651. glProgramUniform1fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  652. BS_CHECK_GL_ERROR();
  653. break;
  654. case GPDT_FLOAT2:
  655. glProgramUniform2fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  656. BS_CHECK_GL_ERROR();
  657. break;
  658. case GPDT_FLOAT3:
  659. glProgramUniform3fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  660. BS_CHECK_GL_ERROR();
  661. break;
  662. case GPDT_FLOAT4:
  663. glProgramUniform4fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  664. BS_CHECK_GL_ERROR();
  665. break;
  666. case GPDT_MATRIX_2X2:
  667. glProgramUniformMatrix2fv(
  668. glProgram,
  669. param.gpuMemOffset,
  670. param.arraySize,
  671. GL_FALSE,
  672. (GLfloat*)ptrData);
  673. BS_CHECK_GL_ERROR();
  674. break;
  675. case GPDT_MATRIX_2X3:
  676. glProgramUniformMatrix3x2fv(
  677. glProgram,
  678. param.gpuMemOffset,
  679. param.arraySize,
  680. GL_FALSE,
  681. (GLfloat*)ptrData);
  682. BS_CHECK_GL_ERROR();
  683. break;
  684. case GPDT_MATRIX_2X4:
  685. glProgramUniformMatrix4x2fv(
  686. glProgram,
  687. param.gpuMemOffset,
  688. param.arraySize,
  689. GL_FALSE,
  690. (GLfloat*)ptrData);
  691. BS_CHECK_GL_ERROR();
  692. break;
  693. case GPDT_MATRIX_3X2:
  694. glProgramUniformMatrix2x3fv(
  695. glProgram,
  696. param.gpuMemOffset,
  697. param.arraySize,
  698. GL_FALSE,
  699. (GLfloat*)ptrData);
  700. BS_CHECK_GL_ERROR();
  701. break;
  702. case GPDT_MATRIX_3X3:
  703. glProgramUniformMatrix3fv(
  704. glProgram,
  705. param.gpuMemOffset,
  706. param.arraySize,
  707. GL_FALSE,
  708. (GLfloat*)ptrData);
  709. BS_CHECK_GL_ERROR();
  710. break;
  711. case GPDT_MATRIX_3X4:
  712. glProgramUniformMatrix4x3fv(
  713. glProgram,
  714. param.gpuMemOffset,
  715. param.arraySize,
  716. GL_FALSE,
  717. (GLfloat*)ptrData);
  718. BS_CHECK_GL_ERROR();
  719. break;
  720. case GPDT_MATRIX_4X2:
  721. glProgramUniformMatrix2x4fv(
  722. glProgram,
  723. param.gpuMemOffset,
  724. param.arraySize,
  725. GL_FALSE,
  726. (GLfloat*)ptrData);
  727. BS_CHECK_GL_ERROR();
  728. break;
  729. case GPDT_MATRIX_4X3:
  730. glProgramUniformMatrix3x4fv(
  731. glProgram,
  732. param.gpuMemOffset,
  733. param.arraySize,
  734. GL_FALSE,
  735. (GLfloat*)ptrData);
  736. BS_CHECK_GL_ERROR();
  737. break;
  738. case GPDT_MATRIX_4X4:
  739. glProgramUniformMatrix4fv(
  740. glProgram,
  741. param.gpuMemOffset,
  742. param.arraySize,
  743. GL_FALSE,
  744. (GLfloat*)ptrData);
  745. BS_CHECK_GL_ERROR();
  746. break;
  747. case GPDT_INT1:
  748. glProgramUniform1iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  749. BS_CHECK_GL_ERROR();
  750. break;
  751. case GPDT_INT2:
  752. glProgramUniform2iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  753. BS_CHECK_GL_ERROR();
  754. break;
  755. case GPDT_INT3:
  756. glProgramUniform3iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  757. BS_CHECK_GL_ERROR();
  758. break;
  759. case GPDT_INT4:
  760. glProgramUniform4iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  761. BS_CHECK_GL_ERROR();
  762. break;
  763. case GPDT_BOOL:
  764. glProgramUniform1uiv(glProgram, param.gpuMemOffset, param.arraySize, (GLuint*)ptrData);
  765. BS_CHECK_GL_ERROR();
  766. break;
  767. default:
  768. case GPDT_UNKNOWN:
  769. break;
  770. }
  771. }
  772. if (uniformBufferData != nullptr)
  773. bs_stack_free(uniformBufferData);
  774. }
  775. else
  776. {
  777. const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(buffer.get());
  778. UINT32 unit = getUniformUnit(binding - 1);
  779. glUniformBlockBinding(glProgram, binding - 1, unit);
  780. BS_CHECK_GL_ERROR();
  781. glBindBufferBase(GL_UNIFORM_BUFFER, unit, glParamBlockBuffer->getGLHandle());
  782. BS_CHECK_GL_ERROR();
  783. }
  784. }
  785. }
  786. }
  787. bs_frame_clear();
  788. activateGLTextureUnit(0);
  789. };
  790. if (commandBuffer == nullptr)
  791. executeRef(gpuParams);
  792. else
  793. {
  794. auto execute = [=]() { executeRef(gpuParams); };
  795. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  796. cb->queueCommand(execute);
  797. }
  798. BS_INC_RENDER_STAT(NumGpuParamBinds);
  799. }
  800. void GLRenderAPI::setStencilRef(UINT32 stencilRefValue, const SPtr<CommandBuffer>& commandBuffer)
  801. {
  802. auto executeRef = [&](UINT32 stencilRefValue)
  803. {
  804. THROW_IF_NOT_CORE_THREAD;
  805. setStencilRefValue(stencilRefValue);
  806. };
  807. if (commandBuffer == nullptr)
  808. executeRef(stencilRefValue);
  809. else
  810. {
  811. auto execute = [=]() { executeRef(stencilRefValue); };
  812. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  813. cb->queueCommand(execute);
  814. }
  815. }
  816. void GLRenderAPI::setViewport(const Rect2& area,
  817. const SPtr<CommandBuffer>& commandBuffer)
  818. {
  819. auto executeRef = [&](const Rect2& area)
  820. {
  821. THROW_IF_NOT_CORE_THREAD;
  822. mViewportNorm = area;
  823. applyViewport();
  824. };
  825. if (commandBuffer == nullptr)
  826. executeRef(area);
  827. else
  828. {
  829. auto execute = [=]() { executeRef(area); };
  830. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  831. cb->queueCommand(execute);
  832. }
  833. }
  834. void GLRenderAPI::setRenderTarget(const SPtr<RenderTarget>& target, UINT32 readOnlyFlags,
  835. RenderSurfaceMask loadMask, const SPtr<CommandBuffer>& commandBuffer)
  836. {
  837. auto executeRef = [&](const SPtr<RenderTarget>& target, UINT32 readOnlyFlags)
  838. {
  839. THROW_IF_NOT_CORE_THREAD;
  840. // Switch context if different from current one
  841. if (target != nullptr && target->getProperties().isWindow)
  842. {
  843. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  844. SPtr<GLContext> newContext;
  845. target->getCustomAttribute("GLCONTEXT", &newContext);
  846. if (newContext && mCurrentContext != newContext)
  847. switchContext(newContext, *window);
  848. else
  849. mCurrentContext->setCurrent(*window);
  850. }
  851. // This must happen after context switch to ensure previous context is still alive
  852. mActiveRenderTarget = target;
  853. GLFrameBufferObject* fbo = nullptr;
  854. if (target != nullptr)
  855. target->getCustomAttribute("FBO", &fbo);
  856. if (fbo != nullptr)
  857. {
  858. fbo->bind();
  859. // Enable / disable sRGB states
  860. if (target->getProperties().hwGamma)
  861. {
  862. glEnable(GL_FRAMEBUFFER_SRGB);
  863. BS_CHECK_GL_ERROR();
  864. }
  865. else
  866. {
  867. glDisable(GL_FRAMEBUFFER_SRGB);
  868. BS_CHECK_GL_ERROR();
  869. }
  870. }
  871. else
  872. {
  873. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  874. BS_CHECK_GL_ERROR();
  875. }
  876. applyViewport();
  877. };
  878. if (commandBuffer == nullptr)
  879. executeRef(target, readOnlyFlags);
  880. else
  881. {
  882. auto execute = [=]() { executeRef(target, readOnlyFlags); };
  883. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  884. cb->queueCommand(execute);
  885. }
  886. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  887. }
  888. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers,
  889. const SPtr<CommandBuffer>& commandBuffer)
  890. {
  891. #if BS_DEBUG_MODE
  892. UINT32 lastIdx = index + numBuffers;
  893. if(lastIdx > MAX_VB_COUNT)
  894. {
  895. LOGERR("Provided vertex buffer slot range is invalid: " + toString(index) + " to " +
  896. toString(index + numBuffers) + ".");
  897. return;
  898. }
  899. #endif
  900. auto executeRef = [&](UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers)
  901. {
  902. THROW_IF_NOT_CORE_THREAD;
  903. std::array<SPtr<VertexBuffer>, MAX_VB_COUNT> boundBuffers;
  904. for (UINT32 i = 0; i < numBuffers; i++)
  905. boundBuffers[index + i] = buffers[i];
  906. for (UINT32 i = 0; i < numBuffers; i++)
  907. mBoundVertexBuffers[index + i] = boundBuffers[index + i];
  908. };
  909. if (commandBuffer == nullptr)
  910. executeRef(index, buffers, numBuffers);
  911. else
  912. {
  913. auto execute = [=]() { executeRef(index, buffers, numBuffers); };
  914. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  915. cb->queueCommand(execute);
  916. }
  917. }
  918. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclaration>& vertexDeclaration,
  919. const SPtr<CommandBuffer>& commandBuffer)
  920. {
  921. auto executeRef = [&](const SPtr<VertexDeclaration>& vertexDeclaration)
  922. {
  923. THROW_IF_NOT_CORE_THREAD;
  924. mBoundVertexDeclaration = vertexDeclaration;
  925. };
  926. if (commandBuffer == nullptr)
  927. executeRef(vertexDeclaration);
  928. else
  929. {
  930. auto execute = [=]() { executeRef(vertexDeclaration); };
  931. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  932. cb->queueCommand(execute);
  933. }
  934. }
  935. void GLRenderAPI::setDrawOperation(DrawOperationType op, const SPtr<CommandBuffer>& commandBuffer)
  936. {
  937. auto executeRef = [&](DrawOperationType op)
  938. {
  939. THROW_IF_NOT_CORE_THREAD;
  940. mCurrentDrawOperation = op;
  941. };
  942. if (commandBuffer == nullptr)
  943. executeRef(op);
  944. else
  945. {
  946. auto execute = [=]() { executeRef(op); };
  947. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  948. cb->queueCommand(execute);
  949. cb->mCurrentDrawOperation = op;
  950. }
  951. }
  952. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBuffer>& buffer, const SPtr<CommandBuffer>& commandBuffer)
  953. {
  954. auto executeRef = [&](const SPtr<IndexBuffer>& buffer)
  955. {
  956. THROW_IF_NOT_CORE_THREAD;
  957. mBoundIndexBuffer = buffer;
  958. };
  959. if (commandBuffer == nullptr)
  960. executeRef(buffer);
  961. else
  962. {
  963. auto execute = [=]() { executeRef(buffer); };
  964. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  965. cb->queueCommand(execute);
  966. }
  967. }
  968. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount,
  969. const SPtr<CommandBuffer>& commandBuffer)
  970. {
  971. auto executeRef = [&](UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount)
  972. {
  973. THROW_IF_NOT_CORE_THREAD;
  974. // Find the correct type to render
  975. GLint primType = getGLDrawMode();
  976. beginDraw();
  977. if (instanceCount <= 1)
  978. {
  979. glDrawArrays(primType, vertexOffset, vertexCount);
  980. BS_CHECK_GL_ERROR();
  981. }
  982. else
  983. {
  984. glDrawArraysInstanced(primType, vertexOffset, vertexCount, instanceCount);
  985. BS_CHECK_GL_ERROR();
  986. }
  987. endDraw();
  988. };
  989. UINT32 primCount;
  990. if (commandBuffer == nullptr)
  991. {
  992. executeRef(vertexOffset, vertexCount, instanceCount);
  993. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  994. }
  995. else
  996. {
  997. auto execute = [=]() { executeRef(vertexOffset, vertexCount, instanceCount); };
  998. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  999. cb->queueCommand(execute);
  1000. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1001. }
  1002. BS_INC_RENDER_STAT(NumDrawCalls);
  1003. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1004. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1005. }
  1006. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1007. UINT32 instanceCount, const SPtr<CommandBuffer>& commandBuffer)
  1008. {
  1009. auto executeRef = [&](UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1010. UINT32 instanceCount)
  1011. {
  1012. THROW_IF_NOT_CORE_THREAD;
  1013. if (mBoundIndexBuffer == nullptr)
  1014. {
  1015. LOGWRN("Cannot draw indexed because index buffer is not set.");
  1016. return;
  1017. }
  1018. // Find the correct type to render
  1019. GLint primType = getGLDrawMode();
  1020. beginDraw();
  1021. SPtr<GLIndexBuffer> indexBuffer = std::static_pointer_cast<GLIndexBuffer>(mBoundIndexBuffer);
  1022. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  1023. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  1024. BS_CHECK_GL_ERROR();
  1025. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  1026. if (instanceCount <= 1)
  1027. {
  1028. glDrawElementsBaseVertex(
  1029. primType,
  1030. indexCount,
  1031. indexType,
  1032. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1033. vertexOffset);
  1034. BS_CHECK_GL_ERROR();
  1035. }
  1036. else
  1037. {
  1038. glDrawElementsInstancedBaseVertex(
  1039. primType,
  1040. indexCount,
  1041. indexType,
  1042. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1043. instanceCount,
  1044. vertexOffset);
  1045. BS_CHECK_GL_ERROR();
  1046. }
  1047. endDraw();
  1048. };
  1049. UINT32 primCount;
  1050. if (commandBuffer == nullptr)
  1051. {
  1052. executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount);
  1053. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  1054. }
  1055. else
  1056. {
  1057. auto execute = [=]() { executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount); };
  1058. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1059. cb->queueCommand(execute);
  1060. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1061. }
  1062. BS_INC_RENDER_STAT(NumDrawCalls);
  1063. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1064. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1065. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  1066. }
  1067. void GLRenderAPI::dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ,
  1068. const SPtr<CommandBuffer>& commandBuffer)
  1069. {
  1070. auto executeRef = [&](UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ)
  1071. {
  1072. THROW_IF_NOT_CORE_THREAD;
  1073. if (mCurrentComputeProgram == nullptr)
  1074. {
  1075. LOGWRN("Cannot dispatch compute without a set compute program.");
  1076. return;
  1077. }
  1078. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  1079. glUseProgram(mCurrentComputeProgram->getGLHandle());
  1080. BS_CHECK_GL_ERROR();
  1081. glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);
  1082. BS_CHECK_GL_ERROR();
  1083. #else
  1084. LOGWRN("Compute shaders not supported on current OpenGL version.");
  1085. #endif
  1086. };
  1087. if (commandBuffer == nullptr)
  1088. executeRef(numGroupsX, numGroupsY, numGroupsZ);
  1089. else
  1090. {
  1091. auto execute = [=]() { executeRef(numGroupsX, numGroupsY, numGroupsZ); };
  1092. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1093. cb->queueCommand(execute);
  1094. }
  1095. BS_INC_RENDER_STAT(NumComputeCalls);
  1096. }
  1097. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom,
  1098. const SPtr<CommandBuffer>& commandBuffer)
  1099. {
  1100. auto executeRef = [&](UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1101. {
  1102. THROW_IF_NOT_CORE_THREAD;
  1103. mScissorTop = top;
  1104. mScissorBottom = bottom;
  1105. mScissorLeft = left;
  1106. mScissorRight = right;
  1107. };
  1108. if (commandBuffer == nullptr)
  1109. executeRef(left, top, right, bottom);
  1110. else
  1111. {
  1112. auto execute = [=]() { executeRef(left, top, right, bottom); };
  1113. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1114. cb->queueCommand(execute);
  1115. }
  1116. }
  1117. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1118. const SPtr<CommandBuffer>& commandBuffer)
  1119. {
  1120. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1121. {
  1122. if (mActiveRenderTarget == nullptr)
  1123. return;
  1124. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1125. Rect2I clearRect(0, 0, rtProps.width, rtProps.height);
  1126. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1127. };
  1128. if (commandBuffer == nullptr)
  1129. executeRef(buffers, color, depth, stencil, targetMask);
  1130. else
  1131. {
  1132. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1133. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1134. cb->queueCommand(execute);
  1135. }
  1136. }
  1137. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1138. const SPtr<CommandBuffer>& commandBuffer)
  1139. {
  1140. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1141. {
  1142. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1143. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1144. };
  1145. if (commandBuffer == nullptr)
  1146. executeRef(buffers, color, depth, stencil, targetMask);
  1147. else
  1148. {
  1149. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1150. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1151. cb->queueCommand(execute);
  1152. }
  1153. }
  1154. void GLRenderAPI::swapBuffers(const SPtr<RenderTarget>& target, UINT32 syncMask)
  1155. {
  1156. THROW_IF_NOT_CORE_THREAD;
  1157. // Switch context if different from current one
  1158. if(!target->getProperties().isWindow)
  1159. return;
  1160. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  1161. SPtr<GLContext> newContext;
  1162. target->getCustomAttribute("GLCONTEXT", &newContext);
  1163. if (newContext && mCurrentContext != newContext)
  1164. switchContext(newContext, *window);
  1165. else
  1166. mCurrentContext->setCurrent(*window);
  1167. target->swapBuffers();
  1168. BS_INC_RENDER_STAT(NumPresents);
  1169. }
  1170. void GLRenderAPI::addCommands(const SPtr<CommandBuffer>& commandBuffer, const SPtr<CommandBuffer>& secondary)
  1171. {
  1172. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1173. SPtr<GLCommandBuffer> secondaryCb = std::static_pointer_cast<GLCommandBuffer>(secondary);
  1174. cb->appendSecondary(secondaryCb);
  1175. }
  1176. void GLRenderAPI::submitCommandBuffer(const SPtr<CommandBuffer>& commandBuffer, UINT32 syncMask)
  1177. {
  1178. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1179. if (cb == nullptr)
  1180. return;
  1181. cb->executeCommands();
  1182. cb->clear();
  1183. }
  1184. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
  1185. UINT8 targetMask)
  1186. {
  1187. THROW_IF_NOT_CORE_THREAD;
  1188. if(mActiveRenderTarget == nullptr)
  1189. return;
  1190. bool colorMask = !mColorWrite[0] || !mColorWrite[1] || !mColorWrite[2] || !mColorWrite[3];
  1191. // Disable scissor test as we want to clear the entire render surface
  1192. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  1193. UINT32 oldScissorTop = mScissorTop;
  1194. UINT32 oldScissorBottom = mScissorBottom;
  1195. UINT32 oldScissorLeft = mScissorLeft;
  1196. UINT32 oldScissorRight = mScissorRight;
  1197. if (scissorTestEnabled)
  1198. {
  1199. glDisable(GL_SCISSOR_TEST);
  1200. BS_CHECK_GL_ERROR();
  1201. }
  1202. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1203. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  1204. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.width && clearRect.height == rtProps.height);
  1205. if (!clearEntireTarget)
  1206. {
  1207. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  1208. setScissorTestEnable(true);
  1209. }
  1210. if (buffers & FBT_COLOR)
  1211. {
  1212. // Enable buffer for writing if it isn't
  1213. if (colorMask)
  1214. {
  1215. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1216. BS_CHECK_GL_ERROR();
  1217. }
  1218. }
  1219. if (buffers & FBT_DEPTH)
  1220. {
  1221. // Enable buffer for writing if it isn't
  1222. if (!mDepthWrite)
  1223. {
  1224. glDepthMask(GL_TRUE);
  1225. BS_CHECK_GL_ERROR();
  1226. }
  1227. }
  1228. if (buffers & FBT_STENCIL)
  1229. {
  1230. // Enable buffer for writing if it isn't
  1231. glStencilMask(0xFFFFFFFF);
  1232. BS_CHECK_GL_ERROR();
  1233. }
  1234. if (targetMask == 0xFF)
  1235. {
  1236. GLbitfield flags = 0;
  1237. if (buffers & FBT_COLOR)
  1238. {
  1239. flags |= GL_COLOR_BUFFER_BIT;
  1240. glClearColor(color.r, color.g, color.b, color.a);
  1241. BS_CHECK_GL_ERROR();
  1242. }
  1243. if (buffers & FBT_DEPTH)
  1244. {
  1245. flags |= GL_DEPTH_BUFFER_BIT;
  1246. glClearDepth(depth);
  1247. BS_CHECK_GL_ERROR();
  1248. }
  1249. if (buffers & FBT_STENCIL)
  1250. {
  1251. flags |= GL_STENCIL_BUFFER_BIT;
  1252. glClearStencil(stencil);
  1253. BS_CHECK_GL_ERROR();
  1254. }
  1255. // Clear buffers
  1256. glClear(flags);
  1257. BS_CHECK_GL_ERROR();
  1258. }
  1259. else
  1260. {
  1261. GLFrameBufferObject* fbo = nullptr;
  1262. mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
  1263. if (buffers & FBT_COLOR)
  1264. {
  1265. for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
  1266. {
  1267. if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
  1268. {
  1269. glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
  1270. BS_CHECK_GL_ERROR();
  1271. }
  1272. }
  1273. }
  1274. if (buffers & FBT_DEPTH)
  1275. {
  1276. if (buffers & FBT_STENCIL)
  1277. {
  1278. glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
  1279. BS_CHECK_GL_ERROR();
  1280. }
  1281. else
  1282. {
  1283. glClearBufferfv(GL_DEPTH, 0, &depth);
  1284. BS_CHECK_GL_ERROR();
  1285. }
  1286. }
  1287. else if (buffers & FBT_STENCIL)
  1288. {
  1289. INT32 stencilClear = (INT32)stencil;
  1290. glClearBufferiv(GL_STENCIL, 0, &stencilClear);
  1291. BS_CHECK_GL_ERROR();
  1292. }
  1293. }
  1294. if (!clearEntireTarget)
  1295. {
  1296. setScissorTestEnable(false);
  1297. }
  1298. // Restore scissor test
  1299. if (scissorTestEnabled)
  1300. {
  1301. glEnable(GL_SCISSOR_TEST);
  1302. BS_CHECK_GL_ERROR();
  1303. mScissorTop = oldScissorTop;
  1304. mScissorBottom = oldScissorBottom;
  1305. mScissorLeft = oldScissorLeft;
  1306. mScissorRight = oldScissorRight;
  1307. }
  1308. // Reset buffer write state
  1309. if (!mDepthWrite && (buffers & FBT_DEPTH))
  1310. {
  1311. glDepthMask(GL_FALSE);
  1312. BS_CHECK_GL_ERROR();
  1313. }
  1314. if (colorMask && (buffers & FBT_COLOR))
  1315. {
  1316. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1317. BS_CHECK_GL_ERROR();
  1318. }
  1319. if (buffers & FBT_STENCIL)
  1320. {
  1321. glStencilMask(mStencilWriteMask);
  1322. BS_CHECK_GL_ERROR();
  1323. }
  1324. BS_INC_RENDER_STAT(NumClears);
  1325. }
  1326. /************************************************************************/
  1327. /* PRIVATE */
  1328. /************************************************************************/
  1329. void GLRenderAPI::setTextureAddressingMode(UINT16 unit, const UVWAddressingMode& uvw)
  1330. {
  1331. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u));
  1332. BS_CHECK_GL_ERROR();
  1333. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v));
  1334. BS_CHECK_GL_ERROR();
  1335. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w));
  1336. BS_CHECK_GL_ERROR();
  1337. }
  1338. void GLRenderAPI::setTextureBorderColor(UINT16 unit, const Color& color)
  1339. {
  1340. GLfloat border[4] = { color.r, color.g, color.b, color.a };
  1341. glTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_BORDER_COLOR, border);
  1342. BS_CHECK_GL_ERROR();
  1343. }
  1344. void GLRenderAPI::setTextureMipmapBias(UINT16 unit, float bias)
  1345. {
  1346. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_LOD_BIAS, bias);
  1347. BS_CHECK_GL_ERROR();
  1348. }
  1349. void GLRenderAPI::setTextureMipmapRange(UINT16 unit, float min, float max)
  1350. {
  1351. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MIN_LOD, min);
  1352. BS_CHECK_GL_ERROR();
  1353. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_LOD, max);
  1354. BS_CHECK_GL_ERROR();
  1355. }
  1356. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op)
  1357. {
  1358. GLint sourceBlend = getBlendMode(sourceFactor);
  1359. GLint destBlend = getBlendMode(destFactor);
  1360. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  1361. {
  1362. glDisable(GL_BLEND);
  1363. BS_CHECK_GL_ERROR();
  1364. }
  1365. else
  1366. {
  1367. glEnable(GL_BLEND);
  1368. BS_CHECK_GL_ERROR();
  1369. glBlendFunc(sourceBlend, destBlend);
  1370. BS_CHECK_GL_ERROR();
  1371. }
  1372. GLint func = GL_FUNC_ADD;
  1373. switch(op)
  1374. {
  1375. case BO_ADD:
  1376. func = GL_FUNC_ADD;
  1377. break;
  1378. case BO_SUBTRACT:
  1379. func = GL_FUNC_SUBTRACT;
  1380. break;
  1381. case BO_REVERSE_SUBTRACT:
  1382. func = GL_FUNC_REVERSE_SUBTRACT;
  1383. break;
  1384. case BO_MIN:
  1385. func = GL_MIN;
  1386. break;
  1387. case BO_MAX:
  1388. func = GL_MAX;
  1389. break;
  1390. }
  1391. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  1392. {
  1393. glBlendEquation(func);
  1394. BS_CHECK_GL_ERROR();
  1395. }
  1396. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  1397. {
  1398. glBlendEquationEXT(func);
  1399. BS_CHECK_GL_ERROR();
  1400. }
  1401. }
  1402. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  1403. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  1404. {
  1405. GLint sourceBlend = getBlendMode(sourceFactor);
  1406. GLint destBlend = getBlendMode(destFactor);
  1407. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1408. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1409. if(sourceFactor == BF_ONE && destFactor == BF_ZERO && sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  1410. {
  1411. glDisable(GL_BLEND);
  1412. BS_CHECK_GL_ERROR();
  1413. }
  1414. else
  1415. {
  1416. glEnable(GL_BLEND);
  1417. BS_CHECK_GL_ERROR();
  1418. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1419. BS_CHECK_GL_ERROR();
  1420. }
  1421. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1422. switch(op)
  1423. {
  1424. case BO_ADD:
  1425. func = GL_FUNC_ADD;
  1426. break;
  1427. case BO_SUBTRACT:
  1428. func = GL_FUNC_SUBTRACT;
  1429. break;
  1430. case BO_REVERSE_SUBTRACT:
  1431. func = GL_FUNC_REVERSE_SUBTRACT;
  1432. break;
  1433. case BO_MIN:
  1434. func = GL_MIN;
  1435. break;
  1436. case BO_MAX:
  1437. func = GL_MAX;
  1438. break;
  1439. }
  1440. switch(alphaOp)
  1441. {
  1442. case BO_ADD:
  1443. alphaFunc = GL_FUNC_ADD;
  1444. break;
  1445. case BO_SUBTRACT:
  1446. alphaFunc = GL_FUNC_SUBTRACT;
  1447. break;
  1448. case BO_REVERSE_SUBTRACT:
  1449. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1450. break;
  1451. case BO_MIN:
  1452. alphaFunc = GL_MIN;
  1453. break;
  1454. case BO_MAX:
  1455. alphaFunc = GL_MAX;
  1456. break;
  1457. }
  1458. glBlendEquationSeparate(func, alphaFunc);
  1459. BS_CHECK_GL_ERROR();
  1460. }
  1461. void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
  1462. {
  1463. if(func == CMPF_ALWAYS_PASS)
  1464. {
  1465. glDisable(GL_ALPHA_TEST);
  1466. BS_CHECK_GL_ERROR();
  1467. }
  1468. else
  1469. {
  1470. glEnable(GL_ALPHA_TEST);
  1471. BS_CHECK_GL_ERROR();
  1472. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  1473. BS_CHECK_GL_ERROR();
  1474. }
  1475. }
  1476. void GLRenderAPI::setAlphaToCoverage(bool enable)
  1477. {
  1478. static bool lasta2c = false;
  1479. if (enable != lasta2c)
  1480. {
  1481. if (enable)
  1482. {
  1483. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1484. BS_CHECK_GL_ERROR();
  1485. }
  1486. else
  1487. {
  1488. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1489. BS_CHECK_GL_ERROR();
  1490. }
  1491. lasta2c = enable;
  1492. }
  1493. }
  1494. void GLRenderAPI::setScissorTestEnable(bool enable)
  1495. {
  1496. if (mActiveRenderTarget == nullptr)
  1497. return;
  1498. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1499. GLsizei x, y, w, h;
  1500. if (enable)
  1501. {
  1502. glEnable(GL_SCISSOR_TEST);
  1503. BS_CHECK_GL_ERROR();
  1504. x = mScissorLeft;
  1505. y = rtProps.height - mScissorBottom;
  1506. w = mScissorRight - mScissorLeft;
  1507. h = mScissorBottom - mScissorTop;
  1508. glScissor(x, y, w, h);
  1509. BS_CHECK_GL_ERROR();
  1510. }
  1511. else
  1512. {
  1513. glDisable(GL_SCISSOR_TEST);
  1514. BS_CHECK_GL_ERROR();
  1515. // GL requires you to reset the scissor when disabling
  1516. x = mViewportLeft;
  1517. y = rtProps.height - (mViewportTop + mViewportHeight);
  1518. w = mViewportWidth;
  1519. h = mViewportHeight;
  1520. glScissor(x, y, w, h);
  1521. BS_CHECK_GL_ERROR();
  1522. }
  1523. mScissorEnabled = enable;
  1524. }
  1525. void GLRenderAPI::setMultisamplingEnable(bool enable)
  1526. {
  1527. if (enable)
  1528. {
  1529. glEnable(GL_MULTISAMPLE);
  1530. BS_CHECK_GL_ERROR();
  1531. }
  1532. else
  1533. {
  1534. glDisable(GL_MULTISAMPLE);
  1535. BS_CHECK_GL_ERROR();
  1536. }
  1537. }
  1538. void GLRenderAPI::setDepthClipEnable(bool enable)
  1539. {
  1540. if (!enable) // If clipping disabled, clamp is enabled
  1541. {
  1542. glEnable(GL_DEPTH_CLAMP);
  1543. BS_CHECK_GL_ERROR();
  1544. }
  1545. else
  1546. {
  1547. glDisable(GL_DEPTH_CLAMP);
  1548. BS_CHECK_GL_ERROR();
  1549. }
  1550. }
  1551. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  1552. {
  1553. if (enable)
  1554. {
  1555. glEnable(GL_LINE_SMOOTH);
  1556. BS_CHECK_GL_ERROR();
  1557. }
  1558. else
  1559. {
  1560. glDisable(GL_LINE_SMOOTH);
  1561. BS_CHECK_GL_ERROR();
  1562. }
  1563. }
  1564. void GLRenderAPI::setCullingMode(CullingMode mode)
  1565. {
  1566. GLenum cullMode;
  1567. switch( mode )
  1568. {
  1569. case CULL_NONE:
  1570. glDisable(GL_CULL_FACE);
  1571. BS_CHECK_GL_ERROR();
  1572. return;
  1573. default:
  1574. case CULL_CLOCKWISE:
  1575. cullMode = GL_FRONT;
  1576. break;
  1577. case CULL_COUNTERCLOCKWISE:
  1578. cullMode = GL_BACK;
  1579. break;
  1580. }
  1581. glEnable(GL_CULL_FACE);
  1582. BS_CHECK_GL_ERROR();
  1583. glCullFace(cullMode);
  1584. BS_CHECK_GL_ERROR();
  1585. }
  1586. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  1587. {
  1588. if (enabled)
  1589. {
  1590. glClearDepth(1.0f);
  1591. BS_CHECK_GL_ERROR();
  1592. glEnable(GL_DEPTH_TEST);
  1593. BS_CHECK_GL_ERROR();
  1594. }
  1595. else
  1596. {
  1597. glDisable(GL_DEPTH_TEST);
  1598. BS_CHECK_GL_ERROR();
  1599. }
  1600. }
  1601. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  1602. {
  1603. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1604. glDepthMask(flag);
  1605. BS_CHECK_GL_ERROR();
  1606. mDepthWrite = enabled;
  1607. }
  1608. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  1609. {
  1610. glDepthFunc(convertCompareFunction(func));
  1611. BS_CHECK_GL_ERROR();
  1612. }
  1613. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  1614. {
  1615. if (constantBias != 0 || slopeScaleBias != 0)
  1616. {
  1617. glEnable(GL_POLYGON_OFFSET_FILL);
  1618. BS_CHECK_GL_ERROR();
  1619. glEnable(GL_POLYGON_OFFSET_POINT);
  1620. BS_CHECK_GL_ERROR();
  1621. glEnable(GL_POLYGON_OFFSET_LINE);
  1622. BS_CHECK_GL_ERROR();
  1623. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  1624. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  1625. BS_CHECK_GL_ERROR();
  1626. }
  1627. else
  1628. {
  1629. glDisable(GL_POLYGON_OFFSET_FILL);
  1630. BS_CHECK_GL_ERROR();
  1631. glDisable(GL_POLYGON_OFFSET_POINT);
  1632. BS_CHECK_GL_ERROR();
  1633. glDisable(GL_POLYGON_OFFSET_LINE);
  1634. BS_CHECK_GL_ERROR();
  1635. }
  1636. }
  1637. void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1638. {
  1639. glColorMask(red, green, blue, alpha);
  1640. BS_CHECK_GL_ERROR();
  1641. mColorWrite[0] = red;
  1642. mColorWrite[1] = blue;
  1643. mColorWrite[2] = green;
  1644. mColorWrite[3] = alpha;
  1645. }
  1646. void GLRenderAPI::setPolygonMode(PolygonMode level)
  1647. {
  1648. GLenum glmode;
  1649. switch(level)
  1650. {
  1651. case PM_WIREFRAME:
  1652. glmode = GL_LINE;
  1653. break;
  1654. default:
  1655. case PM_SOLID:
  1656. glmode = GL_FILL;
  1657. break;
  1658. }
  1659. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1660. BS_CHECK_GL_ERROR();
  1661. }
  1662. void GLRenderAPI::setStencilCheckEnabled(bool enabled)
  1663. {
  1664. if (enabled)
  1665. {
  1666. glEnable(GL_STENCIL_TEST);
  1667. BS_CHECK_GL_ERROR();
  1668. }
  1669. else
  1670. {
  1671. glDisable(GL_STENCIL_TEST);
  1672. BS_CHECK_GL_ERROR();
  1673. }
  1674. }
  1675. void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
  1676. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  1677. {
  1678. if (front)
  1679. {
  1680. glStencilOpSeparate(
  1681. GL_FRONT,
  1682. convertStencilOp(stencilFailOp),
  1683. convertStencilOp(depthFailOp),
  1684. convertStencilOp(passOp));
  1685. BS_CHECK_GL_ERROR();
  1686. }
  1687. else
  1688. {
  1689. glStencilOpSeparate(
  1690. GL_BACK,
  1691. convertStencilOp(stencilFailOp, true),
  1692. convertStencilOp(depthFailOp, true),
  1693. convertStencilOp(passOp, true));
  1694. BS_CHECK_GL_ERROR();
  1695. }
  1696. }
  1697. void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1698. {
  1699. mStencilReadMask = mask;
  1700. if(front)
  1701. {
  1702. mStencilCompareFront = func;
  1703. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1704. BS_CHECK_GL_ERROR();
  1705. }
  1706. else
  1707. {
  1708. mStencilCompareBack = func;
  1709. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1710. BS_CHECK_GL_ERROR();
  1711. }
  1712. }
  1713. void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1714. {
  1715. mStencilWriteMask = mask;
  1716. glStencilMask(mask);
  1717. BS_CHECK_GL_ERROR();
  1718. }
  1719. void GLRenderAPI::setStencilRefValue(UINT32 refValue)
  1720. {
  1721. THROW_IF_NOT_CORE_THREAD;
  1722. mStencilRefValue = refValue;
  1723. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1724. BS_CHECK_GL_ERROR();
  1725. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1726. BS_CHECK_GL_ERROR();
  1727. }
  1728. void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1729. {
  1730. switch(ftype)
  1731. {
  1732. case FT_MIN:
  1733. mMinFilter = fo;
  1734. // Combine with existing mip filter
  1735. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1736. BS_CHECK_GL_ERROR();
  1737. break;
  1738. case FT_MAG:
  1739. switch (fo)
  1740. {
  1741. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1742. case FO_LINEAR:
  1743. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1744. BS_CHECK_GL_ERROR();
  1745. break;
  1746. case FO_POINT:
  1747. case FO_NONE:
  1748. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1749. BS_CHECK_GL_ERROR();
  1750. break;
  1751. default:
  1752. break;
  1753. }
  1754. break;
  1755. case FT_MIP:
  1756. mMipFilter = fo;
  1757. // Combine with existing min filter
  1758. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1759. BS_CHECK_GL_ERROR();
  1760. break;
  1761. }
  1762. }
  1763. void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1764. {
  1765. GLfloat maxSupportAnisotropy = 0;
  1766. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxSupportAnisotropy);
  1767. BS_CHECK_GL_ERROR();
  1768. if (maxAnisotropy > maxSupportAnisotropy)
  1769. maxAnisotropy = maxSupportAnisotropy ? static_cast<UINT32>(maxSupportAnisotropy) : 1;
  1770. if(maxAnisotropy < 1)
  1771. maxAnisotropy = 1;
  1772. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1773. {
  1774. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1775. BS_CHECK_GL_ERROR();
  1776. }
  1777. }
  1778. void GLRenderAPI::setTextureCompareMode(UINT16 unit, CompareFunction compare)
  1779. {
  1780. if (compare == CMPF_ALWAYS_PASS)
  1781. {
  1782. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  1783. BS_CHECK_GL_ERROR();
  1784. }
  1785. else
  1786. {
  1787. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  1788. BS_CHECK_GL_ERROR();
  1789. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_FUNC, convertCompareFunction(compare));
  1790. BS_CHECK_GL_ERROR();
  1791. }
  1792. }
  1793. bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
  1794. {
  1795. if (mActiveTextureUnit != unit)
  1796. {
  1797. if (unit < getCapabilities(0).getNumCombinedTextureUnits())
  1798. {
  1799. glActiveTexture(GL_TEXTURE0 + unit);
  1800. BS_CHECK_GL_ERROR();
  1801. mActiveTextureUnit = unit;
  1802. return true;
  1803. }
  1804. else if (!unit)
  1805. {
  1806. // Always ok to use the first unit
  1807. return true;
  1808. }
  1809. else
  1810. {
  1811. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1812. ". Supported range: 0 .. " + toString(getCapabilities(0).getNumCombinedTextureUnits() - 1));
  1813. return false;
  1814. }
  1815. }
  1816. else
  1817. {
  1818. return true;
  1819. }
  1820. }
  1821. void GLRenderAPI::beginDraw()
  1822. {
  1823. if(mDrawCallInProgress)
  1824. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1825. mDrawCallInProgress = true;
  1826. if(mCurrentVertexProgram == nullptr)
  1827. {
  1828. LOGWRN("Cannot render without a set vertex shader.");
  1829. return;
  1830. }
  1831. if(mBoundVertexDeclaration == nullptr)
  1832. {
  1833. LOGWRN("Cannot render without a set vertex declaration.");
  1834. return;
  1835. }
  1836. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1837. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1838. glUseProgram(0);
  1839. BS_CHECK_GL_ERROR();
  1840. if(mActivePipeline != pipeline)
  1841. {
  1842. glBindProgramPipeline(pipeline->glHandle);
  1843. BS_CHECK_GL_ERROR();
  1844. mActivePipeline = pipeline;
  1845. }
  1846. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(
  1847. mCurrentVertexProgram,
  1848. mBoundVertexDeclaration,
  1849. mBoundVertexBuffers);
  1850. glBindVertexArray(vao.getGLHandle());
  1851. BS_CHECK_GL_ERROR();
  1852. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1853. }
  1854. void GLRenderAPI::endDraw()
  1855. {
  1856. if(!mDrawCallInProgress)
  1857. return;
  1858. mDrawCallInProgress = false;
  1859. }
  1860. GLfloat GLRenderAPI::getCurrentAnisotropy(UINT16 unit)
  1861. {
  1862. GLfloat curAniso = 0;
  1863. glGetTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1864. BS_CHECK_GL_ERROR();
  1865. return curAniso ? curAniso : 1;
  1866. }
  1867. GLint GLRenderAPI::convertStencilOp(StencilOperation op, bool invert) const
  1868. {
  1869. switch (op)
  1870. {
  1871. case SOP_KEEP:
  1872. return GL_KEEP;
  1873. case SOP_ZERO:
  1874. return GL_ZERO;
  1875. case SOP_REPLACE:
  1876. return GL_REPLACE;
  1877. case SOP_INCREMENT:
  1878. return invert ? GL_DECR : GL_INCR;
  1879. case SOP_DECREMENT:
  1880. return invert ? GL_INCR : GL_DECR;
  1881. case SOP_INCREMENT_WRAP:
  1882. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1883. case SOP_DECREMENT_WRAP:
  1884. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1885. case SOP_INVERT:
  1886. return GL_INVERT;
  1887. };
  1888. // to keep compiler happy
  1889. return SOP_KEEP;
  1890. }
  1891. GLint GLRenderAPI::convertCompareFunction(CompareFunction func) const
  1892. {
  1893. switch (func)
  1894. {
  1895. case CMPF_ALWAYS_FAIL:
  1896. return GL_NEVER;
  1897. case CMPF_ALWAYS_PASS:
  1898. return GL_ALWAYS;
  1899. case CMPF_LESS:
  1900. return GL_LESS;
  1901. case CMPF_LESS_EQUAL:
  1902. return GL_LEQUAL;
  1903. case CMPF_EQUAL:
  1904. return GL_EQUAL;
  1905. case CMPF_NOT_EQUAL:
  1906. return GL_NOTEQUAL;
  1907. case CMPF_GREATER_EQUAL:
  1908. return GL_GEQUAL;
  1909. case CMPF_GREATER:
  1910. return GL_GREATER;
  1911. };
  1912. return GL_ALWAYS;
  1913. }
  1914. GLuint GLRenderAPI::getCombinedMinMipFilter() const
  1915. {
  1916. switch (mMinFilter)
  1917. {
  1918. case FO_ANISOTROPIC:
  1919. case FO_LINEAR:
  1920. switch (mMipFilter)
  1921. {
  1922. case FO_ANISOTROPIC:
  1923. case FO_LINEAR:
  1924. // Linear min, linear mip
  1925. return GL_LINEAR_MIPMAP_LINEAR;
  1926. case FO_POINT:
  1927. // Linear min, point mip
  1928. return GL_LINEAR_MIPMAP_NEAREST;
  1929. case FO_NONE:
  1930. // Linear min, no mip
  1931. return GL_LINEAR;
  1932. default:
  1933. break;
  1934. }
  1935. break;
  1936. case FO_POINT:
  1937. case FO_NONE:
  1938. switch (mMipFilter)
  1939. {
  1940. case FO_ANISOTROPIC:
  1941. case FO_LINEAR:
  1942. // Nearest min, linear mip
  1943. return GL_NEAREST_MIPMAP_LINEAR;
  1944. case FO_POINT:
  1945. // Nearest min, point mip
  1946. return GL_NEAREST_MIPMAP_NEAREST;
  1947. case FO_NONE:
  1948. // Nearest min, no mip
  1949. return GL_NEAREST;
  1950. default:
  1951. break;
  1952. }
  1953. break;
  1954. default:
  1955. break;
  1956. }
  1957. // Should never get here
  1958. return 0;
  1959. }
  1960. GLint GLRenderAPI::getBlendMode(BlendFactor blendMode) const
  1961. {
  1962. switch (blendMode)
  1963. {
  1964. case BF_ONE:
  1965. return GL_ONE;
  1966. case BF_ZERO:
  1967. return GL_ZERO;
  1968. case BF_DEST_COLOR:
  1969. return GL_DST_COLOR;
  1970. case BF_SOURCE_COLOR:
  1971. return GL_SRC_COLOR;
  1972. case BF_INV_DEST_COLOR:
  1973. return GL_ONE_MINUS_DST_COLOR;
  1974. case BF_INV_SOURCE_COLOR:
  1975. return GL_ONE_MINUS_SRC_COLOR;
  1976. case BF_DEST_ALPHA:
  1977. return GL_DST_ALPHA;
  1978. case BF_SOURCE_ALPHA:
  1979. return GL_SRC_ALPHA;
  1980. case BF_INV_DEST_ALPHA:
  1981. return GL_ONE_MINUS_DST_ALPHA;
  1982. case BF_INV_SOURCE_ALPHA:
  1983. return GL_ONE_MINUS_SRC_ALPHA;
  1984. };
  1985. return GL_ONE;
  1986. }
  1987. GLint GLRenderAPI::getTextureAddressingMode(TextureAddressingMode tam) const
  1988. {
  1989. switch (tam)
  1990. {
  1991. default:
  1992. case TAM_WRAP:
  1993. return GL_REPEAT;
  1994. case TAM_MIRROR:
  1995. return GL_MIRRORED_REPEAT;
  1996. case TAM_CLAMP:
  1997. return GL_CLAMP_TO_EDGE;
  1998. case TAM_BORDER:
  1999. return GL_CLAMP_TO_BORDER;
  2000. }
  2001. }
  2002. GLint GLRenderAPI::getGLDrawMode() const
  2003. {
  2004. GLint primType;
  2005. // Use adjacency if there is a geometry program and it requested adjacency info
  2006. bool useAdjacency = (mCurrentGeometryProgram != nullptr && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  2007. switch (mCurrentDrawOperation)
  2008. {
  2009. case DOT_POINT_LIST:
  2010. primType = GL_POINTS;
  2011. break;
  2012. case DOT_LINE_LIST:
  2013. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  2014. break;
  2015. case DOT_LINE_STRIP:
  2016. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  2017. break;
  2018. default:
  2019. case DOT_TRIANGLE_LIST:
  2020. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  2021. break;
  2022. case DOT_TRIANGLE_STRIP:
  2023. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  2024. break;
  2025. case DOT_TRIANGLE_FAN:
  2026. primType = GL_TRIANGLE_FAN;
  2027. break;
  2028. }
  2029. return primType;
  2030. }
  2031. SPtr<GLSLGpuProgram> GLRenderAPI::getActiveProgram(GpuProgramType gptype) const
  2032. {
  2033. switch (gptype)
  2034. {
  2035. case GPT_VERTEX_PROGRAM:
  2036. return mCurrentVertexProgram;
  2037. case GPT_FRAGMENT_PROGRAM:
  2038. return mCurrentFragmentProgram;
  2039. case GPT_GEOMETRY_PROGRAM:
  2040. return mCurrentGeometryProgram;
  2041. case GPT_DOMAIN_PROGRAM:
  2042. return mCurrentDomainProgram;
  2043. case GPT_HULL_PROGRAM:
  2044. return mCurrentHullProgram;
  2045. case GPT_COMPUTE_PROGRAM:
  2046. return mCurrentComputeProgram;
  2047. default:
  2048. BS_EXCEPT(InvalidParametersException, "Unsupported gpu program type: " + toString(gptype));
  2049. }
  2050. return nullptr;
  2051. }
  2052. void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  2053. {
  2054. if(caps->getRenderAPIName() != getName())
  2055. {
  2056. BS_EXCEPT(InvalidParametersException,
  2057. "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
  2058. }
  2059. #if BS_DEBUG_MODE && (BS_OPENGL_4_3 || BS_OPENGLES_3_2)
  2060. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  2061. {
  2062. glDebugMessageCallback(&openGlErrorCallback, 0);
  2063. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  2064. }
  2065. #endif
  2066. bs::HardwareBufferManager::startUp();
  2067. HardwareBufferManager::startUp<GLHardwareBufferManager>();
  2068. // GPU Program Manager setup
  2069. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  2070. if(caps->isShaderProfileSupported("glsl")) // Check for most recent GLSL support
  2071. GpuProgramManager::instance().addFactory("glsl", mGLSLProgramFactory);
  2072. if(caps->isShaderProfileSupported("glsl4_1")) // Check for OpenGL 4.1 compatible version
  2073. GpuProgramManager::instance().addFactory("glsl4_1", mGLSLProgramFactory);
  2074. GLRTTManager::startUp<GLRTTManager>();
  2075. UINT32 curTexUnitOffset = 0;
  2076. for (UINT32 i = 0; i < 6; i++)
  2077. curTexUnitOffset += caps->getNumTextureUnits((GpuProgramType)i);
  2078. UINT32 totalNumTexUnits = curTexUnitOffset;
  2079. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  2080. if (totalNumTexUnits > numCombinedTexUnits)
  2081. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  2082. mNumTextureUnits = numCombinedTexUnits;
  2083. mTextureInfos = bs_newN<TextureInfo>(mNumTextureUnits);
  2084. for (UINT16 i = 0; i < mNumTextureUnits; i++)
  2085. mTextureInfos[i].type = GL_TEXTURE_2D;
  2086. bs::TextureManager::startUp<bs::GLTextureManager>(std::ref(*mGLSupport));
  2087. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  2088. }
  2089. void GLRenderAPI::switchContext(const SPtr<GLContext>& context, const RenderWindow& window)
  2090. {
  2091. // Unbind GPU programs and rebind to new context later, because
  2092. // scene manager treat render system as ONE 'context' ONLY, and it
  2093. // cached the GPU programs using state.
  2094. setGraphicsPipeline(nullptr);
  2095. // It's ready for switching
  2096. if (mCurrentContext)
  2097. mCurrentContext->endCurrent();
  2098. mCurrentContext = context;
  2099. mCurrentContext->setCurrent(window);
  2100. // Must reset depth/colour write mask to according with user desired, otherwise,
  2101. // clearFrameBuffer would be wrong because the value we recorded may be
  2102. // different from the real state stored in GL context.
  2103. glDepthMask(mDepthWrite);
  2104. BS_CHECK_GL_ERROR();
  2105. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  2106. BS_CHECK_GL_ERROR();
  2107. glStencilMask(mStencilWriteMask);
  2108. BS_CHECK_GL_ERROR();
  2109. }
  2110. void GLRenderAPI::initCapabilities(RenderAPICapabilities& caps) const
  2111. {
  2112. Vector<String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  2113. DriverVersion driverVersion;
  2114. if (!tokens.empty())
  2115. {
  2116. driverVersion.major = parseINT32(tokens[0]);
  2117. if (tokens.size() > 1)
  2118. driverVersion.minor = parseINT32(tokens[1]);
  2119. if (tokens.size() > 2)
  2120. driverVersion.release = parseINT32(tokens[2]);
  2121. }
  2122. driverVersion.build = 0;
  2123. caps.setDriverVersion(driverVersion);
  2124. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  2125. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  2126. caps.setDeviceName(deviceName);
  2127. caps.setRenderAPIName(getName());
  2128. // determine vendor
  2129. if (strstr(vendorName, "NVIDIA"))
  2130. caps.setVendor(GPU_NVIDIA);
  2131. else if (strstr(vendorName, "ATI"))
  2132. caps.setVendor(GPU_AMD);
  2133. else if (strstr(vendorName, "AMD"))
  2134. caps.setVendor(GPU_AMD);
  2135. else if (strstr(vendorName, "Intel"))
  2136. caps.setVendor(GPU_INTEL);
  2137. else
  2138. caps.setVendor(GPU_UNKNOWN);
  2139. #if BS_OPENGL_4_1
  2140. caps.addShaderProfile("glsl4_1");
  2141. #endif
  2142. #if BS_OPENGL_4_5
  2143. caps.addShaderProfile("glsl");
  2144. #endif
  2145. caps.setCapability(RSC_TEXTURE_COMPRESSION_BC);
  2146. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2147. caps.setCapability(RSC_GEOMETRY_PROGRAM);
  2148. #endif
  2149. GLint maxOutputVertices;
  2150. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2151. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT, &maxOutputVertices);
  2152. BS_CHECK_GL_ERROR();
  2153. #else
  2154. maxOutputVertices = 0;
  2155. #endif
  2156. caps.setGeometryProgramNumOutputVertices(maxOutputVertices);
  2157. // Max number of fragment shader textures
  2158. GLint units;
  2159. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  2160. BS_CHECK_GL_ERROR();
  2161. caps.setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  2162. // Max number of vertex shader textures
  2163. GLint vUnits;
  2164. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  2165. BS_CHECK_GL_ERROR();
  2166. caps.setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  2167. GLint numUniformBlocks;
  2168. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  2169. BS_CHECK_GL_ERROR();
  2170. caps.setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  2171. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  2172. BS_CHECK_GL_ERROR();
  2173. caps.setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  2174. {
  2175. GLint geomUnits;
  2176. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2177. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  2178. BS_CHECK_GL_ERROR();
  2179. #else
  2180. geomUnits = 0;
  2181. #endif
  2182. caps.setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  2183. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2184. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  2185. BS_CHECK_GL_ERROR();
  2186. #else
  2187. numUniformBlocks = 0;
  2188. #endif
  2189. caps.setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  2190. }
  2191. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  2192. {
  2193. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2194. caps.setCapability(RSC_TESSELLATION_PROGRAM);
  2195. #endif
  2196. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2197. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  2198. BS_CHECK_GL_ERROR();
  2199. #else
  2200. numUniformBlocks = 0;
  2201. #endif
  2202. caps.setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  2203. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2204. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  2205. BS_CHECK_GL_ERROR();
  2206. #else
  2207. numUniformBlocks = 0;
  2208. #endif
  2209. caps.setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  2210. }
  2211. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  2212. {
  2213. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2214. caps.setCapability(RSC_COMPUTE_PROGRAM);
  2215. #endif
  2216. GLint computeUnits;
  2217. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2218. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  2219. BS_CHECK_GL_ERROR();
  2220. #else
  2221. computeUnits = 0;
  2222. #endif
  2223. caps.setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  2224. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2225. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  2226. BS_CHECK_GL_ERROR();
  2227. #else
  2228. numUniformBlocks = 0;
  2229. #endif
  2230. caps.setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  2231. // Max number of load-store textures
  2232. GLint lsfUnits;
  2233. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2234. glGetIntegerv(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, &lsfUnits);
  2235. BS_CHECK_GL_ERROR();
  2236. #else
  2237. lsfUnits = 0;
  2238. #endif
  2239. caps.setNumLoadStoreTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(lsfUnits));
  2240. GLint lscUnits;
  2241. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2242. glGetIntegerv(GL_MAX_COMPUTE_IMAGE_UNIFORMS, &lscUnits);
  2243. BS_CHECK_GL_ERROR();
  2244. #else
  2245. lscUnits = 0;
  2246. #endif
  2247. caps.setNumLoadStoreTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(lscUnits));
  2248. GLint combinedLoadStoreTextureUnits;
  2249. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2250. glGetIntegerv(GL_MAX_IMAGE_UNITS, &combinedLoadStoreTextureUnits);
  2251. BS_CHECK_GL_ERROR();
  2252. #else
  2253. combinedLoadStoreTextureUnits = 0;
  2254. #endif
  2255. caps.setNumCombinedLoadStoreTextureUnits(static_cast<UINT16>(combinedLoadStoreTextureUnits));
  2256. }
  2257. GLint combinedTexUnits;
  2258. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  2259. BS_CHECK_GL_ERROR();
  2260. caps.setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  2261. GLint combinedUniformBlockUnits;
  2262. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  2263. BS_CHECK_GL_ERROR();
  2264. caps.setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  2265. caps.setNumMultiRenderTargets(8);
  2266. }
  2267. void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  2268. {
  2269. UINT32 x = 0;
  2270. for (UINT32 i = 0; i < 4; i++)
  2271. {
  2272. for (UINT32 j = 0; j < 4; j++)
  2273. {
  2274. gl_matrix[x] = m[j][i];
  2275. x++;
  2276. }
  2277. }
  2278. }
  2279. void GLRenderAPI::applyViewport()
  2280. {
  2281. if (mActiveRenderTarget == nullptr)
  2282. return;
  2283. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  2284. // Calculate the "lower-left" corner of the viewport
  2285. mViewportLeft = (UINT32)(rtProps.width * mViewportNorm.x);
  2286. mViewportTop = (UINT32)(rtProps.height * mViewportNorm.y);
  2287. mViewportWidth = (UINT32)(rtProps.width * mViewportNorm.width);
  2288. mViewportHeight = (UINT32)(rtProps.height * mViewportNorm.height);
  2289. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2290. BS_CHECK_GL_ERROR();
  2291. // Configure the viewport clipping
  2292. if (!mScissorEnabled)
  2293. {
  2294. glEnable(GL_SCISSOR_TEST);
  2295. BS_CHECK_GL_ERROR();
  2296. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2297. BS_CHECK_GL_ERROR();
  2298. }
  2299. }
  2300. /************************************************************************/
  2301. /* UTILITY */
  2302. /************************************************************************/
  2303. void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  2304. {
  2305. dest = matrix;
  2306. }
  2307. const RenderAPIInfo& GLRenderAPI::getAPIInfo() const
  2308. {
  2309. RenderAPIFeatures featureFlags =
  2310. RenderAPIFeatureFlag::UVYAxisUp |
  2311. RenderAPIFeatureFlag::ColumnMajorMatrices |
  2312. RenderAPIFeatureFlag::MSAAImageStores;
  2313. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2314. featureFlags |= RenderAPIFeatureFlag::TextureViews;
  2315. featureFlags |= RenderAPIFeatureFlag::Compute;
  2316. #endif
  2317. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2318. featureFlags |= RenderAPIFeatureFlag::LoadStore;
  2319. #endif
  2320. static RenderAPIInfo info(0.0f, 0.0f, -1.0f, 1.0f, VET_COLOR_ABGR, featureFlags);
  2321. return info;
  2322. }
  2323. GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
  2324. {
  2325. GpuParamBlockDesc block;
  2326. block.blockSize = 0;
  2327. block.isShareable = true;
  2328. block.name = name;
  2329. block.slot = 0;
  2330. block.set = 0;
  2331. for (auto& param : params)
  2332. {
  2333. UINT32 size;
  2334. if(param.type == GPDT_STRUCT)
  2335. {
  2336. // Structs are always aligned and rounded up to vec4
  2337. size = Math::divideAndRoundUp(param.elementSize, 16U) * 4;
  2338. block.blockSize = Math::divideAndRoundUp(block.blockSize, 4U);
  2339. }
  2340. else
  2341. size = GLSLParamParser::calcInterfaceBlockElementSizeAndOffset(param.type, param.arraySize, block.blockSize);
  2342. if (param.arraySize > 1)
  2343. {
  2344. param.elementSize = size;
  2345. param.arrayElementStride = size;
  2346. param.cpuMemOffset = block.blockSize;
  2347. param.gpuMemOffset = 0;
  2348. block.blockSize += size * param.arraySize;
  2349. }
  2350. else
  2351. {
  2352. param.elementSize = size;
  2353. param.arrayElementStride = size;
  2354. param.cpuMemOffset = block.blockSize;
  2355. param.gpuMemOffset = 0;
  2356. block.blockSize += size;
  2357. }
  2358. param.paramBlockSlot = 0;
  2359. param.paramBlockSet = 0;
  2360. }
  2361. // Constant buffer size must always be a multiple of 16
  2362. if (block.blockSize % 4 != 0)
  2363. block.blockSize += (4 - (block.blockSize % 4));
  2364. return block;
  2365. }
  2366. #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
  2367. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  2368. const GLchar *message, GLvoid *userParam)
  2369. {
  2370. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  2371. {
  2372. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  2373. }
  2374. }
  2375. #endif
  2376. }}