BsGLRenderAPI.cpp 63 KB

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