BsGLRenderAPI.cpp 66 KB

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