2
0

BsGLRenderAPI.cpp 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157
  1. #include "BsGLRenderAPI.h"
  2. #include "BsRenderAPI.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. GLRenderAPI::GLRenderAPI()
  35. : mDepthWrite(true),
  36. mGLSLProgramFactory(nullptr),
  37. mProgramPipelineManager(nullptr),
  38. mActivePipeline(nullptr),
  39. mActiveTextureUnit(0),
  40. mScissorTop(0), mScissorBottom(720), mScissorLeft(0), mScissorRight(1280),
  41. mViewportLeft(0), mViewportTop(0), mViewportWidth(0), mViewportHeight(0),
  42. mStencilReadMask(0xFFFFFFFF),
  43. mStencilWriteMask(0xFFFFFFFF),
  44. mStencilCompareFront(CMPF_ALWAYS_PASS),
  45. mStencilCompareBack(CMPF_ALWAYS_PASS),
  46. mStencilRefValue(0),
  47. mFragmentTexOffset(0),
  48. mVertexTexOffset(0),
  49. mGeometryTexOffset(0),
  50. mTextureTypes(nullptr),
  51. mNumTextureTypes(0),
  52. mFragmentUBOffset(0),
  53. mVertexUBOffset(0),
  54. mGeometryUBOffset(0),
  55. mHullUBOffset(0),
  56. mDomainUBOffset(0),
  57. mComputeUBOffset(0),
  58. mDrawCallInProgress(false),
  59. mCurrentDrawOperation(DOT_TRIANGLE_LIST),
  60. mViewportNorm(0.0f, 0.0f, 1.0f, 1.0f)
  61. {
  62. // Get our GLSupport
  63. mGLSupport = BansheeEngine::getGLSupport();
  64. mViewMatrix = Matrix4::IDENTITY;
  65. mColorWrite[0] = mColorWrite[1] = mColorWrite[2] = mColorWrite[3] = true;
  66. mCurrentContext = 0;
  67. mMainContext = 0;
  68. mGLInitialised = false;
  69. mMinFilter = FO_LINEAR;
  70. mMipFilter = FO_POINT;
  71. mProgramPipelineManager = bs_new<GLSLProgramPipelineManager>();
  72. }
  73. GLRenderAPI::~GLRenderAPI()
  74. {
  75. }
  76. const StringID& GLRenderAPI::getName() const
  77. {
  78. static StringID strName("GLRenderAPI");
  79. return strName;
  80. }
  81. const String& GLRenderAPI::getShadingLanguageName() const
  82. {
  83. static String strName("glsl");
  84. return strName;
  85. }
  86. void GLRenderAPI::initializePrepare()
  87. {
  88. THROW_IF_NOT_CORE_THREAD;
  89. mGLSupport->start();
  90. mVideoModeInfo = mGLSupport->getVideoModeInfo();
  91. RenderWindowManager::startUp<GLRenderWindowManager>(this);
  92. RenderWindowCoreManager::startUp<GLRenderWindowCoreManager>(this);
  93. RenderStateCoreManager::startUp();
  94. QueryManager::startUp<GLQueryManager>();
  95. RenderAPICore::initializePrepare();
  96. }
  97. void GLRenderAPI::initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow)
  98. {
  99. // Get the context from the window and finish initialization
  100. SPtr<GLContext> context;
  101. primaryWindow->getCustomAttribute("GLCONTEXT", &context);
  102. // Set main and current context
  103. mMainContext = context;
  104. mCurrentContext = mMainContext;
  105. // Set primary context as active
  106. if (mCurrentContext)
  107. mCurrentContext->setCurrent();
  108. checkForErrors();
  109. // Setup GLSupport
  110. mGLSupport->initializeExtensions();
  111. checkForErrors();
  112. Vector<BansheeEngine::String> tokens = StringUtil::split(mGLSupport->getGLVersion(), ".");
  113. if (!tokens.empty())
  114. {
  115. mDriverVersion.major = parseInt(tokens[0]);
  116. if (tokens.size() > 1)
  117. mDriverVersion.minor = parseInt(tokens[1]);
  118. if (tokens.size() > 2)
  119. mDriverVersion.release = parseInt(tokens[2]);
  120. }
  121. mDriverVersion.build = 0;
  122. mCurrentCapabilities = createRenderSystemCapabilities();
  123. initFromCaps(mCurrentCapabilities);
  124. GLVertexArrayObjectManager::startUp();
  125. mGLInitialised = true;
  126. RenderAPICore::initializeFinalize(primaryWindow);
  127. }
  128. void GLRenderAPI::destroyCore()
  129. {
  130. RenderAPICore::destroyCore();
  131. // Deleting the GLSL program factory
  132. if (mGLSLProgramFactory)
  133. {
  134. // Remove from manager safely
  135. GpuProgramCoreManager::instance().removeFactory(mGLSLProgramFactory);
  136. bs_delete(mGLSLProgramFactory);
  137. mGLSLProgramFactory = nullptr;
  138. }
  139. // Deleting the hardware buffer manager. Has to be done before the mGLSupport->stop().
  140. HardwareBufferCoreManager::shutDown();
  141. HardwareBufferManager::shutDown();
  142. GLRTTManager::shutDown();
  143. mBoundVertexBuffers.clear();
  144. mBoundVertexDeclaration = nullptr;
  145. mBoundIndexBuffer = nullptr;
  146. mCurrentVertexProgram = nullptr;
  147. mCurrentFragmentProgram = nullptr;
  148. mCurrentGeometryProgram = nullptr;
  149. mCurrentHullProgram = nullptr;
  150. mCurrentDomainProgram = nullptr;
  151. mGLSupport->stop();
  152. TextureCoreManager::shutDown();
  153. TextureManager::shutDown();
  154. QueryManager::shutDown();
  155. RenderWindowCoreManager::shutDown();
  156. RenderWindowManager::shutDown();
  157. RenderStateCoreManager::shutDown();
  158. GLVertexArrayObjectManager::shutDown(); // Note: Needs to be after QueryManager shutdown as some resources might be waiting for queries to complete
  159. mGLInitialised = false;
  160. if(mProgramPipelineManager != nullptr)
  161. bs_delete(mProgramPipelineManager);
  162. if(mGLSupport)
  163. bs_delete(mGLSupport);
  164. if(mTextureTypes != nullptr)
  165. bs_deleteN(mTextureTypes, mNumTextureTypes);
  166. }
  167. void GLRenderAPI::bindGpuProgram(const SPtr<GpuProgramCore>& prg)
  168. {
  169. THROW_IF_NOT_CORE_THREAD;
  170. SPtr<GLSLGpuProgramCore> glprg = std::static_pointer_cast<GLSLGpuProgramCore>(prg);
  171. switch (glprg->getProperties().getType())
  172. {
  173. case GPT_VERTEX_PROGRAM:
  174. mCurrentVertexProgram = glprg;
  175. break;
  176. case GPT_FRAGMENT_PROGRAM:
  177. mCurrentFragmentProgram = glprg;
  178. break;
  179. case GPT_GEOMETRY_PROGRAM:
  180. mCurrentGeometryProgram = glprg;
  181. break;
  182. case GPT_DOMAIN_PROGRAM:
  183. mCurrentDomainProgram = glprg;
  184. break;
  185. case GPT_HULL_PROGRAM:
  186. mCurrentHullProgram = glprg;
  187. break;
  188. }
  189. RenderAPICore::bindGpuProgram(prg);
  190. }
  191. void GLRenderAPI::unbindGpuProgram(GpuProgramType gptype)
  192. {
  193. THROW_IF_NOT_CORE_THREAD;
  194. setActiveProgram(gptype, nullptr);
  195. RenderAPICore::unbindGpuProgram(gptype);
  196. }
  197. void GLRenderAPI::bindGpuParams(GpuProgramType gptype, const SPtr<GpuParamsCore>& bindableParams)
  198. {
  199. THROW_IF_NOT_CORE_THREAD;
  200. bindableParams->updateHardwareBuffers();
  201. const GpuParamDesc& paramDesc = bindableParams->getParamDesc();
  202. SPtr<GLSLGpuProgramCore> activeProgram = getActiveProgram(gptype);
  203. GLuint glProgram = activeProgram->getGLHandle();
  204. for(auto iter = paramDesc.textures.begin(); iter != paramDesc.textures.end(); ++iter)
  205. {
  206. SPtr<TextureCore> texture = bindableParams->getTexture(iter->second.slot);
  207. if (!bindableParams->isLoadStoreTexture(iter->second.slot))
  208. {
  209. if (texture == nullptr)
  210. setTexture(gptype, iter->second.slot, false, nullptr);
  211. else
  212. setTexture(gptype, iter->second.slot, true, texture);
  213. }
  214. else
  215. {
  216. const TextureSurface& surface = bindableParams->getLoadStoreSurface(iter->second.slot);
  217. if (texture == nullptr)
  218. setLoadStoreTexture(gptype, iter->second.slot, false, nullptr, surface);
  219. else
  220. setLoadStoreTexture(gptype, iter->second.slot, true, texture, surface);
  221. }
  222. }
  223. for(auto iter = paramDesc.samplers.begin(); iter != paramDesc.samplers.end(); ++iter)
  224. {
  225. SPtr<SamplerStateCore>& samplerState = bindableParams->getSamplerState(iter->second.slot);
  226. if(samplerState == nullptr)
  227. setSamplerState(gptype, iter->second.slot, SamplerStateCore::getDefault());
  228. else
  229. setSamplerState(gptype, iter->second.slot, samplerState);
  230. glProgramUniform1i(glProgram, iter->second.slot, getGLTextureUnit(gptype, iter->second.slot));
  231. }
  232. UINT8* uniformBufferData = nullptr;
  233. UINT32 blockBinding = 0;
  234. for(auto iter = paramDesc.paramBlocks.begin(); iter != paramDesc.paramBlocks.end(); ++iter)
  235. {
  236. SPtr<GpuParamBlockBufferCore> paramBlockBuffer = bindableParams->getParamBlockBuffer(iter->second.slot);
  237. if(paramBlockBuffer == nullptr)
  238. continue;
  239. if(iter->second.slot == 0)
  240. {
  241. // 0 means uniforms are not in block, in which case we handle it specially
  242. if (uniformBufferData == nullptr && paramBlockBuffer->getSize() > 0)
  243. {
  244. uniformBufferData = (UINT8*)bs_alloc<ScratchAlloc>(paramBlockBuffer->getSize());
  245. paramBlockBuffer->readFromGPU(uniformBufferData); // TODO - Don't read from GPU!? Just read the cached version
  246. }
  247. continue;
  248. }
  249. const GLGpuParamBlockBufferCore* glParamBlockBuffer = static_cast<const GLGpuParamBlockBufferCore*>(paramBlockBuffer.get());
  250. UINT32 globalBlockBinding = getGLUniformBlockBinding(gptype, blockBinding);
  251. glUniformBlockBinding(glProgram, iter->second.slot - 1, globalBlockBinding);
  252. glBindBufferRange(GL_UNIFORM_BUFFER, globalBlockBinding, glParamBlockBuffer->getGLHandle(), 0, glParamBlockBuffer->getSize());
  253. blockBinding++;
  254. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  255. }
  256. bool hasBoundAtLeastOne = false;
  257. for(auto iter = paramDesc.params.begin(); iter != paramDesc.params.end(); ++iter)
  258. {
  259. const GpuParamDataDesc& paramDesc = iter->second;
  260. if(paramDesc.paramBlockSlot != 0) // 0 means uniforms are not in a block
  261. continue;
  262. const UINT8* ptrData = uniformBufferData + paramDesc.cpuMemOffset * sizeof(UINT32);
  263. hasBoundAtLeastOne = true;
  264. // Note: We don't transpose matrices here even though we don't use column major format
  265. // because they are assumed to be pre-transposed in the GpuParams buffer
  266. switch(paramDesc.type)
  267. {
  268. case GPDT_FLOAT1:
  269. glProgramUniform1fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  270. break;
  271. case GPDT_FLOAT2:
  272. glProgramUniform2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  273. break;
  274. case GPDT_FLOAT3:
  275. glProgramUniform3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  276. break;
  277. case GPDT_FLOAT4:
  278. glProgramUniform4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLfloat*)ptrData);
  279. break;
  280. case GPDT_MATRIX_2X2:
  281. glProgramUniformMatrix2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  282. GL_FALSE, (GLfloat*)ptrData);
  283. break;
  284. case GPDT_MATRIX_2X3:
  285. glProgramUniformMatrix3x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  286. GL_FALSE, (GLfloat*)ptrData);
  287. break;
  288. case GPDT_MATRIX_2X4:
  289. glProgramUniformMatrix4x2fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  290. GL_FALSE, (GLfloat*)ptrData);
  291. break;
  292. case GPDT_MATRIX_3X2:
  293. glProgramUniformMatrix2x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  294. GL_FALSE, (GLfloat*)ptrData);
  295. break;
  296. case GPDT_MATRIX_3X3:
  297. glProgramUniformMatrix3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  298. GL_FALSE, (GLfloat*)ptrData);
  299. break;
  300. case GPDT_MATRIX_3X4:
  301. glProgramUniformMatrix4x3fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  302. GL_FALSE, (GLfloat*)ptrData);
  303. break;
  304. case GPDT_MATRIX_4X2:
  305. glProgramUniformMatrix2x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  306. GL_FALSE, (GLfloat*)ptrData);
  307. break;
  308. case GPDT_MATRIX_4X3:
  309. glProgramUniformMatrix3x4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  310. GL_FALSE, (GLfloat*)ptrData);
  311. break;
  312. case GPDT_MATRIX_4X4:
  313. glProgramUniformMatrix4fv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize,
  314. GL_FALSE, (GLfloat*)ptrData);
  315. break;
  316. case GPDT_INT1:
  317. glProgramUniform1iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  318. break;
  319. case GPDT_INT2:
  320. glProgramUniform2iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  321. break;
  322. case GPDT_INT3:
  323. glProgramUniform3iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  324. break;
  325. case GPDT_INT4:
  326. glProgramUniform4iv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLint*)ptrData);
  327. break;
  328. case GPDT_BOOL:
  329. glProgramUniform1uiv(glProgram, paramDesc.gpuMemOffset, paramDesc.arraySize, (GLuint*)ptrData);
  330. break;
  331. case GPDT_UNKNOWN:
  332. break;
  333. }
  334. }
  335. if (hasBoundAtLeastOne)
  336. BS_INC_RENDER_STAT(NumGpuParamBufferBinds);
  337. if(uniformBufferData != nullptr)
  338. {
  339. bs_free<ScratchAlloc>(uniformBufferData);
  340. }
  341. }
  342. void GLRenderAPI::setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr)
  343. {
  344. THROW_IF_NOT_CORE_THREAD;
  345. unit = getGLTextureUnit(gptype, unit);
  346. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  347. GLenum lastTextureType = mTextureTypes[unit];
  348. if (!activateGLTextureUnit(unit))
  349. return;
  350. if (enabled && tex)
  351. {
  352. mTextureTypes[unit] = tex->getGLTextureTarget();
  353. glBindTexture(mTextureTypes[unit], tex->getGLID());
  354. }
  355. else
  356. {
  357. // TODO - This doesn't actually disable all textures set on this image unit, only the 2D ones
  358. // - If a non-2D sampler is used, the texture will still be displayed
  359. glBindTexture(GL_TEXTURE_2D, 0);
  360. }
  361. activateGLTextureUnit(0);
  362. BS_INC_RENDER_STAT(NumTextureBinds);
  363. }
  364. void GLRenderAPI::setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state)
  365. {
  366. THROW_IF_NOT_CORE_THREAD;
  367. const SamplerProperties& stateProps = state->getProperties();
  368. unit = getGLTextureUnit(gptype, unit);
  369. // Set texture layer filtering
  370. setTextureFiltering(unit, FT_MIN, stateProps.getTextureFiltering(FT_MIN));
  371. setTextureFiltering(unit, FT_MAG, stateProps.getTextureFiltering(FT_MAG));
  372. setTextureFiltering(unit, FT_MIP, stateProps.getTextureFiltering(FT_MIP));
  373. // Set texture anisotropy
  374. setTextureAnisotropy(unit, stateProps.getTextureAnisotropy());
  375. // Set mipmap biasing
  376. setTextureMipmapBias(unit, stateProps.getTextureMipmapBias());
  377. // Texture addressing mode
  378. const UVWAddressingMode& uvw = stateProps.getTextureAddressingMode();
  379. setTextureAddressingMode(unit, uvw);
  380. // Set border color
  381. setTextureBorderColor(unit, stateProps.getBorderColor());
  382. BS_INC_RENDER_STAT(NumSamplerBinds);
  383. }
  384. void GLRenderAPI::setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  385. const TextureSurface& surface)
  386. {
  387. THROW_IF_NOT_CORE_THREAD;
  388. // TODO - OpenGL can't bind a certain subset of faces like DX11, only zero, one or all, so I'm ignoring numSlices parameter
  389. if (texPtr != nullptr)
  390. {
  391. SPtr<GLTextureCore> tex = std::static_pointer_cast<GLTextureCore>(texPtr);
  392. glBindImageTexture(unit, tex->getGLID(), surface.mipLevel, surface.numArraySlices > 1,
  393. surface.arraySlice, tex->getGLFormat(), GL_READ_WRITE);
  394. }
  395. else
  396. glBindImageTexture(unit, 0, 0, false, 0, 0, GL_READ_WRITE);
  397. BS_INC_RENDER_STAT(NumTextureBinds);
  398. }
  399. void GLRenderAPI::setBlendState(const SPtr<BlendStateCore>& blendState)
  400. {
  401. THROW_IF_NOT_CORE_THREAD;
  402. const BlendProperties& stateProps = blendState->getProperties();
  403. // Alpha to coverage
  404. setAlphaToCoverage(stateProps.getAlphaToCoverageEnabled());
  405. // Blend states
  406. // OpenGL doesn't allow us to specify blend state per render target, so we just use the first one.
  407. if (stateProps.getBlendEnabled(0))
  408. {
  409. setSceneBlending(stateProps.getSrcBlend(0), stateProps.getDstBlend(0), stateProps.getAlphaSrcBlend(0),
  410. stateProps.getAlphaDstBlend(0), stateProps.getBlendOperation(0), stateProps.getAlphaBlendOperation(0));
  411. }
  412. else
  413. {
  414. setSceneBlending(BF_ONE, BF_ZERO, BO_ADD);
  415. }
  416. // Color write mask
  417. UINT8 writeMask = stateProps.getRenderTargetWriteMask(0);
  418. setColorBufferWriteEnabled((writeMask & 0x1) != 0, (writeMask & 0x2) != 0, (writeMask & 0x4) != 0, (writeMask & 0x8) != 0);
  419. BS_INC_RENDER_STAT(NumBlendStateChanges);
  420. }
  421. void GLRenderAPI::setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState)
  422. {
  423. THROW_IF_NOT_CORE_THREAD;
  424. const RasterizerProperties& stateProps = rasterizerState->getProperties();
  425. setDepthBias(stateProps.getDepthBias(), stateProps.getSlopeScaledDepthBias());
  426. setCullingMode(stateProps.getCullMode());
  427. setPolygonMode(stateProps.getPolygonMode());
  428. setScissorTestEnable(stateProps.getScissorEnable());
  429. setMultisamplingEnable(stateProps.getMultisampleEnable());
  430. setDepthClipEnable(stateProps.getDepthClipEnable());
  431. setAntialiasedLineEnable(stateProps.getAntialiasedLineEnable());
  432. BS_INC_RENDER_STAT(NumRasterizerStateChanges);
  433. }
  434. void GLRenderAPI::setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue)
  435. {
  436. THROW_IF_NOT_CORE_THREAD;
  437. const DepthStencilProperties& stateProps = depthStencilState->getProperties();
  438. // Set stencil buffer options
  439. setStencilCheckEnabled(stateProps.getStencilEnable());
  440. setStencilBufferOperations(stateProps.getStencilFrontFailOp(), stateProps.getStencilFrontZFailOp(), stateProps.getStencilFrontPassOp(), true);
  441. setStencilBufferFunc(stateProps.getStencilFrontCompFunc(), stateProps.getStencilReadMask(), true);
  442. setStencilBufferOperations(stateProps.getStencilBackFailOp(), stateProps.getStencilBackZFailOp(), stateProps.getStencilBackPassOp(), false);
  443. setStencilBufferFunc(stateProps.getStencilBackCompFunc(), stateProps.getStencilReadMask(), false);
  444. setStencilBufferWriteMask(stateProps.getStencilWriteMask());
  445. // Set depth buffer options
  446. setDepthBufferCheckEnabled(stateProps.getDepthReadEnable());
  447. setDepthBufferWriteEnabled(stateProps.getDepthWriteEnable());
  448. setDepthBufferFunction(stateProps.getDepthComparisonFunc());
  449. // Set stencil ref value
  450. setStencilRefValue(stencilRefValue);
  451. BS_INC_RENDER_STAT(NumDepthStencilStateChanges);
  452. }
  453. void GLRenderAPI::setViewport(const Rect2& area)
  454. {
  455. THROW_IF_NOT_CORE_THREAD;
  456. mViewportNorm = area;
  457. applyViewport();
  458. }
  459. void GLRenderAPI::setRenderTarget(const SPtr<RenderTargetCore>& target)
  460. {
  461. THROW_IF_NOT_CORE_THREAD;
  462. // Switch context if different from current one
  463. SPtr<GLContext> newContext;
  464. target->getCustomAttribute("GLCONTEXT", &newContext);
  465. if(newContext && mCurrentContext != newContext)
  466. {
  467. switchContext(newContext);
  468. }
  469. // This must happen after context switch to ensure previous context is still alive
  470. mActiveRenderTarget = target;
  471. GLFrameBufferObject *fbo = 0;
  472. target->getCustomAttribute("FBO", &fbo);
  473. if(fbo)
  474. fbo->bind();
  475. else
  476. // Old style context (window/pbuffer) or copying render texture
  477. glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
  478. if (GLEW_EXT_framebuffer_sRGB)
  479. {
  480. // Enable / disable sRGB states
  481. if (target->getProperties().isHwGammaEnabled())
  482. {
  483. glEnable(GL_FRAMEBUFFER_SRGB_EXT);
  484. // Note: could test GL_FRAMEBUFFER_SRGB_CAPABLE_EXT here before
  485. // enabling, but GL spec says incapable surfaces ignore the setting
  486. // anyway. We test the capability to enable isHardwareGammaEnabled.
  487. }
  488. else
  489. {
  490. glDisable(GL_FRAMEBUFFER_SRGB_EXT);
  491. }
  492. }
  493. applyViewport();
  494. BS_INC_RENDER_STAT(NumRenderTargetChanges);
  495. }
  496. void GLRenderAPI::beginFrame()
  497. {
  498. THROW_IF_NOT_CORE_THREAD;
  499. // Activate the viewport clipping
  500. glEnable(GL_SCISSOR_TEST);
  501. }
  502. void GLRenderAPI::endFrame()
  503. {
  504. THROW_IF_NOT_CORE_THREAD;
  505. // Deactivate the viewport clipping.
  506. glDisable(GL_SCISSOR_TEST);
  507. }
  508. void GLRenderAPI::setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers)
  509. {
  510. THROW_IF_NOT_CORE_THREAD;
  511. if ((index + numBuffers) > (UINT32)mBoundVertexBuffers.size())
  512. mBoundVertexBuffers.resize(index + numBuffers);
  513. for(UINT32 i = 0; i < numBuffers; i++)
  514. {
  515. mBoundVertexBuffers[index + i] = buffers[i];
  516. }
  517. }
  518. void GLRenderAPI::setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration)
  519. {
  520. THROW_IF_NOT_CORE_THREAD;
  521. mBoundVertexDeclaration = vertexDeclaration;
  522. }
  523. void GLRenderAPI::setDrawOperation(DrawOperationType op)
  524. {
  525. THROW_IF_NOT_CORE_THREAD;
  526. mCurrentDrawOperation = op;
  527. }
  528. void GLRenderAPI::setIndexBuffer(const SPtr<IndexBufferCore>& buffer)
  529. {
  530. THROW_IF_NOT_CORE_THREAD;
  531. mBoundIndexBuffer = buffer;
  532. }
  533. void GLRenderAPI::draw(UINT32 vertexOffset, UINT32 vertexCount)
  534. {
  535. // Find the correct type to render
  536. GLint primType = getGLDrawMode();
  537. beginDraw();
  538. glDrawArrays(primType, vertexOffset, vertexCount);
  539. endDraw();
  540. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  541. BS_INC_RENDER_STAT(NumDrawCalls);
  542. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  543. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  544. }
  545. void GLRenderAPI::drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount)
  546. {
  547. if(mBoundIndexBuffer == nullptr)
  548. {
  549. LOGWRN("Cannot draw indexed because index buffer is not set.");
  550. return;
  551. }
  552. // Find the correct type to render
  553. GLint primType = getGLDrawMode();
  554. beginDraw();
  555. SPtr<GLIndexBufferCore> indexBuffer = std::static_pointer_cast<GLIndexBufferCore>(mBoundIndexBuffer);
  556. const IndexBufferProperties& ibProps = indexBuffer->getProperties();
  557. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexBuffer->getGLBufferId());
  558. GLenum indexType = (ibProps.getType() == IT_16BIT) ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT;
  559. glDrawElementsBaseVertex(primType, indexCount, indexType, (GLvoid*)(ibProps.getIndexSize() * startIndex), vertexOffset);
  560. endDraw();
  561. UINT32 primCount = vertexCountToPrimCount(mCurrentDrawOperation, vertexCount);
  562. BS_INC_RENDER_STAT(NumDrawCalls);
  563. BS_ADD_RENDER_STAT(NumVertices, vertexCount);
  564. BS_ADD_RENDER_STAT(NumPrimitives, primCount);
  565. BS_INC_RENDER_STAT(NumIndexBufferBinds);
  566. }
  567. void GLRenderAPI::setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom)
  568. {
  569. THROW_IF_NOT_CORE_THREAD;
  570. mScissorTop = top;
  571. mScissorBottom = bottom;
  572. mScissorLeft = left;
  573. mScissorRight = right;
  574. }
  575. void GLRenderAPI::clearRenderTarget(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  576. {
  577. if(mActiveRenderTarget == nullptr)
  578. return;
  579. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  580. Rect2I clearRect(0, 0, rtProps.getWidth(), rtProps.getHeight());
  581. clearArea(buffers, color, depth, stencil, clearRect);
  582. }
  583. void GLRenderAPI::clearViewport(UINT32 buffers, const Color& color, float depth, UINT16 stencil)
  584. {
  585. Rect2I clearRect(mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight);
  586. clearArea(buffers, color, depth, stencil, clearRect);
  587. }
  588. void GLRenderAPI::clearArea(UINT32 buffers, const Color& color, float depth, UINT16 stencil, const Rect2I& clearRect)
  589. {
  590. THROW_IF_NOT_CORE_THREAD;
  591. if(mActiveRenderTarget == nullptr)
  592. return;
  593. bool colorMask = !mColorWrite[0] || !mColorWrite[1]
  594. || !mColorWrite[2] || !mColorWrite[3];
  595. GLbitfield flags = 0;
  596. if (buffers & FBT_COLOR)
  597. {
  598. flags |= GL_COLOR_BUFFER_BIT;
  599. // Enable buffer for writing if it isn't
  600. if (colorMask)
  601. glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
  602. glClearColor(color.r, color.g, color.b, color.a);
  603. }
  604. if (buffers & FBT_DEPTH)
  605. {
  606. flags |= GL_DEPTH_BUFFER_BIT;
  607. // Enable buffer for writing if it isn't
  608. if (!mDepthWrite)
  609. glDepthMask(GL_TRUE);
  610. glClearDepth(depth);
  611. }
  612. if (buffers & FBT_STENCIL)
  613. {
  614. flags |= GL_STENCIL_BUFFER_BIT;
  615. // Enable buffer for writing if it isn't
  616. glStencilMask(0xFFFFFFFF);
  617. glClearStencil(stencil);
  618. }
  619. // Disable scissor test as we want to clear the entire render surface
  620. GLboolean scissorTestEnabled = glIsEnabled(GL_SCISSOR_TEST);
  621. UINT32 oldScissorTop = mScissorTop;
  622. UINT32 oldScissorBottom = mScissorBottom;
  623. UINT32 oldScissorLeft = mScissorLeft;
  624. UINT32 oldScissorRight = mScissorRight;
  625. if (scissorTestEnabled)
  626. {
  627. glDisable(GL_SCISSOR_TEST);
  628. }
  629. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  630. bool clearEntireTarget = clearRect.width == 0 || clearRect.height == 0;
  631. clearEntireTarget |= (clearRect.x == 0 && clearRect.y == 0 && clearRect.width == rtProps.getWidth() && clearRect.height == rtProps.getHeight());
  632. if(!clearEntireTarget)
  633. {
  634. setScissorRect(clearRect.x, clearRect.y, clearRect.x + clearRect.width, clearRect.y + clearRect.height);
  635. setScissorTestEnable(true);
  636. }
  637. // Clear buffers
  638. glClear(flags);
  639. if(!clearEntireTarget)
  640. {
  641. setScissorTestEnable(false);
  642. }
  643. // Restore scissor test
  644. if (scissorTestEnabled)
  645. {
  646. glEnable(GL_SCISSOR_TEST);
  647. mScissorTop = oldScissorTop;
  648. mScissorBottom = oldScissorBottom;
  649. mScissorLeft = oldScissorLeft;
  650. mScissorRight = oldScissorRight;
  651. }
  652. // Reset buffer write state
  653. if (!mDepthWrite && (buffers & FBT_DEPTH))
  654. {
  655. glDepthMask(GL_FALSE);
  656. }
  657. if (colorMask && (buffers & FBT_COLOR))
  658. {
  659. glColorMask(mColorWrite[0], mColorWrite[1], mColorWrite[2], mColorWrite[3]);
  660. }
  661. if (buffers & FBT_STENCIL)
  662. {
  663. glStencilMask(mStencilWriteMask);
  664. }
  665. BS_INC_RENDER_STAT(NumClears);
  666. }
  667. /************************************************************************/
  668. /* PRIVATE */
  669. /************************************************************************/
  670. void GLRenderAPI::setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw)
  671. {
  672. if (!activateGLTextureUnit(stage))
  673. return;
  674. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_S,
  675. getTextureAddressingMode(uvw.u));
  676. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_T,
  677. getTextureAddressingMode(uvw.v));
  678. glTexParameteri( mTextureTypes[stage], GL_TEXTURE_WRAP_R,
  679. getTextureAddressingMode(uvw.w));
  680. activateGLTextureUnit(0);
  681. }
  682. void GLRenderAPI::setTextureBorderColor(UINT16 stage, const Color& colour)
  683. {
  684. GLfloat border[4] = { colour.r, colour.g, colour.b, colour.a };
  685. if (activateGLTextureUnit(stage))
  686. {
  687. glTexParameterfv(mTextureTypes[stage], GL_TEXTURE_BORDER_COLOR, border);
  688. activateGLTextureUnit(0);
  689. }
  690. }
  691. void GLRenderAPI::setTextureMipmapBias(UINT16 stage, float bias)
  692. {
  693. if (mCurrentCapabilities->hasCapability(RSC_MIPMAP_LOD_BIAS))
  694. {
  695. if (activateGLTextureUnit(stage))
  696. {
  697. glTexParameterf(mTextureTypes[stage], GL_TEXTURE_LOD_BIAS, bias);
  698. activateGLTextureUnit(0);
  699. }
  700. }
  701. }
  702. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op )
  703. {
  704. GLint sourceBlend = getBlendMode(sourceFactor);
  705. GLint destBlend = getBlendMode(destFactor);
  706. if(sourceFactor == BF_ONE && destFactor == BF_ZERO)
  707. {
  708. glDisable(GL_BLEND);
  709. }
  710. else
  711. {
  712. glEnable(GL_BLEND);
  713. glBlendFunc(sourceBlend, destBlend);
  714. }
  715. GLint func = GL_FUNC_ADD;
  716. switch(op)
  717. {
  718. case BO_ADD:
  719. func = GL_FUNC_ADD;
  720. break;
  721. case BO_SUBTRACT:
  722. func = GL_FUNC_SUBTRACT;
  723. break;
  724. case BO_REVERSE_SUBTRACT:
  725. func = GL_FUNC_REVERSE_SUBTRACT;
  726. break;
  727. case BO_MIN:
  728. func = GL_MIN;
  729. break;
  730. case BO_MAX:
  731. func = GL_MAX;
  732. break;
  733. }
  734. if(GLEW_VERSION_1_4 || GLEW_ARB_imaging)
  735. {
  736. glBlendEquation(func);
  737. }
  738. else if(GLEW_EXT_blend_minmax && (func == GL_MIN || func == GL_MAX))
  739. {
  740. glBlendEquationEXT(func);
  741. }
  742. }
  743. void GLRenderAPI::setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor,
  744. BlendFactor sourceFactorAlpha, BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp)
  745. {
  746. GLint sourceBlend = getBlendMode(sourceFactor);
  747. GLint destBlend = getBlendMode(destFactor);
  748. GLint sourceBlendAlpha = getBlendMode(sourceFactorAlpha);
  749. GLint destBlendAlpha = getBlendMode(destFactorAlpha);
  750. if(sourceFactor == BF_ONE && destFactor == BF_ZERO &&
  751. sourceFactorAlpha == BF_ONE && destFactorAlpha == BF_ZERO)
  752. {
  753. glDisable(GL_BLEND);
  754. }
  755. else
  756. {
  757. glEnable(GL_BLEND);
  758. glBlendFuncSeparate(sourceBlend, destBlend, sourceBlendAlpha, destBlendAlpha);
  759. }
  760. GLint func = GL_FUNC_ADD, alphaFunc = GL_FUNC_ADD;
  761. switch(op)
  762. {
  763. case BO_ADD:
  764. func = GL_FUNC_ADD;
  765. break;
  766. case BO_SUBTRACT:
  767. func = GL_FUNC_SUBTRACT;
  768. break;
  769. case BO_REVERSE_SUBTRACT:
  770. func = GL_FUNC_REVERSE_SUBTRACT;
  771. break;
  772. case BO_MIN:
  773. func = GL_MIN;
  774. break;
  775. case BO_MAX:
  776. func = GL_MAX;
  777. break;
  778. }
  779. switch(alphaOp)
  780. {
  781. case BO_ADD:
  782. alphaFunc = GL_FUNC_ADD;
  783. break;
  784. case BO_SUBTRACT:
  785. alphaFunc = GL_FUNC_SUBTRACT;
  786. break;
  787. case BO_REVERSE_SUBTRACT:
  788. alphaFunc = GL_FUNC_REVERSE_SUBTRACT;
  789. break;
  790. case BO_MIN:
  791. alphaFunc = GL_MIN;
  792. break;
  793. case BO_MAX:
  794. alphaFunc = GL_MAX;
  795. break;
  796. }
  797. if(GLEW_VERSION_2_0) {
  798. glBlendEquationSeparate(func, alphaFunc);
  799. }
  800. else if(GLEW_EXT_blend_equation_separate) {
  801. glBlendEquationSeparateEXT(func, alphaFunc);
  802. }
  803. }
  804. void GLRenderAPI::setAlphaTest(CompareFunction func, unsigned char value)
  805. {
  806. if(func == CMPF_ALWAYS_PASS)
  807. {
  808. glDisable(GL_ALPHA_TEST);
  809. }
  810. else
  811. {
  812. glEnable(GL_ALPHA_TEST);
  813. glAlphaFunc(convertCompareFunction(func), value / 255.0f);
  814. }
  815. }
  816. void GLRenderAPI::setAlphaToCoverage(bool enable)
  817. {
  818. static bool lasta2c = false;
  819. if (enable != lasta2c && getCapabilities()->hasCapability(RSC_ALPHA_TO_COVERAGE))
  820. {
  821. if (enable)
  822. glEnable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  823. else
  824. glDisable(GL_SAMPLE_ALPHA_TO_COVERAGE);
  825. lasta2c = enable;
  826. }
  827. }
  828. void GLRenderAPI::setScissorTestEnable(bool enable)
  829. {
  830. const RenderTargetProperties& rtProps = mActiveRenderTarget->getProperties();
  831. // If request texture flipping, use "upper-left", otherwise use "lower-left"
  832. bool flipping = rtProps.requiresTextureFlipping();
  833. // GL measures from the bottom, not the top
  834. UINT32 targetHeight = rtProps.getHeight();
  835. // Calculate the "lower-left" corner of the viewport
  836. GLsizei x = 0, y = 0, w = 0, h = 0;
  837. if (enable)
  838. {
  839. glEnable(GL_SCISSOR_TEST);
  840. // GL uses width / height rather than right / bottom
  841. x = mScissorLeft;
  842. if (flipping)
  843. y = targetHeight - mScissorBottom - 1;
  844. else
  845. y = mScissorTop;
  846. w = mScissorRight - mScissorLeft;
  847. h = mScissorBottom - mScissorTop;
  848. glScissor(x, y, w, h);
  849. }
  850. else
  851. {
  852. glDisable(GL_SCISSOR_TEST);
  853. // GL requires you to reset the scissor when disabling
  854. w = mViewportWidth;
  855. h = mViewportHeight;
  856. x = mViewportLeft;
  857. y = mViewportTop;
  858. glScissor(x, y, w, h);
  859. }
  860. }
  861. void GLRenderAPI::setMultisamplingEnable(bool enable)
  862. {
  863. if (enable)
  864. glEnable(GL_MULTISAMPLE);
  865. else
  866. glDisable(GL_MULTISAMPLE);
  867. }
  868. void GLRenderAPI::setDepthClipEnable(bool enable)
  869. {
  870. if (enable)
  871. glEnable(GL_DEPTH_CLAMP);
  872. else
  873. glDisable(GL_DEPTH_CLAMP);
  874. }
  875. void GLRenderAPI::setAntialiasedLineEnable(bool enable)
  876. {
  877. if (enable)
  878. glEnable(GL_LINE_SMOOTH);
  879. else
  880. glDisable(GL_LINE_SMOOTH);
  881. }
  882. void GLRenderAPI::setCullingMode(CullingMode mode)
  883. {
  884. mCullingMode = mode;
  885. GLenum cullMode;
  886. switch( mode )
  887. {
  888. case CULL_NONE:
  889. glDisable(GL_CULL_FACE);
  890. return;
  891. default:
  892. case CULL_CLOCKWISE:
  893. cullMode = GL_BACK;
  894. break;
  895. case CULL_COUNTERCLOCKWISE:
  896. cullMode = GL_FRONT;
  897. break;
  898. }
  899. glEnable(GL_CULL_FACE);
  900. glCullFace(cullMode);
  901. }
  902. void GLRenderAPI::setDepthBufferCheckEnabled(bool enabled)
  903. {
  904. if (enabled)
  905. {
  906. glClearDepth(1.0f);
  907. glEnable(GL_DEPTH_TEST);
  908. }
  909. else
  910. {
  911. glDisable(GL_DEPTH_TEST);
  912. }
  913. }
  914. void GLRenderAPI::setDepthBufferWriteEnabled(bool enabled)
  915. {
  916. GLboolean flag = enabled ? GL_TRUE : GL_FALSE;
  917. glDepthMask(flag);
  918. mDepthWrite = enabled;
  919. }
  920. void GLRenderAPI::setDepthBufferFunction(CompareFunction func)
  921. {
  922. glDepthFunc(convertCompareFunction(func));
  923. }
  924. void GLRenderAPI::setDepthBias(float constantBias, float slopeScaleBias)
  925. {
  926. if (constantBias != 0 || slopeScaleBias != 0)
  927. {
  928. glEnable(GL_POLYGON_OFFSET_FILL);
  929. glEnable(GL_POLYGON_OFFSET_POINT);
  930. glEnable(GL_POLYGON_OFFSET_LINE);
  931. float scaledConstantBias = -constantBias * float((1 << 24) - 1); // Note: Assumes 24-bit depth buffer
  932. glPolygonOffset(slopeScaleBias, scaledConstantBias);
  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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::setStencilCheckEnabled(bool enabled)
  966. {
  967. if (enabled)
  968. glEnable(GL_STENCIL_TEST);
  969. else
  970. glDisable(GL_STENCIL_TEST);
  971. }
  972. void GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::setStencilBufferWriteMask(UINT32 mask)
  1005. {
  1006. mStencilWriteMask = mask;
  1007. glStencilMask(mask);
  1008. }
  1009. void GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::endDraw()
  1147. {
  1148. if(!mDrawCallInProgress)
  1149. return;
  1150. mDrawCallInProgress = false;
  1151. }
  1152. GLfloat GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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> GLRenderAPI::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 GLRenderAPI::initFromCaps(RenderAPICapabilities* caps)
  1411. {
  1412. if(caps->getRenderSystemName() != getName())
  1413. {
  1414. BS_EXCEPT(InvalidParametersException,
  1415. "Trying to initialize GLRenderAPI 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 GLRenderAPI::switchContext(const SPtr<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. RenderAPICapabilities* GLRenderAPI::createRenderSystemCapabilities() const
  1502. {
  1503. RenderAPICapabilities* rsc = bs_new<RenderAPICapabilities>();
  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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::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 GLRenderAPI::getMinimumDepthInputValue()
  1764. {
  1765. return -1.0f;
  1766. }
  1767. float GLRenderAPI::getMaximumDepthInputValue()
  1768. {
  1769. return 1.0f;
  1770. }
  1771. float GLRenderAPI::getHorizontalTexelOffset()
  1772. {
  1773. return 0.0f;
  1774. }
  1775. float GLRenderAPI::getVerticalTexelOffset()
  1776. {
  1777. return 0.0f;
  1778. }
  1779. VertexElementType GLRenderAPI::getColorVertexElementType() const
  1780. {
  1781. return VET_COLOR_ABGR;
  1782. }
  1783. void GLRenderAPI::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. }