BsGLRenderAPI.cpp 63 KB

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