BsD3D9RenderAPI.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsD3D9Prerequisites.h"
  5. #include "BsRenderAPI.h"
  6. #include "BsRenderAPICapabilities.h"
  7. #include "BsD3D9Mappings.h"
  8. namespace BansheeEngine
  9. {
  10. /** @addtogroup D3D9
  11. * @{
  12. */
  13. /** Implementation of a render system using DirectX 9. Provides abstracted access to various low level DX9 methods. */
  14. class BS_D3D9_EXPORT D3D9RenderAPI : public RenderAPICore
  15. {
  16. public:
  17. /** Constructs a new instance of the render system using the provided module instance. */
  18. D3D9RenderAPI(HINSTANCE hInstance);
  19. ~D3D9RenderAPI();
  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::bindGpuProgram() */
  27. void bindGpuProgram(const SPtr<GpuProgramCore>& prg) override;
  28. /** @copydoc RenderAPICore::unbindGpuProgram() */
  29. void unbindGpuProgram(GpuProgramType gptype) override;
  30. /** @copydoc RenderAPICore::setParamBuffer */
  31. void setParamBuffer(GpuProgramType gptype, UINT32 slot, const SPtr<GpuParamBlockBufferCore>& buffer,
  32. const GpuParamDesc& paramDesc) override;
  33. /** @copydoc RenderAPICore::setVertexBuffers() */
  34. void setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers) override;
  35. /** @copydoc RenderAPICore::setIndexBuffer() */
  36. void setIndexBuffer(const SPtr<IndexBufferCore>& buffer) override;
  37. /** @copydoc RenderAPICore::setVertexDeclaration() */
  38. void setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration) override;
  39. /** @copydoc RenderAPICore::setDrawOperation() */
  40. void setDrawOperation(DrawOperationType op) override;
  41. /** @copydoc RenderAPICore::setTexture() */
  42. void setTexture(GpuProgramType gptype, UINT16 texUnit, const SPtr<TextureCore>& texture) override;
  43. /** @copydoc RenderAPICore::setBuffer */
  44. void setBuffer(GpuProgramType gptype, UINT16 unit, const SPtr<GpuBufferCore>& buffer, bool loadStore = false) override;
  45. /** @copydoc RenderAPICore::setLoadStoreTexture() */
  46. void setLoadStoreTexture(GpuProgramType gptype, UINT16 texUnit, bool enabled, const SPtr<TextureCore>& texture,
  47. const TextureSurface& surface) override;
  48. /** @copydoc RenderAPICore::setSamplerState() */
  49. void setSamplerState(GpuProgramType gptype, UINT16 texUnit, const SPtr<SamplerStateCore>& samplerState) override;
  50. /** @copydoc RenderAPICore::setBlendState() */
  51. void setBlendState(const SPtr<BlendStateCore>& blendState) override;
  52. /** @copydoc RenderAPICore::setRasterizerState() */
  53. void setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState) override;
  54. /** @copydoc RenderAPICore::setDepthStencilState() */
  55. void setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue) override;
  56. /** @copydoc RenderAPICore::setViewport() */
  57. void setViewport(const Rect2& area) override;
  58. /** @copydoc RenderAPICore::beginFrame() */
  59. void beginFrame() override;
  60. /** @copydoc RenderAPICore::endFrame() */
  61. void endFrame() override;
  62. /** @copydoc RenderAPICore::draw() */
  63. void draw(UINT32 vertexOffset, UINT32 vertexCount, UINT32 instanceCount = 0) override;
  64. /** @copydoc RenderAPICore::drawIndexed() */
  65. void drawIndexed(UINT32 startIndex, UINT32 indexCount, UINT32 vertexOffset, UINT32 vertexCount,
  66. UINT32 instanceCount = 0) override;
  67. /** @copydoc RenderAPICore::dispatchCompute() */
  68. void dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY = 1, UINT32 numGroupsZ = 1) override;
  69. /** @copydoc RenderAPICore::setScissorRect() */
  70. void setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom) override;
  71. /** @copydoc RenderAPICore::clearRenderTarget() */
  72. void clearRenderTarget(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  73. UINT8 targetMask = 0xFF) override;
  74. /** @copydoc RenderAPICore::clearViewport() */
  75. void clearViewport(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  76. UINT8 targetMask = 0xFF) override;
  77. /** @copydoc RenderAPICore::convertProjectionMatrix() */
  78. void convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest) override;
  79. /** @copydoc RenderAPICore::getAPIInfo */
  80. const RenderAPIInfo& getAPIInfo() const override;
  81. /** @copydoc RenderAPICore::generateParamBlockDesc() */
  82. GpuParamBlockDesc generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params) override;
  83. /************************************************************************/
  84. /* Internal use by DX9 RenderAPI only */
  85. /************************************************************************/
  86. /** Returns the resource manager instance. */
  87. static D3D9ResourceManager* getResourceManager();
  88. /** Returns the device manager instance. */
  89. static D3D9DeviceManager* getDeviceManager();
  90. /** Returns the internal DirectX 9 device object. */
  91. static IDirect3D9* getDirect3D9();
  92. /** Returns the number of devices that resources should be created on. */
  93. static UINT getResourceCreationDeviceCount();
  94. /** Returns DirectX 9 device used for resource creation at the specified index. */
  95. static IDirect3DDevice9* getResourceCreationDevice(UINT index);
  96. /** Returns the currently active DirectX 9 device. */
  97. static IDirect3DDevice9* getActiveD3D9Device();
  98. /**
  99. * Converts engine multisample options into DirectX 9 specific ones. Also test for multi-sample support on the
  100. * device and returns nearest supported type if requested type is not available.
  101. *
  102. * @param[in] d3d9Device Device to check for multisampling.
  103. * @param[in] multisampleCount Number of requested samples.
  104. * @param[in] d3dPixelFormat Pixel format used by the render target.
  105. * @param[in] fullscreen Are we testing multisampling for a full-screen render target.
  106. * @param[in] outMultisampleType Output parameter containing DirectX type representing valid multisample type.
  107. * @param[in] outMultisampleQuality Output parameter containing multisample quality.
  108. */
  109. void determineMultisampleSettings(IDirect3DDevice9* d3d9Device, UINT32 multisampleCount, D3DFORMAT d3dPixelFormat,
  110. bool fullscreen, D3DMULTISAMPLE_TYPE* outMultisampleType, DWORD* outMultisampleQuality) const;
  111. /** Register a newly open window with the render system. */
  112. void registerWindow(RenderWindowCore& renderWindow);
  113. private:
  114. friend class D3D9Texture;
  115. friend class D3D9RenderWindow;
  116. friend class D3D9Device;
  117. friend class D3D9TextureManager;
  118. friend class D3D9TextureCoreManager;
  119. friend class D3D9DeviceManager;
  120. friend class D3D9RenderWindowManager;
  121. friend class D3D9RenderWindowCoreManager;
  122. /** @copydoc RenderAPICore::initializePrepare */
  123. void initializePrepare() override;
  124. /** @copydoc RenderAPICore::initializeFinalize */
  125. void initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow) override;
  126. /** @copydoc RenderAPICore::destroy_internal */
  127. void destroyCore() override;
  128. /** Returns a list of available drivers and their properties. */
  129. D3D9DriverList* getDirect3DDrivers() const;
  130. /** Sets DirectX 9 render state option. */
  131. HRESULT setRenderState(D3DRENDERSTATETYPE state, DWORD value);
  132. /** Sets DirectX 9 sampler state option for a sampler at the specified index. */
  133. HRESULT setSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value);
  134. /** Sets DirectX 9 texture state option for a texture unit at the specified index. */
  135. HRESULT setTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value);
  136. /** Set a floating point render state option. */
  137. HRESULT setFloatRenderState(D3DRENDERSTATETYPE state, float value)
  138. {
  139. return setRenderState(state, *((LPDWORD)(&value)));
  140. }
  141. /** Returns currently active anisotropy level for the provided texture unit. */
  142. DWORD getCurrentAnisotropy(UINT32 unit);
  143. /**
  144. * Updates active render system capabilities. Requires active render window to check certain capabilities.
  145. *
  146. * @note Also performs an initialization step when called the first time.
  147. */
  148. RenderAPICapabilities* updateRenderSystemCapabilities(D3D9RenderWindowCore* renderWindow);
  149. /** Updates render system capabilities with vertex shader related data. */
  150. void updateVertexShaderCaps(RenderAPICapabilities* rsc) const;
  151. /** Updates render system capabilities with pixel shader related data. */
  152. void updatePixelShaderCaps(RenderAPICapabilities* rsc) const;
  153. /** @copydoc RenderAPICore::setClipPlanesImpl */
  154. void setClipPlanesImpl(const PlaneList& clipPlanes) override;
  155. /** Converts a HRESULT error number into an error description. */
  156. String getErrorDescription(long errorNumber) const;
  157. /** Sets a clip plane with the specified index. */
  158. void setClipPlane(UINT16 index, float A, float B, float C, float D);
  159. /** Enables or disables a clip plane at the specified index. */
  160. void enableClipPlane(UINT16 index, bool enable);
  161. /** Returns current module instance. */
  162. HINSTANCE getInstanceHandle() const { return mhInstance; }
  163. /** Returns the D3D9 specific mode used for drawing, depending on the currently set draw operation. */
  164. D3DPRIMITIVETYPE getD3D9PrimitiveType() const;
  165. /************************************************************************/
  166. /* Sampler states */
  167. /************************************************************************/
  168. /**
  169. * Sets the texture addressing mode for a texture unit. This determines how are UV address values outside of [0, 1]
  170. * range handled when sampling from texture.
  171. */
  172. void setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw);
  173. /**
  174. * Allows you to specify how is the texture bound to the specified texture unit filtered. Different filter types are
  175. * used for different situations like magnifying or minifying a texture.
  176. */
  177. void setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter);
  178. /** Sets anisotropy value for the specified texture unit. */
  179. void setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy);
  180. /**
  181. * Sets the texture border color for a texture unit. Border color determines color returned by the texture sampler
  182. * when border addressing mode is used and texture address is outside of [0, 1] range.
  183. */
  184. void setTextureBorderColor(UINT16 stage, const Color& color);
  185. /**
  186. * Sets the mipmap bias value for a given texture unit. Bias allows you to adjust the mipmap selection calculation.
  187. * Negative values force a larger mipmap to be used, and positive values smaller. Units are in values of mip levels,
  188. * so -1 means use a mipmap one level higher than default.
  189. */
  190. void setTextureMipmapBias(UINT16 unit, float bias);
  191. /************************************************************************/
  192. /* Blend states */
  193. /************************************************************************/
  194. /**
  195. * Sets up blending mode that allows you to combine new pixels with pixels already in the render target. Final pixel
  196. * value = (renderTargetPixel * sourceFactor) op (pixel * destFactor).
  197. */
  198. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op);
  199. /**
  200. * Sets up blending mode that allows you to combine new pixels with pixels already in the render target. Allows you
  201. * to set up separate blend operations for alpha values.
  202. *
  203. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor). (And the same for alpha)
  204. */
  205. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  206. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp);
  207. /**
  208. * Sets alpha test that allows you to reject pixels that fail the comparison function versus the provided reference
  209. * value.
  210. */
  211. void setAlphaTest(CompareFunction func, unsigned char value);
  212. /**
  213. * Enable alpha to coverage. Alpha to coverage allows you to perform blending without needing to worry about order
  214. * of rendering like regular blending does. It requires multi-sampling to be active in order to work, and you need
  215. * to supply an alpha texture that determines object transparency.
  216. */
  217. void setAlphaToCoverage(bool enabled);
  218. /** Enables or disables writing to certain color channels of the render target. */
  219. void setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  220. /************************************************************************/
  221. /* Rasterizer states */
  222. /************************************************************************/
  223. /** Sets vertex winding order. Normally you would use this to cull back facing polygons. */
  224. void setCullingMode(CullingMode mode);
  225. /** Sets the polygon rasterization mode. Determines how are polygons interpreted. */
  226. void setPolygonMode(PolygonMode level);
  227. /**
  228. * Sets a depth bias that will offset the depth values of new pixels by the specified amount. Final depth bias value
  229. * is a combination of the constant depth bias and slope depth bias. Slope depth bias has more effect the higher the
  230. * slope of the rendered polygon.
  231. *
  232. * @note This is useful if you want to avoid z fighting for objects at the same or similar depth.
  233. */
  234. void setDepthBias(float constantBias, float slopeScaleBias);
  235. /**
  236. * Scissor test allows you to mask off rendering in all but a given rectangular area identified by the rectangle
  237. * set by setScissorRect().
  238. */
  239. void setScissorTestEnable(bool enable);
  240. /**
  241. * Only applies when rendering to a multisample render target. If disabled all of the samples will be taken from the
  242. * center of the pixel, effectively making the image aliased. Default value is true where samples are picked
  243. * randomly within the pixel.
  244. */
  245. void setMultisampleAntialiasEnable(bool enable);
  246. /**
  247. * Only applies when rendering to a non-multisample render target. If enabled, lines will be antialiased. Default
  248. * state is disabled.
  249. */
  250. void setAntialiasedLineEnable(bool enable);
  251. /************************************************************************/
  252. /* Depth stencil state */
  253. /************************************************************************/
  254. /** Should new pixels perform depth testing using the set depth comparison function before being written. */
  255. void setDepthBufferCheckEnabled(bool enabled = true);
  256. /** Should new pixels write to the depth buffer. */
  257. void setDepthBufferWriteEnabled(bool enabled = true);
  258. /**
  259. * Sets comparison function used for depth testing. Determines how are new and existing pixel values compared - if
  260. * comparison function returns true the new pixel is written.
  261. */
  262. void setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
  263. /**
  264. * Turns stencil tests on or off. By default this is disabled. Stencil testing allow you to mask out a part of the
  265. * rendered image by using various stencil operations provided.
  266. */
  267. void setStencilCheckEnabled(bool enabled);
  268. /**
  269. * Allows you to set stencil operations that are performed when stencil test passes or fails.
  270. *
  271. * @param[in] stencilFailOp Operation executed when stencil test fails.
  272. * @param[in] depthFailOp Operation executed when stencil test succeeds but depth test fails.
  273. * @param[in] passOp Operation executed when stencil test succeeds and depth test succeeds.
  274. * @param[in] front Should the stencil operations be applied to front or back facing polygons.
  275. */
  276. void setStencilBufferOperations(StencilOperation stencilFailOp = SOP_KEEP,
  277. StencilOperation depthFailOp = SOP_KEEP, StencilOperation passOp = SOP_KEEP,
  278. bool ccw = true);
  279. /**
  280. * Sets a stencil buffer comparison function. The result of this will cause one of 3 actions depending on whether
  281. * the test fails, succeeds but with the depth buffer check still failing, or succeeds with the depth buffer check
  282. * passing too.
  283. *
  284. * @param[in] func Comparison function that determines whether a stencil test fails or passes. Reference value
  285. * gets compared to the value already in the buffer using this function.
  286. * @param[in] ccw If set to true, the stencil operations will be applied to counterclockwise
  287. * faces. Otherwise they will be applied to clockwise faces.
  288. */
  289. void setStencilBufferFunc(CompareFunction func = CMPF_ALWAYS_PASS, bool ccw = true);
  290. /** The bitmask applied to both the stencil value and the reference value before comparison. */
  291. void setStencilBufferReadMask(UINT32 mask = 0xFFFFFFFF);
  292. /** The bitmask applied to the stencil value before writing it to the stencil buffer. */
  293. void setStencilBufferWriteMask(UINT32 mask = 0xFFFFFFFF);
  294. /**
  295. * Sets a reference values used for stencil buffer comparisons. Actual comparison function and stencil operations
  296. * are set by setting the DepthStencilState.
  297. */
  298. void setStencilRefValue(UINT32 refValue);
  299. /**
  300. * Clears an area of the currently active render target.
  301. *
  302. * @param[in] buffers Combination of one or more elements of FrameBufferType denoting which buffers are
  303. * to be cleared.
  304. * @param[in] color (optional) The color to clear the color buffer with, if enabled.
  305. * @param[in] depth (optional) The value to initialize the depth buffer with, if enabled.
  306. * @param[in] stencil (optional) The value to initialize the stencil buffer with, if enabled.
  307. * @param[in] clearArea (optional) Area in pixels to clear.
  308. */
  309. void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0, const Rect2I& clearArea = Rect2I::EMPTY);
  310. /**
  311. * Recalculates actual viewport dimensions based on currently set viewport normalized dimensions and render target
  312. * and applies them for further rendering.
  313. */
  314. void applyViewport();
  315. /** Triggered when device has been lost. */
  316. void notifyOnDeviceLost(D3D9Device* device);
  317. /** Triggered when device is being reset. */
  318. void notifyOnDeviceReset(D3D9Device* device);
  319. private:
  320. /** Holds texture unit settings. */
  321. struct sD3DTextureStageDesc
  322. {
  323. D3D9Mappings::D3DTexType texType;
  324. size_t coordIndex;
  325. IDirect3DBaseTexture9 *pTex;
  326. IDirect3DBaseTexture9 *pVertexTex;
  327. };
  328. static D3D9RenderAPI* msD3D9RenderSystem;
  329. IDirect3D9* mpD3D;
  330. D3D9HLSLProgramFactory* mHLSLProgramFactory;
  331. D3D9ResourceManager* mResourceManager;
  332. D3D9DeviceManager* mDeviceManager;
  333. mutable D3D9DriverList* mDriverList;
  334. D3D9Driver* mActiveD3DDriver;
  335. UINT32 mNumTexStages;
  336. sD3DTextureStageDesc* mTexStageDesc;
  337. bool mIsFrameInProgress;
  338. bool mRestoreFrameOnReset;
  339. HINSTANCE mhInstance;
  340. Rect2 mViewportNorm;
  341. UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
  342. RECT mScissorRect;
  343. DrawOperationType mCurrentDrawOperation;
  344. };
  345. /** @} */
  346. }