BsGLRenderAPI.cpp 73 KB

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