BsGLRenderAPI.h 20 KB

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