BsGLRenderAPI.h 22 KB

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