BsGLRenderAPI.cpp 74 KB

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