BsGLRenderAPI.cpp 67 KB

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