BsGLRenderAPI.cpp 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857
  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. auto& texProps = tex->getProperties();
  591. GLboolean bindAllLayers =
  592. texProps.getNumFaces() == surface.numFaces ||
  593. surface.numFaces == 0;
  594. if(!bindAllLayers && surface.numFaces > 1)
  595. {
  596. LOGWRN("Attempting to bind multiple faces of a load-store texture. You are allowed to bind \
  597. either a single face, or all the faces of the texture. Only the first face will \
  598. be bound instead.");
  599. }
  600. if(surface.numMipLevels > 1)
  601. {
  602. LOGWRN("Attempting to bind multiple mip levels of a load-store texture. This is not \
  603. supported and only the first provided level will be bound.");
  604. }
  605. glBindImageTexture(
  606. unit,
  607. tex->getGLID(),
  608. surface.mipLevel,
  609. bindAllLayers,
  610. surface.face,
  611. GL_READ_WRITE,
  612. tex->getGLFormat());
  613. BS_CHECK_GL_ERROR();
  614. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  615. if (activeProgram != nullptr)
  616. {
  617. GLuint glProgram = activeProgram->getGLHandle();
  618. glProgramUniform1i(glProgram, binding, unit);
  619. BS_CHECK_GL_ERROR();
  620. }
  621. }
  622. else
  623. {
  624. glBindImageTexture(unit, 0, 0, false, 0, GL_READ_WRITE, GL_R32F);
  625. BS_CHECK_GL_ERROR();
  626. }
  627. }
  628. #endif
  629. for (auto& entry : paramDesc->paramBlocks)
  630. {
  631. UINT32 binding = entry.second.slot;
  632. SPtr<GpuParamBlockBuffer> buffer = gpuParams->getParamBlockBuffer(entry.second.set, binding);
  633. if (buffer == nullptr)
  634. continue;
  635. buffer->flushToGPU();
  636. SPtr<GLSLGpuProgram> activeProgram = getActiveProgram(type);
  637. GLuint glProgram = activeProgram->getGLHandle();
  638. // 0 means uniforms are not in block, in which case we handle it specially
  639. if (binding == 0)
  640. {
  641. UINT8* uniformBufferData = (UINT8*)bs_stack_alloc(buffer->getSize());
  642. buffer->read(0, uniformBufferData, buffer->getSize());
  643. for (auto iter = paramDesc->params.begin(); iter != paramDesc->params.end(); ++iter)
  644. {
  645. const GpuParamDataDesc& param = iter->second;
  646. if (param.paramBlockSlot != 0) // 0 means uniforms are not in a block
  647. continue;
  648. const UINT8* ptrData = uniformBufferData + param.cpuMemOffset * sizeof(UINT32);
  649. // Note: We don't transpose matrices here even though we don't use column major format
  650. // because they are assumed to be pre-transposed in the GpuParams buffer
  651. switch (param.type)
  652. {
  653. case GPDT_FLOAT1:
  654. glProgramUniform1fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  655. BS_CHECK_GL_ERROR();
  656. break;
  657. case GPDT_FLOAT2:
  658. glProgramUniform2fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  659. BS_CHECK_GL_ERROR();
  660. break;
  661. case GPDT_FLOAT3:
  662. glProgramUniform3fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  663. BS_CHECK_GL_ERROR();
  664. break;
  665. case GPDT_FLOAT4:
  666. glProgramUniform4fv(glProgram, param.gpuMemOffset, param.arraySize, (GLfloat*)ptrData);
  667. BS_CHECK_GL_ERROR();
  668. break;
  669. case GPDT_MATRIX_2X2:
  670. glProgramUniformMatrix2fv(
  671. glProgram,
  672. param.gpuMemOffset,
  673. param.arraySize,
  674. GL_FALSE,
  675. (GLfloat*)ptrData);
  676. BS_CHECK_GL_ERROR();
  677. break;
  678. case GPDT_MATRIX_2X3:
  679. glProgramUniformMatrix3x2fv(
  680. glProgram,
  681. param.gpuMemOffset,
  682. param.arraySize,
  683. GL_FALSE,
  684. (GLfloat*)ptrData);
  685. BS_CHECK_GL_ERROR();
  686. break;
  687. case GPDT_MATRIX_2X4:
  688. glProgramUniformMatrix4x2fv(
  689. glProgram,
  690. param.gpuMemOffset,
  691. param.arraySize,
  692. GL_FALSE,
  693. (GLfloat*)ptrData);
  694. BS_CHECK_GL_ERROR();
  695. break;
  696. case GPDT_MATRIX_3X2:
  697. glProgramUniformMatrix2x3fv(
  698. glProgram,
  699. param.gpuMemOffset,
  700. param.arraySize,
  701. GL_FALSE,
  702. (GLfloat*)ptrData);
  703. BS_CHECK_GL_ERROR();
  704. break;
  705. case GPDT_MATRIX_3X3:
  706. glProgramUniformMatrix3fv(
  707. glProgram,
  708. param.gpuMemOffset,
  709. param.arraySize,
  710. GL_FALSE,
  711. (GLfloat*)ptrData);
  712. BS_CHECK_GL_ERROR();
  713. break;
  714. case GPDT_MATRIX_3X4:
  715. glProgramUniformMatrix4x3fv(
  716. glProgram,
  717. param.gpuMemOffset,
  718. param.arraySize,
  719. GL_FALSE,
  720. (GLfloat*)ptrData);
  721. BS_CHECK_GL_ERROR();
  722. break;
  723. case GPDT_MATRIX_4X2:
  724. glProgramUniformMatrix2x4fv(
  725. glProgram,
  726. param.gpuMemOffset,
  727. param.arraySize,
  728. GL_FALSE,
  729. (GLfloat*)ptrData);
  730. BS_CHECK_GL_ERROR();
  731. break;
  732. case GPDT_MATRIX_4X3:
  733. glProgramUniformMatrix3x4fv(
  734. glProgram,
  735. param.gpuMemOffset,
  736. param.arraySize,
  737. GL_FALSE,
  738. (GLfloat*)ptrData);
  739. BS_CHECK_GL_ERROR();
  740. break;
  741. case GPDT_MATRIX_4X4:
  742. glProgramUniformMatrix4fv(
  743. glProgram,
  744. param.gpuMemOffset,
  745. param.arraySize,
  746. GL_FALSE,
  747. (GLfloat*)ptrData);
  748. BS_CHECK_GL_ERROR();
  749. break;
  750. case GPDT_INT1:
  751. glProgramUniform1iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  752. BS_CHECK_GL_ERROR();
  753. break;
  754. case GPDT_INT2:
  755. glProgramUniform2iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  756. BS_CHECK_GL_ERROR();
  757. break;
  758. case GPDT_INT3:
  759. glProgramUniform3iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  760. BS_CHECK_GL_ERROR();
  761. break;
  762. case GPDT_INT4:
  763. glProgramUniform4iv(glProgram, param.gpuMemOffset, param.arraySize, (GLint*)ptrData);
  764. BS_CHECK_GL_ERROR();
  765. break;
  766. case GPDT_BOOL:
  767. glProgramUniform1uiv(glProgram, param.gpuMemOffset, param.arraySize, (GLuint*)ptrData);
  768. BS_CHECK_GL_ERROR();
  769. break;
  770. default:
  771. case GPDT_UNKNOWN:
  772. break;
  773. }
  774. }
  775. if (uniformBufferData != nullptr)
  776. bs_stack_free(uniformBufferData);
  777. }
  778. else
  779. {
  780. const GLGpuParamBlockBuffer* glParamBlockBuffer = static_cast<const GLGpuParamBlockBuffer*>(buffer.get());
  781. UINT32 unit = getUniformUnit(binding - 1);
  782. glUniformBlockBinding(glProgram, binding - 1, unit);
  783. BS_CHECK_GL_ERROR();
  784. glBindBufferBase(GL_UNIFORM_BUFFER, unit, glParamBlockBuffer->getGLHandle());
  785. BS_CHECK_GL_ERROR();
  786. }
  787. }
  788. }
  789. }
  790. bs_frame_clear();
  791. activateGLTextureUnit(0);
  792. };
  793. if (commandBuffer == nullptr)
  794. executeRef(gpuParams);
  795. else
  796. {
  797. auto execute = [=]() { executeRef(gpuParams); };
  798. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  799. cb->queueCommand(execute);
  800. }
  801. BS_INC_RENDER_STAT(NumGpuParamBinds);
  802. }
  803. void GLRenderAPI::setStencilRef(UINT32 stencilRefValue, const SPtr<CommandBuffer>& commandBuffer)
  804. {
  805. auto executeRef = [&](UINT32 stencilRefValue)
  806. {
  807. THROW_IF_NOT_CORE_THREAD;
  808. setStencilRefValue(stencilRefValue);
  809. };
  810. if (commandBuffer == nullptr)
  811. executeRef(stencilRefValue);
  812. else
  813. {
  814. auto execute = [=]() { executeRef(stencilRefValue); };
  815. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  816. cb->queueCommand(execute);
  817. }
  818. }
  819. void GLRenderAPI::setViewport(const Rect2& area,
  820. const SPtr<CommandBuffer>& commandBuffer)
  821. {
  822. auto executeRef = [&](const Rect2& area)
  823. {
  824. THROW_IF_NOT_CORE_THREAD;
  825. mViewportNorm = area;
  826. applyViewport();
  827. };
  828. if (commandBuffer == nullptr)
  829. executeRef(area);
  830. else
  831. {
  832. auto execute = [=]() { executeRef(area); };
  833. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  834. cb->queueCommand(execute);
  835. }
  836. }
  837. void GLRenderAPI::setRenderTarget(const SPtr<RenderTarget>& target, UINT32 readOnlyFlags,
  838. RenderSurfaceMask loadMask, const SPtr<CommandBuffer>& commandBuffer)
  839. {
  840. auto executeRef = [&](const SPtr<RenderTarget>& target, UINT32 readOnlyFlags)
  841. {
  842. THROW_IF_NOT_CORE_THREAD;
  843. // Switch context if different from current one
  844. if (target != nullptr && target->getProperties().isWindow)
  845. {
  846. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  847. SPtr<GLContext> newContext;
  848. target->getCustomAttribute("GLCONTEXT", &newContext);
  849. if (newContext && mCurrentContext != newContext)
  850. switchContext(newContext, *window);
  851. else
  852. mCurrentContext->setCurrent(*window);
  853. }
  854. // This must happen after context switch to ensure previous context is still alive
  855. mActiveRenderTarget = target;
  856. GLFrameBufferObject* fbo = nullptr;
  857. if (target != nullptr)
  858. target->getCustomAttribute("FBO", &fbo);
  859. if (fbo != nullptr)
  860. {
  861. fbo->bind();
  862. // Enable / disable sRGB states
  863. if (target->getProperties().hwGamma)
  864. {
  865. glEnable(GL_FRAMEBUFFER_SRGB);
  866. BS_CHECK_GL_ERROR();
  867. }
  868. else
  869. {
  870. glDisable(GL_FRAMEBUFFER_SRGB);
  871. BS_CHECK_GL_ERROR();
  872. }
  873. }
  874. else
  875. {
  876. glBindFramebuffer(GL_FRAMEBUFFER, 0);
  877. BS_CHECK_GL_ERROR();
  878. }
  879. applyViewport();
  880. };
  881. if (commandBuffer == nullptr)
  882. executeRef(target, readOnlyFlags);
  883. else
  884. {
  885. auto execute = [=]() { executeRef(target, readOnlyFlags); };
  886. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  887. cb->queueCommand(execute);
  888. }
  889. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  890. }
  891. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers,
  892. const SPtr<CommandBuffer>& commandBuffer)
  893. {
  894. #if BS_DEBUG_MODE
  895. UINT32 lastIdx = index + numBuffers;
  896. if(lastIdx > MAX_VB_COUNT)
  897. {
  898. LOGERR("Provided vertex buffer slot range is invalid: " + toString(index) + " to " +
  899. toString(index + numBuffers) + ".");
  900. return;
  901. }
  902. #endif
  903. auto executeRef = [&](UINT32 index, SPtr<VertexBuffer>* buffers, UINT32 numBuffers)
  904. {
  905. THROW_IF_NOT_CORE_THREAD;
  906. std::array<SPtr<VertexBuffer>, MAX_VB_COUNT> boundBuffers;
  907. for (UINT32 i = 0; i < numBuffers; i++)
  908. boundBuffers[index + i] = buffers[i];
  909. for (UINT32 i = 0; i < numBuffers; i++)
  910. mBoundVertexBuffers[index + i] = boundBuffers[index + i];
  911. };
  912. if (commandBuffer == nullptr)
  913. executeRef(index, buffers, numBuffers);
  914. else
  915. {
  916. auto execute = [=]() { executeRef(index, buffers, numBuffers); };
  917. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  918. cb->queueCommand(execute);
  919. }
  920. }
  921. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclaration>& vertexDeclaration,
  922. const SPtr<CommandBuffer>& commandBuffer)
  923. {
  924. auto executeRef = [&](const SPtr<VertexDeclaration>& vertexDeclaration)
  925. {
  926. THROW_IF_NOT_CORE_THREAD;
  927. mBoundVertexDeclaration = vertexDeclaration;
  928. };
  929. if (commandBuffer == nullptr)
  930. executeRef(vertexDeclaration);
  931. else
  932. {
  933. auto execute = [=]() { executeRef(vertexDeclaration); };
  934. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  935. cb->queueCommand(execute);
  936. }
  937. }
  938. void GLRenderAPI::setDrawOperation(DrawOperationType op, const SPtr<CommandBuffer>& commandBuffer)
  939. {
  940. auto executeRef = [&](DrawOperationType op)
  941. {
  942. THROW_IF_NOT_CORE_THREAD;
  943. mCurrentDrawOperation = op;
  944. };
  945. if (commandBuffer == nullptr)
  946. executeRef(op);
  947. else
  948. {
  949. auto execute = [=]() { executeRef(op); };
  950. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  951. cb->queueCommand(execute);
  952. cb->mCurrentDrawOperation = op;
  953. }
  954. }
  955. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBuffer>& buffer, const SPtr<CommandBuffer>& commandBuffer)
  956. {
  957. auto executeRef = [&](const SPtr<IndexBuffer>& buffer)
  958. {
  959. THROW_IF_NOT_CORE_THREAD;
  960. mBoundIndexBuffer = buffer;
  961. };
  962. if (commandBuffer == nullptr)
  963. executeRef(buffer);
  964. else
  965. {
  966. auto execute = [=]() { executeRef(buffer); };
  967. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  968. cb->queueCommand(execute);
  969. }
  970. }
  971. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount,
  972. const SPtr<CommandBuffer>& commandBuffer)
  973. {
  974. auto executeRef = [&](UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount)
  975. {
  976. THROW_IF_NOT_CORE_THREAD;
  977. // Find the correct type to render
  978. GLint primType = getGLDrawMode();
  979. beginDraw();
  980. if (instanceCount <= 1)
  981. {
  982. glDrawArrays(primType, vertexOffset, vertexCount);
  983. BS_CHECK_GL_ERROR();
  984. }
  985. else
  986. {
  987. glDrawArraysInstanced(primType, vertexOffset, vertexCount, instanceCount);
  988. BS_CHECK_GL_ERROR();
  989. }
  990. endDraw();
  991. };
  992. UINT32 primCount;
  993. if (commandBuffer == nullptr)
  994. {
  995. executeRef(vertexOffset, vertexCount, instanceCount);
  996. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  997. }
  998. else
  999. {
  1000. auto execute = [=]() { executeRef(vertexOffset, vertexCount, instanceCount); };
  1001. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1002. cb->queueCommand(execute);
  1003. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1004. }
  1005. BS_INC_RENDER_STAT(NumDrawCalls);
  1006. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1007. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1008. }
  1009. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1010. UINT32 instanceCount, const SPtr<CommandBuffer>& commandBuffer)
  1011. {
  1012. auto executeRef = [&](UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  1013. UINT32 instanceCount)
  1014. {
  1015. THROW_IF_NOT_CORE_THREAD;
  1016. if (mBoundIndexBuffer == nullptr)
  1017. {
  1018. LOGWRN("Cannot draw indexed because index buffer is not set.");
  1019. return;
  1020. }
  1021. // Find the correct type to render
  1022. GLint primType = getGLDrawMode();
  1023. beginDraw();
  1024. SPtr<GLIndexBuffer> indexBuffer = std::static_pointer_cast<GLIndexBuffer>(mBoundIndexBuffer);
  1025. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  1026. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  1027. BS_CHECK_GL_ERROR();
  1028. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  1029. if (instanceCount <= 1)
  1030. {
  1031. glDrawElementsBaseVertex(
  1032. primType,
  1033. indexCount,
  1034. indexType,
  1035. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1036. vertexOffset);
  1037. BS_CHECK_GL_ERROR();
  1038. }
  1039. else
  1040. {
  1041. glDrawElementsInstancedBaseVertex(
  1042. primType,
  1043. indexCount,
  1044. indexType,
  1045. (GLvoid*)(UINT64)(ibProps.getIndexSize() * startIndex),
  1046. instanceCount,
  1047. vertexOffset);
  1048. BS_CHECK_GL_ERROR();
  1049. }
  1050. endDraw();
  1051. };
  1052. UINT32 primCount;
  1053. if (commandBuffer == nullptr)
  1054. {
  1055. executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount);
  1056. primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  1057. }
  1058. else
  1059. {
  1060. auto execute = [=]() { executeRef(startIndex, indexCount, vertexOffset, vertexCount, instanceCount); };
  1061. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1062. cb->queueCommand(execute);
  1063. primCount = vertexCountToPrimCount(cb->mCurrentDrawOperation, vertexCount);
  1064. }
  1065. BS_INC_RENDER_STAT(NumDrawCalls);
  1066. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  1067. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  1068. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  1069. }
  1070. void GLRenderAPI::dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ,
  1071. const SPtr<CommandBuffer>& commandBuffer)
  1072. {
  1073. auto executeRef = [&](UINT32 numGroupsX, UINT32 numGroupsY, UINT32 numGroupsZ)
  1074. {
  1075. THROW_IF_NOT_CORE_THREAD;
  1076. if (mCurrentComputeProgram == nullptr)
  1077. {
  1078. LOGWRN("Cannot dispatch compute without a set compute program.");
  1079. return;
  1080. }
  1081. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  1082. glUseProgram(mCurrentComputeProgram->getGLHandle());
  1083. BS_CHECK_GL_ERROR();
  1084. glDispatchCompute(numGroupsX, numGroupsY, numGroupsZ);
  1085. BS_CHECK_GL_ERROR();
  1086. #else
  1087. LOGWRN("Compute shaders not supported on current OpenGL version.");
  1088. #endif
  1089. };
  1090. if (commandBuffer == nullptr)
  1091. executeRef(numGroupsX, numGroupsY, numGroupsZ);
  1092. else
  1093. {
  1094. auto execute = [=]() { executeRef(numGroupsX, numGroupsY, numGroupsZ); };
  1095. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1096. cb->queueCommand(execute);
  1097. }
  1098. BS_INC_RENDER_STAT(NumComputeCalls);
  1099. }
  1100. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom,
  1101. const SPtr<CommandBuffer>& commandBuffer)
  1102. {
  1103. auto executeRef = [&](UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  1104. {
  1105. THROW_IF_NOT_CORE_THREAD;
  1106. mScissorTop = top;
  1107. mScissorBottom = bottom;
  1108. mScissorLeft = left;
  1109. mScissorRight = right;
  1110. };
  1111. if (commandBuffer == nullptr)
  1112. executeRef(left, top, right, bottom);
  1113. else
  1114. {
  1115. auto execute = [=]() { executeRef(left, top, right, bottom); };
  1116. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1117. cb->queueCommand(execute);
  1118. }
  1119. }
  1120. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1121. const SPtr<CommandBuffer>& commandBuffer)
  1122. {
  1123. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1124. {
  1125. if (mActiveRenderTarget == nullptr)
  1126. return;
  1127. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1128. Rect2I clearRect(0, 0, rtProps.width, rtProps.height);
  1129. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1130. };
  1131. if (commandBuffer == nullptr)
  1132. executeRef(buffers, color, depth, stencil, targetMask);
  1133. else
  1134. {
  1135. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1136. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1137. cb->queueCommand(execute);
  1138. }
  1139. }
  1140. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask,
  1141. const SPtr<CommandBuffer>& commandBuffer)
  1142. {
  1143. auto executeRef = [&](UINT32 buffers, const Color& color, float depth, UINT16 stencil, UINT8 targetMask)
  1144. {
  1145. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1146. clearArea(buffers, color, depth, stencil, clearRect, targetMask);
  1147. };
  1148. if (commandBuffer == nullptr)
  1149. executeRef(buffers, color, depth, stencil, targetMask);
  1150. else
  1151. {
  1152. auto execute = [=]() { executeRef(buffers, color, depth, stencil, targetMask); };
  1153. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1154. cb->queueCommand(execute);
  1155. }
  1156. }
  1157. void GLRenderAPI::swapBuffers(const SPtr<RenderTarget>& target, UINT32 syncMask)
  1158. {
  1159. THROW_IF_NOT_CORE_THREAD;
  1160. // Switch context if different from current one
  1161. if(!target->getProperties().isWindow)
  1162. return;
  1163. RenderWindow* window = static_cast<RenderWindow*>(target.get());
  1164. SPtr<GLContext> newContext;
  1165. target->getCustomAttribute("GLCONTEXT", &newContext);
  1166. if (newContext && mCurrentContext != newContext)
  1167. switchContext(newContext, *window);
  1168. else
  1169. mCurrentContext->setCurrent(*window);
  1170. target->swapBuffers();
  1171. BS_INC_RENDER_STAT(NumPresents);
  1172. }
  1173. void GLRenderAPI::addCommands(const SPtr<CommandBuffer>& commandBuffer, const SPtr<CommandBuffer>& secondary)
  1174. {
  1175. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1176. SPtr<GLCommandBuffer> secondaryCb = std::static_pointer_cast<GLCommandBuffer>(secondary);
  1177. cb->appendSecondary(secondaryCb);
  1178. }
  1179. void GLRenderAPI::submitCommandBuffer(const SPtr<CommandBuffer>& commandBuffer, UINT32 syncMask)
  1180. {
  1181. SPtr<GLCommandBuffer> cb = std::static_pointer_cast<GLCommandBuffer>(commandBuffer);
  1182. if (cb == nullptr)
  1183. return;
  1184. cb->executeCommands();
  1185. cb->clear();
  1186. }
  1187. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect,
  1188. UINT8 targetMask)
  1189. {
  1190. THROW_IF_NOT_CORE_THREAD;
  1191. if(mActiveRenderTarget == nullptr)
  1192. return;
  1193. bool colorMask = !mColorWrite[0] || !mColorWrite[1] || !mColorWrite[2] || !mColorWrite[3];
  1194. // Disable scissor test as we want to clear the entire render surface
  1195. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  1196. UINT32 oldScissorTop = mScissorTop;
  1197. UINT32 oldScissorBottom = mScissorBottom;
  1198. UINT32 oldScissorLeft = mScissorLeft;
  1199. UINT32 oldScissorRight = mScissorRight;
  1200. if (scissorTestEnabled)
  1201. {
  1202. glDisable(GL_SCISSOR_TEST);
  1203. BS_CHECK_GL_ERROR();
  1204. }
  1205. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1206. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  1207. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.width && clearRect.height == rtProps.height);
  1208. if (!clearEntireTarget)
  1209. {
  1210. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  1211. setScissorTestEnable(true);
  1212. }
  1213. if (buffers & FBT_COLOR)
  1214. {
  1215. // Enable buffer for writing if it isn't
  1216. if (colorMask)
  1217. {
  1218. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  1219. BS_CHECK_GL_ERROR();
  1220. }
  1221. }
  1222. if (buffers & FBT_DEPTH)
  1223. {
  1224. // Enable buffer for writing if it isn't
  1225. if (!mDepthWrite)
  1226. {
  1227. glDepthMask(GL_TRUE);
  1228. BS_CHECK_GL_ERROR();
  1229. }
  1230. }
  1231. if (buffers & FBT_STENCIL)
  1232. {
  1233. // Enable buffer for writing if it isn't
  1234. glStencilMask(0xFFFFFFFF);
  1235. BS_CHECK_GL_ERROR();
  1236. }
  1237. if (targetMask == 0xFF)
  1238. {
  1239. GLbitfield flags = 0;
  1240. if (buffers & FBT_COLOR)
  1241. {
  1242. flags |= GL_COLOR_BUFFER_BIT;
  1243. glClearColor(color.r, color.g, color.b, color.a);
  1244. BS_CHECK_GL_ERROR();
  1245. }
  1246. if (buffers & FBT_DEPTH)
  1247. {
  1248. flags |= GL_DEPTH_BUFFER_BIT;
  1249. glClearDepth(depth);
  1250. BS_CHECK_GL_ERROR();
  1251. }
  1252. if (buffers & FBT_STENCIL)
  1253. {
  1254. flags |= GL_STENCIL_BUFFER_BIT;
  1255. glClearStencil(stencil);
  1256. BS_CHECK_GL_ERROR();
  1257. }
  1258. // Clear buffers
  1259. glClear(flags);
  1260. BS_CHECK_GL_ERROR();
  1261. }
  1262. else
  1263. {
  1264. GLFrameBufferObject* fbo = nullptr;
  1265. mActiveRenderTarget->getCustomAttribute("FBO", &fbo);
  1266. if (buffers & FBT_COLOR)
  1267. {
  1268. for (UINT32 i = 0; i < BS_MAX_MULTIPLE_RENDER_TARGETS; i++)
  1269. {
  1270. if (fbo->hasColorBuffer(i) && ((1 << i) & targetMask) != 0)
  1271. {
  1272. glClearBufferfv(GL_COLOR, i, (GLfloat*)&color);
  1273. BS_CHECK_GL_ERROR();
  1274. }
  1275. }
  1276. }
  1277. if (buffers & FBT_DEPTH)
  1278. {
  1279. if (buffers & FBT_STENCIL)
  1280. {
  1281. glClearBufferfi(GL_DEPTH_STENCIL, 0, depth, stencil);
  1282. BS_CHECK_GL_ERROR();
  1283. }
  1284. else
  1285. {
  1286. glClearBufferfv(GL_DEPTH, 0, &depth);
  1287. BS_CHECK_GL_ERROR();
  1288. }
  1289. }
  1290. else if (buffers & FBT_STENCIL)
  1291. {
  1292. INT32 stencilClear = (INT32)stencil;
  1293. glClearBufferiv(GL_STENCIL, 0, &stencilClear);
  1294. BS_CHECK_GL_ERROR();
  1295. }
  1296. }
  1297. if (!clearEntireTarget)
  1298. {
  1299. setScissorTestEnable(false);
  1300. }
  1301. // Restore scissor test
  1302. if (scissorTestEnabled)
  1303. {
  1304. glEnable(GL_SCISSOR_TEST);
  1305. BS_CHECK_GL_ERROR();
  1306. mScissorTop = oldScissorTop;
  1307. mScissorBottom = oldScissorBottom;
  1308. mScissorLeft = oldScissorLeft;
  1309. mScissorRight = oldScissorRight;
  1310. }
  1311. // Reset buffer write state
  1312. if (!mDepthWrite && (buffers & FBT_DEPTH))
  1313. {
  1314. glDepthMask(GL_FALSE);
  1315. BS_CHECK_GL_ERROR();
  1316. }
  1317. if (colorMask && (buffers & FBT_COLOR))
  1318. {
  1319. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  1320. BS_CHECK_GL_ERROR();
  1321. }
  1322. if (buffers & FBT_STENCIL)
  1323. {
  1324. glStencilMask(mStencilWriteMask);
  1325. BS_CHECK_GL_ERROR();
  1326. }
  1327. BS_INC_RENDER_STAT(NumClears);
  1328. }
  1329. /************************************************************************/
  1330. /* PRIVATE */
  1331. /************************************************************************/
  1332. void GLRenderAPI::setTextureAddressingMode(UINT16 unit, const UVWAddressingMode& uvw)
  1333. {
  1334. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_S, getTextureAddressingMode(uvw.u));
  1335. BS_CHECK_GL_ERROR();
  1336. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_T, getTextureAddressingMode(uvw.v));
  1337. BS_CHECK_GL_ERROR();
  1338. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_WRAP_R, getTextureAddressingMode(uvw.w));
  1339. BS_CHECK_GL_ERROR();
  1340. }
  1341. void GLRenderAPI::setTextureBorderColor(UINT16 unit, const Color& color)
  1342. {
  1343. GLfloat border[4] = { color.r, color.g, color.b, color.a };
  1344. glTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_BORDER_COLOR, border);
  1345. BS_CHECK_GL_ERROR();
  1346. }
  1347. void GLRenderAPI::setTextureMipmapBias(UINT16 unit, float bias)
  1348. {
  1349. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_LOD_BIAS, bias);
  1350. BS_CHECK_GL_ERROR();
  1351. }
  1352. void GLRenderAPI::setTextureMipmapRange(UINT16 unit, float min, float max)
  1353. {
  1354. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MIN_LOD, min);
  1355. BS_CHECK_GL_ERROR();
  1356. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_LOD, max);
  1357. BS_CHECK_GL_ERROR();
  1358. }
  1359. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op)
  1360. {
  1361. GLint sourceBlend = getBlendMode(sourceFactor);
  1362. GLint destBlend = getBlendMode(destFactor);
  1363. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  1364. {
  1365. glDisable(GL_BLEND);
  1366. BS_CHECK_GL_ERROR();
  1367. }
  1368. else
  1369. {
  1370. glEnable(GL_BLEND);
  1371. BS_CHECK_GL_ERROR();
  1372. glBlendFunc(sourceBlend, destBlend);
  1373. BS_CHECK_GL_ERROR();
  1374. }
  1375. GLint func = GL_FUNC_ADD;
  1376. switch(op)
  1377. {
  1378. case BO_ADD:
  1379. func = GL_FUNC_ADD;
  1380. break;
  1381. case BO_SUBTRACT:
  1382. func = GL_FUNC_SUBTRACT;
  1383. break;
  1384. case BO_REVERSE_SUBTRACT:
  1385. func = GL_FUNC_REVERSE_SUBTRACT;
  1386. break;
  1387. case BO_MIN:
  1388. func = GL_MIN;
  1389. break;
  1390. case BO_MAX:
  1391. func = GL_MAX;
  1392. break;
  1393. }
  1394. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  1395. {
  1396. glBlendEquation(func);
  1397. BS_CHECK_GL_ERROR();
  1398. }
  1399. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  1400. {
  1401. glBlendEquationEXT(func);
  1402. BS_CHECK_GL_ERROR();
  1403. }
  1404. }
  1405. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  1406. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  1407. {
  1408. GLint sourceBlend = getBlendMode(sourceFactor);
  1409. GLint destBlend = getBlendMode(destFactor);
  1410. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  1411. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  1412. if(sourceFactor == BF_ONE && destFactor == BF_ZERO && sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  1413. {
  1414. glDisable(GL_BLEND);
  1415. BS_CHECK_GL_ERROR();
  1416. }
  1417. else
  1418. {
  1419. glEnable(GL_BLEND);
  1420. BS_CHECK_GL_ERROR();
  1421. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  1422. BS_CHECK_GL_ERROR();
  1423. }
  1424. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  1425. switch(op)
  1426. {
  1427. case BO_ADD:
  1428. func = GL_FUNC_ADD;
  1429. break;
  1430. case BO_SUBTRACT:
  1431. func = GL_FUNC_SUBTRACT;
  1432. break;
  1433. case BO_REVERSE_SUBTRACT:
  1434. func = GL_FUNC_REVERSE_SUBTRACT;
  1435. break;
  1436. case BO_MIN:
  1437. func = GL_MIN;
  1438. break;
  1439. case BO_MAX:
  1440. func = GL_MAX;
  1441. break;
  1442. }
  1443. switch(alphaOp)
  1444. {
  1445. case BO_ADD:
  1446. alphaFunc = GL_FUNC_ADD;
  1447. break;
  1448. case BO_SUBTRACT:
  1449. alphaFunc = GL_FUNC_SUBTRACT;
  1450. break;
  1451. case BO_REVERSE_SUBTRACT:
  1452. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  1453. break;
  1454. case BO_MIN:
  1455. alphaFunc = GL_MIN;
  1456. break;
  1457. case BO_MAX:
  1458. alphaFunc = GL_MAX;
  1459. break;
  1460. }
  1461. glBlendEquationSeparate(func, alphaFunc);
  1462. BS_CHECK_GL_ERROR();
  1463. }
  1464. void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
  1465. {
  1466. if(func == CMPF_ALWAYS_PASS)
  1467. {
  1468. glDisable(GL_ALPHA_TEST);
  1469. BS_CHECK_GL_ERROR();
  1470. }
  1471. else
  1472. {
  1473. glEnable(GL_ALPHA_TEST);
  1474. BS_CHECK_GL_ERROR();
  1475. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  1476. BS_CHECK_GL_ERROR();
  1477. }
  1478. }
  1479. void GLRenderAPI::setAlphaToCoverage(bool enable)
  1480. {
  1481. static bool lasta2c = false;
  1482. if (enable != lasta2c)
  1483. {
  1484. if (enable)
  1485. {
  1486. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1487. BS_CHECK_GL_ERROR();
  1488. }
  1489. else
  1490. {
  1491. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  1492. BS_CHECK_GL_ERROR();
  1493. }
  1494. lasta2c = enable;
  1495. }
  1496. }
  1497. void GLRenderAPI::setScissorTestEnable(bool enable)
  1498. {
  1499. if (mActiveRenderTarget == nullptr)
  1500. return;
  1501. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1502. GLsizei x, y, w, h;
  1503. if (enable)
  1504. {
  1505. glEnable(GL_SCISSOR_TEST);
  1506. BS_CHECK_GL_ERROR();
  1507. x = mScissorLeft;
  1508. y = rtProps.height - mScissorBottom;
  1509. w = mScissorRight - mScissorLeft;
  1510. h = mScissorBottom - mScissorTop;
  1511. glScissor(x, y, w, h);
  1512. BS_CHECK_GL_ERROR();
  1513. }
  1514. else
  1515. {
  1516. glDisable(GL_SCISSOR_TEST);
  1517. BS_CHECK_GL_ERROR();
  1518. // GL requires you to reset the scissor when disabling
  1519. x = mViewportLeft;
  1520. y = rtProps.height - (mViewportTop + mViewportHeight);
  1521. w = mViewportWidth;
  1522. h = mViewportHeight;
  1523. glScissor(x, y, w, h);
  1524. BS_CHECK_GL_ERROR();
  1525. }
  1526. mScissorEnabled = enable;
  1527. }
  1528. void GLRenderAPI::setMultisamplingEnable(bool enable)
  1529. {
  1530. if (enable)
  1531. {
  1532. glEnable(GL_MULTISAMPLE);
  1533. BS_CHECK_GL_ERROR();
  1534. }
  1535. else
  1536. {
  1537. glDisable(GL_MULTISAMPLE);
  1538. BS_CHECK_GL_ERROR();
  1539. }
  1540. }
  1541. void GLRenderAPI::setDepthClipEnable(bool enable)
  1542. {
  1543. if (!enable) // If clipping disabled, clamp is enabled
  1544. {
  1545. glEnable(GL_DEPTH_CLAMP);
  1546. BS_CHECK_GL_ERROR();
  1547. }
  1548. else
  1549. {
  1550. glDisable(GL_DEPTH_CLAMP);
  1551. BS_CHECK_GL_ERROR();
  1552. }
  1553. }
  1554. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  1555. {
  1556. if (enable)
  1557. {
  1558. glEnable(GL_LINE_SMOOTH);
  1559. BS_CHECK_GL_ERROR();
  1560. }
  1561. else
  1562. {
  1563. glDisable(GL_LINE_SMOOTH);
  1564. BS_CHECK_GL_ERROR();
  1565. }
  1566. }
  1567. void GLRenderAPI::setCullingMode(CullingMode mode)
  1568. {
  1569. GLenum cullMode;
  1570. switch( mode )
  1571. {
  1572. case CULL_NONE:
  1573. glDisable(GL_CULL_FACE);
  1574. BS_CHECK_GL_ERROR();
  1575. return;
  1576. default:
  1577. case CULL_CLOCKWISE:
  1578. cullMode = GL_FRONT;
  1579. break;
  1580. case CULL_COUNTERCLOCKWISE:
  1581. cullMode = GL_BACK;
  1582. break;
  1583. }
  1584. glEnable(GL_CULL_FACE);
  1585. BS_CHECK_GL_ERROR();
  1586. glCullFace(cullMode);
  1587. BS_CHECK_GL_ERROR();
  1588. }
  1589. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  1590. {
  1591. if (enabled)
  1592. {
  1593. glClearDepth(1.0f);
  1594. BS_CHECK_GL_ERROR();
  1595. glEnable(GL_DEPTH_TEST);
  1596. BS_CHECK_GL_ERROR();
  1597. }
  1598. else
  1599. {
  1600. glDisable(GL_DEPTH_TEST);
  1601. BS_CHECK_GL_ERROR();
  1602. }
  1603. }
  1604. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  1605. {
  1606. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  1607. glDepthMask(flag);
  1608. BS_CHECK_GL_ERROR();
  1609. mDepthWrite = enabled;
  1610. }
  1611. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  1612. {
  1613. glDepthFunc(convertCompareFunction(func));
  1614. BS_CHECK_GL_ERROR();
  1615. }
  1616. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  1617. {
  1618. if (constantBias != 0 || slopeScaleBias != 0)
  1619. {
  1620. glEnable(GL_POLYGON_OFFSET_FILL);
  1621. BS_CHECK_GL_ERROR();
  1622. glEnable(GL_POLYGON_OFFSET_POINT);
  1623. BS_CHECK_GL_ERROR();
  1624. glEnable(GL_POLYGON_OFFSET_LINE);
  1625. BS_CHECK_GL_ERROR();
  1626. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  1627. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  1628. BS_CHECK_GL_ERROR();
  1629. }
  1630. else
  1631. {
  1632. glDisable(GL_POLYGON_OFFSET_FILL);
  1633. BS_CHECK_GL_ERROR();
  1634. glDisable(GL_POLYGON_OFFSET_POINT);
  1635. BS_CHECK_GL_ERROR();
  1636. glDisable(GL_POLYGON_OFFSET_LINE);
  1637. BS_CHECK_GL_ERROR();
  1638. }
  1639. }
  1640. void GLRenderAPI::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  1641. {
  1642. glColorMask(red, green, blue, alpha);
  1643. BS_CHECK_GL_ERROR();
  1644. mColorWrite[0] = red;
  1645. mColorWrite[1] = blue;
  1646. mColorWrite[2] = green;
  1647. mColorWrite[3] = alpha;
  1648. }
  1649. void GLRenderAPI::setPolygonMode(PolygonMode level)
  1650. {
  1651. GLenum glmode;
  1652. switch(level)
  1653. {
  1654. case PM_WIREFRAME:
  1655. glmode = GL_LINE;
  1656. break;
  1657. default:
  1658. case PM_SOLID:
  1659. glmode = GL_FILL;
  1660. break;
  1661. }
  1662. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  1663. BS_CHECK_GL_ERROR();
  1664. }
  1665. void GLRenderAPI::setStencilCheckEnabled(bool enabled)
  1666. {
  1667. if (enabled)
  1668. {
  1669. glEnable(GL_STENCIL_TEST);
  1670. BS_CHECK_GL_ERROR();
  1671. }
  1672. else
  1673. {
  1674. glDisable(GL_STENCIL_TEST);
  1675. BS_CHECK_GL_ERROR();
  1676. }
  1677. }
  1678. void GLRenderAPI::setStencilBufferOperations(StencilOperation stencilFailOp,
  1679. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  1680. {
  1681. if (front)
  1682. {
  1683. glStencilOpSeparate(
  1684. GL_FRONT,
  1685. convertStencilOp(stencilFailOp),
  1686. convertStencilOp(depthFailOp),
  1687. convertStencilOp(passOp));
  1688. BS_CHECK_GL_ERROR();
  1689. }
  1690. else
  1691. {
  1692. glStencilOpSeparate(
  1693. GL_BACK,
  1694. convertStencilOp(stencilFailOp, true),
  1695. convertStencilOp(depthFailOp, true),
  1696. convertStencilOp(passOp, true));
  1697. BS_CHECK_GL_ERROR();
  1698. }
  1699. }
  1700. void GLRenderAPI::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  1701. {
  1702. mStencilReadMask = mask;
  1703. if(front)
  1704. {
  1705. mStencilCompareFront = func;
  1706. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1707. BS_CHECK_GL_ERROR();
  1708. }
  1709. else
  1710. {
  1711. mStencilCompareBack = func;
  1712. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1713. BS_CHECK_GL_ERROR();
  1714. }
  1715. }
  1716. void GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1717. {
  1718. mStencilWriteMask = mask;
  1719. glStencilMask(mask);
  1720. BS_CHECK_GL_ERROR();
  1721. }
  1722. void GLRenderAPI::setStencilRefValue(UINT32 refValue)
  1723. {
  1724. THROW_IF_NOT_CORE_THREAD;
  1725. mStencilRefValue = refValue;
  1726. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1727. BS_CHECK_GL_ERROR();
  1728. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1729. BS_CHECK_GL_ERROR();
  1730. }
  1731. void GLRenderAPI::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1732. {
  1733. switch(ftype)
  1734. {
  1735. case FT_MIN:
  1736. mMinFilter = fo;
  1737. // Combine with existing mip filter
  1738. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1739. BS_CHECK_GL_ERROR();
  1740. break;
  1741. case FT_MAG:
  1742. switch (fo)
  1743. {
  1744. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1745. case FO_LINEAR:
  1746. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1747. BS_CHECK_GL_ERROR();
  1748. break;
  1749. case FO_POINT:
  1750. case FO_NONE:
  1751. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1752. BS_CHECK_GL_ERROR();
  1753. break;
  1754. default:
  1755. break;
  1756. }
  1757. break;
  1758. case FT_MIP:
  1759. mMipFilter = fo;
  1760. // Combine with existing min filter
  1761. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1762. BS_CHECK_GL_ERROR();
  1763. break;
  1764. }
  1765. }
  1766. void GLRenderAPI::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1767. {
  1768. GLfloat maxSupportAnisotropy = 0;
  1769. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &maxSupportAnisotropy);
  1770. BS_CHECK_GL_ERROR();
  1771. if (maxAnisotropy > maxSupportAnisotropy)
  1772. maxAnisotropy = maxSupportAnisotropy ? static_cast<UINT32>(maxSupportAnisotropy) : 1;
  1773. if(maxAnisotropy < 1)
  1774. maxAnisotropy = 1;
  1775. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1776. {
  1777. glTexParameterf(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1778. BS_CHECK_GL_ERROR();
  1779. }
  1780. }
  1781. void GLRenderAPI::setTextureCompareMode(UINT16 unit, CompareFunction compare)
  1782. {
  1783. if (compare == CMPF_ALWAYS_PASS)
  1784. {
  1785. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_NONE);
  1786. BS_CHECK_GL_ERROR();
  1787. }
  1788. else
  1789. {
  1790. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_REF_TO_TEXTURE);
  1791. BS_CHECK_GL_ERROR();
  1792. glTexParameteri(mTextureInfos[unit].type, GL_TEXTURE_COMPARE_FUNC, convertCompareFunction(compare));
  1793. BS_CHECK_GL_ERROR();
  1794. }
  1795. }
  1796. bool GLRenderAPI::activateGLTextureUnit(UINT16 unit)
  1797. {
  1798. if (mActiveTextureUnit != unit)
  1799. {
  1800. if (unit < getCapabilities(0).getNumCombinedTextureUnits())
  1801. {
  1802. glActiveTexture(GL_TEXTURE0 + unit);
  1803. BS_CHECK_GL_ERROR();
  1804. mActiveTextureUnit = unit;
  1805. return true;
  1806. }
  1807. else if (!unit)
  1808. {
  1809. // Always ok to use the first unit
  1810. return true;
  1811. }
  1812. else
  1813. {
  1814. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1815. ". Supported range: 0 .. " + toString(getCapabilities(0).getNumCombinedTextureUnits() - 1));
  1816. return false;
  1817. }
  1818. }
  1819. else
  1820. {
  1821. return true;
  1822. }
  1823. }
  1824. void GLRenderAPI::beginDraw()
  1825. {
  1826. if(mDrawCallInProgress)
  1827. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1828. mDrawCallInProgress = true;
  1829. if(mCurrentVertexProgram == nullptr)
  1830. {
  1831. LOGWRN("Cannot render without a set vertex shader.");
  1832. return;
  1833. }
  1834. if(mBoundVertexDeclaration == nullptr)
  1835. {
  1836. LOGWRN("Cannot render without a set vertex declaration.");
  1837. return;
  1838. }
  1839. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1840. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1841. glUseProgram(0);
  1842. BS_CHECK_GL_ERROR();
  1843. if(mActivePipeline != pipeline)
  1844. {
  1845. glBindProgramPipeline(pipeline->glHandle);
  1846. BS_CHECK_GL_ERROR();
  1847. mActivePipeline = pipeline;
  1848. }
  1849. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(
  1850. mCurrentVertexProgram,
  1851. mBoundVertexDeclaration,
  1852. mBoundVertexBuffers);
  1853. glBindVertexArray(vao.getGLHandle());
  1854. BS_CHECK_GL_ERROR();
  1855. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1856. }
  1857. void GLRenderAPI::endDraw()
  1858. {
  1859. if(!mDrawCallInProgress)
  1860. return;
  1861. mDrawCallInProgress = false;
  1862. }
  1863. GLfloat GLRenderAPI::getCurrentAnisotropy(UINT16 unit)
  1864. {
  1865. GLfloat curAniso = 0;
  1866. glGetTexParameterfv(mTextureInfos[unit].type, GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1867. BS_CHECK_GL_ERROR();
  1868. return curAniso ? curAniso : 1;
  1869. }
  1870. GLint GLRenderAPI::convertStencilOp(StencilOperation op, bool invert) const
  1871. {
  1872. switch (op)
  1873. {
  1874. case SOP_KEEP:
  1875. return GL_KEEP;
  1876. case SOP_ZERO:
  1877. return GL_ZERO;
  1878. case SOP_REPLACE:
  1879. return GL_REPLACE;
  1880. case SOP_INCREMENT:
  1881. return invert ? GL_DECR : GL_INCR;
  1882. case SOP_DECREMENT:
  1883. return invert ? GL_INCR : GL_DECR;
  1884. case SOP_INCREMENT_WRAP:
  1885. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1886. case SOP_DECREMENT_WRAP:
  1887. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1888. case SOP_INVERT:
  1889. return GL_INVERT;
  1890. };
  1891. // to keep compiler happy
  1892. return SOP_KEEP;
  1893. }
  1894. GLint GLRenderAPI::convertCompareFunction(CompareFunction func) const
  1895. {
  1896. switch (func)
  1897. {
  1898. case CMPF_ALWAYS_FAIL:
  1899. return GL_NEVER;
  1900. case CMPF_ALWAYS_PASS:
  1901. return GL_ALWAYS;
  1902. case CMPF_LESS:
  1903. return GL_LESS;
  1904. case CMPF_LESS_EQUAL:
  1905. return GL_LEQUAL;
  1906. case CMPF_EQUAL:
  1907. return GL_EQUAL;
  1908. case CMPF_NOT_EQUAL:
  1909. return GL_NOTEQUAL;
  1910. case CMPF_GREATER_EQUAL:
  1911. return GL_GEQUAL;
  1912. case CMPF_GREATER:
  1913. return GL_GREATER;
  1914. };
  1915. return GL_ALWAYS;
  1916. }
  1917. GLuint GLRenderAPI::getCombinedMinMipFilter() const
  1918. {
  1919. switch (mMinFilter)
  1920. {
  1921. case FO_ANISOTROPIC:
  1922. case FO_LINEAR:
  1923. switch (mMipFilter)
  1924. {
  1925. case FO_ANISOTROPIC:
  1926. case FO_LINEAR:
  1927. // Linear min, linear mip
  1928. return GL_LINEAR_MIPMAP_LINEAR;
  1929. case FO_POINT:
  1930. // Linear min, point mip
  1931. return GL_LINEAR_MIPMAP_NEAREST;
  1932. case FO_NONE:
  1933. // Linear min, no mip
  1934. return GL_LINEAR;
  1935. default:
  1936. break;
  1937. }
  1938. break;
  1939. case FO_POINT:
  1940. case FO_NONE:
  1941. switch (mMipFilter)
  1942. {
  1943. case FO_ANISOTROPIC:
  1944. case FO_LINEAR:
  1945. // Nearest min, linear mip
  1946. return GL_NEAREST_MIPMAP_LINEAR;
  1947. case FO_POINT:
  1948. // Nearest min, point mip
  1949. return GL_NEAREST_MIPMAP_NEAREST;
  1950. case FO_NONE:
  1951. // Nearest min, no mip
  1952. return GL_NEAREST;
  1953. default:
  1954. break;
  1955. }
  1956. break;
  1957. default:
  1958. break;
  1959. }
  1960. // Should never get here
  1961. return 0;
  1962. }
  1963. GLint GLRenderAPI::getBlendMode(BlendFactor blendMode) const
  1964. {
  1965. switch (blendMode)
  1966. {
  1967. case BF_ONE:
  1968. return GL_ONE;
  1969. case BF_ZERO:
  1970. return GL_ZERO;
  1971. case BF_DEST_COLOR:
  1972. return GL_DST_COLOR;
  1973. case BF_SOURCE_COLOR:
  1974. return GL_SRC_COLOR;
  1975. case BF_INV_DEST_COLOR:
  1976. return GL_ONE_MINUS_DST_COLOR;
  1977. case BF_INV_SOURCE_COLOR:
  1978. return GL_ONE_MINUS_SRC_COLOR;
  1979. case BF_DEST_ALPHA:
  1980. return GL_DST_ALPHA;
  1981. case BF_SOURCE_ALPHA:
  1982. return GL_SRC_ALPHA;
  1983. case BF_INV_DEST_ALPHA:
  1984. return GL_ONE_MINUS_DST_ALPHA;
  1985. case BF_INV_SOURCE_ALPHA:
  1986. return GL_ONE_MINUS_SRC_ALPHA;
  1987. };
  1988. return GL_ONE;
  1989. }
  1990. GLint GLRenderAPI::getTextureAddressingMode(TextureAddressingMode tam) const
  1991. {
  1992. switch (tam)
  1993. {
  1994. default:
  1995. case TAM_WRAP:
  1996. return GL_REPEAT;
  1997. case TAM_MIRROR:
  1998. return GL_MIRRORED_REPEAT;
  1999. case TAM_CLAMP:
  2000. return GL_CLAMP_TO_EDGE;
  2001. case TAM_BORDER:
  2002. return GL_CLAMP_TO_BORDER;
  2003. }
  2004. }
  2005. GLint GLRenderAPI::getGLDrawMode() const
  2006. {
  2007. GLint primType;
  2008. // Use adjacency if there is a geometry program and it requested adjacency info
  2009. bool useAdjacency = (mCurrentGeometryProgram != nullptr && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  2010. switch (mCurrentDrawOperation)
  2011. {
  2012. case DOT_POINT_LIST:
  2013. primType = GL_POINTS;
  2014. break;
  2015. case DOT_LINE_LIST:
  2016. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  2017. break;
  2018. case DOT_LINE_STRIP:
  2019. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  2020. break;
  2021. default:
  2022. case DOT_TRIANGLE_LIST:
  2023. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  2024. break;
  2025. case DOT_TRIANGLE_STRIP:
  2026. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  2027. break;
  2028. case DOT_TRIANGLE_FAN:
  2029. primType = GL_TRIANGLE_FAN;
  2030. break;
  2031. }
  2032. return primType;
  2033. }
  2034. SPtr<GLSLGpuProgram> GLRenderAPI::getActiveProgram(GpuProgramType gptype) const
  2035. {
  2036. switch (gptype)
  2037. {
  2038. case GPT_VERTEX_PROGRAM:
  2039. return mCurrentVertexProgram;
  2040. case GPT_FRAGMENT_PROGRAM:
  2041. return mCurrentFragmentProgram;
  2042. case GPT_GEOMETRY_PROGRAM:
  2043. return mCurrentGeometryProgram;
  2044. case GPT_DOMAIN_PROGRAM:
  2045. return mCurrentDomainProgram;
  2046. case GPT_HULL_PROGRAM:
  2047. return mCurrentHullProgram;
  2048. case GPT_COMPUTE_PROGRAM:
  2049. return mCurrentComputeProgram;
  2050. default:
  2051. BS_EXCEPT(InvalidParametersException, "Unsupported gpu program type: " + toString(gptype));
  2052. }
  2053. return nullptr;
  2054. }
  2055. void GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  2056. {
  2057. if(caps->getRenderAPIName() != getName())
  2058. {
  2059. BS_EXCEPT(InvalidParametersException,
  2060. "Trying to initialize GLRenderAPI from RenderSystemCapabilities that do not support OpenGL");
  2061. }
  2062. #if BS_DEBUG_MODE && (BS_OPENGL_4_3 || BS_OPENGLES_3_2)
  2063. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  2064. {
  2065. glDebugMessageCallback(&openGlErrorCallback, 0);
  2066. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  2067. }
  2068. #endif
  2069. bs::HardwareBufferManager::startUp();
  2070. HardwareBufferManager::startUp<GLHardwareBufferManager>();
  2071. // GPU Program Manager setup
  2072. if(caps->isShaderProfileSupported("glsl"))
  2073. {
  2074. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  2075. GpuProgramManager::instance().addFactory(mGLSLProgramFactory);
  2076. }
  2077. GLRTTManager::startUp<GLRTTManager>();
  2078. UINT32 curTexUnitOffset = 0;
  2079. for (UINT32 i = 0; i < 6; i++)
  2080. curTexUnitOffset += caps->getNumTextureUnits((GpuProgramType)i);
  2081. UINT32 totalNumTexUnits = curTexUnitOffset;
  2082. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  2083. if (totalNumTexUnits > numCombinedTexUnits)
  2084. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  2085. mNumTextureUnits = numCombinedTexUnits;
  2086. mTextureInfos = bs_newN<TextureInfo>(mNumTextureUnits);
  2087. for (UINT16 i = 0; i < mNumTextureUnits; i++)
  2088. mTextureInfos[i].type = GL_TEXTURE_2D;
  2089. bs::TextureManager::startUp<bs::GLTextureManager>(std::ref(*mGLSupport));
  2090. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  2091. }
  2092. void GLRenderAPI::switchContext(const SPtr<GLContext>& context, const RenderWindow& window)
  2093. {
  2094. // Unbind GPU programs and rebind to new context later, because
  2095. // scene manager treat render system as ONE 'context' ONLY, and it
  2096. // cached the GPU programs using state.
  2097. setGraphicsPipeline(nullptr);
  2098. // It's ready for switching
  2099. if (mCurrentContext)
  2100. mCurrentContext->endCurrent();
  2101. mCurrentContext = context;
  2102. mCurrentContext->setCurrent(window);
  2103. // Must reset depth/colour write mask to according with user desired, otherwise,
  2104. // clearFrameBuffer would be wrong because the value we recorded may be
  2105. // different from the real state stored in GL context.
  2106. glDepthMask(mDepthWrite);
  2107. BS_CHECK_GL_ERROR();
  2108. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  2109. BS_CHECK_GL_ERROR();
  2110. glStencilMask(mStencilWriteMask);
  2111. BS_CHECK_GL_ERROR();
  2112. }
  2113. void GLRenderAPI::initCapabilities(RenderAPICapabilities& caps) const
  2114. {
  2115. Vector<String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  2116. DriverVersion driverVersion;
  2117. if (!tokens.empty())
  2118. {
  2119. driverVersion.major = parseINT32(tokens[0]);
  2120. if (tokens.size() > 1)
  2121. driverVersion.minor = parseINT32(tokens[1]);
  2122. if (tokens.size() > 2)
  2123. driverVersion.release = parseINT32(tokens[2]);
  2124. }
  2125. driverVersion.build = 0;
  2126. caps.setDriverVersion(driverVersion);
  2127. const char* deviceName = (const char*)glGetString(GL_RENDERER);
  2128. const char* vendorName = (const char*)glGetString(GL_VENDOR);
  2129. caps.setDeviceName(deviceName);
  2130. caps.setRenderAPIName(getName());
  2131. // determine vendor
  2132. if (strstr(vendorName, "NVIDIA"))
  2133. caps.setVendor(GPU_NVIDIA);
  2134. else if (strstr(vendorName, "ATI"))
  2135. caps.setVendor(GPU_AMD);
  2136. else if (strstr(vendorName, "AMD"))
  2137. caps.setVendor(GPU_AMD);
  2138. else if (strstr(vendorName, "Intel"))
  2139. caps.setVendor(GPU_INTEL);
  2140. else
  2141. caps.setVendor(GPU_UNKNOWN);
  2142. caps.addShaderProfile("glsl");
  2143. caps.setCapability(RSC_TEXTURE_COMPRESSION_BC);
  2144. // Check if geometry shaders are supported
  2145. if (getGLSupport()->checkExtension("GL_ARB_geometry_shader4"))
  2146. {
  2147. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2148. caps.setCapability(RSC_GEOMETRY_PROGRAM);
  2149. #endif
  2150. GLint maxOutputVertices;
  2151. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2152. glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&maxOutputVertices);
  2153. BS_CHECK_GL_ERROR();
  2154. #else
  2155. maxOutputVertices = 0;
  2156. #endif
  2157. caps.setGeometryProgramNumOutputVertices(maxOutputVertices);
  2158. }
  2159. // Max number of fragment shader textures
  2160. GLint units;
  2161. glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &units);
  2162. BS_CHECK_GL_ERROR();
  2163. caps.setNumTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(units));
  2164. // Max number of vertex shader textures
  2165. GLint vUnits;
  2166. glGetIntegerv(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, &vUnits);
  2167. BS_CHECK_GL_ERROR();
  2168. caps.setNumTextureUnits(GPT_VERTEX_PROGRAM, static_cast<UINT16>(vUnits));
  2169. GLint numUniformBlocks;
  2170. glGetIntegerv(GL_MAX_VERTEX_UNIFORM_BLOCKS, &numUniformBlocks);
  2171. BS_CHECK_GL_ERROR();
  2172. caps.setNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM, numUniformBlocks);
  2173. glGetIntegerv(GL_MAX_FRAGMENT_UNIFORM_BLOCKS, &numUniformBlocks);
  2174. BS_CHECK_GL_ERROR();
  2175. caps.setNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM, numUniformBlocks);
  2176. if (mGLSupport->checkExtension("GL_ARB_geometry_shader4"))
  2177. {
  2178. GLint geomUnits;
  2179. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2180. glGetIntegerv(GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS, &geomUnits);
  2181. BS_CHECK_GL_ERROR();
  2182. #else
  2183. geomUnits = 0;
  2184. #endif
  2185. caps.setNumTextureUnits(GPT_GEOMETRY_PROGRAM, static_cast<UINT16>(geomUnits));
  2186. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2187. glGetIntegerv(GL_MAX_GEOMETRY_UNIFORM_BLOCKS, &numUniformBlocks);
  2188. BS_CHECK_GL_ERROR();
  2189. #else
  2190. numUniformBlocks = 0;
  2191. #endif
  2192. caps.setNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM, numUniformBlocks);
  2193. }
  2194. if (mGLSupport->checkExtension("GL_ARB_tessellation_shader"))
  2195. {
  2196. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2197. caps.setCapability(RSC_TESSELLATION_PROGRAM);
  2198. #endif
  2199. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2200. glGetIntegerv(GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS, &numUniformBlocks);
  2201. BS_CHECK_GL_ERROR();
  2202. #else
  2203. numUniformBlocks = 0;
  2204. #endif
  2205. caps.setNumGpuParamBlockBuffers(GPT_HULL_PROGRAM, numUniformBlocks);
  2206. #if BS_OPENGL_4_1 || BS_OPENGLES_3_2
  2207. glGetIntegerv(GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS, &numUniformBlocks);
  2208. BS_CHECK_GL_ERROR();
  2209. #else
  2210. numUniformBlocks = 0;
  2211. #endif
  2212. caps.setNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM, numUniformBlocks);
  2213. }
  2214. if (mGLSupport->checkExtension("GL_ARB_compute_shader"))
  2215. {
  2216. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2217. caps.setCapability(RSC_COMPUTE_PROGRAM);
  2218. #endif
  2219. GLint computeUnits;
  2220. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2221. glGetIntegerv(GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS, &computeUnits);
  2222. BS_CHECK_GL_ERROR();
  2223. #else
  2224. computeUnits = 0;
  2225. #endif
  2226. caps.setNumTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(computeUnits));
  2227. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2228. glGetIntegerv(GL_MAX_COMPUTE_UNIFORM_BLOCKS, &numUniformBlocks);
  2229. BS_CHECK_GL_ERROR();
  2230. #else
  2231. numUniformBlocks = 0;
  2232. #endif
  2233. caps.setNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM, numUniformBlocks);
  2234. // Max number of load-store textures
  2235. GLint lsfUnits;
  2236. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2237. glGetIntegerv(GL_MAX_FRAGMENT_IMAGE_UNIFORMS, &lsfUnits);
  2238. BS_CHECK_GL_ERROR();
  2239. #else
  2240. lsfUnits = 0;
  2241. #endif
  2242. caps.setNumLoadStoreTextureUnits(GPT_FRAGMENT_PROGRAM, static_cast<UINT16>(lsfUnits));
  2243. GLint lscUnits;
  2244. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2245. glGetIntegerv(GL_MAX_COMPUTE_IMAGE_UNIFORMS, &lscUnits);
  2246. BS_CHECK_GL_ERROR();
  2247. #else
  2248. lscUnits = 0;
  2249. #endif
  2250. caps.setNumLoadStoreTextureUnits(GPT_COMPUTE_PROGRAM, static_cast<UINT16>(lscUnits));
  2251. GLint combinedLoadStoreTextureUnits;
  2252. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2253. glGetIntegerv(GL_MAX_IMAGE_UNITS, &combinedLoadStoreTextureUnits);
  2254. BS_CHECK_GL_ERROR();
  2255. #else
  2256. combinedLoadStoreTextureUnits = 0;
  2257. #endif
  2258. caps.setNumCombinedLoadStoreTextureUnits(static_cast<UINT16>(combinedLoadStoreTextureUnits));
  2259. }
  2260. GLint combinedTexUnits;
  2261. glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, &combinedTexUnits);
  2262. BS_CHECK_GL_ERROR();
  2263. caps.setNumCombinedTextureUnits(static_cast<UINT16>(combinedTexUnits));
  2264. GLint combinedUniformBlockUnits;
  2265. glGetIntegerv(GL_MAX_COMBINED_UNIFORM_BLOCKS, &combinedUniformBlockUnits);
  2266. BS_CHECK_GL_ERROR();
  2267. caps.setNumCombinedGpuParamBlockBuffers(static_cast<UINT16>(combinedUniformBlockUnits));
  2268. caps.setNumMultiRenderTargets(8);
  2269. }
  2270. void GLRenderAPI::makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m)
  2271. {
  2272. UINT32 x = 0;
  2273. for (UINT32 i = 0; i < 4; i++)
  2274. {
  2275. for (UINT32 j = 0; j < 4; j++)
  2276. {
  2277. gl_matrix[x] = m[j][i];
  2278. x++;
  2279. }
  2280. }
  2281. }
  2282. void GLRenderAPI::applyViewport()
  2283. {
  2284. if (mActiveRenderTarget == nullptr)
  2285. return;
  2286. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  2287. // Calculate the "lower-left" corner of the viewport
  2288. mViewportLeft = (UINT32)(rtProps.width * mViewportNorm.x);
  2289. mViewportTop = (UINT32)(rtProps.height * mViewportNorm.y);
  2290. mViewportWidth = (UINT32)(rtProps.width * mViewportNorm.width);
  2291. mViewportHeight = (UINT32)(rtProps.height * mViewportNorm.height);
  2292. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2293. BS_CHECK_GL_ERROR();
  2294. // Configure the viewport clipping
  2295. if (!mScissorEnabled)
  2296. {
  2297. glEnable(GL_SCISSOR_TEST);
  2298. BS_CHECK_GL_ERROR();
  2299. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  2300. BS_CHECK_GL_ERROR();
  2301. }
  2302. }
  2303. /************************************************************************/
  2304. /* UTILITY */
  2305. /************************************************************************/
  2306. void GLRenderAPI::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  2307. {
  2308. dest = matrix;
  2309. }
  2310. const RenderAPIInfo& GLRenderAPI::getAPIInfo() const
  2311. {
  2312. RenderAPIFeatures featureFlags =
  2313. RenderAPIFeatureFlag::UVYAxisUp |
  2314. RenderAPIFeatureFlag::ColumnMajorMatrices |
  2315. RenderAPIFeatureFlag::MSAAImageStores;
  2316. #if BS_OPENGL_4_3 || BS_OPENGLES_3_1
  2317. featureFlags |= RenderAPIFeatureFlag::TextureViews;
  2318. featureFlags |= RenderAPIFeatureFlag::Compute;
  2319. #endif
  2320. #if BS_OPENGL_4_2 || BS_OPENGLES_3_1
  2321. featureFlags |= RenderAPIFeatureFlag::LoadStore;
  2322. #endif
  2323. static RenderAPIInfo info(0.0f, 0.0f, -1.0f, 1.0f, VET_COLOR_ABGR, featureFlags);
  2324. return info;
  2325. }
  2326. GpuParamBlockDesc GLRenderAPI::generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params)
  2327. {
  2328. GpuParamBlockDesc block;
  2329. block.blockSize = 0;
  2330. block.isShareable = true;
  2331. block.name = name;
  2332. block.slot = 0;
  2333. block.set = 0;
  2334. for (auto& param : params)
  2335. {
  2336. const GpuParamDataTypeInfo& typeInfo = bs::GpuParams::PARAM_SIZES.lookup[param.type];
  2337. UINT32 size = typeInfo.size / 4;
  2338. UINT32 alignment = typeInfo.alignment / 4;
  2339. // Fix alignment if needed
  2340. UINT32 alignOffset = block.blockSize % alignment;
  2341. if (alignOffset != 0)
  2342. {
  2343. UINT32 padding = (alignment - alignOffset);
  2344. block.blockSize += padding;
  2345. }
  2346. if (param.arraySize > 1)
  2347. {
  2348. // Array elements are always padded and aligned to vec4
  2349. alignOffset = size % typeInfo.baseTypeSize;
  2350. if (alignOffset != 0)
  2351. {
  2352. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  2353. size += padding;
  2354. }
  2355. alignOffset = block.blockSize % typeInfo.baseTypeSize;
  2356. if (alignOffset != 0)
  2357. {
  2358. UINT32 padding = (typeInfo.baseTypeSize - alignOffset);
  2359. block.blockSize += padding;
  2360. }
  2361. param.elementSize = size;
  2362. param.arrayElementStride = size;
  2363. param.cpuMemOffset = block.blockSize;
  2364. param.gpuMemOffset = 0;
  2365. block.blockSize += size * param.arraySize;
  2366. }
  2367. else
  2368. {
  2369. param.elementSize = size;
  2370. param.arrayElementStride = size;
  2371. param.cpuMemOffset = block.blockSize;
  2372. param.gpuMemOffset = 0;
  2373. block.blockSize += size;
  2374. }
  2375. param.paramBlockSlot = 0;
  2376. param.paramBlockSet = 0;
  2377. }
  2378. // Constant buffer size must always be a multiple of 16
  2379. if (block.blockSize % 4 != 0)
  2380. block.blockSize += (4 - (block.blockSize % 4));
  2381. return block;
  2382. }
  2383. #if BS_OPENGL_4_3 || BS_OPENGLES_3_2
  2384. void openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length,
  2385. const GLchar *message, GLvoid *userParam)
  2386. {
  2387. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  2388. {
  2389. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  2390. }
  2391. }
  2392. #endif
  2393. }}