BsGLRenderSystem.cpp 58 KB

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