BsGLRenderAPI.h 19 KB

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