OgreD3D9RenderSystem.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. /*
  2. -----------------------------------------------------------------------------
  3. This source file is part of OGRE
  4. (Object-oriented Graphics Rendering Engine)
  5. For the latest info, see http://www.ogre3d.org
  6. Copyright (c) 2000-2011 Torus Knot Software Ltd
  7. Permission is hereby granted, free of charge, to any person obtaining a copy
  8. of this software and associated documentation files (the "Software"), to deal
  9. in the Software without restriction, including without limitation the rights
  10. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. copies of the Software, and to permit persons to whom the Software is
  12. furnished to do so, subject to the following conditions:
  13. The above copyright notice and this permission notice shall be included in
  14. all copies or substantial portions of the Software.
  15. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. THE SOFTWARE.
  22. -----------------------------------------------------------------------------
  23. */
  24. #ifndef __D3D9RENDERSYSTEM_H__
  25. #define __D3D9RENDERSYSTEM_H__
  26. #include "OgreD3D9Prerequisites.h"
  27. #include "OgreString.h"
  28. #include "OgreStringConverter.h"
  29. #include "OgreConfigOptionMap.h"
  30. #include "CmRenderSystem.h"
  31. #include "CmRenderSystemCapabilities.h"
  32. #include "OgreD3D9Mappings.h"
  33. namespace CamelotEngine
  34. {
  35. #define MAX_LIGHTS 8
  36. class D3D9DriverList;
  37. class D3D9Driver;
  38. class D3D9Device;
  39. class D3D9DeviceManager;
  40. class D3D9ResourceManager;
  41. /**
  42. Implementation of DirectX9 as a rendering system.
  43. */
  44. class _OgreD3D9Export D3D9RenderSystem : public RenderSystem
  45. {
  46. private:
  47. /// Direct3D
  48. IDirect3D9* mpD3D;
  49. // Stored options
  50. ConfigOptionMap mOptions;
  51. size_t mFSAASamples;
  52. String mFSAAHint;
  53. /// instance
  54. HINSTANCE mhInstance;
  55. /// List of D3D drivers installed (video cards)
  56. D3D9DriverList* mDriverList;
  57. /// Currently active driver
  58. D3D9Driver* mActiveD3DDriver;
  59. /// NVPerfHUD allowed?
  60. bool mUseNVPerfHUD;
  61. /// Per-stage constant support? (not in main caps since D3D specific & minor)
  62. bool mPerStageConstantSupport;
  63. /// Fast singleton access.
  64. static D3D9RenderSystem* msD3D9RenderSystem;
  65. /// structure holding texture unit settings for every stage
  66. struct sD3DTextureStageDesc
  67. {
  68. /// the type of the texture
  69. D3D9Mappings::eD3DTexType texType;
  70. /// which texCoordIndex to use
  71. size_t coordIndex;
  72. /// type of auto tex. calc. used
  73. TexCoordCalcMethod autoTexCoordType;
  74. /// Frustum, used if the above is projection
  75. const Frustum *frustum;
  76. /// texture
  77. IDirect3DBaseTexture9 *pTex;
  78. /// vertex texture
  79. IDirect3DBaseTexture9 *pVertexTex;
  80. } mTexStageDesc[CM_MAX_TEXTURE_LAYERS];
  81. // Array of up to 8 lights, indexed as per API
  82. // Note that a null value indicates a free slot
  83. Light* mLights[MAX_LIGHTS];
  84. D3D9DriverList* getDirect3DDrivers();
  85. void refreshD3DSettings();
  86. void refreshFSAAOptions();
  87. void setD3D9Light( size_t index, Light* light );
  88. // state management methods, very primitive !!!
  89. HRESULT __SetRenderState(D3DRENDERSTATETYPE state, DWORD value);
  90. HRESULT __SetSamplerState(DWORD sampler, D3DSAMPLERSTATETYPE type, DWORD value);
  91. HRESULT __SetTextureStageState(DWORD stage, D3DTEXTURESTAGESTATETYPE type, DWORD value);
  92. HRESULT __SetFloatRenderState(D3DRENDERSTATETYPE state, float value)
  93. {
  94. #if OGRE_DOUBLE_PRECISION == 1
  95. float temp = static_cast<float>(value);
  96. return __SetRenderState(state, *((LPDWORD)(&temp)));
  97. #else
  98. return __SetRenderState(state, *((LPDWORD)(&value)));
  99. #endif
  100. }
  101. /// return anisotropy level
  102. DWORD _getCurrentAnisotropy(size_t unit);
  103. /// check if a FSAA is supported
  104. bool _checkMultiSampleQuality(D3DMULTISAMPLE_TYPE type, DWORD *outQuality, D3DFORMAT format, UINT adapterNum, D3DDEVTYPE deviceType, BOOL fullScreen);
  105. D3D9HardwareBufferManager* mHardwareBufferManager;
  106. D3D9GpuProgramManager* mGpuProgramManager;
  107. D3D9HLSLProgramFactory* mHLSLProgramFactory;
  108. D3D9ResourceManager* mResourceManager;
  109. D3D9DeviceManager* mDeviceManager;
  110. size_t mLastVertexSourceCount;
  111. /// Internal method for populating the capabilities structure
  112. virtual RenderSystemCapabilities* createRenderSystemCapabilities() const;
  113. RenderSystemCapabilities* updateRenderSystemCapabilities(D3D9RenderWindow* renderWindow);
  114. /** See RenderSystem definition */
  115. virtual void initialiseFromRenderSystemCapabilities(RenderSystemCapabilities* caps, RenderTarget* primary);
  116. void convertVertexShaderCaps(RenderSystemCapabilities* rsc) const;
  117. void convertPixelShaderCaps(RenderSystemCapabilities* rsc) const;
  118. bool checkVertexTextureFormats(D3D9RenderWindow* renderWindow) const;
  119. HashMap<IDirect3DDevice9*, unsigned short> mCurrentLights;
  120. /// Saved last view matrix
  121. Matrix4 mViewMatrix;
  122. D3DXMATRIX mDxViewMat, mDxProjMat, mDxWorldMat;
  123. typedef vector<D3D9RenderWindow*>::type D3D9RenderWindowList;
  124. // List of additional windows after the first (swap chains)
  125. D3D9RenderWindowList mRenderWindows;
  126. /** Mapping of texture format -> DepthStencil. Used as cache by _getDepthStencilFormatFor
  127. */
  128. typedef HashMap<unsigned int, D3DFORMAT> DepthStencilHash;
  129. DepthStencilHash mDepthStencilHash;
  130. /** Mapping of depthstencil format -> depthstencil buffer
  131. Keep one depthstencil buffer around for every format that is used, it must be large
  132. enough to hold the largest rendering target.
  133. This is used as cache by _getDepthStencilFor.
  134. */
  135. struct ZBufferIdentifier
  136. {
  137. IDirect3DDevice9* device;
  138. D3DFORMAT format;
  139. D3DMULTISAMPLE_TYPE multisampleType;
  140. };
  141. struct ZBufferRef
  142. {
  143. IDirect3DSurface9 *surface;
  144. size_t width, height;
  145. };
  146. struct ZBufferIdentifierComparator
  147. {
  148. bool operator()(const ZBufferIdentifier& z0, const ZBufferIdentifier& z1) const;
  149. };
  150. typedef deque<ZBufferRef>::type ZBufferRefQueue;
  151. typedef map<ZBufferIdentifier, ZBufferRefQueue, ZBufferIdentifierComparator>::type ZBufferHash;
  152. ZBufferHash mZBufferHash;
  153. protected:
  154. void setClipPlanesImpl(const PlaneList& clipPlanes);
  155. public:
  156. // constructor
  157. D3D9RenderSystem( HINSTANCE hInstance );
  158. // destructor
  159. ~D3D9RenderSystem();
  160. virtual void initConfigOptions();
  161. // Overridden RenderSystem functions
  162. String validateConfigOptions();
  163. RenderWindow* _initialise( bool autoCreateWindow, const String& windowTitle = "OGRE Render Window" );
  164. /// @copydoc RenderSystem::_createRenderWindow
  165. RenderWindow* _createRenderWindow(const String &name, unsigned int width, unsigned int height,
  166. bool fullScreen, const NameValuePairList *miscParams = 0);
  167. /// @copydoc RenderSystem::_createRenderWindows
  168. bool _createRenderWindows(const RenderWindowDescriptionList& renderWindowDescriptions,
  169. RenderWindowList& createdWindows);
  170. /**
  171. * Set current render target to target, enabling its GL context if needed
  172. */
  173. void _setRenderTarget(RenderTarget *target);
  174. /// @copydoc RenderSystem::createMultiRenderTarget
  175. virtual MultiRenderTarget * createMultiRenderTarget(const String & name);
  176. String getErrorDescription( long errorNumber ) const;
  177. const String& getName() const;
  178. // Low-level overridden members
  179. void setConfigOption( const String &name, const String &value );
  180. void reinitialise();
  181. void shutdown();
  182. void setAmbientLight( float r, float g, float b );
  183. void setShadingType( ShadeOptions so );
  184. void setLightingEnabled( bool enabled );
  185. void destroyRenderTarget(const String& name);
  186. VertexElementType getColourVertexElementType() const;
  187. void setStencilCheckEnabled(bool enabled);
  188. void setStencilBufferParams(CompareFunction func = CMPF_ALWAYS_PASS,
  189. UINT32 refValue = 0, UINT32 mask = 0xFFFFFFFF,
  190. StencilOperation stencilFailOp = SOP_KEEP,
  191. StencilOperation depthFailOp = SOP_KEEP,
  192. StencilOperation passOp = SOP_KEEP,
  193. bool twoSidedOperation = false);
  194. void setNormaliseNormals(bool normalise);
  195. // Low-level overridden members, mainly for internal use
  196. void _useLights(const LightList& lights, unsigned short limit);
  197. void _setWorldMatrix( const Matrix4 &m );
  198. void _setViewMatrix( const Matrix4 &m );
  199. void _setProjectionMatrix( const Matrix4 &m );
  200. void _setSurfaceParams( const ColourValue &ambient, const ColourValue &diffuse, const ColourValue &specular, const ColourValue &emissive, float shininess, TrackVertexColourType tracking );
  201. void _setPointSpritesEnabled(bool enabled);
  202. void _setPointParameters(float size, bool attenuationEnabled,
  203. float constant, float linear, float quadratic, float minSize, float maxSize);
  204. void _setTexture(size_t unit, bool enabled, const TexturePtr &texPtr);
  205. void _setVertexTexture(size_t unit, const TexturePtr& tex);
  206. void _disableTextureUnit(size_t texUnit);
  207. void _setTextureCoordSet( size_t unit, size_t index );
  208. void _setTextureCoordCalculation(size_t unit, TexCoordCalcMethod m,
  209. const Frustum* frustum = 0);
  210. void _setTextureBlendMode( size_t unit, const LayerBlendModeEx& bm );
  211. void _setTextureAddressingMode(size_t stage, const TextureState::UVWAddressingMode& uvw);
  212. void _setTextureBorderColour(size_t stage, const ColourValue& colour);
  213. void _setTextureMipmapBias(size_t unit, float bias);
  214. void _setTextureMatrix( size_t unit, const Matrix4 &xform );
  215. void _setSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendOperation op );
  216. void _setSeparateSceneBlending( SceneBlendFactor sourceFactor, SceneBlendFactor destFactor, SceneBlendFactor sourceFactorAlpha, SceneBlendFactor destFactorAlpha, SceneBlendOperation op, SceneBlendOperation alphaOp );
  217. void _setAlphaRejectSettings( CompareFunction func, unsigned char value, bool alphaToCoverage );
  218. void _setViewport( Viewport *vp );
  219. void _beginFrame();
  220. virtual RenderSystemContext* _pauseFrame(void);
  221. virtual void _resumeFrame(RenderSystemContext* context);
  222. void _endFrame();
  223. void _setCullingMode( CullingMode mode );
  224. void _setDepthBufferParams( bool depthTest = true, bool depthWrite = true, CompareFunction depthFunction = CMPF_LESS_EQUAL );
  225. void _setDepthBufferCheckEnabled( bool enabled = true );
  226. void _setColourBufferWriteEnabled(bool red, bool green, bool blue, bool alpha);
  227. void _setDepthBufferWriteEnabled(bool enabled = true);
  228. void _setDepthBufferFunction( CompareFunction func = CMPF_LESS_EQUAL );
  229. void _setDepthBias(float constantBias, float slopeScaleBias);
  230. void _setFog( FogMode mode = FOG_NONE, const ColourValue& colour = ColourValue::White, float expDensity = 1.0, float linearStart = 0.0, float linearEnd = 1.0 );
  231. void _convertProjectionMatrix(const Matrix4& matrix,
  232. Matrix4& dest, bool forGpuProgram = false);
  233. void _makeProjectionMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  234. Matrix4& dest, bool forGpuProgram = false);
  235. void _makeProjectionMatrix(float left, float right, float bottom, float top, float nearPlane,
  236. float farPlane, Matrix4& dest, bool forGpuProgram = false);
  237. void _makeOrthoMatrix(const Radian& fovy, float aspect, float nearPlane, float farPlane,
  238. Matrix4& dest, bool forGpuProgram = false);
  239. void _applyObliqueDepthProjection(Matrix4& matrix, const Plane& plane,
  240. bool forGpuProgram);
  241. void _setPolygonMode(PolygonMode level);
  242. void _setTextureUnitFiltering(size_t unit, FilterType ftype, FilterOptions filter);
  243. void _setTextureLayerAnisotropy(size_t unit, unsigned int maxAnisotropy);
  244. void setVertexDeclaration(VertexDeclaration* decl);
  245. void setVertexBufferBinding(VertexBufferBinding* binding);
  246. void _render(const RenderOperation& op);
  247. /** See
  248. RenderSystem
  249. */
  250. void bindGpuProgram(GpuProgram* prg);
  251. /** See
  252. RenderSystem
  253. */
  254. void unbindGpuProgram(GpuProgramType gptype);
  255. /** See
  256. RenderSystem
  257. */
  258. void bindGpuProgramParameters(GpuProgramType gptype,
  259. GpuProgramParametersSharedPtr params, UINT16 variabilityMask);
  260. void bindGpuProgramPassIterationParameters(GpuProgramType gptype);
  261. void setScissorTest(bool enabled, size_t left = 0, size_t top = 0, size_t right = 800, size_t bottom = 600);
  262. void clearFrameBuffer(unsigned int buffers,
  263. const ColourValue& colour = ColourValue::Black,
  264. float depth = 1.0f, unsigned short stencil = 0);
  265. void setClipPlane (UINT16 index, float A, float B, float C, float D);
  266. void enableClipPlane (UINT16 index, bool enable);
  267. HardwareOcclusionQuery* createHardwareOcclusionQuery();
  268. float getHorizontalTexelOffset();
  269. float getVerticalTexelOffset();
  270. float getMinimumDepthInputValue();
  271. float getMaximumDepthInputValue();
  272. void registerThread();
  273. void unregisterThread();
  274. void preExtraThreadsStarted();
  275. void postExtraThreadsStarted();
  276. static D3D9ResourceManager* getResourceManager();
  277. static D3D9DeviceManager* getDeviceManager();
  278. static IDirect3D9* getDirect3D9();
  279. static UINT getResourceCreationDeviceCount();
  280. static IDirect3DDevice9* getResourceCreationDevice(UINT index);
  281. static IDirect3DDevice9* getActiveD3D9Device();
  282. /**
  283. Get the matching Z-Buffer identifier for a certain render target
  284. */
  285. ZBufferIdentifier getZBufferIdentifier(RenderTarget* rt);
  286. /** Check which depthStencil formats can be used with a certain pixel format,
  287. and return the best suited.
  288. */
  289. D3DFORMAT _getDepthStencilFormatFor(D3DFORMAT fmt);
  290. /** Get a depth stencil surface that is compatible with an internal pixel format and
  291. multisample type.
  292. @returns A directx surface, or 0 if there is no compatible depthstencil possible.
  293. */
  294. IDirect3DSurface9* _getDepthStencilFor(D3DFORMAT fmt, D3DMULTISAMPLE_TYPE multisample, DWORD multisample_quality, size_t width, size_t height);
  295. /** Clear all cached depth stencil surfaces
  296. */
  297. void _cleanupDepthStencils(IDirect3DDevice9* d3d9Device);
  298. /** Check whether or not filtering is supported for the precise texture format requested
  299. with the given usage options.
  300. */
  301. bool _checkTextureFilteringSupported(TextureType ttype, PixelFormat format, int usage);
  302. /// Take in some requested FSAA settings and output supported D3D settings
  303. void determineFSAASettings(IDirect3DDevice9* d3d9Device, size_t fsaa, const String& fsaaHint, D3DFORMAT d3dPixelFormat,
  304. bool fullScreen, D3DMULTISAMPLE_TYPE *outMultisampleType, DWORD *outMultisampleQuality);
  305. /// @copydoc RenderSystem::getDisplayMonitorCount
  306. unsigned int getDisplayMonitorCount() const;
  307. protected:
  308. /// Notify when a device has been lost.
  309. void notifyOnDeviceLost(D3D9Device* device);
  310. /// Notify when a device has been reset.
  311. void notifyOnDeviceReset(D3D9Device* device);
  312. typedef map<RenderTarget*, ZBufferRef>::type TargetDepthStencilMap;
  313. TargetDepthStencilMap mCheckedOutTextures;
  314. private:
  315. friend class D3D9Device;
  316. friend class D3D9DeviceManager;
  317. };
  318. }
  319. #endif