BsGLRenderSystem.cpp 57 KB

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