BsGLRenderSystem.cpp 57 KB

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