BsGLRenderAPI.cpp 66 KB

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