BsGLRenderAPI.cpp 74 KB

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