BsGLRenderSystem.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  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. mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  61. {
  62. // Get our GLSupport
  63. mGLSupport = BansheeEngine::getGLSupport();
  64. mViewMatrix = Matrix4::IDENTITY;
  65. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  66. mCurrentContext = 0;
  67. mMainContext = 0;
  68. mGLInitialised = false;
  69. mMinFilter = FO_LINEAR;
  70. mMipFilter = FO_POINT;
  71. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  72. }
  73. GLRenderSystem::~GLRenderSystem()
  74. {
  75. }
  76. const String& GLRenderSystem::getName() const
  77. {
  78. static String strName("GLRenderSystem");
  79. return strName;
  80. }
  81. const String& GLRenderSystem::getShadingLanguageName() const
  82. {
  83. static String strName("glsl");
  84. return strName;
  85. }
  86. void GLRenderSystem::initializePrepare()
  87. {
  88. THROW_IF_NOT_CORE_THREAD;
  89. mGLSupport->start();
  90. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  91. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  92. RenderWindowCoreManager::startUp<GLRenderWindowCoreManager>(this);
  93. RenderStateManager::startUp();
  94. RenderStateCoreManager::startUp();
  95. QueryManager::startUp<GLQueryManager>();
  96. RenderSystem::initializePrepare();
  97. }
  98. void GLRenderSystem::initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow)
  99. {
  100. // Get the context from the window and finish initialization
  101. GLContext *context = nullptr;
  102. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  103. // Set main and current context
  104. mMainContext = context;
  105. mCurrentContext = mMainContext;
  106. // Set primary context as active
  107. if (mCurrentContext)
  108. mCurrentContext->setCurrent();
  109. checkForErrors();
  110. // Setup GLSupport
  111. mGLSupport->initializeExtensions();
  112. checkForErrors();
  113. Vector<BansheeEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  114. if (!tokens.empty())
  115. {
  116. mDriverVersion.major = parseInt(tokens[0]);
  117. if (tokens.size() > 1)
  118. mDriverVersion.minor = parseInt(tokens[1]);
  119. if (tokens.size() > 2)
  120. mDriverVersion.release = parseInt(tokens[2]);
  121. }
  122. mDriverVersion.build = 0;
  123. mCurrentCapabilities = createRenderSystemCapabilities();
  124. initFromCaps(mCurrentCapabilities);
  125. GLVertexArrayObjectManager::startUp();
  126. mGLInitialised = true;
  127. RenderSystem::initializeFinalize(primaryWindow);
  128. }
  129. void GLRenderSystem::destroy_internal()
  130. {
  131. RenderSystem::destroy_internal();
  132. // Deleting the GLSL program factory
  133. if (mGLSLProgramFactory)
  134. {
  135. // Remove from manager safely
  136. GpuProgramCoreManager::instance().removeFactory(mGLSLProgramFactory);
  137. bs_delete(mGLSLProgramFactory);
  138. mGLSLProgramFactory = nullptr;
  139. }
  140. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  141. HardwareBufferCoreManager::shutDown();
  142. HardwareBufferManager::shutDown();
  143. GLRTTManager::shutDown();
  144. mBoundVertexBuffers.clear();
  145. mBoundVertexDeclaration = nullptr;
  146. mBoundIndexBuffer = nullptr;
  147. mCurrentVertexProgram = nullptr;
  148. mCurrentFragmentProgram = nullptr;
  149. mCurrentGeometryProgram = nullptr;
  150. mCurrentHullProgram = nullptr;
  151. mCurrentDomainProgram = nullptr;
  152. mGLSupport->stop();
  153. TextureCoreManager::shutDown();
  154. TextureManager::shutDown();
  155. QueryManager::shutDown();
  156. RenderWindowCoreManager::shutDown();
  157. RenderWindowManager::shutDown();
  158. RenderStateCoreManager::shutDown();
  159. RenderStateManager::shutDown();
  160. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  161. mGLInitialised = false;
  162. if(mProgramPipelineManager != nullptr)
  163. bs_delete(mProgramPipelineManager);
  164. if(mGLSupport)
  165. bs_delete(mGLSupport);
  166. if(mTextureTypes != nullptr)
  167. bs_deleteN(mTextureTypes, mNumTextureTypes);
  168. }
  169. void GLRenderSystem::bindGpuProgram(const SPtr<GpuProgramCore>& prg)
  170. {
  171. THROW_IF_NOT_CORE_THREAD;
  172. SPtr<GLSLGpuProgramCore> glprg = std::static_pointer_cast<GLSLGpuProgramCore>(prg);
  173. switch (glprg->getProperties().getType())
  174. {
  175. case GPT_VERTEX_PROGRAM:
  176. mCurrentVertexProgram = glprg;
  177. break;
  178. case GPT_FRAGMENT_PROGRAM:
  179. mCurrentFragmentProgram = glprg;
  180. break;
  181. case GPT_GEOMETRY_PROGRAM:
  182. mCurrentGeometryProgram = glprg;
  183. break;
  184. case GPT_DOMAIN_PROGRAM:
  185. mCurrentDomainProgram = glprg;
  186. break;
  187. case GPT_HULL_PROGRAM:
  188. mCurrentHullProgram = glprg;
  189. break;
  190. }
  191. RenderSystem::bindGpuProgram(prg);
  192. }
  193. void GLRenderSystem::unbindGpuProgram(GpuProgramType gptype)
  194. {
  195. THROW_IF_NOT_CORE_THREAD;
  196. setActiveProgram(gptype, nullptr);
  197. RenderSystem::unbindGpuProgram(gptype);
  198. }
  199. void GLRenderSystem::bindGpuParams(GpuProgramType gptype, const SPtr<GpuParamsCore>& bindableParams)
  200. {
  201. THROW_IF_NOT_CORE_THREAD;
  202. bindableParams->updateHardwareBuffers();
  203. const GpuParamDesc& paramDesc = bindableParams->getParamDesc();
  204. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  205. GLuint glProgram = activeProgram->getGLHandle();
  206. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  207. {
  208. SPtr<TextureCore> texture = bindableParams->getTexture(iter->second.slot);
  209. if (!bindableParams->isLoadStoreTexture(iter->second.slot))
  210. {
  211. if (texture == nullptr)
  212. setTexture(gptype, iter->second.slot, false, nullptr);
  213. else
  214. setTexture(gptype, iter->second.slot, true, texture);
  215. }
  216. else
  217. {
  218. const TextureSurface& surface = bindableParams->getLoadStoreSurface(iter->second.slot);
  219. if (texture == nullptr)
  220. setLoadStoreTexture(gptype, iter->second.slot, false, nullptr, surface);
  221. else
  222. setLoadStoreTexture(gptype, iter->second.slot, true, texture, surface);
  223. }
  224. }
  225. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  226. {
  227. SPtr<SamplerStateCore>& samplerState = bindableParams->getSamplerState(iter->second.slot);
  228. if(samplerState == nullptr)
  229. setSamplerState(gptype, iter->second.slot, SamplerState::getDefault()->getCore());
  230. else
  231. setSamplerState(gptype, iter->second.slot, samplerState);
  232. glProgramUniform1i(glProgram, iter->second.slot, getGLTextureUnit(gptype, iter->second.slot));
  233. }
  234. UINT8* uniformBufferData = nullptr;
  235. UINT32 blockBinding = 0;
  236. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  237. {
  238. SPtr<GpuParamBlockBufferCore> paramBlockBuffer = bindableParams->getParamBlockBuffer(iter->second.slot);
  239. if(paramBlockBuffer == nullptr)
  240. continue;
  241. if(iter->second.slot == 0)
  242. {
  243. // 0 means uniforms are not in block, in which case we handle it specially
  244. if (uniformBufferData == nullptr && paramBlockBuffer->getSize() > 0)
  245. {
  246. uniformBufferData = (UINT8*)bs_alloc<ScratchAlloc>(paramBlockBuffer->getSize());
  247. paramBlockBuffer->readFromGPU(uniformBufferData);
  248. }
  249. continue;
  250. }
  251. const GLGpuParamBlockBufferCore* glParamBlockBuffer = static_cast<const GLGpuParamBlockBufferCore*>(paramBlockBuffer.get());
  252. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  253. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  254. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  255. blockBinding++;
  256. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  257. }
  258. bool hasBoundAtLeastOne = false;
  259. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  260. {
  261. const GpuParamDataDesc& paramDesc = iter->second;
  262. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  263. continue;
  264. const UINT8* ptrData = uniformBufferData + paramDesc.cpuMemOffset * sizeof(UINT32);
  265. hasBoundAtLeastOne = true;
  266. // Note: We don't transpose matrices here even though we don't use column major format
  267. // because they are assumed to be pre-transposed in the GpuParams buffer
  268. switch(paramDesc.type)
  269. {
  270. case GPDT_FLOAT1:
  271. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  272. break;
  273. case GPDT_FLOAT2:
  274. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  275. break;
  276. case GPDT_FLOAT3:
  277. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  278. break;
  279. case GPDT_FLOAT4:
  280. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  281. break;
  282. case GPDT_MATRIX_2X2:
  283. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  284. GL_FALSE, (GLfloat*)ptrData);
  285. break;
  286. case GPDT_MATRIX_2X3:
  287. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  288. GL_FALSE, (GLfloat*)ptrData);
  289. break;
  290. case GPDT_MATRIX_2X4:
  291. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  292. GL_FALSE, (GLfloat*)ptrData);
  293. break;
  294. case GPDT_MATRIX_3X2:
  295. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  296. GL_FALSE, (GLfloat*)ptrData);
  297. break;
  298. case GPDT_MATRIX_3X3:
  299. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  300. GL_FALSE, (GLfloat*)ptrData);
  301. break;
  302. case GPDT_MATRIX_3X4:
  303. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  304. GL_FALSE, (GLfloat*)ptrData);
  305. break;
  306. case GPDT_MATRIX_4X2:
  307. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  308. GL_FALSE, (GLfloat*)ptrData);
  309. break;
  310. case GPDT_MATRIX_4X3:
  311. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  312. GL_FALSE, (GLfloat*)ptrData);
  313. break;
  314. case GPDT_MATRIX_4X4:
  315. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  316. GL_FALSE, (GLfloat*)ptrData);
  317. break;
  318. case GPDT_INT1:
  319. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  320. break;
  321. case GPDT_INT2:
  322. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  323. break;
  324. case GPDT_INT3:
  325. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  326. break;
  327. case GPDT_INT4:
  328. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  329. break;
  330. case GPDT_BOOL:
  331. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  332. break;
  333. case GPDT_UNKNOWN:
  334. break;
  335. }
  336. }
  337. if (hasBoundAtLeastOne)
  338. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  339. if(uniformBufferData != nullptr)
  340. {
  341. bs_free<ScratchAlloc>(uniformBufferData);
  342. }
  343. }
  344. void GLRenderSystem::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr)
  345. {
  346. THROW_IF_NOT_CORE_THREAD;
  347. unit = getGLTextureUnit(gptype, unit);
  348. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  349. GLenum lastTextureType = mTextureTypes[unit];
  350. if (!activateGLTextureUnit(unit))
  351. return;
  352. if (enabled && tex)
  353. {
  354. mTextureTypes[unit] = tex->getGLTextureTarget();
  355. glBindTexture(mTextureTypes[unit], tex->getGLID());
  356. }
  357. else
  358. {
  359. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  360. // - If a non-2D sampler is used, the texture will still be displayed
  361. glBindTexture(GL_TEXTURE_2D, 0);
  362. }
  363. activateGLTextureUnit(0);
  364. BS_INC_RENDER_STAT(NumTextureBinds);
  365. }
  366. void GLRenderSystem::setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state)
  367. {
  368. THROW_IF_NOT_CORE_THREAD;
  369. const SamplerProperties& stateProps = state->getProperties();
  370. unit = getGLTextureUnit(gptype, unit);
  371. // Set texture layer filtering
  372. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  373. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  374. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  375. // Set texture anisotropy
  376. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  377. // Set mipmap biasing
  378. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  379. // Texture addressing mode
  380. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  381. setTextureAddressingMode(unit, uvw);
  382. // Set border color
  383. setTextureBorderColor(unit, stateProps.getBorderColor());
  384. BS_INC_RENDER_STAT(NumSamplerBinds);
  385. }
  386. void GLRenderSystem::setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  387. const TextureSurface& surface)
  388. {
  389. THROW_IF_NOT_CORE_THREAD;
  390. // TODO - OpenGL can't bind a certain subset of faces like DX11, only zero, one or all, so I'm ignoring numSlices parameter
  391. if (texPtr != nullptr)
  392. {
  393. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  394. glBindImageTexture(unit, tex->getGLID(), surface.mipLevel, surface.numArraySlices > 1,
  395. surface.arraySlice, tex->getGLFormat(), GL_READ_WRITE);
  396. }
  397. else
  398. glBindImageTexture(unit, 0, 0, false, 0, 0, GL_READ_WRITE);
  399. BS_INC_RENDER_STAT(NumTextureBinds);
  400. }
  401. void GLRenderSystem::setBlendState(const SPtr<BlendStateCore>& blendState)
  402. {
  403. THROW_IF_NOT_CORE_THREAD;
  404. const BlendProperties& stateProps = blendState->getProperties();
  405. // Alpha to coverage
  406. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  407. // Blend states
  408. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  409. if (stateProps.getBlendEnabled(0))
  410. {
  411. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  412. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  413. }
  414. else
  415. {
  416. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  417. }
  418. // Color write mask
  419. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  420. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  421. BS_INC_RENDER_STAT(NumBlendStateChanges);
  422. }
  423. void GLRenderSystem::setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState)
  424. {
  425. THROW_IF_NOT_CORE_THREAD;
  426. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  427. setDepthBias((float)stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  428. setCullingMode(stateProps.getCullMode());
  429. setPolygonMode(stateProps.getPolygonMode());
  430. setScissorTestEnable(stateProps.getScissorEnable());
  431. setMultisamplingEnable(stateProps.getMultisampleEnable());
  432. setDepthClipEnable(stateProps.getDepthClipEnable());
  433. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  434. BS_INC_RENDER_STAT(NumRasterizerStateChanges);
  435. }
  436. void GLRenderSystem::setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue)
  437. {
  438. THROW_IF_NOT_CORE_THREAD;
  439. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  440. // Set stencil buffer options
  441. setStencilCheckEnabled(stateProps.getStencilEnable());
  442. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  443. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  444. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  445. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  446. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  447. // Set depth buffer options
  448. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  449. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  450. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  451. // Set stencil ref value
  452. setStencilRefValue(stencilRefValue);
  453. BS_INC_RENDER_STAT(NumDepthStencilStateChanges);
  454. }
  455. void GLRenderSystem::setViewport(const Rect2& area)
  456. {
  457. THROW_IF_NOT_CORE_THREAD;
  458. mViewportNorm = area;
  459. applyViewport();
  460. }
  461. void GLRenderSystem::setRenderTarget(const SPtr<RenderTargetCore>& target)
  462. {
  463. THROW_IF_NOT_CORE_THREAD;
  464. mActiveRenderTarget = target;
  465. // Switch context if different from current one
  466. GLContext *newContext = 0;
  467. target->getCustomAttribute("GLCONTEXT", &newContext);
  468. if(newContext && mCurrentContext != newContext)
  469. {
  470. switchContext(newContext);
  471. }
  472. GLFrameBufferObject *fbo = 0;
  473. target->getCustomAttribute("FBO", &fbo);
  474. if(fbo)
  475. fbo->bind();
  476. else
  477. // Old style context (window/pbuffer) or copying render texture
  478. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  479. if (GLEW_EXT_framebuffer_sRGB)
  480. {
  481. // Enable / disable sRGB states
  482. if (target->getProperties().isHwGammaEnabled())
  483. {
  484. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  485. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  486. // enabling, but GL spec says incapable surfaces ignore the setting
  487. // anyway. We test the capability to enable isHardwareGammaEnabled.
  488. }
  489. else
  490. {
  491. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  492. }
  493. }
  494. applyViewport();
  495. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  496. }
  497. void GLRenderSystem::beginFrame()
  498. {
  499. THROW_IF_NOT_CORE_THREAD;
  500. // Activate the viewport clipping
  501. glEnable(GL_SCISSOR_TEST);
  502. }
  503. void GLRenderSystem::endFrame()
  504. {
  505. THROW_IF_NOT_CORE_THREAD;
  506. // Deactivate the viewport clipping.
  507. glDisable(GL_SCISSOR_TEST);
  508. }
  509. void GLRenderSystem::setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers)
  510. {
  511. THROW_IF_NOT_CORE_THREAD;
  512. if ((index + numBuffers) > (UINT32)mBoundVertexBuffers.size())
  513. mBoundVertexBuffers.resize(index + numBuffers);
  514. for(UINT32 i = 0; i < numBuffers; i++)
  515. {
  516. mBoundVertexBuffers[index + i] = buffers[i];
  517. }
  518. }
  519. void GLRenderSystem::setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration)
  520. {
  521. THROW_IF_NOT_CORE_THREAD;
  522. mBoundVertexDeclaration = vertexDeclaration;
  523. }
  524. void GLRenderSystem::setDrawOperation(DrawOperationType op)
  525. {
  526. THROW_IF_NOT_CORE_THREAD;
  527. mCurrentDrawOperation = op;
  528. }
  529. void GLRenderSystem::setIndexBuffer(const SPtr<IndexBufferCore>& buffer)
  530. {
  531. THROW_IF_NOT_CORE_THREAD;
  532. mBoundIndexBuffer = buffer;
  533. }
  534. void GLRenderSystem::draw(UINT32 vertexOffset, UINT32 vertexCount)
  535. {
  536. // Find the correct type to render
  537. GLint primType = getGLDrawMode();
  538. beginDraw();
  539. glDrawArrays(primType, vertexOffset, vertexCount);
  540. endDraw();
  541. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  542. BS_INC_RENDER_STAT(NumDrawCalls);
  543. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  544. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  545. }
  546. void GLRenderSystem::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  547. {
  548. if(mBoundIndexBuffer == nullptr)
  549. {
  550. LOGWRN("Cannot draw indexed because index buffer is not set.");
  551. return;
  552. }
  553. // Find the correct type to render
  554. GLint primType = getGLDrawMode();
  555. beginDraw();
  556. SPtr<GLIndexBufferCore> indexBuffer = std::static_pointer_cast<GLIndexBufferCore>(mBoundIndexBuffer);
  557. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  558. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  559. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  560. glDrawElementsBaseVertex(primType, indexCount, indexType, (GLvoid*)(ibProps.getIndexSize() * startIndex), vertexOffset);
  561. endDraw();
  562. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  563. BS_INC_RENDER_STAT(NumDrawCalls);
  564. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  565. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  566. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  567. }
  568. void GLRenderSystem::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  569. {
  570. THROW_IF_NOT_CORE_THREAD;
  571. mScissorTop = top;
  572. mScissorBottom = bottom;
  573. mScissorLeft = left;
  574. mScissorRight = right;
  575. }
  576. void GLRenderSystem::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  577. {
  578. if(mActiveRenderTarget == nullptr)
  579. return;
  580. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  581. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  582. clearArea(buffers, color, depth, stencil, clearRect);
  583. }
  584. void GLRenderSystem::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  585. {
  586. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  587. clearArea(buffers, color, depth, stencil, clearRect);
  588. }
  589. void GLRenderSystem::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect)
  590. {
  591. THROW_IF_NOT_CORE_THREAD;
  592. if(mActiveRenderTarget == nullptr)
  593. return;
  594. bool colorMask = !mColorWrite[0] || !mColorWrite[1]
  595. || !mColorWrite[2] || !mColorWrite[3];
  596. GLbitfield flags = 0;
  597. if (buffers & FBT_COLOR)
  598. {
  599. flags |= GL_COLOR_BUFFER_BIT;
  600. // Enable buffer for writing if it isn't
  601. if (colorMask)
  602. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  603. glClearColor(color.r, color.g, color.b, color.a);
  604. }
  605. if (buffers & FBT_DEPTH)
  606. {
  607. flags |= GL_DEPTH_BUFFER_BIT;
  608. // Enable buffer for writing if it isn't
  609. if (!mDepthWrite)
  610. glDepthMask(GL_TRUE);
  611. glClearDepth(depth);
  612. }
  613. if (buffers & FBT_STENCIL)
  614. {
  615. flags |= GL_STENCIL_BUFFER_BIT;
  616. // Enable buffer for writing if it isn't
  617. glStencilMask(0xFFFFFFFF);
  618. glClearStencil(stencil);
  619. }
  620. // Disable scissor test as we want to clear the entire render surface
  621. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  622. UINT32 oldScissorTop = mScissorTop;
  623. UINT32 oldScissorBottom = mScissorBottom;
  624. UINT32 oldScissorLeft = mScissorLeft;
  625. UINT32 oldScissorRight = mScissorRight;
  626. if (scissorTestEnabled)
  627. {
  628. glDisable(GL_SCISSOR_TEST);
  629. }
  630. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  631. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  632. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  633. if(!clearEntireTarget)
  634. {
  635. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  636. setScissorTestEnable(true);
  637. }
  638. // Clear buffers
  639. glClear(flags);
  640. if(!clearEntireTarget)
  641. {
  642. setScissorTestEnable(false);
  643. }
  644. // Restore scissor test
  645. if (scissorTestEnabled)
  646. {
  647. glEnable(GL_SCISSOR_TEST);
  648. mScissorTop = oldScissorTop;
  649. mScissorBottom = oldScissorBottom;
  650. mScissorLeft = oldScissorLeft;
  651. mScissorRight = oldScissorRight;
  652. }
  653. // Reset buffer write state
  654. if (!mDepthWrite && (buffers & FBT_DEPTH))
  655. {
  656. glDepthMask(GL_FALSE);
  657. }
  658. if (colorMask && (buffers & FBT_COLOR))
  659. {
  660. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  661. }
  662. if (buffers & FBT_STENCIL)
  663. {
  664. glStencilMask(mStencilWriteMask);
  665. }
  666. BS_INC_RENDER_STAT(NumClears);
  667. }
  668. /************************************************************************/
  669. /* PRIVATE */
  670. /************************************************************************/
  671. void GLRenderSystem::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  672. {
  673. if (!activateGLTextureUnit(stage))
  674. return;
  675. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  676. getTextureAddressingMode(uvw.u));
  677. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  678. getTextureAddressingMode(uvw.v));
  679. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  680. getTextureAddressingMode(uvw.w));
  681. activateGLTextureUnit(0);
  682. }
  683. void GLRenderSystem::setTextureBorderColor(UINT16 stage, const Color& colour)
  684. {
  685. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  686. if (activateGLTextureUnit(stage))
  687. {
  688. glTexParameterfv(mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  689. activateGLTextureUnit(0);
  690. }
  691. }
  692. void GLRenderSystem::setTextureMipmapBias(UINT16 stage, float bias)
  693. {
  694. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  695. {
  696. if (activateGLTextureUnit(stage))
  697. {
  698. glTexParameterf(mTextureTypes[stage], GL_TEXTURE_LOD_BIAS, bias);
  699. activateGLTextureUnit(0);
  700. }
  701. }
  702. }
  703. void GLRenderSystem::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  704. {
  705. GLint sourceBlend = getBlendMode(sourceFactor);
  706. GLint destBlend = getBlendMode(destFactor);
  707. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  708. {
  709. glDisable(GL_BLEND);
  710. }
  711. else
  712. {
  713. glEnable(GL_BLEND);
  714. glBlendFunc(sourceBlend, destBlend);
  715. }
  716. GLint func = GL_FUNC_ADD;
  717. switch(op)
  718. {
  719. case BO_ADD:
  720. func = GL_FUNC_ADD;
  721. break;
  722. case BO_SUBTRACT:
  723. func = GL_FUNC_SUBTRACT;
  724. break;
  725. case BO_REVERSE_SUBTRACT:
  726. func = GL_FUNC_REVERSE_SUBTRACT;
  727. break;
  728. case BO_MIN:
  729. func = GL_MIN;
  730. break;
  731. case BO_MAX:
  732. func = GL_MAX;
  733. break;
  734. }
  735. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  736. {
  737. glBlendEquation(func);
  738. }
  739. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  740. {
  741. glBlendEquationEXT(func);
  742. }
  743. }
  744. void GLRenderSystem::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  745. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  746. {
  747. GLint sourceBlend = getBlendMode(sourceFactor);
  748. GLint destBlend = getBlendMode(destFactor);
  749. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  750. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  751. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  752. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  753. {
  754. glDisable(GL_BLEND);
  755. }
  756. else
  757. {
  758. glEnable(GL_BLEND);
  759. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  760. }
  761. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  762. switch(op)
  763. {
  764. case BO_ADD:
  765. func = GL_FUNC_ADD;
  766. break;
  767. case BO_SUBTRACT:
  768. func = GL_FUNC_SUBTRACT;
  769. break;
  770. case BO_REVERSE_SUBTRACT:
  771. func = GL_FUNC_REVERSE_SUBTRACT;
  772. break;
  773. case BO_MIN:
  774. func = GL_MIN;
  775. break;
  776. case BO_MAX:
  777. func = GL_MAX;
  778. break;
  779. }
  780. switch(alphaOp)
  781. {
  782. case BO_ADD:
  783. alphaFunc = GL_FUNC_ADD;
  784. break;
  785. case BO_SUBTRACT:
  786. alphaFunc = GL_FUNC_SUBTRACT;
  787. break;
  788. case BO_REVERSE_SUBTRACT:
  789. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  790. break;
  791. case BO_MIN:
  792. alphaFunc = GL_MIN;
  793. break;
  794. case BO_MAX:
  795. alphaFunc = GL_MAX;
  796. break;
  797. }
  798. if(GLEW_VERSION_2_0) {
  799. glBlendEquationSeparate(func, alphaFunc);
  800. }
  801. else if(GLEW_EXT_blend_equation_separate) {
  802. glBlendEquationSeparateEXT(func, alphaFunc);
  803. }
  804. }
  805. void GLRenderSystem::setAlphaTest(CompareFunction func, unsigned char value)
  806. {
  807. if(func == CMPF_ALWAYS_PASS)
  808. {
  809. glDisable(GL_ALPHA_TEST);
  810. }
  811. else
  812. {
  813. glEnable(GL_ALPHA_TEST);
  814. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  815. }
  816. }
  817. void GLRenderSystem::setAlphaToCoverage(bool enable)
  818. {
  819. static bool lasta2c = false;
  820. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  821. {
  822. if (enable)
  823. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  824. else
  825. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  826. lasta2c = enable;
  827. }
  828. }
  829. void GLRenderSystem::setScissorTestEnable(bool enable)
  830. {
  831. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  832. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  833. bool flipping = rtProps.requiresTextureFlipping();
  834. // GL measures from the bottom, not the top
  835. UINT32 targetHeight = rtProps.getHeight();
  836. // Calculate the "lower-left" corner of the viewport
  837. GLsizei x = 0, y = 0, w = 0, h = 0;
  838. if (enable)
  839. {
  840. glEnable(GL_SCISSOR_TEST);
  841. // GL uses width / height rather than right / bottom
  842. x = mScissorLeft;
  843. if (flipping)
  844. y = targetHeight - mScissorBottom - 1;
  845. else
  846. y = mScissorTop;
  847. w = mScissorRight - mScissorLeft;
  848. h = mScissorBottom - mScissorTop;
  849. glScissor(x, y, w, h);
  850. }
  851. else
  852. {
  853. glDisable(GL_SCISSOR_TEST);
  854. // GL requires you to reset the scissor when disabling
  855. w = mViewportWidth;
  856. h = mViewportHeight;
  857. x = mViewportLeft;
  858. y = mViewportTop;
  859. glScissor(x, y, w, h);
  860. }
  861. }
  862. void GLRenderSystem::setMultisamplingEnable(bool enable)
  863. {
  864. if (enable)
  865. glEnable(GL_MULTISAMPLE);
  866. else
  867. glDisable(GL_MULTISAMPLE);
  868. }
  869. void GLRenderSystem::setDepthClipEnable(bool enable)
  870. {
  871. if (enable)
  872. glEnable(GL_DEPTH_CLAMP);
  873. else
  874. glDisable(GL_DEPTH_CLAMP);
  875. }
  876. void GLRenderSystem::setAntialiasedLineEnable(bool enable)
  877. {
  878. if (enable)
  879. glEnable(GL_LINE_SMOOTH);
  880. else
  881. glDisable(GL_LINE_SMOOTH);
  882. }
  883. void GLRenderSystem::setCullingMode(CullingMode mode)
  884. {
  885. mCullingMode = mode;
  886. GLenum cullMode;
  887. switch( mode )
  888. {
  889. case CULL_NONE:
  890. glDisable(GL_CULL_FACE);
  891. return;
  892. default:
  893. case CULL_CLOCKWISE:
  894. cullMode = GL_BACK;
  895. break;
  896. case CULL_COUNTERCLOCKWISE:
  897. cullMode = GL_FRONT;
  898. break;
  899. }
  900. glEnable(GL_CULL_FACE);
  901. glCullFace(cullMode);
  902. }
  903. void GLRenderSystem::setDepthBufferCheckEnabled(bool enabled)
  904. {
  905. if (enabled)
  906. {
  907. glClearDepth(1.0f);
  908. glEnable(GL_DEPTH_TEST);
  909. }
  910. else
  911. {
  912. glDisable(GL_DEPTH_TEST);
  913. }
  914. }
  915. void GLRenderSystem::setDepthBufferWriteEnabled(bool enabled)
  916. {
  917. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  918. glDepthMask(flag);
  919. mDepthWrite = enabled;
  920. }
  921. void GLRenderSystem::setDepthBufferFunction(CompareFunction func)
  922. {
  923. glDepthFunc(convertCompareFunction(func));
  924. }
  925. void GLRenderSystem::setDepthBias(float constantBias, float slopeScaleBias)
  926. {
  927. if (constantBias != 0 || slopeScaleBias != 0)
  928. {
  929. glEnable(GL_POLYGON_OFFSET_FILL);
  930. glEnable(GL_POLYGON_OFFSET_POINT);
  931. glEnable(GL_POLYGON_OFFSET_LINE);
  932. glPolygonOffset(-slopeScaleBias, -constantBias);
  933. }
  934. else
  935. {
  936. glDisable(GL_POLYGON_OFFSET_FILL);
  937. glDisable(GL_POLYGON_OFFSET_POINT);
  938. glDisable(GL_POLYGON_OFFSET_LINE);
  939. }
  940. }
  941. void GLRenderSystem::setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha)
  942. {
  943. glColorMask(red, green, blue, alpha);
  944. // record this
  945. mColorWrite[0] = red;
  946. mColorWrite[1] = blue;
  947. mColorWrite[2] = green;
  948. mColorWrite[3] = alpha;
  949. }
  950. void GLRenderSystem::setPolygonMode(PolygonMode level)
  951. {
  952. GLenum glmode;
  953. switch(level)
  954. {
  955. case PM_WIREFRAME:
  956. glmode = GL_LINE;
  957. break;
  958. default:
  959. case PM_SOLID:
  960. glmode = GL_FILL;
  961. break;
  962. }
  963. glPolygonMode(GL_FRONT_AND_BACK, glmode);
  964. }
  965. void GLRenderSystem::setStencilCheckEnabled(bool enabled)
  966. {
  967. if (enabled)
  968. glEnable(GL_STENCIL_TEST);
  969. else
  970. glDisable(GL_STENCIL_TEST);
  971. }
  972. void GLRenderSystem::setStencilBufferOperations(StencilOperation stencilFailOp,
  973. StencilOperation depthFailOp, StencilOperation passOp, bool front)
  974. {
  975. if (front)
  976. {
  977. glStencilOpSeparate(GL_FRONT,
  978. convertStencilOp(stencilFailOp),
  979. convertStencilOp(depthFailOp),
  980. convertStencilOp(passOp));
  981. }
  982. else
  983. {
  984. glStencilOpSeparate(GL_BACK,
  985. convertStencilOp(stencilFailOp, true),
  986. convertStencilOp(depthFailOp, true),
  987. convertStencilOp(passOp, true));
  988. }
  989. }
  990. void GLRenderSystem::setStencilBufferFunc(CompareFunction func, UINT32 mask, bool front)
  991. {
  992. mStencilReadMask = mask;
  993. if(front)
  994. {
  995. mStencilCompareFront = func;
  996. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  997. }
  998. else
  999. {
  1000. mStencilCompareBack = func;
  1001. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1002. }
  1003. }
  1004. void GLRenderSystem::setStencilBufferWriteMask(UINT32 mask)
  1005. {
  1006. mStencilWriteMask = mask;
  1007. glStencilMask(mask);
  1008. }
  1009. void GLRenderSystem::setStencilRefValue(UINT32 refValue)
  1010. {
  1011. THROW_IF_NOT_CORE_THREAD;
  1012. mStencilRefValue = refValue;
  1013. glStencilFuncSeparate(GL_FRONT, convertCompareFunction(mStencilCompareFront), mStencilRefValue, mStencilReadMask);
  1014. glStencilFuncSeparate(GL_BACK, convertCompareFunction(mStencilCompareBack), mStencilRefValue, mStencilReadMask);
  1015. }
  1016. void GLRenderSystem::setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions fo)
  1017. {
  1018. if (!activateGLTextureUnit(unit))
  1019. return;
  1020. switch(ftype)
  1021. {
  1022. case FT_MIN:
  1023. mMinFilter = fo;
  1024. // Combine with existing mip filter
  1025. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1026. break;
  1027. case FT_MAG:
  1028. switch (fo)
  1029. {
  1030. case FO_ANISOTROPIC: // GL treats linear and aniso the same
  1031. case FO_LINEAR:
  1032. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  1033. break;
  1034. case FO_POINT:
  1035. case FO_NONE:
  1036. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  1037. break;
  1038. }
  1039. break;
  1040. case FT_MIP:
  1041. mMipFilter = fo;
  1042. // Combine with existing min filter
  1043. glTexParameteri(mTextureTypes[unit], GL_TEXTURE_MIN_FILTER, getCombinedMinMipFilter());
  1044. break;
  1045. }
  1046. activateGLTextureUnit(0);
  1047. }
  1048. void GLRenderSystem::setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy)
  1049. {
  1050. if (!mCurrentCapabilities->hasCapability(RSC_ANISOTROPY))
  1051. return;
  1052. if (!activateGLTextureUnit(unit))
  1053. return;
  1054. GLfloat largest_supported_anisotropy = 0;
  1055. glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &largest_supported_anisotropy);
  1056. if (maxAnisotropy > largest_supported_anisotropy)
  1057. maxAnisotropy = largest_supported_anisotropy ?
  1058. static_cast<UINT32>(largest_supported_anisotropy) : 1;
  1059. if(maxAnisotropy < 1)
  1060. maxAnisotropy = 1;
  1061. if (getCurrentAnisotropy(unit) != maxAnisotropy)
  1062. glTexParameterf(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, (float)maxAnisotropy);
  1063. activateGLTextureUnit(0);
  1064. }
  1065. void GLRenderSystem::setClipPlanesImpl(const PlaneList& clipPlanes)
  1066. {
  1067. size_t i = 0;
  1068. size_t numClipPlanes;
  1069. GLdouble clipPlane[4];
  1070. numClipPlanes = clipPlanes.size();
  1071. for (i = 0; i < numClipPlanes; ++i)
  1072. {
  1073. GLenum clipPlaneId = static_cast<GLenum>(GL_CLIP_PLANE0 + i);
  1074. const Plane& plane = clipPlanes[i];
  1075. if (i >= 6)
  1076. {
  1077. BS_EXCEPT(RenderingAPIException, "Unable to set clip plane");
  1078. }
  1079. clipPlane[0] = plane.normal.x;
  1080. clipPlane[1] = plane.normal.y;
  1081. clipPlane[2] = plane.normal.z;
  1082. clipPlane[3] = plane.d;
  1083. glClipPlane(clipPlaneId, clipPlane);
  1084. glEnable(clipPlaneId);
  1085. }
  1086. // Disable remaining clip planes
  1087. for (; i < 6; ++i)
  1088. {
  1089. glDisable(static_cast<GLenum>(GL_CLIP_PLANE0 + i));
  1090. }
  1091. }
  1092. bool GLRenderSystem::activateGLTextureUnit(UINT16 unit)
  1093. {
  1094. if (mActiveTextureUnit != unit)
  1095. {
  1096. if (unit < getCapabilities()->getNumCombinedTextureUnits())
  1097. {
  1098. glActiveTexture(GL_TEXTURE0 + unit);
  1099. mActiveTextureUnit = unit;
  1100. return true;
  1101. }
  1102. else if (!unit)
  1103. {
  1104. // always ok to use the first unit
  1105. return true;
  1106. }
  1107. else
  1108. {
  1109. LOGWRN("Provided texture unit index is higher than OpenGL supports. Provided: " + toString(unit) +
  1110. ". Supported range: 0 .. " + toString(getCapabilities()->getNumCombinedTextureUnits() - 1));
  1111. return false;
  1112. }
  1113. }
  1114. else
  1115. {
  1116. return true;
  1117. }
  1118. }
  1119. void GLRenderSystem::beginDraw()
  1120. {
  1121. if(mDrawCallInProgress)
  1122. BS_EXCEPT(InternalErrorException, "Calling beginDraw without finishing previous draw call. Please call endDraw().");
  1123. mDrawCallInProgress = true;
  1124. if(mCurrentVertexProgram == nullptr)
  1125. {
  1126. LOGWRN("Cannot render without a set vertex shader.");
  1127. return;
  1128. }
  1129. if(mBoundVertexDeclaration == nullptr)
  1130. {
  1131. LOGWRN("Cannot render without a set vertex declaration.");
  1132. return;
  1133. }
  1134. const GLSLProgramPipeline* pipeline = mProgramPipelineManager->getPipeline(mCurrentVertexProgram.get(),
  1135. mCurrentFragmentProgram.get(), mCurrentGeometryProgram.get(), mCurrentHullProgram.get(), mCurrentDomainProgram.get());
  1136. if(mActivePipeline != pipeline)
  1137. {
  1138. glBindProgramPipeline(pipeline->glHandle);
  1139. mActivePipeline = pipeline;
  1140. }
  1141. const GLVertexArrayObject& vao = GLVertexArrayObjectManager::instance().getVAO(mCurrentVertexProgram, mBoundVertexDeclaration, mBoundVertexBuffers);
  1142. glBindVertexArray(vao.getGLHandle());
  1143. BS_INC_RENDER_STAT(NumVertexBufferBinds);
  1144. BS_INC_RENDER_STAT(NumGpuProgramBinds);
  1145. }
  1146. void GLRenderSystem::endDraw()
  1147. {
  1148. if(!mDrawCallInProgress)
  1149. return;
  1150. mDrawCallInProgress = false;
  1151. }
  1152. GLfloat GLRenderSystem::getCurrentAnisotropy(UINT16 unit)
  1153. {
  1154. GLfloat curAniso = 0;
  1155. glGetTexParameterfv(mTextureTypes[unit], GL_TEXTURE_MAX_ANISOTROPY_EXT, &curAniso);
  1156. return curAniso ? curAniso : 1;
  1157. }
  1158. GLint GLRenderSystem::convertStencilOp(StencilOperation op, bool invert) const
  1159. {
  1160. switch (op)
  1161. {
  1162. case SOP_KEEP:
  1163. return GL_KEEP;
  1164. case SOP_ZERO:
  1165. return GL_ZERO;
  1166. case SOP_REPLACE:
  1167. return GL_REPLACE;
  1168. case SOP_INCREMENT:
  1169. return invert ? GL_DECR : GL_INCR;
  1170. case SOP_DECREMENT:
  1171. return invert ? GL_INCR : GL_DECR;
  1172. case SOP_INCREMENT_WRAP:
  1173. return invert ? GL_DECR_WRAP_EXT : GL_INCR_WRAP_EXT;
  1174. case SOP_DECREMENT_WRAP:
  1175. return invert ? GL_INCR_WRAP_EXT : GL_DECR_WRAP_EXT;
  1176. case SOP_INVERT:
  1177. return GL_INVERT;
  1178. };
  1179. // to keep compiler happy
  1180. return SOP_KEEP;
  1181. }
  1182. GLint GLRenderSystem::convertCompareFunction(CompareFunction func) const
  1183. {
  1184. switch (func)
  1185. {
  1186. case CMPF_ALWAYS_FAIL:
  1187. return GL_NEVER;
  1188. case CMPF_ALWAYS_PASS:
  1189. return GL_ALWAYS;
  1190. case CMPF_LESS:
  1191. return GL_LESS;
  1192. case CMPF_LESS_EQUAL:
  1193. return GL_LEQUAL;
  1194. case CMPF_EQUAL:
  1195. return GL_EQUAL;
  1196. case CMPF_NOT_EQUAL:
  1197. return GL_NOTEQUAL;
  1198. case CMPF_GREATER_EQUAL:
  1199. return GL_GEQUAL;
  1200. case CMPF_GREATER:
  1201. return GL_GREATER;
  1202. };
  1203. return GL_ALWAYS;
  1204. }
  1205. GLuint GLRenderSystem::getCombinedMinMipFilter() const
  1206. {
  1207. switch (mMinFilter)
  1208. {
  1209. case FO_ANISOTROPIC:
  1210. case FO_LINEAR:
  1211. switch (mMipFilter)
  1212. {
  1213. case FO_ANISOTROPIC:
  1214. case FO_LINEAR:
  1215. // Linear min, linear mip
  1216. return GL_LINEAR_MIPMAP_LINEAR;
  1217. case FO_POINT:
  1218. // Linear min, point mip
  1219. return GL_LINEAR_MIPMAP_NEAREST;
  1220. case FO_NONE:
  1221. // Linear min, no mip
  1222. return GL_LINEAR;
  1223. }
  1224. break;
  1225. case FO_POINT:
  1226. case FO_NONE:
  1227. switch (mMipFilter)
  1228. {
  1229. case FO_ANISOTROPIC:
  1230. case FO_LINEAR:
  1231. // Nearest min, linear mip
  1232. return GL_NEAREST_MIPMAP_LINEAR;
  1233. case FO_POINT:
  1234. // Nearest min, point mip
  1235. return GL_NEAREST_MIPMAP_NEAREST;
  1236. case FO_NONE:
  1237. // Nearest min, no mip
  1238. return GL_NEAREST;
  1239. }
  1240. break;
  1241. }
  1242. // Should never get here
  1243. return 0;
  1244. }
  1245. GLint GLRenderSystem::getBlendMode(BlendFactor blendMode) const
  1246. {
  1247. switch (blendMode)
  1248. {
  1249. case BF_ONE:
  1250. return GL_ONE;
  1251. case BF_ZERO:
  1252. return GL_ZERO;
  1253. case BF_DEST_COLOR:
  1254. return GL_DST_COLOR;
  1255. case BF_SOURCE_COLOR:
  1256. return GL_SRC_COLOR;
  1257. case BF_INV_DEST_COLOR:
  1258. return GL_ONE_MINUS_DST_COLOR;
  1259. case BF_INV_SOURCE_COLOR:
  1260. return GL_ONE_MINUS_SRC_COLOR;
  1261. case BF_DEST_ALPHA:
  1262. return GL_DST_ALPHA;
  1263. case BF_SOURCE_ALPHA:
  1264. return GL_SRC_ALPHA;
  1265. case BF_INV_DEST_ALPHA:
  1266. return GL_ONE_MINUS_DST_ALPHA;
  1267. case BF_INV_SOURCE_ALPHA:
  1268. return GL_ONE_MINUS_SRC_ALPHA;
  1269. };
  1270. return GL_ONE;
  1271. }
  1272. GLint GLRenderSystem::getTextureAddressingMode(TextureAddressingMode tam) const
  1273. {
  1274. switch (tam)
  1275. {
  1276. default:
  1277. case TAM_WRAP:
  1278. return GL_REPEAT;
  1279. case TAM_MIRROR:
  1280. return GL_MIRRORED_REPEAT;
  1281. case TAM_CLAMP:
  1282. return GL_CLAMP_TO_EDGE;
  1283. case TAM_BORDER:
  1284. return GL_CLAMP_TO_BORDER;
  1285. }
  1286. }
  1287. GLint GLRenderSystem::getGLDrawMode() const
  1288. {
  1289. GLint primType;
  1290. // Use adjacency if there is a geometry program and it requested adjacency info
  1291. bool useAdjacency = (mGeometryProgramBound && mCurrentGeometryProgram->isAdjacencyInfoRequired());
  1292. switch (mCurrentDrawOperation)
  1293. {
  1294. case DOT_POINT_LIST:
  1295. primType = GL_POINTS;
  1296. break;
  1297. case DOT_LINE_LIST:
  1298. primType = useAdjacency ? GL_LINES_ADJACENCY_EXT : GL_LINES;
  1299. break;
  1300. case DOT_LINE_STRIP:
  1301. primType = useAdjacency ? GL_LINE_STRIP_ADJACENCY_EXT : GL_LINE_STRIP;
  1302. break;
  1303. default:
  1304. case DOT_TRIANGLE_LIST:
  1305. primType = useAdjacency ? GL_TRIANGLES_ADJACENCY_EXT : GL_TRIANGLES;
  1306. break;
  1307. case DOT_TRIANGLE_STRIP:
  1308. primType = useAdjacency ? GL_TRIANGLE_STRIP_ADJACENCY_EXT : GL_TRIANGLE_STRIP;
  1309. break;
  1310. case DOT_TRIANGLE_FAN:
  1311. primType = GL_TRIANGLE_FAN;
  1312. break;
  1313. }
  1314. return primType;
  1315. }
  1316. UINT32 GLRenderSystem::getGLTextureUnit(GpuProgramType gptype, UINT32 unit)
  1317. {
  1318. if (gptype != GPT_VERTEX_PROGRAM && gptype != GPT_FRAGMENT_PROGRAM && gptype != GPT_GEOMETRY_PROGRAM)
  1319. {
  1320. BS_EXCEPT(InvalidParametersException, "OpenGL cannot assign textures to this gpu program type: " + toString(gptype));
  1321. }
  1322. UINT32 numSupportedUnits = mCurrentCapabilities->getNumTextureUnits(gptype);
  1323. if (unit < 0 || unit >= numSupportedUnits)
  1324. {
  1325. BS_EXCEPT(InvalidParametersException, "Invalid texture unit index for the provided stage. Unit index: " + toString(unit) + ". Stage: " +
  1326. toString(gptype) + ". Supported range is 0 .. " + toString(numSupportedUnits - 1));
  1327. }
  1328. switch (gptype)
  1329. {
  1330. case GPT_FRAGMENT_PROGRAM:
  1331. return mFragmentTexOffset + unit;
  1332. case GPT_VERTEX_PROGRAM:
  1333. return mVertexTexOffset + unit;
  1334. case GPT_GEOMETRY_PROGRAM:
  1335. return mGeometryTexOffset + unit;
  1336. default:
  1337. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1338. }
  1339. }
  1340. UINT32 GLRenderSystem::getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding)
  1341. {
  1342. UINT32 maxNumBindings = mCurrentCapabilities->getNumGpuParamBlockBuffers(gptype);
  1343. if (binding < 0 || binding >= maxNumBindings)
  1344. {
  1345. BS_EXCEPT(InvalidParametersException, "Invalid buffer binding for the provided stage. Buffer binding: " + toString(binding) + ". Stage: " +
  1346. toString(gptype) + ". Supported range is 0 .. " + toString(maxNumBindings - 1));
  1347. }
  1348. switch (gptype)
  1349. {
  1350. case GPT_FRAGMENT_PROGRAM:
  1351. return mFragmentUBOffset + binding;
  1352. case GPT_VERTEX_PROGRAM:
  1353. return mVertexUBOffset + binding;
  1354. case GPT_GEOMETRY_PROGRAM:
  1355. return mGeometryUBOffset + binding;
  1356. case GPT_HULL_PROGRAM:
  1357. return mHullUBOffset + binding;
  1358. case GPT_DOMAIN_PROGRAM:
  1359. return mDomainUBOffset + binding;
  1360. case GPT_COMPUTE_PROGRAM:
  1361. return mComputeUBOffset + binding;
  1362. default:
  1363. BS_EXCEPT(InternalErrorException, "Invalid program type: " + toString(gptype));
  1364. }
  1365. }
  1366. void GLRenderSystem::setActiveProgram(GpuProgramType gptype, const SPtr<GLSLGpuProgramCore>& program)
  1367. {
  1368. switch (gptype)
  1369. {
  1370. case GPT_VERTEX_PROGRAM:
  1371. mCurrentVertexProgram = program;
  1372. break;
  1373. case GPT_FRAGMENT_PROGRAM:
  1374. mCurrentFragmentProgram = program;
  1375. break;
  1376. case GPT_GEOMETRY_PROGRAM:
  1377. mCurrentGeometryProgram = program;
  1378. break;
  1379. case GPT_DOMAIN_PROGRAM:
  1380. mCurrentDomainProgram = program;
  1381. break;
  1382. case GPT_HULL_PROGRAM:
  1383. mCurrentHullProgram = program;
  1384. break;
  1385. }
  1386. }
  1387. SPtr<GLSLGpuProgramCore> GLRenderSystem::getActiveProgram(GpuProgramType gptype) const
  1388. {
  1389. switch (gptype)
  1390. {
  1391. case GPT_VERTEX_PROGRAM:
  1392. return mCurrentVertexProgram;
  1393. break;
  1394. case GPT_FRAGMENT_PROGRAM:
  1395. return mCurrentFragmentProgram;
  1396. break;
  1397. case GPT_GEOMETRY_PROGRAM:
  1398. return mCurrentGeometryProgram;
  1399. break;
  1400. case GPT_DOMAIN_PROGRAM:
  1401. return mCurrentDomainProgram;
  1402. break;
  1403. case GPT_HULL_PROGRAM:
  1404. return mCurrentHullProgram;
  1405. break;
  1406. default:
  1407. BS_EXCEPT(InvalidParametersException, "Insupported gpu program type: " + toString(gptype));
  1408. }
  1409. }
  1410. void GLRenderSystem::initFromCaps(RenderSystemCapabilities* caps)
  1411. {
  1412. if(caps->getRenderSystemName() != getName())
  1413. {
  1414. BS_EXCEPT(InvalidParametersException,
  1415. "Trying to initialize GLRenderSystem from RenderSystemCapabilities that do not support OpenGL");
  1416. }
  1417. #if BS_DEBUG_MODE
  1418. if (mGLSupport->checkExtension("GL_ARB_debug_output"))
  1419. {
  1420. glDebugMessageCallback(&openGlErrorCallback, 0);
  1421. glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
  1422. }
  1423. #endif
  1424. HardwareBufferManager::startUp();
  1425. HardwareBufferCoreManager::startUp<GLHardwareBufferCoreManager>();
  1426. // GPU Program Manager setup
  1427. if(caps->isShaderProfileSupported("glsl"))
  1428. {
  1429. mGLSLProgramFactory = bs_new<GLSLProgramFactory>();
  1430. GpuProgramCoreManager::instance().addFactory(mGLSLProgramFactory);
  1431. }
  1432. // Check for framebuffer object extension
  1433. if(caps->hasCapability(RSC_FBO))
  1434. {
  1435. if(caps->hasCapability(RSC_HWRENDER_TO_TEXTURE))
  1436. {
  1437. // Create FBO manager
  1438. GLRTTManager::startUp<GLRTTManager>();
  1439. }
  1440. }
  1441. else
  1442. {
  1443. BS_EXCEPT(RenderingAPIException, "GPU doesn't support frame buffer objects. OpenGL versions lower than 3.0 are not supported.");
  1444. }
  1445. mFragmentTexOffset = 0;
  1446. mVertexTexOffset = caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1447. mGeometryTexOffset = mVertexTexOffset + caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1448. UINT16 numCombinedTexUnits = caps->getNumCombinedTextureUnits();
  1449. UINT32 totalNumTexUnits = caps->getNumTextureUnits(GPT_VERTEX_PROGRAM);
  1450. totalNumTexUnits += caps->getNumTextureUnits(GPT_FRAGMENT_PROGRAM);
  1451. totalNumTexUnits += caps->getNumTextureUnits(GPT_GEOMETRY_PROGRAM);
  1452. totalNumTexUnits += caps->getNumTextureUnits(GPT_HULL_PROGRAM);
  1453. totalNumTexUnits += caps->getNumTextureUnits(GPT_DOMAIN_PROGRAM);
  1454. totalNumTexUnits += caps->getNumTextureUnits(GPT_COMPUTE_PROGRAM);
  1455. if(totalNumTexUnits > numCombinedTexUnits)
  1456. BS_EXCEPT(InternalErrorException, "Number of combined texture units less than the number of individual units!?");
  1457. mNumTextureTypes = numCombinedTexUnits;
  1458. mTextureTypes = bs_newN<GLenum>(mNumTextureTypes);
  1459. for(UINT16 i = 0; i < numCombinedTexUnits; i++)
  1460. mTextureTypes[i] = GL_TEXTURE_2D;
  1461. mVertexUBOffset = 0;
  1462. UINT32 totalNumUniformBlocks = caps->getNumGpuParamBlockBuffers(GPT_VERTEX_PROGRAM);
  1463. mFragmentUBOffset = totalNumUniformBlocks;
  1464. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_FRAGMENT_PROGRAM);
  1465. mGeometryUBOffset = totalNumUniformBlocks;
  1466. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_GEOMETRY_PROGRAM);
  1467. mHullUBOffset = totalNumUniformBlocks;
  1468. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_HULL_PROGRAM);
  1469. mDomainUBOffset = totalNumUniformBlocks;
  1470. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_DOMAIN_PROGRAM);
  1471. mComputeUBOffset = totalNumUniformBlocks;
  1472. totalNumUniformBlocks += caps->getNumGpuParamBlockBuffers(GPT_COMPUTE_PROGRAM);
  1473. UINT16 numCombinedUniformBlocks = caps->getNumCombinedGpuParamBlockBuffers();
  1474. if(totalNumUniformBlocks > numCombinedUniformBlocks)
  1475. BS_EXCEPT(InternalErrorException, "Number of combined uniform block buffers less than the number of individual per-stage buffers!?");
  1476. TextureManager::startUp<GLTextureManager>(std::ref(*mGLSupport));
  1477. TextureCoreManager::startUp<GLTextureCoreManager>(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. void GLRenderSystem::applyViewport()
  1742. {
  1743. if (mActiveRenderTarget == nullptr)
  1744. return;
  1745. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  1746. // Calculate the "lower-left" corner of the viewport
  1747. mViewportLeft = (UINT32)(rtProps.getWidth() * mViewportNorm.x);
  1748. mViewportTop = (UINT32)(rtProps.getHeight() * mViewportNorm.y);
  1749. mViewportWidth = (UINT32)(rtProps.getWidth() * mViewportNorm.width);
  1750. mViewportHeight = (UINT32)(rtProps.getHeight() * mViewportNorm.height);
  1751. if (rtProps.requiresTextureFlipping())
  1752. {
  1753. // Convert "upper-left" corner to "lower-left"
  1754. mViewportTop = rtProps.getHeight() - (mViewportTop + mViewportHeight) - 1;
  1755. }
  1756. glViewport(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1757. // Configure the viewport clipping
  1758. glScissor(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  1759. }
  1760. /************************************************************************/
  1761. /* UTILITY */
  1762. /************************************************************************/
  1763. float GLRenderSystem::getMinimumDepthInputValue()
  1764. {
  1765. return -1.0f;
  1766. }
  1767. float GLRenderSystem::getMaximumDepthInputValue()
  1768. {
  1769. return 1.0f;
  1770. }
  1771. float GLRenderSystem::getHorizontalTexelOffset()
  1772. {
  1773. return 0.0f;
  1774. }
  1775. float GLRenderSystem::getVerticalTexelOffset()
  1776. {
  1777. return 0.0f;
  1778. }
  1779. VertexElementType GLRenderSystem::getColorVertexElementType() const
  1780. {
  1781. return VET_COLOR_ABGR;
  1782. }
  1783. void GLRenderSystem::convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest)
  1784. {
  1785. dest = matrix;
  1786. }
  1787. void __stdcall openGlErrorCallback(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, GLvoid *userParam)
  1788. {
  1789. if (type != GL_DEBUG_TYPE_PERFORMANCE && type != GL_DEBUG_TYPE_OTHER)
  1790. {
  1791. BS_EXCEPT(RenderingAPIException, "OpenGL error: " + String(message));
  1792. }
  1793. }
  1794. }