BsD3D9RenderAPI.h 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  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. /**
  11. * @brief Implementation of a render system using DirectX 9. Provides abstracted
  12. * access to various low level DX9 methods.
  13. */
  14. class BS_D3D9_EXPORT D3D9RenderAPI : public RenderAPICore
  15. {
  16. public:
  17. /**
  18. * @brief Constructs a new instance of the render system using the provided module instance.
  19. */
  20. D3D9RenderAPI(HINSTANCE hInstance);
  21. ~D3D9RenderAPI();
  22. /**
  23. * @copydoc RenderAPICore::getName()
  24. */
  25. const StringID& getName() const override;
  26. /**
  27. * @copydoc RenderAPICore::getShadingLanguageName()
  28. */
  29. const String& getShadingLanguageName() const override;
  30. /**
  31. * @copydoc RenderAPICore::setRenderTarget()
  32. */
  33. void setRenderTarget(const SPtr<RenderTargetCore>& target, bool readOnlyDepthStencil = false) override;
  34. /**
  35. * @copydoc RenderAPICore::bindGpuProgram()
  36. */
  37. void bindGpuProgram(const SPtr<GpuProgramCore>& prg) override;
  38. /**
  39. * @copydoc RenderAPICore::unbindGpuProgram()
  40. */
  41. void unbindGpuProgram(GpuProgramType gptype) override;
  42. /**
  43. * @copydoc RenderAPICore::setConstantBuffers()
  44. */
  45. void setConstantBuffers(GpuProgramType gptype, const SPtr<GpuParamsCore>& params) override;
  46. /**
  47. * @copydoc RenderAPICore::setVertexBuffers()
  48. */
  49. void setVertexBuffers(UINT32 index, SPtr<VertexBufferCore>* buffers, UINT32 numBuffers) override;
  50. /**
  51. * @copydoc RenderAPICore::setIndexBuffer()
  52. */
  53. void setIndexBuffer(const SPtr<IndexBufferCore>& buffer) override;
  54. /**
  55. * @copydoc RenderAPICore::setVertexDeclaration()
  56. */
  57. void setVertexDeclaration(const SPtr<VertexDeclarationCore>& vertexDeclaration) override;
  58. /**
  59. * @copydoc RenderAPICore::setDrawOperation()
  60. */
  61. void setDrawOperation(DrawOperationType op) override;
  62. /**
  63. * @copydoc RenderAPICore::setTexture()
  64. */
  65. void setTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr) override;
  66. /**
  67. * @copydoc RenderAPICore::setLoadStoreTexture()
  68. */
  69. void setLoadStoreTexture(GpuProgramType gptype, UINT16 unit, bool enabled, const SPtr<TextureCore>& texPtr,
  70. const TextureSurface& surface) override;
  71. /**
  72. * @copydoc RenderAPICore::setSamplerState()
  73. */
  74. void setSamplerState(GpuProgramType gptype, UINT16 unit, const SPtr<SamplerStateCore>& state) override;
  75. /**
  76. * @copydoc RenderAPICore::setBlendState()
  77. */
  78. void setBlendState(const SPtr<BlendStateCore>& blendState) override;
  79. /**
  80. * @copydoc RenderAPICore::setRasterizerState()
  81. */
  82. void setRasterizerState(const SPtr<RasterizerStateCore>& rasterizerState) override;
  83. /**
  84. * @copydoc RenderAPICore::setDepthStencilState()
  85. */
  86. void setDepthStencilState(const SPtr<DepthStencilStateCore>& depthStencilState, UINT32 stencilRefValue) override;
  87. /**
  88. * @copydoc RenderAPICore::setViewport()
  89. */
  90. void setViewport(const Rect2& vp) 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::drawIndexed()
  109. */
  110. void dispatchCompute(UINT32 numGroupsX, UINT32 numGroupsY = 1, UINT32 numGroupsZ = 1) override;
  111. /**
  112. * @copydoc RenderAPICore::setScissorRect()
  113. */
  114. void setScissorRect(UINT32 left, UINT32 top, UINT32 right, UINT32 bottom) override;
  115. /**
  116. * @copydoc RenderAPICore::clearRenderTarget()
  117. */
  118. void clearRenderTarget(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  119. UINT8 targetMask = 0xFF) override;
  120. /**
  121. * @copydoc RenderAPICore::clearViewport()
  122. */
  123. void clearViewport(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0,
  124. UINT8 targetMask = 0xFF) override;
  125. /**
  126. * @copydoc RenderAPICore::convertProjectionMatrix()
  127. */
  128. void convertProjectionMatrix(const Matrix4& matrix, Matrix4& dest) override;
  129. /**
  130. * @copydoc RenderAPICore::getHorizontalTexelOffset
  131. */
  132. float getHorizontalTexelOffset() override;
  133. /**
  134. * @copydoc RenderAPICore::getVerticalTexelOffset
  135. */
  136. float getVerticalTexelOffset() override;
  137. /**
  138. * @copydoc RenderAPICore::getMinimumDepthInputValue
  139. */
  140. float getMinimumDepthInputValue() override;
  141. /**
  142. * @copydoc RenderAPICore::getMaximumDepthInputValue
  143. */
  144. float getMaximumDepthInputValue() override;
  145. /**
  146. * @copydoc RenderAPICore::getColorVertexElementType
  147. */
  148. VertexElementType getColorVertexElementType() const override;
  149. /**
  150. * @copydoc RenderAPICore::getColorVertexElementType
  151. */
  152. bool getVertexColorFlipRequired() const override { return true; }
  153. /**
  154. * @copydoc RenderAPICore::generateParamBlockDesc()
  155. */
  156. GpuParamBlockDesc generateParamBlockDesc(const String& name, Vector<GpuParamDataDesc>& params) override;
  157. /************************************************************************/
  158. /* Internal use by DX9 RenderAPI only */
  159. /************************************************************************/
  160. /**
  161. * @brief Returns the resource manager instance.
  162. */
  163. static D3D9ResourceManager* getResourceManager();
  164. /**
  165. * @brief Returns the device manager instance.
  166. */
  167. static D3D9DeviceManager* getDeviceManager();
  168. /**
  169. * @brief Returns the internal DirectX 9 device object.
  170. */
  171. static IDirect3D9* getDirect3D9();
  172. /**
  173. * @brief Returns the number of devices that resources should be created on.
  174. */
  175. static UINT getResourceCreationDeviceCount();
  176. /**
  177. * @brief Returns DirectX 9 device used for resource creation at the specified index.
  178. */
  179. static IDirect3DDevice9* getResourceCreationDevice(UINT index);
  180. /**
  181. * @brief Returns the currently active DirectX 9 device.
  182. */
  183. static IDirect3DDevice9* getActiveD3D9Device();
  184. /**
  185. * @brief Converts engine multisample options into DirectX 9 specific ones.
  186. * Also test for multi-sample support on the device and returns nearest
  187. * supported type if requested type is not available.
  188. *
  189. * @param d3d9Device Device to check for multisampling.
  190. * @param multisampleCount Number of requested samples.
  191. * @param d3dPixelFormat Pixel format used by the render target.
  192. * @param fullscreen Are we testing multisampling for a full-screen render target.
  193. * @param outMultisampleType Output parameter containing DirectX type representing valid multisample type.
  194. * @param outMultisampleQuality Output parameter containing multisample quality.
  195. */
  196. void determineMultisampleSettings(IDirect3DDevice9* d3d9Device, UINT32 multisampleCount, D3DFORMAT d3dPixelFormat,
  197. bool fullScreen, D3DMULTISAMPLE_TYPE* outMultisampleType, DWORD* outMultisampleQuality) const;
  198. /**
  199. * @brief Register a newly open window with the render system.
  200. */
  201. void registerWindow(RenderWindowCore& renderWindow);
  202. private:
  203. friend class D3D9Texture;
  204. friend class D3D9RenderWindow;
  205. friend class D3D9Device;
  206. friend class D3D9TextureManager;
  207. friend class D3D9TextureCoreManager;
  208. friend class D3D9DeviceManager;
  209. friend class D3D9RenderWindowManager;
  210. friend class D3D9RenderWindowCoreManager;
  211. /**
  212. * @copydoc RenderAPICore::initializePrepare
  213. */
  214. void initializePrepare() override;
  215. /**
  216. * @copydoc RenderAPICore::initializeFinalize
  217. */
  218. void initializeFinalize(const SPtr<RenderWindowCore>& primaryWindow) override;
  219. /**
  220. * @copydoc RenderAPICore::destroy_internal
  221. */
  222. void destroyCore() override;
  223. /**
  224. * @brief Returns a list of available drivers and their properties.
  225. */
  226. D3D9DriverList* getDirect3DDrivers() const;
  227. /**
  228. * @brief Sets DirectX 9 render state option.
  229. */
  230. HRESULT setRenderState(D3DRENDERSTATETYPE state, DWORD value);
  231. /**
  232. * @brief Sets DirectX 9 sampler state option for a sampler at the specified index.
  233. */
  234. HRESULT setSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value);
  235. /**
  236. * @brief Sets DirectX 9 texture state option for a texture unit at the specified index.
  237. */
  238. HRESULT setTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value);
  239. /**
  240. * @brief Set a floating point render state option.
  241. */
  242. HRESULT setFloatRenderState(D3DRENDERSTATETYPE state, float value)
  243. {
  244. return setRenderState(state, *((LPDWORD)(&value)));
  245. }
  246. /**
  247. * @brief Returns currently active anisotropy level for the provided texture unit.
  248. */
  249. DWORD getCurrentAnisotropy(UINT32 unit);
  250. /**
  251. * @brief Updates active render system capabilities. Requires active render window to check
  252. * certain capabilities.
  253. *
  254. * @note Also performs an initialization step when called the first time.
  255. */
  256. RenderAPICapabilities* updateRenderSystemCapabilities(D3D9RenderWindowCore* renderWindow);
  257. /**
  258. * @brief Updates render system capabilities with vertex shader related data.
  259. */
  260. void updateVertexShaderCaps(RenderAPICapabilities* rsc) const;
  261. /**
  262. * @brief Updates render system capabilities with pixel shader related data.
  263. */
  264. void updatePixelShaderCaps(RenderAPICapabilities* rsc) const;
  265. /**
  266. * @copydoc RenderAPICore::setClipPlanesImpl
  267. */
  268. void setClipPlanesImpl(const PlaneList& clipPlanes) override;
  269. /**
  270. * @brief Converts a HRESULT error number into an error description.
  271. */
  272. String getErrorDescription(long errorNumber) const;
  273. /**
  274. * @brief Sets a clip plane with the specified index.
  275. */
  276. void setClipPlane(UINT16 index, float A, float B, float C, float D);
  277. /**
  278. * @brief Enables or disables a clip plane at the specified index.
  279. */
  280. void enableClipPlane(UINT16 index, bool enable);
  281. /**
  282. * @brief Returns current module instance.
  283. */
  284. HINSTANCE getInstanceHandle() const { return mhInstance; }
  285. /**
  286. * @brief Returns the D3D9 specific mode used for drawing, depending on the
  287. * currently set draw operation.
  288. */
  289. D3DPRIMITIVETYPE getD3D9PrimitiveType() const;
  290. /************************************************************************/
  291. /* Sampler states */
  292. /************************************************************************/
  293. /**
  294. * @brief Sets the texture addressing mode for a texture unit. This determines
  295. * how are UV address values outside of [0, 1] range handled when sampling
  296. * from texture.
  297. */
  298. void setTextureAddressingMode(UINT16 stage, const UVWAddressingMode& uvw);
  299. /**
  300. * @brief Allows you to specify how is the texture bound to the specified texture unit filtered.
  301. * Different filter types are used for different situations like magnifying or minifying a texture.
  302. */
  303. void setTextureFiltering(UINT16 unit, FilterType ftype, FilterOptions filter);
  304. /**
  305. * @brief Sets anisotropy value for the specified texture unit.
  306. */
  307. void setTextureAnisotropy(UINT16 unit, unsigned int maxAnisotropy);
  308. /**
  309. * @brief Sets the texture border color for a texture unit. Border color
  310. * determines color returned by the texture sampler when border addressing mode
  311. * is used and texture address is outside of [0, 1] range.
  312. */
  313. void setTextureBorderColor(UINT16 stage, const Color& color);
  314. /**
  315. * @brief Sets the mipmap bias value for a given texture unit. Bias allows
  316. * you to adjust the mipmap selection calculation. Negative values force a
  317. * larger mipmap to be used, and positive values smaller. Units are in values
  318. * of mip levels, so -1 means use a mipmap one level higher than default.
  319. */
  320. void setTextureMipmapBias(UINT16 unit, float bias);
  321. /************************************************************************/
  322. /* Blend states */
  323. /************************************************************************/
  324. /**
  325. * @brief Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  326. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor).
  327. */
  328. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendOperation op);
  329. /**
  330. * @brief Sets up blending mode that allows you to combine new pixels with pixels already in the render target.
  331. * Allows you to set up separate blend operations for alpha values.
  332. *
  333. * Final pixel value = (renderTargetPixel * sourceFactor) op (pixel * destFactor). (And the same for alpha)
  334. */
  335. void setSceneBlending(BlendFactor sourceFactor, BlendFactor destFactor, BlendFactor sourceFactorAlpha,
  336. BlendFactor destFactorAlpha, BlendOperation op, BlendOperation alphaOp);
  337. /**
  338. * @brief Sets alpha test that allows you to reject pixels that fail the comparison function
  339. * versus the provided reference value.
  340. */
  341. void setAlphaTest(CompareFunction func, unsigned char value);
  342. /**
  343. * @brief Enable alpha to coverage. Alpha to coverage allows you to perform blending without needing
  344. * to worry about order of rendering like regular blending does. It requires multi-sampling to
  345. * be active in order to work, and you need to supply an alpha texture that determines object transparency.
  346. */
  347. void setAlphaToCoverage(bool enabled);
  348. /**
  349. * @brief Enables or disables writing to certain color channels of the render target.
  350. */
  351. void setColorBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  352. /************************************************************************/
  353. /* Rasterizer states */
  354. /************************************************************************/
  355. /**
  356. * @brief Sets vertex winding order. Normally you would use this to cull back facing
  357. * polygons.
  358. */
  359. void setCullingMode(CullingMode mode);
  360. /**
  361. * @brief Sets the polygon rasterization mode. Determines how are polygons interpreted.
  362. */
  363. void setPolygonMode(PolygonMode level);
  364. /**
  365. * @brief Sets a depth bias that will offset the depth values of new pixels by the specified amount.
  366. * Final depth bias value is a combination of the constant depth bias and slope depth bias.
  367. * Slope depth bias has more effect the higher the slope of the rendered polygon.
  368. *
  369. * @note This is useful if you want to avoid z fighting for objects at the same or similar depth.
  370. */
  371. void setDepthBias(float constantBias, float slopeScaleBias);
  372. /**
  373. * @brief Scissor test allows you to mask off rendering in all but a given rectangular area
  374. * identified by the rectangle set by setScissorRect().
  375. */
  376. void setScissorTestEnable(bool enable);
  377. /**
  378. * @brief Only applies when rendering to a multisample render target.
  379. * If disabled all of the samples will be taken from the center of the pixel,
  380. * effectively making the image aliased. Default value is true where samples are
  381. * picked randomly within the pixel.
  382. */
  383. void setMultisampleAntialiasEnable(bool enable);
  384. /**
  385. * @brief Only applies when rendering to a non-multisample render target.
  386. * If enabled, lines will be antialiased. Default state is disabled.
  387. */
  388. void setAntialiasedLineEnable(bool enable);
  389. /************************************************************************/
  390. /* Depth stencil state */
  391. /************************************************************************/
  392. /**
  393. * @brief Should new pixels perform depth testing using the set depth comparison function before
  394. * being written.
  395. */
  396. void setDepthBufferCheckEnabled(bool enabled = true);
  397. /**
  398. * @brief Should new pixels write to the depth buffer.
  399. */
  400. void setDepthBufferWriteEnabled(bool enabled = true);
  401. /**
  402. * @brief Sets comparison function used for depth testing. Determines how are new and existing
  403. * pixel values compared - if comparison function returns true the new pixel is written.
  404. */
  405. void setDepthBufferFunction(CompareFunction func = CMPF_LESS_EQUAL);
  406. /**
  407. * @brief Turns stencil tests on or off. By default this is disabled.
  408. * Stencil testing allow you to mask out a part of the rendered image by using
  409. * various stencil operations provided.
  410. */
  411. void setStencilCheckEnabled(bool enabled);
  412. /**
  413. * @brief Allows you to set stencil operations that are performed when stencil test passes or fails.
  414. *
  415. * @param stencilFailOp Operation executed when stencil test fails.
  416. * @param depthFailOp Operation executed when stencil test succeeds but depth test fails.
  417. * @param passOp Operation executed when stencil test succeeds and depth test succeeds.
  418. * @param front Should the stencil operations be applied to front or back facing polygons.
  419. */
  420. void setStencilBufferOperations(StencilOperation stencilFailOp = SOP_KEEP,
  421. StencilOperation depthFailOp = SOP_KEEP, StencilOperation passOp = SOP_KEEP,
  422. bool ccw = true);
  423. /**
  424. * @brief Sets a stencil buffer comparison function. The result of this will cause one of 3 actions
  425. * depending on whether the test fails, succeeds but with the depth buffer check still failing,
  426. * or succeeds with the depth buffer check passing too.
  427. *
  428. * @param func Comparison function that determines whether a stencil test fails or passes. Reference value
  429. * gets compared to the value already in the buffer using this function.
  430. * @param ccw If set to true, the stencil operations will be applied to counterclockwise
  431. * faces. Otherwise they will be applied to clockwise faces.
  432. */
  433. void setStencilBufferFunc(CompareFunction func = CMPF_ALWAYS_PASS, bool ccw = true);
  434. /**
  435. * @brief The bitmask applied to both the stencil value and the reference value
  436. * before comparison.
  437. */
  438. void setStencilBufferReadMask(UINT32 mask = 0xFFFFFFFF);
  439. /**
  440. * @brief The bitmask applied to the stencil value before writing it to the stencil buffer.
  441. */
  442. void setStencilBufferWriteMask(UINT32 mask = 0xFFFFFFFF);
  443. /**
  444. * @brief Sets a reference values used for stencil buffer comparisons.
  445. * Actual comparison function and stencil operations are set by setting the DepthStencilState.
  446. */
  447. void setStencilRefValue(UINT32 refValue);
  448. /**
  449. * @brief Clears an area of the currently active render target.
  450. *
  451. * @param buffers Combination of one or more elements of FrameBufferType
  452. * denoting which buffers are to be cleared.
  453. * @param color (optional) The color to clear the color buffer with, if enabled.
  454. * @param depth (optional) The value to initialize the depth buffer with, if enabled.
  455. * @param stencil (optional) The value to initialize the stencil buffer with, if enabled.
  456. * @param clearArea (optional) Area in pixels to clear.
  457. */
  458. void clearArea(UINT32 buffers, const Color& color = Color::Black, float depth = 1.0f, UINT16 stencil = 0, const Rect2I& clearArea = Rect2I::EMPTY);
  459. /**
  460. * @brief Recalculates actual viewport dimensions based on currently
  461. * set viewport normalized dimensions and render target and applies
  462. * them for further rendering.
  463. */
  464. void applyViewport();
  465. /**
  466. * @brief Triggered when device has been lost.
  467. */
  468. void notifyOnDeviceLost(D3D9Device* device);
  469. /**
  470. * @brief Triggered when device is being reset.
  471. */
  472. void notifyOnDeviceReset(D3D9Device* device);
  473. private:
  474. /**
  475. * @brief Holds texture unit settings.
  476. */
  477. struct sD3DTextureStageDesc
  478. {
  479. D3D9Mappings::D3DTexType texType;
  480. size_t coordIndex;
  481. IDirect3DBaseTexture9 *pTex;
  482. IDirect3DBaseTexture9 *pVertexTex;
  483. };
  484. static D3D9RenderAPI* msD3D9RenderSystem;
  485. IDirect3D9* mpD3D;
  486. D3D9HLSLProgramFactory* mHLSLProgramFactory;
  487. D3D9ResourceManager* mResourceManager;
  488. D3D9DeviceManager* mDeviceManager;
  489. mutable D3D9DriverList* mDriverList;
  490. D3D9Driver* mActiveD3DDriver;
  491. UINT32 mNumTexStages;
  492. sD3DTextureStageDesc* mTexStageDesc;
  493. bool mIsFrameInProgress;
  494. bool mRestoreFrameOnReset;
  495. HINSTANCE mhInstance;
  496. Rect2 mViewportNorm;
  497. UINT32 mViewportLeft, mViewportTop, mViewportWidth, mViewportHeight;
  498. RECT mScissorRect;
  499. DrawOperationType mCurrentDrawOperation;
  500. };
  501. }