BsGLRenderAPI.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsGLPrerequisites.h"
  5. #include "BsRenderAPI.h"
  6. #include "BsGLHardwareBufferManager.h"
  7. #include "BsGLSLProgramFactory.h"
  8. #include "BsMatrix4.h"
  9. namespace BansheeEngine
  10. {
  11. /**
  12. * @brief Implementation of a render system using OpenGL. Provides abstracted
  13. * access to various low level OpenGL methods.
  14. */
  15. class BS_RSGL_EXPORT GLRenderAPI : public RenderAPICore
  16. {
  17. public:
  18. GLRenderAPI();
  19. ~GLRenderAPI();
  20. /**
  21. * @copydoc RenderAPICore::getName()
  22. */
  23. const StringID& getName() const override;
  24. /**
  25. * @copydoc RenderAPICore::getShadingLanguageName()
  26. */
  27. const String& getShadingLanguageName() const override;
  28. /**
  29. * @copydoc RenderAPICore::setRenderTarget()
  30. */
  31. void setRenderTarget(const SPtr<RenderTargetCore>& target, bool readOnlyDepthStencil = false) override;
  32. /**
  33. * @copydoc RenderAPICore::setVertexBuffers()
  34. */
  35. void setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers) override;
  36. /**
  37. * @copydoc RenderAPICore::setIndexBuffer()
  38. */
  39. void setIndexBuffer(const SPtr<IndexBufferCore>& buffer) override;
  40. /**
  41. * @copydoc RenderAPICore::setVertexDeclaration()
  42. */
  43. void setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration) override;
  44. /**
  45. * @copydoc RenderAPICore::setDrawOperation()
  46. */
  47. void setDrawOperation(DrawOperationType op) override;
  48. /**
  49. * @copydoc RenderAPICore::setScissorRect()
  50. */
  51. void setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom) override;
  52. /**
  53. * @copydoc RenderAPICore::setTexture()
  54. */
  55. void setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& tex) override;
  56. /**
  57. * @copydoc RenderAPICore::setLoadStoreTexture
  58. */
  59. void setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  60. const TextureSurface& surface) override;
  61. /**
  62. * @copydoc RenderAPICore::setSamplerState()
  63. */
  64. void setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state) override;
  65. /**
  66. * @copydoc RenderAPICore::setBlendState()
  67. */
  68. void setBlendState(const SPtr<BlendStateCore>& blendState) override;
  69. /**
  70. * @copydoc RenderAPICore::setRasterizerState()
  71. */
  72. void setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState) override;
  73. /**
  74. * @copydoc RenderAPICore::setDepthStencilState()
  75. */
  76. void setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue) override;
  77. /**
  78. * @copydoc RenderAPICore::setViewport()
  79. */
  80. void setViewport(const Rect2& area) override;
  81. /**
  82. * @copydoc RenderAPICore::bindGpuProgram()
  83. */
  84. void bindGpuProgram(const SPtr<GpuProgramCore>& prg) override;
  85. /**
  86. * @copydoc RenderAPICore::unbindGpuProgram()
  87. */
  88. void unbindGpuProgram(GpuProgramType gptype) override;
  89. /**
  90. * @copydoc RenderAPICore::setConstantBuffers()
  91. */
  92. void setConstantBuffers(GpuProgramType gptype, const SPtr<GpuParamsCore>& params) override;
  93. /**
  94. * @copydoc RenderAPICore::beginFrame()
  95. */
  96. void beginFrame() override;
  97. /**
  98. * @copydoc RenderAPICore::endFrame()
  99. */
  100. void endFrame() override;
  101. /**
  102. * @copydoc RenderAPICore::draw()
  103. */
  104. void draw(UINT32 vertexOffset, UINT32 vertexCount) override;
  105. /**
  106. * @copydoc RenderAPICore::drawIndexed()
  107. */
  108. void drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount) override;
  109. /**
  110. * @copydoc RenderAPICore::dispatchCompute()
  111. */
  112. void dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY = 1, UINT32 numGroupsZ = 1) override;
  113. /**
  114. * @copydoc RenderAPICore::clearRenderTarget()
  115. */
  116. void clearRenderTarget(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  117. UINT8 targetMask = 0xFF) override;
  118. /**
  119. * @copydoc RenderAPICore::clearViewport()
  120. */
  121. void clearViewport(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  122. UINT8 targetMask = 0xFF) override;
  123. /**
  124. * @copydoc RenderAPICore::getColorVertexElementType()
  125. */
  126. VertexElementType getColorVertexElementType() const override;
  127. /**
  128. * @copydoc RenderAPICore::getHorizontalTexelOffset()
  129. */
  130. float getHorizontalTexelOffset() override;
  131. /**
  132. * @copydoc RenderAPICore::getVerticalTexelOffset()
  133. */
  134. float getVerticalTexelOffset() override;
  135. /**
  136. * @copydoc RenderAPICore::getMinimumDepthInputValue()
  137. */
  138. float getMinimumDepthInputValue() override;
  139. /**
  140. * @copydoc RenderAPICore::getMaximumDepthInputValue()
  141. */
  142. float getMaximumDepthInputValue() override;
  143. /**
  144. * @copydoc RenderAPICore::convertProjectionMatrix()
  145. */
  146. void convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest) override;
  147. /**
  148. * @copydoc RenderAPICore::getGpuProgramHasColumnMajorMatrices
  149. */
  150. bool getGpuProgramHasColumnMajorMatrices() const override;
  151. /**
  152. * @copydoc RenderAPICore::generateParamBlockDesc()
  153. */
  154. GpuParamBlockDesc generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params) override;
  155. /************************************************************************/
  156. /* Internal use by OpenGL RenderSystem only */
  157. /************************************************************************/
  158. /**
  159. * @brief Query has the main context been initialized.
  160. */
  161. bool _isContextInitialized() const { return mGLInitialised; }
  162. /**
  163. * @brief Returns main context. Caller must ensure the context has been initialized.
  164. */
  165. SPtr<GLContext> getMainContext() const { return mMainContext; }
  166. /**
  167. * @brief Returns a support object you may use for creating
  168. */
  169. GLSupport* getGLSupport() const { return mGLSupport; }
  170. protected:
  171. /**
  172. * @copydoc RenderAPICore::initializePrepare
  173. */
  174. void initializePrepare() override;
  175. /**
  176. * @copydoc RenderAPICore::initializeFinalize
  177. */
  178. void initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow) override;
  179. /**
  180. * @copydoc RenderAPICore::destroy_internal().
  181. */
  182. void destroyCore() override;
  183. /**
  184. * @brief Call before doing a draw operation, this method sets everything up.
  185. */
  186. void beginDraw();
  187. /**
  188. * @brief Needs to accompany every beginDraw after you are done with a single draw operation.
  189. */
  190. void endDraw();
  191. /**
  192. * @brief Clear a part of a render target.
  193. */
  194. void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  195. const Rect2I& clearArea = Rect2I::EMPTY, UINT8 targetMask = 0xFF);
  196. /**
  197. * @brief Set up clip planes against which all geometry will get clipped.
  198. */
  199. void setClipPlanesImpl(const PlaneList& clipPlanes) override;
  200. /**
  201. * @brief Set up a clip plane at a specific clip plane index. If enabled,
  202. * geometry will be clipped against the positive side of the plane.
  203. *
  204. * @note Valid index range is [0, 5].
  205. */
  206. void setClipPlane(UINT16 index, float A, float B, float C, float D);
  207. /**
  208. * @brief Enable or disable clipping against a clip plane at the specified index.
  209. *
  210. * @note Valid index range is [0, 5].
  211. */
  212. void enableClipPlane (UINT16 index, bool enable);
  213. /**
  214. * @brief Changes the currently active texture unit. Any texture related operations
  215. * will then be performed on this unit.
  216. */
  217. bool activateGLTextureUnit(UINT16 unit);
  218. /**
  219. * @brief Changes the active GPU program.
  220. */
  221. void setActiveProgram(GpuProgramType gptype, const SPtr<GLSLGpuProgramCore>& program);
  222. /**
  223. * @brief Retrieves the active GPU program of the specified type.
  224. */
  225. SPtr<GLSLGpuProgramCore> getActiveProgram(GpuProgramType gptype) const;
  226. /**
  227. * @brief Converts Banshee blend mode to OpenGL blend mode.
  228. */
  229. GLint getBlendMode(BlendFactor blendMode) const;
  230. /**
  231. * @brief Converts Banshee texture addressing mode to OpenGL texture addressing mode.
  232. */
  233. GLint getTextureAddressingMode(TextureAddressingMode tam) const;
  234. /**
  235. * @brief Gets a combined min/mip filter value usable by OpenGL from the currently
  236. * set min and mip filters.
  237. */
  238. GLuint getCombinedMinMipFilter() const;
  239. /**
  240. * @brief OpenGL shares all texture slots, but the engine prefers to keep textures
  241. * separate per-stage. This will convert texture unit that is set per stage
  242. * into a global texture unit usable by OpenGL.
  243. */
  244. UINT32 getGLTextureUnit(GpuProgramType gptype, UINT32 unit);
  245. /**
  246. * @brief OpenGL shares all buffer bindings, but the engine prefers to keep buffers
  247. * separate per-stage. This will convert block buffer binding that is set per stage
  248. * into a global block buffer binding usable by OpenGL.
  249. */
  250. UINT32 getGLUniformBlockBinding(GpuProgramType gptype, UINT32 binding);
  251. /**
  252. * @brief Returns the OpenGL specific mode used for drawing, depending on the
  253. * currently set draw operation;
  254. */
  255. GLint getGLDrawMode() const;
  256. /**
  257. * @brief Creates render system capabilities that specify which features are
  258. * or aren't supported.
  259. */
  260. RenderAPICapabilities* createRenderSystemCapabilities() const;
  261. /**
  262. * @brief Finish initialization by setting up any systems dependant on render system
  263. * capabilities.
  264. */
  265. void initFromCaps(RenderAPICapabilities* caps);
  266. /**
  267. * @brief Switch the currently used OpenGL context. You will need to re-bind
  268. * any previously bound values manually. (e.g. textures, gpu programs and such)
  269. */
  270. void switchContext(const SPtr<GLContext>& context);
  271. /************************************************************************/
  272. /* Sampler states */
  273. /************************************************************************/
  274. /**
  275. * @brief Sets the texture addressing mode for a texture unit. This determines
  276. * how are UV address values outside of [0, 1] range handled when sampling
  277. * from texture.
  278. */
  279. void setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw);
  280. /**
  281. * @brief Sets the texture border color for a texture unit. Border color
  282. * determines color returned by the texture sampler when border addressing mode
  283. * is used and texture address is outside of [0, 1] range.
  284. */
  285. void setTextureBorderColor(UINT16 stage, const Color& color);
  286. /**
  287. * @brief Sets the mipmap bias value for a given texture unit. Bias allows
  288. * you to adjust the mipmap selection calculation. Negative values force a
  289. * larger mipmap to be used, and positive values smaller. Units are in values
  290. * of mip levels, so -1 means use a mipmap one level higher than default.
  291. */
  292. void setTextureMipmapBias(UINT16 unit, float bias);
  293. /**
  294. * @brief Allows you to specify how is the texture bound to the specified texture unit filtered.
  295. * Different filter types are used for different situations like magnifying or minifying a texture.
  296. */
  297. void setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter);
  298. /**
  299. * @brief Sets anisotropy value for the specified texture unit.
  300. */
  301. void setTextureAnisotropy(UINT16 unit, UINT32 maxAnisotropy);
  302. /**
  303. * @brief Gets anisotropy value for the specified texture unit.
  304. */
  305. GLfloat getCurrentAnisotropy(UINT16 unit);
  306. /************************************************************************/
  307. /* Blend states */
  308. /************************************************************************/
  309. /**
  310. * @brief Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  311. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor).
  312. */
  313. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op);
  314. /**
  315. * @brief Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  316. * Allows you to set up separate blend operations for alpha values.
  317. *
  318. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor). (And the same for alpha)
  319. */
  320. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  321. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp);
  322. /**
  323. * @brief Sets alpha test that allows you to reject pixels that fail the comparison function
  324. * versus the provided reference value.
  325. */
  326. void setAlphaTest(CompareFunction func, unsigned char value);
  327. /**
  328. * @brief Enable alpha to coverage. Alpha to coverage allows you to perform blending without needing
  329. * to worry about order of rendering like regular blending does. It requires multi-sampling to
  330. * be active in order to work, and you need to supply an alpha texture that determines object transparency.
  331. */
  332. void setAlphaToCoverage(bool enabled);
  333. /**
  334. * @brief Enables or disables writing to certain color channels of the render target.
  335. */
  336. void setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  337. /************************************************************************/
  338. /* Rasterizer states */
  339. /************************************************************************/
  340. /**
  341. * @brief Sets vertex winding order. Normally you would use this to cull back facing
  342. * polygons.
  343. */
  344. void setCullingMode(CullingMode mode);
  345. /**
  346. * @brief Sets the polygon rasterization mode. Determines how are polygons interpreted.
  347. */
  348. void setPolygonMode(PolygonMode level);
  349. /**
  350. * @brief Sets a depth bias that will offset the depth values of new pixels by the specified amount.
  351. * Final depth bias value is a combination of the constant depth bias and slope depth bias.
  352. * Slope depth bias has more effect the higher the slope of the rendered polygon.
  353. *
  354. * @note This is useful if you want to avoid z fighting for objects at the same or similar depth.
  355. */
  356. void setDepthBias(float constantBias, float slopeScaleBias);
  357. /**
  358. * @brief Scissor test allows you to mask off rendering in all but a given rectangular area
  359. * identified by the rectangle set by setScissorRect().
  360. */
  361. void setScissorTestEnable(bool enable);
  362. /**
  363. * @brief Enables or disables multisample antialiasing.
  364. */
  365. void setMultisamplingEnable(bool enable);
  366. /**
  367. * @brief Enables or disables depth clipping (i.e. near/fear plane clipping).
  368. */
  369. void setDepthClipEnable(bool enable);
  370. /**
  371. * @brief Enables or disables antialiased line rendering.
  372. */
  373. void setAntialiasedLineEnable(bool enable);
  374. /************************************************************************/
  375. /* Depth stencil state */
  376. /************************************************************************/
  377. /**
  378. * @brief Should new pixels perform depth testing using the set depth comparison function before
  379. * being written.
  380. */
  381. void setDepthBufferCheckEnabled(bool enabled = true);
  382. /**
  383. * @brief Should new pixels write to the depth buffer.
  384. */
  385. void setDepthBufferWriteEnabled(bool enabled = true);
  386. /**
  387. * @brief Sets comparison function used for depth testing. Determines how are new and existing
  388. * pixel values compared - if comparison function returns true the new pixel is written.
  389. */
  390. void setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
  391. /**
  392. * @brief Turns stencil tests on or off. By default this is disabled.
  393. * Stencil testing allow you to mask out a part of the rendered image by using
  394. * various stencil operations provided.
  395. */
  396. void setStencilCheckEnabled(bool enabled);
  397. /**
  398. * @brief Allows you to set stencil operations that are performed when stencil test passes or fails.
  399. *
  400. * @param stencilFailOp Operation executed when stencil test fails.
  401. * @param depthFailOp Operation executed when stencil test succeeds but depth test fails.
  402. * @param passOp Operation executed when stencil test succeeds and depth test succeeds.
  403. * @param front Should the stencil operations be applied to front or back facing polygons.
  404. */
  405. void setStencilBufferOperations(StencilOperation stencilFailOp = SOP_KEEP,
  406. StencilOperation depthFailOp = SOP_KEEP, StencilOperation passOp = SOP_KEEP,
  407. bool front = true);
  408. /**
  409. * @brief Sets a stencil buffer comparison function. The result of this will cause one of 3 actions
  410. * depending on whether the test fails, succeeds but with the depth buffer check still failing,
  411. * or succeeds with the depth buffer check passing too.
  412. *
  413. * @param func Comparison function that determines whether a stencil test fails or passes. Reference value
  414. * gets compared to the value already in the buffer using this function.
  415. * @param mask The bitmask applied to both the stencil value and the reference value
  416. * before comparison
  417. * @param ccw If set to true, the stencil operations will be applied to counterclockwise
  418. * faces. Otherwise they will be applied to clockwise faces.
  419. */
  420. void setStencilBufferFunc(CompareFunction func = CMPF_ALWAYS_PASS, UINT32 mask = 0xFFFFFFFF, bool front = true);
  421. /**
  422. * @brief The bitmask applied to the stencil value before writing it to the stencil buffer.
  423. */
  424. void setStencilBufferWriteMask(UINT32 mask = 0xFFFFFFFF);
  425. /**
  426. * @brief Sets a reference values used for stencil buffer comparisons.
  427. * Actual comparison function and stencil operations are set by setting the DepthStencilState.
  428. */
  429. void setStencilRefValue(UINT32 refValue);
  430. /************************************************************************/
  431. /* UTILITY METHODS */
  432. /************************************************************************/
  433. /**
  434. * @brief Recalculates actual viewport dimensions based on currently
  435. * set viewport normalized dimensions and render target and applies
  436. * them for further rendering.
  437. */
  438. void applyViewport();
  439. /**
  440. * @brief Converts the provided matrix m into a representation usable by OpenGL.
  441. */
  442. void makeGLMatrix(GLfloat gl_matrix[16], const Matrix4& m);
  443. /**
  444. * @brief Converts the engine depth/stencil compare function into OpenGL representation.
  445. */
  446. GLint convertCompareFunction(CompareFunction func) const;
  447. /**
  448. * @brief Convers the engine stencil operation in OpenGL representation. Optionally inverts
  449. * the operation (increment becomes decrement, etc.).
  450. */
  451. GLint convertStencilOp(StencilOperation op, bool invert = false) const;
  452. /**
  453. * @brief Checks if there are any OpenGL errors and prints them to the log.
  454. */
  455. bool checkForErrors() const;
  456. private:
  457. Rect2 mViewportNorm;
  458. UINT32 mScissorTop, mScissorBottom, mScissorLeft, mScissorRight;
  459. UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
  460. UINT32 mStencilReadMask;
  461. UINT32 mStencilWriteMask;
  462. UINT32 mStencilRefValue;
  463. CompareFunction mStencilCompareFront;
  464. CompareFunction mStencilCompareBack;
  465. // View matrix to set world against
  466. Matrix4 mViewMatrix;
  467. // Last min & mip filtering options, so we can combine them
  468. FilterOptions mMinFilter;
  469. FilterOptions mMipFilter;
  470. // Holds texture type settings for every stage
  471. UINT32 mNumTextureTypes;
  472. GLenum* mTextureTypes;
  473. bool mDepthWrite;
  474. bool mColorWrite[4];
  475. GLSupport* mGLSupport;
  476. bool mGLInitialised;
  477. GLSLProgramFactory* mGLSLProgramFactory;
  478. GLSLProgramPipelineManager* mProgramPipelineManager;
  479. SPtr<GLSLGpuProgramCore> mCurrentVertexProgram;
  480. SPtr<GLSLGpuProgramCore> mCurrentFragmentProgram;
  481. SPtr<GLSLGpuProgramCore> mCurrentGeometryProgram;
  482. SPtr<GLSLGpuProgramCore> mCurrentHullProgram;
  483. SPtr<GLSLGpuProgramCore> mCurrentDomainProgram;
  484. SPtr<GLSLGpuProgramCore> mCurrentComputeProgram;
  485. const GLSLProgramPipeline* mActivePipeline;
  486. UINT32 mFragmentTexOffset;
  487. UINT32 mVertexTexOffset;
  488. UINT32 mGeometryTexOffset;
  489. UINT32 mFragmentUBOffset;
  490. UINT32 mVertexUBOffset;
  491. UINT32 mGeometryUBOffset;
  492. UINT32 mHullUBOffset;
  493. UINT32 mDomainUBOffset;
  494. UINT32 mComputeUBOffset;
  495. Vector<SPtr<VertexBufferCore>> mBoundVertexBuffers;
  496. SPtr<VertexDeclarationCore> mBoundVertexDeclaration;
  497. SPtr<IndexBufferCore> mBoundIndexBuffer;
  498. DrawOperationType mCurrentDrawOperation;
  499. SPtr<GLContext> mMainContext;
  500. SPtr<GLContext> mCurrentContext;
  501. bool mDrawCallInProgress;
  502. UINT16 mActiveTextureUnit;
  503. };
  504. }