BsGLRenderAPI.cpp 72 KB

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