Counter Strike : Global Offensive Source Code
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

915 lines
41 KiB

  1. //========== Copyright 2005, Valve Corporation, All rights reserved. ========
  2. //
  3. // Purpose:
  4. //
  5. //=============================================================================
  6. #ifndef CMATERIALSYSTEM_H
  7. #define CMATERIALSYSTEM_H
  8. #include "tier1/delegates.h"
  9. #include "materialsystem_global.h"
  10. #include "materialsystem/imaterialsystem.h"
  11. #include "materialsystem/ishaderapi.h"
  12. #include "imaterialinternal.h"
  13. #include "imaterialsysteminternal.h"
  14. #include "shaderapi/ishaderutil.h"
  15. #include "materialsystem/deformations.h"
  16. #include "cmaterialdict.h"
  17. #include "cmatlightmaps.h"
  18. #include "cmatpaintmaps.h"
  19. #include "cmatrendercontext.h"
  20. #include "cmatqueuedrendercontext.h"
  21. #include "materialsystem_global.h"
  22. #include "custom_material.h"
  23. #include "composite_texture.h"
  24. #ifndef MATSYS_INTERNAL
  25. #error "This file is private to the implementation of IMaterialSystem/IMaterialSystemInternal"
  26. #endif
  27. #if defined( _WIN32 )
  28. #pragma once
  29. #endif
  30. #ifdef _PS3
  31. #include "tls_ps3.h"
  32. inline IMatRenderContextInternal *& Ps3TlsMaterialSystemRenderContextFn() { void **ppv = &( GetTLSGlobals()->pMaterialSystemRenderContext ); return *( IMatRenderContextInternal ** ) ppv; }
  33. #define Ps3TlsMaterialSystemRenderContext Ps3TlsMaterialSystemRenderContextFn()
  34. #endif
  35. //-----------------------------------------------------------------------------
  36. class CJob;
  37. struct DeferredUpdateLightmapInfo_t;
  38. // typedefs to allow use of delegation macros
  39. typedef int LightmapOffset_t[2];
  40. //-----------------------------------------------------------------------------
  41. extern CThreadFastMutex g_MatSysMutex;
  42. enum AsyncTextureLoadError_t
  43. {
  44. ASYNCTEXTURE_LOADERROR_NONE = 0,
  45. ASYNCTEXTURE_LOADERROR_FILEOPEN = -1,
  46. ASYNCTEXTRUE_LOADERROR_READING = -2,
  47. };
  48. struct AsyncTextureLoad_t
  49. {
  50. AsyncTextureContext_t *m_pContext;
  51. void *m_pData;
  52. int m_nNumReadBytes;
  53. AsyncTextureLoadError_t m_LoadError;
  54. };
  55. //-----------------------------------------------------------------------------
  56. // The material system implementation
  57. //-----------------------------------------------------------------------------
  58. class CMaterialSystem : public CTier2AppSystem< IMaterialSystemInternal >, public IShaderUtil
  59. {
  60. typedef CTier2AppSystem< IMaterialSystemInternal > BaseClass;
  61. public:
  62. CMaterialSystem();
  63. ~CMaterialSystem();
  64. //---------------------------------------------------------
  65. // Initialization and shutdown
  66. //---------------------------------------------------------
  67. //
  68. // IAppSystem
  69. //
  70. virtual bool Connect( CreateInterfaceFn factory );
  71. virtual void Disconnect();
  72. virtual void * QueryInterface( const char *pInterfaceName );
  73. virtual InitReturnVal_t Init();
  74. virtual void Shutdown();
  75. virtual const AppSystemInfo_t * GetDependencies( ) { return NULL; }
  76. virtual AppSystemTier_t GetTier() { return APP_SYSTEM_TIER2; }
  77. virtual void Reconnect( CreateInterfaceFn factory, const char *pInterfaceName ) { BaseClass::Reconnect( factory, pInterfaceName ); }
  78. CreateInterfaceFn Init( const char* pShaderDLL,
  79. IMaterialProxyFactory* pMaterialProxyFactory,
  80. CreateInterfaceFn fileSystemFactory,
  81. CreateInterfaceFn cvarFactory );
  82. // Call this to set an explicit shader version to use
  83. // Must be called before Init().
  84. void SetShaderAPI( const char *pShaderAPIDLL );
  85. // Must be called before Init(), if you're going to call it at all...
  86. void SetAdapter( int nAdapter, int nFlags );
  87. void ModInit();
  88. void ModShutdown();
  89. private:
  90. // Used to dynamically load and unload the shader api
  91. CreateInterfaceFn CreateShaderAPI( const char* pShaderDLL );
  92. void DestroyShaderAPI();
  93. // Method to get at interfaces supported by the SHADDERAPI
  94. void * QueryShaderAPI( const char *pInterfaceName );
  95. // Initializes the color correction terms
  96. void InitColorCorrection();
  97. // force the thread mode to single threaded, synchronizes with render thread if running
  98. void ForceSingleThreaded();
  99. void ThreadRelease( void ); // Tell QMS to release GL
  100. void ThreadAcquire( void ); // Tell QMS to acquire GL
  101. public:
  102. virtual void SetThreadMode( MaterialThreadMode_t nextThreadMode, int nServiceThread );
  103. virtual MaterialThreadMode_t GetThreadMode(); // current thread mode
  104. virtual bool IsRenderThreadSafe( );
  105. virtual bool AllowThreading( bool bAllow, int nServiceThread );
  106. virtual void ExecuteQueued();
  107. virtual void OnDebugEvent( const char * pEvent = "" );
  108. //---------------------------------------------------------
  109. // Component accessors
  110. //---------------------------------------------------------
  111. const CMatLightmaps * GetLightmaps() const { return &m_Lightmaps; }
  112. CMatLightmaps * GetLightmaps() { return &m_Lightmaps; }
  113. const CMatPaintmaps * GetPaintmaps( void ) const { return &m_Paintmaps; }
  114. CMatPaintmaps * GetPaintmaps( void ) { return &m_Paintmaps; }
  115. IMatRenderContext * GetRenderContext();
  116. IMatRenderContext * CreateRenderContext( MaterialContextType_t type );
  117. IMatRenderContext * SetRenderContext( IMatRenderContext * );
  118. #ifdef _PS3
  119. const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = Ps3TlsMaterialSystemRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  120. IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = Ps3TlsMaterialSystemRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  121. #elif defined(_X360)
  122. const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = m_pRenderContexts[(int)ThreadInMainThread()]; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  123. IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = m_pRenderContexts[(int)ThreadInMainThread()]; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  124. #else
  125. const IMatRenderContextInternal * GetRenderContextInternal() const { IMatRenderContextInternal *pRenderContext = m_pRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  126. IMatRenderContextInternal * GetRenderContextInternal() { IMatRenderContextInternal *pRenderContext = m_pRenderContext; return ( pRenderContext ) ? pRenderContext : &m_HardwareRenderContext; }
  127. #endif
  128. const CMaterialDict * GetMaterialDict() const { return &m_MaterialDict; }
  129. CMaterialDict * GetMaterialDict() { return &m_MaterialDict; }
  130. virtual void ReloadFilesInList( IFileList *pFilesToReload );
  131. public:
  132. //---------------------------------------------------------
  133. // Config management
  134. //---------------------------------------------------------
  135. // IMaterialSystem
  136. virtual IMaterialSystemHardwareConfig * GetHardwareConfig( const char *pVersion, int *returnCode );
  137. // Get the current config for this video card (as last set by control panel or the default if not)
  138. virtual bool UpdateConfig( bool forceUpdate );
  139. virtual bool OverrideConfig( const MaterialSystem_Config_t &config, bool bForceUpdate );
  140. const MaterialSystem_Config_t & GetCurrentConfigForVideoCard() const;
  141. // Gets *recommended* configuration information associated with the display card and dxsupport.
  142. virtual bool GetRecommendedVideoConfig( KeyValues *pKeyValues );
  143. virtual bool GetRecommendedConfigurationInfo( int nDXLevel, KeyValues * pKeyValues );
  144. // IShaderUtil
  145. MaterialSystem_Config_t & GetConfig();
  146. private:
  147. //---------------------------------
  148. // This is called when the config changes
  149. void GenerateConfigFromConfigKeyValues( MaterialSystem_Config_t *pConfig, bool bOverwriteCommandLineValues );
  150. // Read/write config into convars
  151. void ReadConfigFromConVars( MaterialSystem_Config_t *pConfig );
  152. void WriteConfigIntoConVars( const MaterialSystem_Config_t &config );
  153. public:
  154. // -----------------------------------------------------------
  155. // Device methods
  156. // -----------------------------------------------------------
  157. int GetDisplayAdapterCount() const;
  158. int GetCurrentAdapter() const;
  159. void GetDisplayAdapterInfo( int adapter, MaterialAdapterInfo_t& info ) const;
  160. int GetModeCount( int adapter ) const;
  161. void GetModeInfo( int adapter, int mode, MaterialVideoMode_t& info ) const;
  162. void AddModeChangeCallBack( ModeChangeCallbackFunc_t func );
  163. void RemoveModeChangeCallBack( ModeChangeCallbackFunc_t func );
  164. // Returns the mode info for the current display device
  165. void GetDisplayMode( MaterialVideoMode_t& info ) const;
  166. bool SetMode( void* hwnd, const MaterialSystem_Config_t &config );
  167. // Reports support for a given MSAA mode
  168. bool SupportsMSAAMode( int nMSAAMode );
  169. // Reports support for a given CSAA mode
  170. bool SupportsCSAAMode( int nNumSamples, int nQualityLevel );
  171. bool SupportsHDRMode( HDRType_t nHDRModede );
  172. bool UsesSRGBCorrectBlending() const;
  173. // Shadow depth bias factors
  174. void SetShadowDepthBiasFactors( float fShadowSlopeScaleDepthBias, float fShadowDepthBias );
  175. void FlipCulling( bool bFlipCulling );
  176. const MaterialSystemHardwareIdentifier_t &GetVideoCardIdentifier() const;
  177. // Use this to spew information about the 3D layer
  178. void SpewDriverInfo() const;
  179. DELEGATE_TO_OBJECT_2VC( GetBackBufferDimensions, int &, int &, g_pShaderDevice );
  180. DELEGATE_TO_OBJECT_0C( ImageFormat, GetBackBufferFormat, g_pShaderDevice );
  181. DELEGATE_TO_OBJECT_0C( const AspectRatioInfo_t &, GetAspectRatioInfo, g_pShaderAPI );
  182. DELEGATE_TO_OBJECT_1V( PushDeformation, DeformationBase_t const *, g_pShaderAPI );
  183. DELEGATE_TO_OBJECT_0V( PopDeformation, g_pShaderAPI );
  184. DELEGATE_TO_OBJECT_0C(int, GetNumActiveDeformations, g_pShaderAPI );
  185. // -----------------------------------------------------------
  186. // Window methods
  187. // -----------------------------------------------------------
  188. // Creates/ destroys a child window
  189. bool AddView( void* hwnd );
  190. void RemoveView( void* hwnd );
  191. // Sets the view
  192. void SetView( void* hwnd );
  193. // -----------------------------------------------------------
  194. // Control flow
  195. // -----------------------------------------------------------
  196. void BeginFrame( float frameTime );
  197. void EndFrame();
  198. virtual bool IsInFrame( ) const;
  199. void Flush( bool flushHardware = false );
  200. void SwapBuffers();
  201. uint32 GetCurrentFrameCount();
  202. // Flushes managed textures from the texture cacher
  203. void EvictManagedResources();
  204. void ReleaseResources();
  205. void ReacquireResources();
  206. // Recomputes a state snapshot
  207. void RecomputeAllStateSnapshots();
  208. void NoteAnisotropicLevel( int currentLevel );
  209. // -----------------------------------------------------------
  210. // Device loss/restore
  211. // -----------------------------------------------------------
  212. // Installs a function to be called when we need to release vertex buffers
  213. void AddReleaseFunc( MaterialBufferReleaseFunc_t func );
  214. void RemoveReleaseFunc( MaterialBufferReleaseFunc_t func );
  215. // Installs a function to be called when we need to restore vertex buffers
  216. void AddRestoreFunc( MaterialBufferRestoreFunc_t func );
  217. void RemoveRestoreFunc( MaterialBufferRestoreFunc_t func );
  218. // Called by the shader API when it's just about to lose video memory
  219. void ReleaseShaderObjects( int nChangeFlags );
  220. void RestoreShaderObjects( CreateInterfaceFn shaderFactory, int nChangeFlags = 0 );
  221. // Installs a function to be called when we need to delete objects at the end of the render frame
  222. virtual void AddEndFrameCleanupFunc( EndFrameCleanupFunc_t func );
  223. virtual void RemoveEndFrameCleanupFunc( EndFrameCleanupFunc_t func );
  224. // Gets called when the level is shuts down, will call the registered callback
  225. virtual void OnLevelShutdown();
  226. // Installs a function to be called when the level is shuts down
  227. virtual bool AddOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData );
  228. virtual bool RemoveOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData );
  229. // Installs a function to be called when we need to perform operation before next rendering context is started
  230. virtual void AddEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func );
  231. virtual void RemoveEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func );
  232. virtual void OnLevelLoadingComplete();
  233. // Release temporary HW memory...
  234. void ResetTempHWMemory( bool bExitingLevel = false );
  235. // For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
  236. void HandleDeviceLost();
  237. // -----------------------------------------------------------
  238. // Shaders
  239. // -----------------------------------------------------------
  240. int ShaderCount() const;
  241. int GetShaders( int nFirstShader, int nCount, IShader **ppShaderList ) const;
  242. int ShaderFlagCount() const;
  243. const char * ShaderFlagName( int nIndex ) const;
  244. void GetShaderFallback( const char *pShaderName, char *pFallbackShader, int nFallbackLength );
  245. // -----------------------------------------------------------
  246. // Material proxies
  247. // -----------------------------------------------------------
  248. IMaterialProxyFactory* GetMaterialProxyFactory();
  249. void SetMaterialProxyFactory( IMaterialProxyFactory* pFactory );
  250. IClientMaterialSystem* GetClientMaterialSystemInterface();
  251. // -----------------------------------------------------------
  252. // Refresh the spinner on load screens
  253. // -----------------------------------------------------------
  254. void RefreshFrontBufferNonInteractive();
  255. virtual uint32 GetFrameTimestamps( ApplicationPerformanceCountersInfo_t &apci, ApplicationInstantCountersInfo_t & aici );
  256. bool CanDownloadTextures() const;
  257. // -----------------------------------------------------------
  258. // Editor mode
  259. // -----------------------------------------------------------
  260. bool InEditorMode() const;
  261. // Used to enable editor materials. Must be called before Init.
  262. void EnableEditorMaterials();
  263. void EnableGBuffers( void );
  264. // Can we use editor materials?
  265. bool CanUseEditorMaterials( void ) const;
  266. int GetConfigurationFlags( void ) const;
  267. // -----------------------------------------------------------
  268. // Stub mode mode
  269. // -----------------------------------------------------------
  270. void SetInStubMode( bool bInStubMode );
  271. bool IsInStubMode();
  272. //---------------------------------------------------------
  273. // Image formats
  274. //---------------------------------------------------------
  275. ImageFormatInfo_t const& ImageFormatInfo( ImageFormat fmt) const;
  276. int GetMemRequired( int width, int height, int depth, ImageFormat format, bool mipmap );
  277. bool ConvertImageFormat( unsigned char *src, enum ImageFormat srcImageFormat,
  278. unsigned char *dst, enum ImageFormat dstImageFormat,
  279. int width, int height, int srcStride = 0, int dstStride = 0 );
  280. //---------------------------------------------------------
  281. // Debug support
  282. //---------------------------------------------------------
  283. void CreateDebugMaterials();
  284. void CleanUpDebugMaterials();
  285. void CleanUpErrorMaterial();
  286. void DebugPrintUsedMaterials( const char *pSearchSubString, bool bVerbose );
  287. void DebugPrintUsedTextures();
  288. void ToggleSuppressMaterial( const char* pMaterialName );
  289. void ToggleDebugMaterial( const char* pMaterialName );
  290. //---------------------------------------------------------
  291. // Misc features
  292. //---------------------------------------------------------
  293. //returns whether fast clipping is being used or not - needed to be exposed for better per-object clip behavior
  294. bool UsingFastClipping();
  295. int StencilBufferBits();
  296. //---------------------------------------------------------
  297. // Standard material and textures
  298. //---------------------------------------------------------
  299. void AllocateStandardTextures();
  300. void ReleaseStandardTextures();
  301. IMaterialInternal * GetDrawFlatMaterial() { return m_pDrawFlatMaterial; }
  302. IMaterialInternal * GetBufferClearObeyStencil( int i ) { return m_pBufferClearObeyStencil[i]; }
  303. IMaterialInternal * GetReloadZcullMaterial() { return m_pReloadZcullMaterial; }
  304. IMaterialInternal * GetRenderTargetBlitMaterial() { return m_pRenderTargetBlitMaterial; }
  305. ShaderAPITextureHandle_t GetFullbrightLightmapTextureHandle() const { return m_FullbrightLightmapTextureHandle; }
  306. ShaderAPITextureHandle_t GetFullbrightBumpedLightmapTextureHandle() const { return m_FullbrightBumpedLightmapTextureHandle; }
  307. ShaderAPITextureHandle_t GetBlackTextureHandle() const { return m_BlackTextureHandle; }
  308. ShaderAPITextureHandle_t GetBlackAlphaZeroTextureHandle() const { return m_BlackAlphaZeroTextureHandle; }
  309. ShaderAPITextureHandle_t GetFlatNormalTextureHandle() const { return m_FlatNormalTextureHandle; }
  310. ShaderAPITextureHandle_t GetFlatSSBumpTextureHandle() const { return m_FlatSSBumpTextureHandle; }
  311. ShaderAPITextureHandle_t GetGreyTextureHandle() const { return m_GreyTextureHandle; }
  312. ShaderAPITextureHandle_t GetGreyAlphaZeroTextureHandle() const { return m_GreyAlphaZeroTextureHandle; }
  313. ShaderAPITextureHandle_t GetWhiteTextureHandle() const { return m_WhiteTextureHandle; }
  314. ShaderAPITextureHandle_t GetLinearToGammaTableTextureHandle() const { return m_LinearToGammaTableTextureHandle; }
  315. ShaderAPITextureHandle_t GetLinearToGammaIdentityTableTextureHandle() const { return m_LinearToGammaIdentityTableTextureHandle; }
  316. ShaderAPITextureHandle_t GetMaxDepthTextureHandle() const { return m_MaxDepthTextureHandle; }
  317. //---------------------------------------------------------
  318. // Material and texture management
  319. //---------------------------------------------------------
  320. void UncacheAllMaterials();
  321. void UncacheUnusedMaterials( bool bRecomputeStateSnapshots );
  322. void CacheUsedMaterials();
  323. void ReloadTextures();
  324. void ReloadMaterials( const char *pSubString = NULL );
  325. // Create new materials
  326. IMaterial * CreateMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues );
  327. IMaterial * FindMaterial( const char *materialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL );
  328. virtual IMaterial * FindProceduralMaterial( const char *pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues = NULL );
  329. const char * GetForcedTextureLoadPathID() { return m_pForcedTextureLoadPathID; }
  330. bool LoadKeyValuesFromVMTFile( KeyValues &vmtKeyValues, const char *pMaterialName, bool bUsesUNCFilename );
  331. //---------------------------------
  332. DELEGATE_TO_OBJECT_0C( MaterialHandle_t, FirstMaterial, &m_MaterialDict );
  333. DELEGATE_TO_OBJECT_1C( MaterialHandle_t, NextMaterial, MaterialHandle_t, &m_MaterialDict );
  334. DELEGATE_TO_OBJECT_0C( MaterialHandle_t, InvalidMaterial, &m_MaterialDict );
  335. DELEGATE_TO_OBJECT_1C( IMaterial *, GetMaterial, MaterialHandle_t, &m_MaterialDict );
  336. DELEGATE_TO_OBJECT_1C( IMaterialInternal *, GetMaterialInternal, MaterialHandle_t, &m_MaterialDict );
  337. DELEGATE_TO_OBJECT_0C( int, GetNumMaterials, &m_MaterialDict );
  338. DELEGATE_TO_OBJECT_1V( AddMaterialToMaterialList, IMaterialInternal *, &m_MaterialDict );
  339. DELEGATE_TO_OBJECT_1V( RemoveMaterial, IMaterialInternal *, &m_MaterialDict );
  340. DELEGATE_TO_OBJECT_1V( RemoveMaterialSubRect, IMaterialInternal *, &m_MaterialDict );
  341. //---------------------------------
  342. ITexture * FindTexture( const char* pTextureName, const char *pTextureGroupName, bool complain = true, int nAdditionalCreationFlags = 0 );
  343. bool IsTextureLoaded( const char* pTextureName ) const;
  344. bool GetTextureInformation( char const *szTextureName, MaterialTextureInfo_t &info ) const;
  345. void AddTextureAlias( const char *pAlias, const char *pRealName );
  346. void RemoveTextureAlias( const char *pAlias );
  347. void SetExcludedTextures( const char *pScriptName, bool bUsingWeaponModelCache );
  348. void UpdateExcludedTextures( void );
  349. void ClearForceExcludes( void );
  350. // Creates a procedural texture
  351. ITexture * CreateProceduralTexture( const char *pTextureName,
  352. const char *pTextureGroupName,
  353. int w,
  354. int h,
  355. ImageFormat fmt,
  356. int nFlags );
  357. virtual ICustomMaterialManager *GetCustomMaterialManager();
  358. virtual ICompositeTextureGenerator *GetCompositeTextureGenerator();
  359. #if defined( _X360 )
  360. // Create a texture for displaying gamerpics.
  361. // This function allocates the texture in the correct gamerpic format, but it does not fill in the gamerpic data.
  362. virtual ITexture * CreateGamerpicTexture( const char *pTextureName,
  363. const char *pTextureGroupName,
  364. int nFlags );
  365. // Update the given texture with the player gamerpic for the local player at the given index.
  366. // Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
  367. virtual bool UpdateLocalGamerpicTexture( ITexture *pTexture, DWORD userIndex );
  368. // Update the given texture with a remote player's gamerpic.
  369. // Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
  370. virtual bool UpdateRemoteGamerpicTexture( ITexture *pTexture, XUID xuid );
  371. #endif // _X360
  372. //
  373. // Render targets
  374. //
  375. void BeginRenderTargetAllocation();
  376. void EndRenderTargetAllocation(); // Simulate an Alt-Tab in here, which causes a release/restore of all resources
  377. void FinishRenderTargetAllocation( void );
  378. void ReEnableRenderTargetAllocation_IRealizeIfICallThisAllTexturesWillBeUnloadedAndLoadTimeWillSufferHorribly( void );
  379. // Creates a texture for use as a render target
  380. ITexture * CreateRenderTargetTexture( int w,
  381. int h,
  382. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  383. ImageFormat format,
  384. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED );
  385. ITexture * CreateNamedRenderTargetTextureEx( const char *pRTName, // Pass in NULL here for an unnamed render target.
  386. int w,
  387. int h,
  388. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  389. ImageFormat format,
  390. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  391. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  392. unsigned int renderTargetFlags = 0 );
  393. ITexture * CreateNamedRenderTargetTexture( const char *pRTName,
  394. int w,
  395. int h,
  396. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  397. ImageFormat format,
  398. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  399. bool bClampTexCoords = true,
  400. bool bAutoMipMap = false );
  401. ITexture * CreateNamedRenderTargetTextureEx2( const char *pRTName, // Pass in NULL here for an unnamed render target.
  402. int w,
  403. int h,
  404. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  405. ImageFormat format,
  406. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  407. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  408. unsigned int renderTargetFlags = 0 );
  409. ITexture * CreateNamedMultiRenderTargetTexture( const char *pRTName, // Pass in NULL here for an unnamed render target.
  410. int w,
  411. int h,
  412. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  413. ImageFormat format,
  414. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  415. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  416. unsigned int renderTargetFlags = 0 );
  417. // -----------------------------------------------------------
  418. bool OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices );
  419. bool OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists );
  420. bool OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices );
  421. DELEGATE_TO_OBJECT_3( bool, OnSetFlexMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
  422. DELEGATE_TO_OBJECT_3( bool, OnSetColorMesh, IMesh *, IMesh *, int, GetRenderContextInternal() );
  423. DELEGATE_TO_OBJECT_2( bool, OnSetPrimitiveType, IMesh *, MaterialPrimitiveType_t, GetRenderContextInternal() );
  424. DELEGATE_TO_OBJECT_0V( SyncMatrices, GetRenderContextInternal() );
  425. DELEGATE_TO_OBJECT_1V( SyncMatrix, MaterialMatrixMode_t, GetRenderContextInternal() );
  426. void OnThreadEvent( uint32 threadEvent );
  427. DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetLightmapTexture, ShaderAPITextureHandle_t, GetRenderContextInternal() );
  428. DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetPaintmapTexture, ShaderAPITextureHandle_t, GetRenderContextInternal() );
  429. // -----------------------------------------------------------
  430. // Lightmaps delegates
  431. // -----------------------------------------------------------
  432. DELEGATE_TO_OBJECT_0V( BeginLightmapAllocation, &m_Lightmaps );
  433. void EndLightmapAllocation()
  434. {
  435. GetLightmaps()->EndLightmapAllocation();
  436. AllocateStandardTextures();
  437. }
  438. void CleanupLightmaps()
  439. {
  440. GetLightmaps()->CleanupLightmaps();
  441. }
  442. DELEGATE_TO_OBJECT_4( int, AllocateLightmap, int, int, LightmapOffset_t, IMaterial *, &m_Lightmaps );
  443. DELEGATE_TO_OBJECT_1( int, AllocateWhiteLightmap, IMaterial *, &m_Lightmaps );
  444. DELEGATE_TO_OBJECT_3( int, AllocateDynamicLightmap, LightmapOffset_t, int *, int, &m_Lightmaps );
  445. void UpdateLightmap( int, LightmapOffset_t, LightmapOffset_t, float *, float *, float *, float * );
  446. DELEGATE_TO_OBJECT_0( int, GetNumSortIDs, &m_Lightmaps );
  447. DELEGATE_TO_OBJECT_1V( GetSortInfo, MaterialSystem_SortInfo_t *, &m_Lightmaps );
  448. DELEGATE_TO_OBJECT_3VC( GetLightmapPageSize, int, int *, int *, &m_Lightmaps );
  449. DELEGATE_TO_OBJECT_0V( ResetMaterialLightmapPageInfo, &m_Lightmaps );
  450. DELEGATE_TO_OBJECT_0C( int, GetNumLightmapPages, &m_Lightmaps );
  451. DELEGATE_TO_OBJECT_1C( int, GetLightmapWidth, int, &m_Lightmaps );
  452. DELEGATE_TO_OBJECT_1C( int, GetLightmapHeight, int, &m_Lightmaps );
  453. DELEGATE_TO_OBJECT_0V( BeginUpdateLightmaps, &m_Lightmaps );
  454. DELEGATE_TO_OBJECT_0V( EndUpdateLightmaps, &m_Lightmaps );
  455. // -----------------------------------------------------------
  456. // Paint map delegates
  457. // -----------------------------------------------------------
  458. DELEGATE_TO_OBJECT_1( void, RegisterPaintmapDataManager, IPaintmapDataManager *, &m_Paintmaps );
  459. DELEGATE_TO_OBJECT_0V( BeginUpdatePaintmaps, &m_Paintmaps );
  460. DELEGATE_TO_OBJECT_0V( EndUpdatePaintmaps, &m_Paintmaps );
  461. void UpdatePaintmap( int paintmap, BYTE* pPaintData, int numRects, Rect_t* pRects );
  462. // -----------------------------------------------------------
  463. // Stereo
  464. // -----------------------------------------------------------
  465. bool IsStereoSupported();
  466. bool IsStereoActiveThisFrame() const;
  467. void NVStereoUpdate();
  468. bool m_bStereoBoolsInitialized;
  469. bool m_bIsStereoSupported;
  470. bool m_bIsStereoActiveThisFrame;
  471. // -----------------------------------------------------------
  472. // Render context delegates
  473. // -----------------------------------------------------------
  474. // IMaterialSystem
  475. DELEGATE_TO_OBJECT_3V( ClearBuffers, bool, bool, bool, GetRenderContextInternal() );
  476. // IMaterialSystemInternal
  477. DELEGATE_TO_OBJECT_0( IMaterial *, GetCurrentMaterial, GetRenderContextInternal() );
  478. DELEGATE_TO_OBJECT_0( int, GetLightmapPage, GetRenderContextInternal() );
  479. DELEGATE_TO_OBJECT_0( ITexture *, GetLocalCubemap, GetRenderContextInternal() );
  480. DELEGATE_TO_OBJECT_1V( ForceDepthFuncEquals, bool, GetRenderContextInternal() );
  481. DELEGATE_TO_OBJECT_0( MaterialHeightClipMode_t, GetHeightClipMode, GetRenderContextInternal() );
  482. DELEGATE_TO_OBJECT_0C( bool, InFlashlightMode, GetRenderContextInternal() );
  483. DELEGATE_TO_OBJECT_0C( bool, IsRenderingPaint, GetRenderContextInternal() );
  484. DELEGATE_TO_OBJECT_0C( bool, IsCascadedShadowMapping, GetRenderContextInternal() );
  485. // IShaderUtil
  486. DELEGATE_TO_OBJECT_3V( BindStandardTexture, Sampler_t, TextureBindFlags_t, StandardTextureId_t, &m_HardwareRenderContext );
  487. DELEGATE_TO_OBJECT_1( ShaderAPITextureHandle_t, GetStandardTexture, StandardTextureId_t, &m_HardwareRenderContext );
  488. DELEGATE_TO_OBJECT_2V( BindStandardVertexTexture, VertexTextureSampler_t, StandardTextureId_t, &m_HardwareRenderContext );
  489. DELEGATE_TO_OBJECT_2V( GetLightmapDimensions, int *, int *, &m_HardwareRenderContext );
  490. DELEGATE_TO_OBJECT_3V( GetStandardTextureDimensions, int *, int *, StandardTextureId_t, &m_HardwareRenderContext );
  491. DELEGATE_TO_OBJECT_0( float, GetSubDHeight, &m_HardwareRenderContext );
  492. DELEGATE_TO_OBJECT_0( MorphFormat_t, GetBoundMorphFormat, &m_HardwareRenderContext );
  493. DELEGATE_TO_OBJECT_1( ITexture *, GetRenderTargetEx, int, &m_HardwareRenderContext );
  494. DELEGATE_TO_OBJECT_7V( DrawClearBufferQuad, unsigned char, unsigned char, unsigned char, unsigned char, bool, bool, bool, &m_HardwareRenderContext );
  495. #if defined( _PS3 )
  496. DELEGATE_TO_OBJECT_0V( DrawReloadZcullQuad, &m_HardwareRenderContext );
  497. #endif // _PS3
  498. DELEGATE_TO_OBJECT_0C( int, MaxHWMorphBatchCount, g_pMorphMgr );
  499. DELEGATE_TO_OBJECT_1V( GetCurrentColorCorrection, ShaderColorCorrectionInfo_t*, g_pColorCorrectionSystem );
  500. virtual ShaderAPITextureHandle_t GetShaderAPITextureBindHandle( ITexture *pTexture, int nFrameVar, int nTextureChannel = 0 );
  501. #if defined( _X360 )
  502. void ListUsedMaterials();
  503. HXUIFONT OpenTrueTypeFont( const char *pFontname, int tall, int style );
  504. void CloseTrueTypeFont( HXUIFONT hFont );
  505. bool GetTrueTypeFontMetrics( HXUIFONT hFont, wchar_t wchFirst, wchar_t wchLast, XUIFontMetrics *pFontMetrics, XUICharMetrics *pCharMetrics );
  506. // Render a sequence of characters and extract the data into a buffer
  507. // For each character, provide the width+height of the font texture subrect,
  508. // an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
  509. bool GetTrueTypeGlyphs( HXUIFONT hFont, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pOffset );
  510. void ReadBackBuffer( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pData, ImageFormat dstFormat, int nDstStride );
  511. void PersistDisplay();
  512. void *GetD3DDevice();
  513. bool OwnGPUResources( bool bEnable );
  514. #elif defined( _PS3 )
  515. void ListUsedMaterials();
  516. virtual HPS3FONT OpenTrueTypeFont( const char *pFontname, int tall, int style );
  517. virtual void CloseTrueTypeFont( HPS3FONT hFont );
  518. virtual bool GetTrueTypeFontMetrics( HPS3FONT hFont, int nFallbackTall, wchar_t wchFirst, wchar_t wchLast, CPS3FontMetrics *pFontMetrics, CPS3CharMetrics *pCharMetrics );
  519. // Render a sequence of characters and extract the data into a buffer
  520. // For each character, provide the width+height of the font texture subrect,
  521. // an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
  522. virtual bool GetTrueTypeGlyphs( HPS3FONT hFont, int nFallbackTall, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pRGBAOffset );
  523. virtual void TransmitScreenshotToVX();
  524. virtual void CompactRsxLocalMemory( char const *szReason );
  525. virtual void SetFlipPresentFrequency( int nNumVBlanks );
  526. static void RunQMS(void* cmat, void* ptr)
  527. {
  528. ((CMaterialSystem*)cmat)->ThreadExecuteQueuedContext((CMatQueuedRenderContext *)ptr);
  529. }
  530. #endif
  531. virtual void SpinPresent( uint nFrames );
  532. MaterialLock_t Lock();
  533. void Unlock( MaterialLock_t );
  534. CMatCallQueue * GetRenderCallQueue();
  535. uint GetRenderThreadId() const { return m_nRenderThreadID; }
  536. void UnbindMaterial( IMaterial *pMaterial );
  537. virtual void CompactMemory();
  538. // Get stats on GPU memory usage
  539. virtual void GetGPUMemoryStats( GPUMemoryStats &stats );
  540. bool IsLevelLoadingComplete() const;
  541. void OnAsyncTextureDataComplete( AsyncTextureContext_t *pContext, void *pData, int nNumReadBytes, AsyncTextureLoadError_t loadError );
  542. // -----------------------------------------------------------
  543. private:
  544. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterials", DebugPrintUsedMaterials, "Show materials.", 0 );
  545. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showmaterialsverbose", DebugPrintUsedMaterialsVerbose, "Show materials (verbose version).", 0 );
  546. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showtextures", DebugPrintUsedTextures, "Show used textures.", 0 );
  547. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadallmaterials", ReloadAllMaterials, "Reloads all materials", FCVAR_CHEAT );
  548. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadmaterial", ReloadMaterials, "Reloads a single material", FCVAR_CHEAT );
  549. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_reloadtextures", ReloadTextures, "Reloads all textures", FCVAR_CHEAT );
  550. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_showaspectratioinfo", DebugPrintAspectRatioInfo, "Spew info about the hardware aspect ratio", FCVAR_DEVELOPMENTONLY );
  551. #if defined( _X360 ) || defined(_PS3)
  552. CON_COMMAND_MEMBER_F( CMaterialSystem, "mat_material_list", ListUsedMaterials, "Show used textures.", 0 );
  553. #endif
  554. friend void* InstantiateMaterialSystemV76Interface();
  555. friend CMaterialSystem *CMatLightmaps::GetMaterialSystem() const;
  556. friend CMaterialSystem *CMatPaintmaps::GetMaterialSystem() const;
  557. void ThreadExecuteQueuedContext( CMatQueuedRenderContext *pContext );
  558. IThreadPool * CreateMatQueueThreadPool();
  559. void DestroyMatQueueThreadPool();
  560. #if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
  561. void DoStartupShaderPreloading( void );
  562. #endif
  563. void ServiceAsyncTextureLoads();
  564. void ServiceEndFramePriorToNextContext();
  565. // -----------------------------------------------------------
  566. CMaterialDict m_MaterialDict;
  567. CMatLightmaps m_Lightmaps;
  568. CMatPaintmaps m_Paintmaps;
  569. #if defined(_X360)
  570. static IMatRenderContextInternal *CMaterialSystem::m_pRenderContexts[2];
  571. #elif !defined(_PS3)
  572. static CTHREADLOCALPTR(IMatRenderContextInternal) m_pRenderContext;
  573. #endif
  574. CMatRenderContext m_HardwareRenderContext;
  575. CMatQueuedRenderContext m_QueuedRenderContexts[2];
  576. int m_iCurQueuedContext;
  577. MaterialThreadMode_t m_ThreadMode;
  578. MaterialThreadMode_t m_IdealThreadMode;
  579. int m_nServiceThread;
  580. //---------------------------------
  581. char * m_pShaderDLL;
  582. CSysModule * m_ShaderHInst; // Used to dynamically load the shader DLL
  583. CreateInterfaceFn m_ShaderAPIFactory;
  584. int m_nAdapter;
  585. int m_nAdapterFlags;
  586. int m_nConfigurationFlags; // MATCONFIG_FLAGS_xxxx
  587. ShaderDisplayMode_t m_nAdapterInfo;
  588. //---------------------------------
  589. IMaterialProxyFactory * m_pMaterialProxyFactory;
  590. IClientMaterialSystem * m_pClientMaterialSystemInterface;
  591. //---------------------------------
  592. // Callback methods for releasing + restoring video memory
  593. CUtlVector< MaterialBufferReleaseFunc_t > m_ReleaseFunc;
  594. CUtlVector< MaterialBufferRestoreFunc_t > m_RestoreFunc;
  595. CUtlVector< EndFrameCleanupFunc_t > m_EndFrameCleanupFunc;
  596. class COnLevelShutdownFunc
  597. {
  598. public:
  599. COnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData )
  600. :
  601. m_Func(func),
  602. m_pUserData(pUserData)
  603. {
  604. // Do nothing... Is there a CUtlPair class or something like that?
  605. }
  606. bool operator==(const COnLevelShutdownFunc & other) const
  607. {
  608. return ( (m_Func == other.m_Func) && (m_pUserData == other.m_pUserData) );
  609. }
  610. OnLevelShutdownFunc_t m_Func;
  611. void * m_pUserData;
  612. };
  613. CUtlVector< COnLevelShutdownFunc > m_OnLevelShutdownFuncs;
  614. CUtlVector< EndFramePriorToNextContextFunc_t > m_EndFramePriorToNextContextFunc;
  615. //---------------------------------
  616. bool m_bRequestedEditorMaterials;
  617. bool m_bRequestedGBuffers;
  618. //---------------------------------
  619. // Store texids for various things
  620. ShaderAPITextureHandle_t m_FullbrightLightmapTextureHandle;
  621. ShaderAPITextureHandle_t m_FullbrightBumpedLightmapTextureHandle;
  622. ShaderAPITextureHandle_t m_BlackTextureHandle;
  623. ShaderAPITextureHandle_t m_BlackAlphaZeroTextureHandle;
  624. ShaderAPITextureHandle_t m_FlatNormalTextureHandle;
  625. ShaderAPITextureHandle_t m_FlatSSBumpTextureHandle;
  626. ShaderAPITextureHandle_t m_GreyTextureHandle;
  627. ShaderAPITextureHandle_t m_GreyAlphaZeroTextureHandle;
  628. ShaderAPITextureHandle_t m_WhiteTextureHandle;
  629. ShaderAPITextureHandle_t m_LinearToGammaTableTextureHandle; //linear to gamma srgb conversion lookup for the current hardware
  630. ShaderAPITextureHandle_t m_LinearToGammaIdentityTableTextureHandle; //An identity lookup for when srgb writes are off
  631. ShaderAPITextureHandle_t m_MaxDepthTextureHandle; //a 1x1 texture with maximum depth values.
  632. // Have we allocated the standard lightmaps?
  633. bool m_StandardTexturesAllocated;
  634. // Do we need to restore mananged resources next time RestoreShaderObjects is called
  635. bool m_bRestoreManangedResources;
  636. // Deferred material reload ( so we don't call it when ALT-TABd
  637. bool m_bDeferredMaterialReload;
  638. char *m_pSubString; // allocated substring for deferred material reload
  639. //---------------------------------
  640. // Shared materials used for debugging....
  641. //---------------------------------
  642. enum BufferClearType_t //bClearColor + ( bClearAlpha << 1 ) + ( bClearDepth << 2 )
  643. {
  644. BUFFER_CLEAR_NONE,
  645. BUFFER_CLEAR_COLOR,
  646. BUFFER_CLEAR_ALPHA,
  647. BUFFER_CLEAR_COLOR_AND_ALPHA,
  648. BUFFER_CLEAR_DEPTH,
  649. BUFFER_CLEAR_COLOR_AND_DEPTH,
  650. BUFFER_CLEAR_ALPHA_AND_DEPTH,
  651. BUFFER_CLEAR_COLOR_AND_ALPHA_AND_DEPTH,
  652. BUFFER_CLEAR_TYPE_COUNT
  653. };
  654. IMaterialInternal * m_pBufferClearObeyStencil[BUFFER_CLEAR_TYPE_COUNT];
  655. IMaterialInternal * m_pReloadZcullMaterial;
  656. IMaterialInternal * m_pDrawFlatMaterial;
  657. IMaterialInternal * m_pRenderTargetBlitMaterial;
  658. IMaterialInternal * m_pBIKPreloadMaterial; // PORTAL2 - a dummy material which is used to ensure that the (~2 KB) bink shaders are always loaded
  659. //---------------------------------
  660. const char * m_pForcedTextureLoadPathID;
  661. uint m_nRenderThreadID;
  662. // nesting counter for render target allocation
  663. int m_nAllocatingRenderTargets;
  664. bool m_bDisableRenderTargetAllocationForever;
  665. bool m_bInStubMode;
  666. bool m_bGeneratedConfig;
  667. bool m_bInFrame;
  668. bool m_bForcedSingleThreaded;
  669. bool m_bAllowQueuedRendering;
  670. bool m_bThreadHasOwnership;
  671. bool m_bLevelLoadingComplete;
  672. CTSQueue< AsyncTextureLoad_t > m_QueuedAsyncTextureLoads;
  673. AsyncTextureLoad_t m_AsyncTextureLoad;
  674. AsyncTextureLoad_t * m_pActiveAsyncTextureLoad;
  675. //---------------------------------
  676. CCustomMaterialManager m_CustomMaterialManager;
  677. CCompositeTextureGenerator m_CompositeTextureGenerator;
  678. #ifdef DX_TO_GL_ABSTRACTION
  679. uint m_ThreadOwnershipID;
  680. #endif
  681. #ifndef _PS3
  682. CJob * m_pActiveAsyncJob;
  683. #else
  684. bool m_bQMSJobSubmitted;
  685. #endif
  686. CUtlVector<uint32> m_threadEvents;
  687. IThreadPool * m_pMatQueueThreadPool;
  688. #if defined(_PS3) // some PS3-specific font info (hey, it was either do this or have a pointer to a pimpl struct)
  689. CUtlVector< HPS3FONT > m_vExtantFonts; // used to catch leaks -- can't store a vector of the CellFonts directly bc the handle is a pointer and can't store pointers into a vector
  690. void InitializePS3Fonts();
  691. enum { kPS3_DEFAULT_MAX_USER_FONTS = 256 };
  692. public:
  693. virtual bool PS3InitFontLibrary( unsigned fontFileCacheSizeInBytes, unsigned maxNumFonts );
  694. virtual void PS3DumpFontLibrary();
  695. virtual void *PS3GetFontLibPtr();
  696. protected:
  697. #else
  698. inline void InitializePS3Fonts(){};
  699. #endif
  700. };
  701. //-----------------------------------------------------------------------------
  702. inline CMaterialSystem *CMatLightmaps::GetMaterialSystem() const
  703. {
  704. return GET_OUTER( CMaterialSystem, m_Lightmaps );
  705. }
  706. inline CMaterialSystem *CMatPaintmaps::GetMaterialSystem() const
  707. {
  708. return GET_OUTER( CMaterialSystem, m_Paintmaps );
  709. }
  710. //-----------------------------------------------------------------------------
  711. #endif // CMATERIALSYSTEM_H