BsGLRenderAPI.cpp 66 KB

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