Team Fortress 2 Source Code as on 22/4/2020
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.

1828 lines
70 KiB

  1. //========= Copyright Valve Corporation, All rights reserved. ============//
  2. //
  3. // Purpose:
  4. //
  5. // $NoKeywords: $
  6. //
  7. //===========================================================================//
  8. #ifndef IMATERIALSYSTEM_H
  9. #define IMATERIALSYSTEM_H
  10. #ifdef _WIN32
  11. #pragma once
  12. #endif
  13. #define OVERBRIGHT 2.0f
  14. #define OO_OVERBRIGHT ( 1.0f / 2.0f )
  15. #define GAMMA 2.2f
  16. #define TEXGAMMA 2.2f
  17. #include "mathlib/vector.h"
  18. #include "mathlib/vector4d.h"
  19. #include "mathlib/vmatrix.h"
  20. #include "tier1/interface.h"
  21. #include "tier1/refcount.h"
  22. #include "appframework/IAppSystem.h"
  23. #include "bitmap/imageformat.h"
  24. #include "texture_group_names.h"
  25. #include "vtf/vtf.h"
  26. #include "materialsystem/deformations.h"
  27. #include "materialsystem/imaterialsystemhardwareconfig.h"
  28. #include "materialsystem/IColorCorrection.h"
  29. //-----------------------------------------------------------------------------
  30. // forward declarations
  31. //-----------------------------------------------------------------------------
  32. class IMaterial;
  33. class IMesh;
  34. class IVertexBuffer;
  35. class IIndexBuffer;
  36. struct MaterialSystem_Config_t;
  37. class VMatrix;
  38. struct matrix3x4_t;
  39. class ITexture;
  40. class ITextureCompositor;
  41. struct MaterialSystemHardwareIdentifier_t;
  42. class KeyValues;
  43. class IShader;
  44. class IVertexTexture;
  45. class IMorph;
  46. class IMatRenderContext;
  47. class ICallQueue;
  48. struct MorphWeight_t;
  49. class IFileList;
  50. //-----------------------------------------------------------------------------
  51. // The vertex format type
  52. //-----------------------------------------------------------------------------
  53. typedef uint64 VertexFormat_t;
  54. //-----------------------------------------------------------------------------
  55. // important enumeration
  56. //-----------------------------------------------------------------------------
  57. // NOTE NOTE NOTE!!!! If you up this, grep for "NEW_INTERFACE" to see if there is anything
  58. // waiting to be enabled during an interface revision.
  59. // V081 - 10/25/2016 - Added new Suspend/Resume texture streaming interfaces. Might also have added more calls here due
  60. // to the streaming work that didn't get bumped, but we're not guarding versions on the TF branch
  61. // very judiciously since we need to audit them when merging to SDK branch either way.
  62. #define MATERIAL_SYSTEM_INTERFACE_VERSION "VMaterialSystem081"
  63. #ifdef POSIX
  64. #define ABSOLUTE_MINIMUM_DXLEVEL 90
  65. #else
  66. #define ABSOLUTE_MINIMUM_DXLEVEL 80
  67. #endif
  68. enum ShaderParamType_t
  69. {
  70. SHADER_PARAM_TYPE_TEXTURE,
  71. SHADER_PARAM_TYPE_INTEGER,
  72. SHADER_PARAM_TYPE_COLOR,
  73. SHADER_PARAM_TYPE_VEC2,
  74. SHADER_PARAM_TYPE_VEC3,
  75. SHADER_PARAM_TYPE_VEC4,
  76. SHADER_PARAM_TYPE_ENVMAP, // obsolete
  77. SHADER_PARAM_TYPE_FLOAT,
  78. SHADER_PARAM_TYPE_BOOL,
  79. SHADER_PARAM_TYPE_FOURCC,
  80. SHADER_PARAM_TYPE_MATRIX,
  81. SHADER_PARAM_TYPE_MATERIAL,
  82. SHADER_PARAM_TYPE_STRING,
  83. SHADER_PARAM_TYPE_MATRIX4X2
  84. };
  85. enum MaterialMatrixMode_t
  86. {
  87. MATERIAL_VIEW = 0,
  88. MATERIAL_PROJECTION,
  89. // Texture matrices
  90. MATERIAL_TEXTURE0,
  91. MATERIAL_TEXTURE1,
  92. MATERIAL_TEXTURE2,
  93. MATERIAL_TEXTURE3,
  94. MATERIAL_TEXTURE4,
  95. MATERIAL_TEXTURE5,
  96. MATERIAL_TEXTURE6,
  97. MATERIAL_TEXTURE7,
  98. MATERIAL_MODEL,
  99. // Total number of matrices
  100. NUM_MATRIX_MODES = MATERIAL_MODEL+1,
  101. // Number of texture transforms
  102. NUM_TEXTURE_TRANSFORMS = MATERIAL_TEXTURE7 - MATERIAL_TEXTURE0 + 1
  103. };
  104. // FIXME: How do I specify the actual number of matrix modes?
  105. const int NUM_MODEL_TRANSFORMS = 53;
  106. const int MATERIAL_MODEL_MAX = MATERIAL_MODEL + NUM_MODEL_TRANSFORMS;
  107. enum MaterialPrimitiveType_t
  108. {
  109. MATERIAL_POINTS = 0x0,
  110. MATERIAL_LINES,
  111. MATERIAL_TRIANGLES,
  112. MATERIAL_TRIANGLE_STRIP,
  113. MATERIAL_LINE_STRIP,
  114. MATERIAL_LINE_LOOP, // a single line loop
  115. MATERIAL_POLYGON, // this is a *single* polygon
  116. MATERIAL_QUADS,
  117. MATERIAL_INSTANCED_QUADS, // (X360) like MATERIAL_QUADS, but uses vertex instancing
  118. // This is used for static meshes that contain multiple types of
  119. // primitive types. When calling draw, you'll need to specify
  120. // a primitive type.
  121. MATERIAL_HETEROGENOUS
  122. };
  123. enum MaterialPropertyTypes_t
  124. {
  125. MATERIAL_PROPERTY_NEEDS_LIGHTMAP = 0, // bool
  126. MATERIAL_PROPERTY_OPACITY, // int (enum MaterialPropertyOpacityTypes_t)
  127. MATERIAL_PROPERTY_REFLECTIVITY, // vec3_t
  128. MATERIAL_PROPERTY_NEEDS_BUMPED_LIGHTMAPS // bool
  129. };
  130. // acceptable property values for MATERIAL_PROPERTY_OPACITY
  131. enum MaterialPropertyOpacityTypes_t
  132. {
  133. MATERIAL_ALPHATEST = 0,
  134. MATERIAL_OPAQUE,
  135. MATERIAL_TRANSLUCENT
  136. };
  137. enum MaterialBufferTypes_t
  138. {
  139. MATERIAL_FRONT = 0,
  140. MATERIAL_BACK
  141. };
  142. enum MaterialCullMode_t
  143. {
  144. MATERIAL_CULLMODE_CCW, // this culls polygons with counterclockwise winding
  145. MATERIAL_CULLMODE_CW // this culls polygons with clockwise winding
  146. };
  147. enum MaterialIndexFormat_t
  148. {
  149. MATERIAL_INDEX_FORMAT_UNKNOWN = -1,
  150. MATERIAL_INDEX_FORMAT_16BIT = 0,
  151. MATERIAL_INDEX_FORMAT_32BIT,
  152. };
  153. enum MaterialFogMode_t
  154. {
  155. MATERIAL_FOG_NONE,
  156. MATERIAL_FOG_LINEAR,
  157. MATERIAL_FOG_LINEAR_BELOW_FOG_Z,
  158. };
  159. enum MaterialHeightClipMode_t
  160. {
  161. MATERIAL_HEIGHTCLIPMODE_DISABLE,
  162. MATERIAL_HEIGHTCLIPMODE_RENDER_ABOVE_HEIGHT,
  163. MATERIAL_HEIGHTCLIPMODE_RENDER_BELOW_HEIGHT
  164. };
  165. enum MaterialNonInteractiveMode_t
  166. {
  167. MATERIAL_NON_INTERACTIVE_MODE_NONE = -1,
  168. MATERIAL_NON_INTERACTIVE_MODE_STARTUP = 0,
  169. MATERIAL_NON_INTERACTIVE_MODE_LEVEL_LOAD,
  170. MATERIAL_NON_INTERACTIVE_MODE_COUNT,
  171. };
  172. //-----------------------------------------------------------------------------
  173. // Special morph used in decalling pass
  174. //-----------------------------------------------------------------------------
  175. #define MATERIAL_MORPH_DECAL ( (IMorph*)1 )
  176. //-----------------------------------------------------------------------------
  177. //
  178. //-----------------------------------------------------------------------------
  179. enum MaterialThreadMode_t
  180. {
  181. MATERIAL_SINGLE_THREADED,
  182. MATERIAL_QUEUED_SINGLE_THREADED,
  183. MATERIAL_QUEUED_THREADED
  184. };
  185. //-----------------------------------------------------------------------------
  186. //
  187. //-----------------------------------------------------------------------------
  188. enum MaterialContextType_t
  189. {
  190. MATERIAL_HARDWARE_CONTEXT,
  191. MATERIAL_QUEUED_CONTEXT,
  192. MATERIAL_NULL_CONTEXT
  193. };
  194. //-----------------------------------------------------------------------------
  195. //
  196. //-----------------------------------------------------------------------------
  197. enum MaterialFindContext_t
  198. {
  199. MATERIAL_FINDCONTEXT_NONE,
  200. MATERIAL_FINDCONTEXT_ISONAMODEL,
  201. };
  202. //-----------------------------------------------------------------------------
  203. // Light structure
  204. //-----------------------------------------------------------------------------
  205. #include "mathlib/lightdesc.h"
  206. #if 0
  207. enum LightType_t
  208. {
  209. MATERIAL_LIGHT_DISABLE = 0,
  210. MATERIAL_LIGHT_POINT,
  211. MATERIAL_LIGHT_DIRECTIONAL,
  212. MATERIAL_LIGHT_SPOT,
  213. };
  214. enum LightType_OptimizationFlags_t
  215. {
  216. LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION0 = 1,
  217. LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION1 = 2,
  218. LIGHTTYPE_OPTIMIZATIONFLAGS_HAS_ATTENUATION2 = 4,
  219. };
  220. struct LightDesc_t
  221. {
  222. LightType_t m_Type;
  223. Vector m_Color;
  224. Vector m_Position;
  225. Vector m_Direction;
  226. float m_Range;
  227. float m_Falloff;
  228. float m_Attenuation0;
  229. float m_Attenuation1;
  230. float m_Attenuation2;
  231. float m_Theta;
  232. float m_Phi;
  233. // These aren't used by DX8. . used for software lighting.
  234. float m_ThetaDot;
  235. float m_PhiDot;
  236. unsigned int m_Flags;
  237. LightDesc_t() {}
  238. private:
  239. // No copy constructors allowed
  240. LightDesc_t(const LightDesc_t& vOther);
  241. };
  242. #endif
  243. #define CREATERENDERTARGETFLAGS_HDR 0x00000001
  244. #define CREATERENDERTARGETFLAGS_AUTOMIPMAP 0x00000002
  245. #define CREATERENDERTARGETFLAGS_UNFILTERABLE_OK 0x00000004
  246. // XBOX ONLY:
  247. #define CREATERENDERTARGETFLAGS_NOEDRAM 0x00000008 // inhibit allocation in 360 EDRAM
  248. #define CREATERENDERTARGETFLAGS_TEMP 0x00000010 // only allocates memory upon first resolve, destroyed at level end
  249. //-----------------------------------------------------------------------------
  250. // allowed stencil operations. These match the d3d operations
  251. //-----------------------------------------------------------------------------
  252. enum StencilOperation_t
  253. {
  254. #if !defined( _X360 )
  255. STENCILOPERATION_KEEP = 1,
  256. STENCILOPERATION_ZERO = 2,
  257. STENCILOPERATION_REPLACE = 3,
  258. STENCILOPERATION_INCRSAT = 4,
  259. STENCILOPERATION_DECRSAT = 5,
  260. STENCILOPERATION_INVERT = 6,
  261. STENCILOPERATION_INCR = 7,
  262. STENCILOPERATION_DECR = 8,
  263. #else
  264. STENCILOPERATION_KEEP = D3DSTENCILOP_KEEP,
  265. STENCILOPERATION_ZERO = D3DSTENCILOP_ZERO,
  266. STENCILOPERATION_REPLACE = D3DSTENCILOP_REPLACE,
  267. STENCILOPERATION_INCRSAT = D3DSTENCILOP_INCRSAT,
  268. STENCILOPERATION_DECRSAT = D3DSTENCILOP_DECRSAT,
  269. STENCILOPERATION_INVERT = D3DSTENCILOP_INVERT,
  270. STENCILOPERATION_INCR = D3DSTENCILOP_INCR,
  271. STENCILOPERATION_DECR = D3DSTENCILOP_DECR,
  272. #endif
  273. STENCILOPERATION_FORCE_DWORD = 0x7fffffff
  274. };
  275. enum StencilComparisonFunction_t
  276. {
  277. #if !defined( _X360 )
  278. STENCILCOMPARISONFUNCTION_NEVER = 1,
  279. STENCILCOMPARISONFUNCTION_LESS = 2,
  280. STENCILCOMPARISONFUNCTION_EQUAL = 3,
  281. STENCILCOMPARISONFUNCTION_LESSEQUAL = 4,
  282. STENCILCOMPARISONFUNCTION_GREATER = 5,
  283. STENCILCOMPARISONFUNCTION_NOTEQUAL = 6,
  284. STENCILCOMPARISONFUNCTION_GREATEREQUAL = 7,
  285. STENCILCOMPARISONFUNCTION_ALWAYS = 8,
  286. #else
  287. STENCILCOMPARISONFUNCTION_NEVER = D3DCMP_NEVER,
  288. STENCILCOMPARISONFUNCTION_LESS = D3DCMP_LESS,
  289. STENCILCOMPARISONFUNCTION_EQUAL = D3DCMP_EQUAL,
  290. STENCILCOMPARISONFUNCTION_LESSEQUAL = D3DCMP_LESSEQUAL,
  291. STENCILCOMPARISONFUNCTION_GREATER = D3DCMP_GREATER,
  292. STENCILCOMPARISONFUNCTION_NOTEQUAL = D3DCMP_NOTEQUAL,
  293. STENCILCOMPARISONFUNCTION_GREATEREQUAL = D3DCMP_GREATEREQUAL,
  294. STENCILCOMPARISONFUNCTION_ALWAYS = D3DCMP_ALWAYS,
  295. #endif
  296. STENCILCOMPARISONFUNCTION_FORCE_DWORD = 0x7fffffff
  297. };
  298. //-----------------------------------------------------------------------------
  299. // Enumeration for the various fields capable of being morphed
  300. //-----------------------------------------------------------------------------
  301. enum MorphFormatFlags_t
  302. {
  303. MORPH_POSITION = 0x0001, // 3D
  304. MORPH_NORMAL = 0x0002, // 3D
  305. MORPH_WRINKLE = 0x0004, // 1D
  306. MORPH_SPEED = 0x0008, // 1D
  307. MORPH_SIDE = 0x0010, // 1D
  308. };
  309. //-----------------------------------------------------------------------------
  310. // The morph format type
  311. //-----------------------------------------------------------------------------
  312. typedef unsigned int MorphFormat_t;
  313. //-----------------------------------------------------------------------------
  314. // Standard lightmaps
  315. //-----------------------------------------------------------------------------
  316. enum StandardLightmap_t
  317. {
  318. MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE = -1,
  319. MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE_BUMP = -2,
  320. MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED = -3
  321. };
  322. struct MaterialSystem_SortInfo_t
  323. {
  324. IMaterial *material;
  325. int lightmapPageID;
  326. };
  327. #define MAX_FB_TEXTURES 4
  328. //-----------------------------------------------------------------------------
  329. // Information about each adapter
  330. //-----------------------------------------------------------------------------
  331. enum
  332. {
  333. MATERIAL_ADAPTER_NAME_LENGTH = 512
  334. };
  335. struct MaterialAdapterInfo_t
  336. {
  337. char m_pDriverName[MATERIAL_ADAPTER_NAME_LENGTH];
  338. unsigned int m_VendorID;
  339. unsigned int m_DeviceID;
  340. unsigned int m_SubSysID;
  341. unsigned int m_Revision;
  342. int m_nDXSupportLevel; // This is the *preferred* dx support level
  343. int m_nMaxDXSupportLevel;
  344. unsigned int m_nDriverVersionHigh;
  345. unsigned int m_nDriverVersionLow;
  346. };
  347. //-----------------------------------------------------------------------------
  348. // Video mode info..
  349. //-----------------------------------------------------------------------------
  350. struct MaterialVideoMode_t
  351. {
  352. int m_Width; // if width and height are 0 and you select
  353. int m_Height; // windowed mode, it'll use the window size
  354. ImageFormat m_Format; // use ImageFormats (ignored for windowed mode)
  355. int m_RefreshRate; // 0 == default (ignored for windowed mode)
  356. };
  357. // fixme: should move this into something else.
  358. struct FlashlightState_t
  359. {
  360. FlashlightState_t()
  361. {
  362. m_bEnableShadows = false; // Provide reasonable defaults for shadow depth mapping parameters
  363. m_bDrawShadowFrustum = false;
  364. m_flShadowMapResolution = 1024.0f;
  365. m_flShadowFilterSize = 3.0f;
  366. m_flShadowSlopeScaleDepthBias = 16.0f;
  367. m_flShadowDepthBias = 0.0005f;
  368. m_flShadowJitterSeed = 0.0f;
  369. m_flShadowAtten = 0.0f;
  370. m_bScissor = false;
  371. m_nLeft = -1;
  372. m_nTop = -1;
  373. m_nRight = -1;
  374. m_nBottom = -1;
  375. m_nShadowQuality = 0;
  376. }
  377. Vector m_vecLightOrigin;
  378. Quaternion m_quatOrientation;
  379. float m_NearZ;
  380. float m_FarZ;
  381. float m_fHorizontalFOVDegrees;
  382. float m_fVerticalFOVDegrees;
  383. float m_fQuadraticAtten;
  384. float m_fLinearAtten;
  385. float m_fConstantAtten;
  386. float m_Color[4];
  387. ITexture *m_pSpotlightTexture;
  388. int m_nSpotlightTextureFrame;
  389. // Shadow depth mapping parameters
  390. bool m_bEnableShadows;
  391. bool m_bDrawShadowFrustum;
  392. float m_flShadowMapResolution;
  393. float m_flShadowFilterSize;
  394. float m_flShadowSlopeScaleDepthBias;
  395. float m_flShadowDepthBias;
  396. float m_flShadowJitterSeed;
  397. float m_flShadowAtten;
  398. int m_nShadowQuality;
  399. // Getters for scissor members
  400. bool DoScissor() { return m_bScissor; }
  401. int GetLeft() { return m_nLeft; }
  402. int GetTop() { return m_nTop; }
  403. int GetRight() { return m_nRight; }
  404. int GetBottom() { return m_nBottom; }
  405. private:
  406. friend class CShadowMgr;
  407. bool m_bScissor;
  408. int m_nLeft;
  409. int m_nTop;
  410. int m_nRight;
  411. int m_nBottom;
  412. };
  413. // Passed as the callback object to Async functions in the material system
  414. // so that callers don't have to worry about memory going out of scope before the
  415. // results return.
  416. abstract_class IAsyncTextureOperationReceiver : public IRefCounted
  417. {
  418. public:
  419. virtual void OnAsyncCreateComplete( ITexture* pTex, void* pExtraArgs ) = 0;
  420. virtual void OnAsyncFindComplete( ITexture* pTex, void* pExtraArgs ) = 0;
  421. virtual void OnAsyncMapComplete( ITexture* pTex, void* pExtraArgs, void* pMemory, int nPitch ) = 0;
  422. virtual void OnAsyncReadbackBegin( ITexture* pDst, ITexture* pSrc, void* pExtraArgs ) = 0;
  423. virtual int GetRefCount() const = 0;
  424. };
  425. //-----------------------------------------------------------------------------
  426. // Flags to be used with the Init call
  427. //-----------------------------------------------------------------------------
  428. enum MaterialInitFlags_t
  429. {
  430. MATERIAL_INIT_ALLOCATE_FULLSCREEN_TEXTURE = 0x2,
  431. MATERIAL_INIT_REFERENCE_RASTERIZER = 0x4,
  432. };
  433. //-----------------------------------------------------------------------------
  434. // Flags to specify type of depth buffer used with RT
  435. //-----------------------------------------------------------------------------
  436. // GR - this is to add RT with no depth buffer bound
  437. enum MaterialRenderTargetDepth_t
  438. {
  439. MATERIAL_RT_DEPTH_SHARED = 0x0,
  440. MATERIAL_RT_DEPTH_SEPARATE = 0x1,
  441. MATERIAL_RT_DEPTH_NONE = 0x2,
  442. MATERIAL_RT_DEPTH_ONLY = 0x3,
  443. };
  444. //-----------------------------------------------------------------------------
  445. // A function to be called when we need to release all vertex buffers
  446. // NOTE: The restore function will tell the caller if all the vertex formats
  447. // changed so that it can flush caches, etc. if it needs to (for dxlevel support)
  448. //-----------------------------------------------------------------------------
  449. enum RestoreChangeFlags_t
  450. {
  451. MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED = 0x1,
  452. };
  453. // NOTE: All size modes will force the render target to be smaller than or equal to
  454. // the size of the framebuffer.
  455. enum RenderTargetSizeMode_t
  456. {
  457. RT_SIZE_NO_CHANGE=0, // Only allowed for render targets that don't want a depth buffer
  458. // (because if they have a depth buffer, the render target must be less than or equal to the size of the framebuffer).
  459. RT_SIZE_DEFAULT=1, // Don't play with the specified width and height other than making sure it fits in the framebuffer.
  460. RT_SIZE_PICMIP=2, // Apply picmip to the render target's width and height.
  461. RT_SIZE_HDR=3, // frame_buffer_width / 4
  462. RT_SIZE_FULL_FRAME_BUFFER=4, // Same size as frame buffer, or next lower power of 2 if we can't do that.
  463. RT_SIZE_OFFSCREEN=5, // Target of specified size, don't mess with dimensions
  464. RT_SIZE_FULL_FRAME_BUFFER_ROUNDED_UP=6, // Same size as the frame buffer, rounded up if necessary for systems that can't do non-power of two textures.
  465. RT_SIZE_REPLAY_SCREENSHOT = 7, // Rounded down to power of 2, essentially...
  466. RT_SIZE_LITERAL = 8, // Use the size passed in. Don't clamp it to the frame buffer size. Really.
  467. RT_SIZE_LITERAL_PICMIP = 9 // Use the size passed in, don't clamp to the frame buffer size, but do apply picmip restrictions.
  468. };
  469. typedef void (*MaterialBufferReleaseFunc_t)( );
  470. typedef void (*MaterialBufferRestoreFunc_t)( int nChangeFlags ); // see RestoreChangeFlags_t
  471. typedef void (*ModeChangeCallbackFunc_t)( void );
  472. typedef int VertexBufferHandle_t;
  473. typedef unsigned short MaterialHandle_t;
  474. DECLARE_POINTER_HANDLE( OcclusionQueryObjectHandle_t );
  475. #define INVALID_OCCLUSION_QUERY_OBJECT_HANDLE ( (OcclusionQueryObjectHandle_t)0 )
  476. class IMaterialProxyFactory;
  477. class ITexture;
  478. class IMaterialSystemHardwareConfig;
  479. class CShadowMgr;
  480. DECLARE_POINTER_HANDLE( MaterialLock_t );
  481. //-----------------------------------------------------------------------------
  482. //
  483. //-----------------------------------------------------------------------------
  484. abstract_class IMaterialSystem : public IAppSystem
  485. {
  486. public:
  487. // Placeholder for API revision
  488. virtual bool Connect( CreateInterfaceFn factory ) = 0;
  489. virtual void Disconnect() = 0;
  490. virtual void *QueryInterface( const char *pInterfaceName ) = 0;
  491. virtual InitReturnVal_t Init() = 0;
  492. virtual void Shutdown() = 0;
  493. //---------------------------------------------------------
  494. // Initialization and shutdown
  495. //---------------------------------------------------------
  496. // Call this to initialize the material system
  497. // returns a method to create interfaces in the shader dll
  498. virtual CreateInterfaceFn Init( char const* pShaderAPIDLL,
  499. IMaterialProxyFactory *pMaterialProxyFactory,
  500. CreateInterfaceFn fileSystemFactory,
  501. CreateInterfaceFn cvarFactory=NULL ) = 0;
  502. // Call this to set an explicit shader version to use
  503. // Must be called before Init().
  504. virtual void SetShaderAPI( char const *pShaderAPIDLL ) = 0;
  505. // Must be called before Init(), if you're going to call it at all...
  506. virtual void SetAdapter( int nAdapter, int nFlags ) = 0;
  507. // Call this when the mod has been set up, which may occur after init
  508. // At this point, the game + gamebin paths have been set up
  509. virtual void ModInit() = 0;
  510. virtual void ModShutdown() = 0;
  511. //---------------------------------------------------------
  512. //
  513. //---------------------------------------------------------
  514. virtual void SetThreadMode( MaterialThreadMode_t mode, int nServiceThread = -1 ) = 0;
  515. virtual MaterialThreadMode_t GetThreadMode( ) = 0;
  516. virtual bool IsRenderThreadSafe( ) = 0;
  517. virtual void ExecuteQueued() = 0;
  518. //---------------------------------------------------------
  519. // Config management
  520. //---------------------------------------------------------
  521. virtual IMaterialSystemHardwareConfig *GetHardwareConfig( const char *pVersion, int *returnCode ) = 0;
  522. // Call this before rendering each frame with the current config
  523. // for the material system.
  524. // Will do whatever is necessary to get the material system into the correct state
  525. // upon configuration change. .doesn't much else otherwise.
  526. virtual bool UpdateConfig( bool bForceUpdate ) = 0;
  527. // Force this to be the config; update all material system convars to match the state
  528. // return true if lightmaps need to be redownloaded
  529. virtual bool OverrideConfig( const MaterialSystem_Config_t &config, bool bForceUpdate ) = 0;
  530. // Get the current config for this video card (as last set by UpdateConfig)
  531. virtual const MaterialSystem_Config_t &GetCurrentConfigForVideoCard() const = 0;
  532. // Gets *recommended* configuration information associated with the display card,
  533. // given a particular dx level to run under.
  534. // Use dxlevel 0 to use the recommended dx level.
  535. // The function returns false if an invalid dxlevel was specified
  536. // UNDONE: To find out all convars affected by configuration, we'll need to change
  537. // the dxsupport.pl program to output all column headers into a single keyvalue block
  538. // and then we would read that in, and send it back to the client
  539. virtual bool GetRecommendedConfigurationInfo( int nDXLevel, KeyValues * pKeyValues ) = 0;
  540. // -----------------------------------------------------------
  541. // Device methods
  542. // -----------------------------------------------------------
  543. // Gets the number of adapters...
  544. virtual int GetDisplayAdapterCount() const = 0;
  545. // Returns the current adapter in use
  546. virtual int GetCurrentAdapter() const = 0;
  547. // Returns info about each adapter
  548. virtual void GetDisplayAdapterInfo( int adapter, MaterialAdapterInfo_t& info ) const = 0;
  549. // Returns the number of modes
  550. virtual int GetModeCount( int adapter ) const = 0;
  551. // Returns mode information..
  552. virtual void GetModeInfo( int adapter, int mode, MaterialVideoMode_t& info ) const = 0;
  553. virtual void AddModeChangeCallBack( ModeChangeCallbackFunc_t func ) = 0;
  554. // Returns the mode info for the current display device
  555. virtual void GetDisplayMode( MaterialVideoMode_t& mode ) const = 0;
  556. // Sets the mode...
  557. virtual bool SetMode( void* hwnd, const MaterialSystem_Config_t &config ) = 0;
  558. virtual bool SupportsMSAAMode( int nMSAAMode ) = 0;
  559. // FIXME: REMOVE! Get video card identitier
  560. virtual const MaterialSystemHardwareIdentifier_t &GetVideoCardIdentifier( void ) const = 0;
  561. // Use this to spew information about the 3D layer
  562. virtual void SpewDriverInfo() const = 0;
  563. virtual void GetDXLevelDefaults(uint &max_dxlevel,uint &recommended_dxlevel) = 0;
  564. // Get the image format of the back buffer. . useful when creating render targets, etc.
  565. virtual void GetBackBufferDimensions( int &width, int &height) const = 0;
  566. virtual ImageFormat GetBackBufferFormat() const = 0;
  567. virtual bool SupportsHDRMode( HDRType_t nHDRModede ) = 0;
  568. // -----------------------------------------------------------
  569. // Window methods
  570. // -----------------------------------------------------------
  571. // Creates/ destroys a child window
  572. virtual bool AddView( void* hwnd ) = 0;
  573. virtual void RemoveView( void* hwnd ) = 0;
  574. // Sets the view
  575. virtual void SetView( void* hwnd ) = 0;
  576. // -----------------------------------------------------------
  577. // Control flow
  578. // -----------------------------------------------------------
  579. virtual void BeginFrame( float frameTime ) = 0;
  580. virtual void EndFrame( ) = 0;
  581. virtual void Flush( bool flushHardware = false ) = 0;
  582. /// FIXME: This stuff needs to be cleaned up and abstracted.
  583. // Stuff that gets exported to the launcher through the engine
  584. virtual void SwapBuffers( ) = 0;
  585. // Flushes managed textures from the texture cacher
  586. virtual void EvictManagedResources() = 0;
  587. virtual void ReleaseResources(void) = 0;
  588. virtual void ReacquireResources(void ) = 0;
  589. // -----------------------------------------------------------
  590. // Device loss/restore
  591. // -----------------------------------------------------------
  592. // Installs a function to be called when we need to release vertex buffers + textures
  593. virtual void AddReleaseFunc( MaterialBufferReleaseFunc_t func ) = 0;
  594. virtual void RemoveReleaseFunc( MaterialBufferReleaseFunc_t func ) = 0;
  595. // Installs a function to be called when we need to restore vertex buffers
  596. virtual void AddRestoreFunc( MaterialBufferRestoreFunc_t func ) = 0;
  597. virtual void RemoveRestoreFunc( MaterialBufferRestoreFunc_t func ) = 0;
  598. // Release temporary HW memory...
  599. virtual void ResetTempHWMemory( bool bExitingLevel = false ) = 0;
  600. // For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
  601. virtual void HandleDeviceLost() = 0;
  602. // -----------------------------------------------------------
  603. // Shaders
  604. // -----------------------------------------------------------
  605. // Used to iterate over all shaders for editing purposes
  606. // GetShaders returns the number of shaders it actually found
  607. virtual int ShaderCount() const = 0;
  608. virtual int GetShaders( int nFirstShader, int nMaxCount, IShader **ppShaderList ) const = 0;
  609. // FIXME: Is there a better way of doing this?
  610. // Returns shader flag names for editors to be able to edit them
  611. virtual int ShaderFlagCount() const = 0;
  612. virtual const char * ShaderFlagName( int nIndex ) const = 0;
  613. // Gets the actual shader fallback for a particular shader
  614. virtual void GetShaderFallback( const char *pShaderName, char *pFallbackShader, int nFallbackLength ) = 0;
  615. // -----------------------------------------------------------
  616. // Material proxies
  617. // -----------------------------------------------------------
  618. virtual IMaterialProxyFactory *GetMaterialProxyFactory() = 0;
  619. // Sets the material proxy factory. Calling this causes all materials to be uncached.
  620. virtual void SetMaterialProxyFactory( IMaterialProxyFactory* pFactory ) = 0;
  621. // -----------------------------------------------------------
  622. // Editor mode
  623. // -----------------------------------------------------------
  624. // Used to enable editor materials. Must be called before Init.
  625. virtual void EnableEditorMaterials() = 0;
  626. // -----------------------------------------------------------
  627. // Stub mode mode
  628. // -----------------------------------------------------------
  629. // Force it to ignore Draw calls.
  630. virtual void SetInStubMode( bool bInStubMode ) = 0;
  631. //---------------------------------------------------------
  632. // Debug support
  633. //---------------------------------------------------------
  634. virtual void DebugPrintUsedMaterials( const char *pSearchSubString, bool bVerbose ) = 0;
  635. virtual void DebugPrintUsedTextures( void ) = 0;
  636. virtual void ToggleSuppressMaterial( char const* pMaterialName ) = 0;
  637. virtual void ToggleDebugMaterial( char const* pMaterialName ) = 0;
  638. //---------------------------------------------------------
  639. // Misc features
  640. //---------------------------------------------------------
  641. //returns whether fast clipping is being used or not - needed to be exposed for better per-object clip behavior
  642. virtual bool UsingFastClipping( void ) = 0;
  643. virtual int StencilBufferBits( void ) = 0; //number of bits per pixel in the stencil buffer
  644. //---------------------------------------------------------
  645. // Material and texture management
  646. //---------------------------------------------------------
  647. // Stop attempting to stream in textures in response to usage. Useful for phases such as loading or other explicit
  648. // operations that shouldn't take usage of textures as a signal to stream them in at full rez.
  649. virtual void SuspendTextureStreaming( ) = 0;
  650. virtual void ResumeTextureStreaming( ) = 0;
  651. // uncache all materials. . good for forcing reload of materials.
  652. virtual void UncacheAllMaterials( ) = 0;
  653. // Remove any materials from memory that aren't in use as determined
  654. // by the IMaterial's reference count.
  655. virtual void UncacheUnusedMaterials( bool bRecomputeStateSnapshots = false ) = 0;
  656. // Load any materials into memory that are to be used as determined
  657. // by the IMaterial's reference count.
  658. virtual void CacheUsedMaterials( ) = 0;
  659. // Force all textures to be reloaded from disk.
  660. virtual void ReloadTextures( ) = 0;
  661. // Reloads materials
  662. virtual void ReloadMaterials( const char *pSubString = NULL ) = 0;
  663. // Create a procedural material. The keyvalues looks like a VMT file
  664. virtual IMaterial * CreateMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues ) = 0;
  665. // Find a material by name.
  666. // The name of a material is a full path to
  667. // the vmt file starting from "hl2/materials" (or equivalent) without
  668. // a file extension.
  669. // eg. "dev/dev_bumptest" refers to somethign similar to:
  670. // "d:/hl2/hl2/materials/dev/dev_bumptest.vmt"
  671. //
  672. // Most of the texture groups for pTextureGroupName are listed in texture_group_names.h.
  673. //
  674. // Note: if the material can't be found, this returns a checkerboard material. You can
  675. // find out if you have that material by calling IMaterial::IsErrorMaterial().
  676. // (Or use the global IsErrorMaterial function, which checks if it's null too).
  677. virtual IMaterial * FindMaterial( char const* pMaterialName, const char *pTextureGroupName, bool complain = true, const char *pComplainPrefix = NULL ) = 0;
  678. // Query whether a material is loaded (eg, whether FindMaterial will be nonblocking)
  679. virtual bool IsMaterialLoaded( char const* pMaterialName ) = 0;
  680. //---------------------------------
  681. // This is the interface for knowing what materials are available
  682. // is to use the following functions to get a list of materials. The
  683. // material names will have the full path to the material, and that is the
  684. // only way that the directory structure of the materials will be seen through this
  685. // interface.
  686. // NOTE: This is mostly for worldcraft to get a list of materials to put
  687. // in the "texture" browser.in Worldcraft
  688. virtual MaterialHandle_t FirstMaterial() const = 0;
  689. // returns InvalidMaterial if there isn't another material.
  690. // WARNING: you must call GetNextMaterial until it returns NULL,
  691. // otherwise there will be a memory leak.
  692. virtual MaterialHandle_t NextMaterial( MaterialHandle_t h ) const = 0;
  693. // This is the invalid material
  694. virtual MaterialHandle_t InvalidMaterial() const = 0;
  695. // Returns a particular material
  696. virtual IMaterial* GetMaterial( MaterialHandle_t h ) const = 0;
  697. // Get the total number of materials in the system. These aren't just the used
  698. // materials, but the complete collection.
  699. virtual int GetNumMaterials( ) const = 0;
  700. //---------------------------------
  701. virtual void SetAsyncTextureLoadCache( void* hFileCache ) = 0;
  702. virtual ITexture * FindTexture( char const* pTextureName, const char *pTextureGroupName, bool complain = true, int nAdditionalCreationFlags = 0 ) = 0;
  703. // Checks to see if a particular texture is loaded
  704. virtual bool IsTextureLoaded( char const* pTextureName ) const = 0;
  705. // Creates a procedural texture
  706. virtual ITexture * CreateProceduralTexture( const char *pTextureName,
  707. const char *pTextureGroupName,
  708. int w,
  709. int h,
  710. ImageFormat fmt,
  711. int nFlags ) = 0;
  712. //
  713. // Render targets
  714. //
  715. virtual void BeginRenderTargetAllocation() = 0;
  716. virtual void EndRenderTargetAllocation() = 0; // Simulate an Alt-Tab in here, which causes a release/restore of all resources
  717. // Creates a render target
  718. // If depth == true, a depth buffer is also allocated. If not, then
  719. // the screen's depth buffer is used.
  720. // Creates a texture for use as a render target
  721. virtual ITexture * CreateRenderTargetTexture( int w,
  722. int h,
  723. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  724. ImageFormat format,
  725. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED ) = 0;
  726. virtual ITexture * CreateNamedRenderTargetTextureEx( const char *pRTName, // Pass in NULL here for an unnamed render target.
  727. int w,
  728. int h,
  729. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  730. ImageFormat format,
  731. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  732. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  733. unsigned int renderTargetFlags = 0 ) = 0;
  734. virtual ITexture * CreateNamedRenderTargetTexture( const char *pRTName,
  735. int w,
  736. int h,
  737. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  738. ImageFormat format,
  739. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  740. bool bClampTexCoords = true,
  741. bool bAutoMipMap = false ) = 0;
  742. // Must be called between the above Begin-End calls!
  743. virtual ITexture * CreateNamedRenderTargetTextureEx2( const char *pRTName, // Pass in NULL here for an unnamed render target.
  744. int w,
  745. int h,
  746. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  747. ImageFormat format,
  748. MaterialRenderTargetDepth_t depth = MATERIAL_RT_DEPTH_SHARED,
  749. unsigned int textureFlags = TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT,
  750. unsigned int renderTargetFlags = 0 ) = 0;
  751. // -----------------------------------------------------------
  752. // Lightmaps
  753. // -----------------------------------------------------------
  754. // To allocate lightmaps, sort the whole world by material twice.
  755. // The first time through, call AllocateLightmap for every surface.
  756. // that has a lightmap.
  757. // The second time through, call AllocateWhiteLightmap for every
  758. // surface that expects to use shaders that expect lightmaps.
  759. virtual void BeginLightmapAllocation( ) = 0;
  760. virtual void EndLightmapAllocation( ) = 0;
  761. // returns the sorting id for this surface
  762. virtual int AllocateLightmap( int width, int height,
  763. int offsetIntoLightmapPage[2],
  764. IMaterial *pMaterial ) = 0;
  765. // returns the sorting id for this surface
  766. virtual int AllocateWhiteLightmap( IMaterial *pMaterial ) = 0;
  767. // lightmaps are in linear color space
  768. // lightmapPageID is returned by GetLightmapPageIDForSortID
  769. // lightmapSize and offsetIntoLightmapPage are returned by AllocateLightmap.
  770. // You should never call UpdateLightmap for a lightmap allocated through
  771. // AllocateWhiteLightmap.
  772. virtual void UpdateLightmap( int lightmapPageID, int lightmapSize[2],
  773. int offsetIntoLightmapPage[2],
  774. float *pFloatImage, float *pFloatImageBump1,
  775. float *pFloatImageBump2, float *pFloatImageBump3 ) = 0;
  776. // fixme: could just be an array of ints for lightmapPageIDs since the material
  777. // for a surface is already known.
  778. virtual int GetNumSortIDs( ) = 0;
  779. virtual void GetSortInfo( MaterialSystem_SortInfo_t *sortInfoArray ) = 0;
  780. // Read the page size of an existing lightmap by sort id (returned from AllocateLightmap())
  781. virtual void GetLightmapPageSize( int lightmap, int *width, int *height ) const = 0;
  782. virtual void ResetMaterialLightmapPageInfo() = 0;
  783. virtual void ClearBuffers( bool bClearColor, bool bClearDepth, bool bClearStencil = false ) = 0;
  784. // -----------------------------------------------------------
  785. // X360 specifics
  786. // -----------------------------------------------------------
  787. #if defined( _X360 )
  788. virtual void ListUsedMaterials( void ) = 0;
  789. virtual HXUIFONT OpenTrueTypeFont( const char *pFontname, int tall, int style ) = 0;
  790. virtual void CloseTrueTypeFont( HXUIFONT hFont ) = 0;
  791. virtual bool GetTrueTypeFontMetrics( HXUIFONT hFont, XUIFontMetrics *pFontMetrics, XUICharMetrics charMetrics[256] ) = 0;
  792. // Render a sequence of characters and extract the data into a buffer
  793. // For each character, provide the width+height of the font texture subrect,
  794. // an offset to apply when rendering the glyph, and an offset into a buffer to receive the RGBA data
  795. virtual bool GetTrueTypeGlyphs( HXUIFONT hFont, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pRGBAOffset ) = 0;
  796. virtual void PersistDisplay() = 0;
  797. virtual void *GetD3DDevice() = 0;
  798. virtual bool OwnGPUResources( bool bEnable ) = 0;
  799. #endif
  800. // -----------------------------------------------------------
  801. // Access the render contexts
  802. // -----------------------------------------------------------
  803. virtual IMatRenderContext * GetRenderContext() = 0;
  804. virtual bool SupportsShadowDepthTextures( void ) = 0;
  805. virtual void BeginUpdateLightmaps( void ) = 0;
  806. virtual void EndUpdateLightmaps( void ) = 0;
  807. // -----------------------------------------------------------
  808. // Methods to force the material system into non-threaded, non-queued mode
  809. // -----------------------------------------------------------
  810. virtual MaterialLock_t Lock() = 0;
  811. virtual void Unlock( MaterialLock_t ) = 0;
  812. // Vendor-dependent shadow depth texture format
  813. virtual ImageFormat GetShadowDepthTextureFormat() = 0;
  814. virtual bool SupportsFetch4( void ) = 0;
  815. // Create a custom render context. Cannot be used to create MATERIAL_HARDWARE_CONTEXT
  816. virtual IMatRenderContext *CreateRenderContext( MaterialContextType_t type ) = 0;
  817. // Set a specified render context to be the global context for the thread. Returns the prior context.
  818. virtual IMatRenderContext *SetRenderContext( IMatRenderContext * ) = 0;
  819. virtual bool SupportsCSAAMode( int nNumSamples, int nQualityLevel ) = 0;
  820. virtual void RemoveModeChangeCallBack( ModeChangeCallbackFunc_t func ) = 0;
  821. // Finds or create a procedural material.
  822. virtual IMaterial * FindProceduralMaterial( const char *pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues ) = 0;
  823. virtual ImageFormat GetNullTextureFormat() = 0;
  824. virtual void AddTextureAlias( const char *pAlias, const char *pRealName ) = 0;
  825. virtual void RemoveTextureAlias( const char *pAlias ) = 0;
  826. // returns a lightmap page ID for this allocation, -1 if none available
  827. // frameID is a number that should be changed every frame to prevent locking any textures that are
  828. // being used to draw in the previous frame
  829. virtual int AllocateDynamicLightmap( int lightmapSize[2], int *pOutOffsetIntoPage, int frameID ) = 0;
  830. virtual void SetExcludedTextures( const char *pScriptName ) = 0;
  831. virtual void UpdateExcludedTextures( void ) = 0;
  832. virtual bool IsInFrame( ) const = 0;
  833. virtual void CompactMemory() = 0;
  834. // For sv_pure mode. The filesystem figures out which files the client needs to reload to be "pure" ala the server's preferences.
  835. virtual void ReloadFilesInList( IFileList *pFilesToReload ) = 0;
  836. virtual bool AllowThreading( bool bAllow, int nServiceThread ) = 0;
  837. // Extended version of FindMaterial().
  838. // Contains context in so it can make decisions (i.e. if it's a model, ignore certain cheat parameters)
  839. virtual IMaterial * FindMaterialEx( char const* pMaterialName, const char *pTextureGroupName, int nContext, bool complain = true, const char *pComplainPrefix = NULL ) = 0;
  840. #ifdef DX_TO_GL_ABSTRACTION
  841. virtual void DoStartupShaderPreloading( void ) = 0;
  842. #endif
  843. // Sets the override sizes for all render target size tests. These replace the frame buffer size.
  844. // Set them when you are rendering primarily to something larger than the frame buffer (as in VR mode).
  845. virtual void SetRenderTargetFrameBufferSizeOverrides( int nWidth, int nHeight ) = 0;
  846. // Returns the (possibly overridden) framebuffer size for render target sizing.
  847. virtual void GetRenderTargetFrameBufferDimensions( int & nWidth, int & nHeight ) = 0;
  848. // returns the display device name that matches the adapter index we were started with
  849. virtual char *GetDisplayDeviceName() const = 0;
  850. // creates a texture suitable for use with materials from a raw stream of bits.
  851. // The bits will be retained by the material system and can be freed upon return.
  852. virtual ITexture* CreateTextureFromBits(int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits) = 0;
  853. // Lie to the material system to pretend to be in render target allocation mode at the beginning of time.
  854. // This was a thing that mattered a lot to old hardware, but doesn't matter at all to new hardware,
  855. // where new is defined to be "anything from the last decade." However, we want to preserve legacy behavior
  856. // for the old games because it's easier than testing them.
  857. virtual void OverrideRenderTargetAllocation( bool rtAlloc ) = 0;
  858. // creates a texture compositor that will attempt to composite a new textuer from the steps of the specified KeyValues.
  859. virtual ITextureCompositor* NewTextureCompositor( int w, int h, const char* pCompositeName, int nTeamNum, uint64 randomSeed, KeyValues* stageDesc, uint32 texCompositeCreateFlags = 0 ) = 0;
  860. // Loads the texture with the specified name, calls pRecipient->OnAsyncFindComplete with the result from the main thread.
  861. // once the texture load is complete. If the texture cannot be found, the returned texture will return true for IsError().
  862. virtual void AsyncFindTexture( const char* pFilename, const char *pTextureGroupName, IAsyncTextureOperationReceiver* pRecipient, void* pExtraArgs, bool bComplain = true, int nAdditionalCreationFlags = 0 ) = 0;
  863. // creates a texture suitable for use with materials from a raw stream of bits.
  864. // The bits will be retained by the material system and can be freed upon return.
  865. virtual ITexture* CreateNamedTextureFromBitsEx( const char* pName, const char *pTextureGroupName, int w, int h, int mips, ImageFormat fmt, int srcBufferSize, byte* srcBits, int nFlags ) = 0;
  866. // Creates a texture compositor template for use in later code.
  867. virtual bool AddTextureCompositorTemplate( const char* pName, KeyValues* pTmplDesc, int nTexCompositeTemplateFlags = 0 ) = 0;
  868. // Performs final verification of all compositor templates (after they've all been initially loaded).
  869. virtual bool VerifyTextureCompositorTemplates( ) = 0;
  870. };
  871. //-----------------------------------------------------------------------------
  872. //
  873. //-----------------------------------------------------------------------------
  874. abstract_class IMatRenderContext : public IRefCounted
  875. {
  876. public:
  877. virtual void BeginRender() = 0;
  878. virtual void EndRender() = 0;
  879. virtual void Flush( bool flushHardware = false ) = 0;
  880. virtual void BindLocalCubemap( ITexture *pTexture ) = 0;
  881. // pass in an ITexture (that is build with "rendertarget" "1") or
  882. // pass in NULL for the regular backbuffer.
  883. virtual void SetRenderTarget( ITexture *pTexture ) = 0;
  884. virtual ITexture * GetRenderTarget( void ) = 0;
  885. virtual void GetRenderTargetDimensions( int &width, int &height) const = 0;
  886. // Bind a material is current for rendering.
  887. virtual void Bind( IMaterial *material, void *proxyData = 0 ) = 0;
  888. // Bind a lightmap page current for rendering. You only have to
  889. // do this for materials that require lightmaps.
  890. virtual void BindLightmapPage( int lightmapPageID ) = 0;
  891. // inputs are between 0 and 1
  892. virtual void DepthRange( float zNear, float zFar ) = 0;
  893. virtual void ClearBuffers( bool bClearColor, bool bClearDepth, bool bClearStencil = false ) = 0;
  894. // read to a unsigned char rgb image.
  895. virtual void ReadPixels( int x, int y, int width, int height, unsigned char *data, ImageFormat dstFormat ) = 0;
  896. // Sets lighting
  897. virtual void SetAmbientLight( float r, float g, float b ) = 0;
  898. virtual void SetLight( int lightNum, const LightDesc_t& desc ) = 0;
  899. // The faces of the cube are specified in the same order as cubemap textures
  900. virtual void SetAmbientLightCube( Vector4D cube[6] ) = 0;
  901. // Blit the backbuffer to the framebuffer texture
  902. virtual void CopyRenderTargetToTexture( ITexture *pTexture ) = 0;
  903. // Set the current texture that is a copy of the framebuffer.
  904. virtual void SetFrameBufferCopyTexture( ITexture *pTexture, int textureIndex = 0 ) = 0;
  905. virtual ITexture *GetFrameBufferCopyTexture( int textureIndex ) = 0;
  906. //
  907. // end vertex array api
  908. //
  909. // matrix api
  910. virtual void MatrixMode( MaterialMatrixMode_t matrixMode ) = 0;
  911. virtual void PushMatrix( void ) = 0;
  912. virtual void PopMatrix( void ) = 0;
  913. virtual void LoadMatrix( VMatrix const& matrix ) = 0;
  914. virtual void LoadMatrix( matrix3x4_t const& matrix ) = 0;
  915. virtual void MultMatrix( VMatrix const& matrix ) = 0;
  916. virtual void MultMatrix( matrix3x4_t const& matrix ) = 0;
  917. virtual void MultMatrixLocal( VMatrix const& matrix ) = 0;
  918. virtual void MultMatrixLocal( matrix3x4_t const& matrix ) = 0;
  919. virtual void GetMatrix( MaterialMatrixMode_t matrixMode, VMatrix *matrix ) = 0;
  920. virtual void GetMatrix( MaterialMatrixMode_t matrixMode, matrix3x4_t *matrix ) = 0;
  921. virtual void LoadIdentity( void ) = 0;
  922. virtual void Ortho( double left, double top, double right, double bottom, double zNear, double zFar ) = 0;
  923. virtual void PerspectiveX( double fovx, double aspect, double zNear, double zFar ) = 0;
  924. virtual void PickMatrix( int x, int y, int width, int height ) = 0;
  925. virtual void Rotate( float angle, float x, float y, float z ) = 0;
  926. virtual void Translate( float x, float y, float z ) = 0;
  927. virtual void Scale( float x, float y, float z ) = 0;
  928. // end matrix api
  929. // Sets/gets the viewport
  930. virtual void Viewport( int x, int y, int width, int height ) = 0;
  931. virtual void GetViewport( int& x, int& y, int& width, int& height ) const = 0;
  932. // The cull mode
  933. virtual void CullMode( MaterialCullMode_t cullMode ) = 0;
  934. // end matrix api
  935. // This could easily be extended to a general user clip plane
  936. virtual void SetHeightClipMode( MaterialHeightClipMode_t nHeightClipMode ) = 0;
  937. // garymcthack : fog z is always used for heightclipz for now.
  938. virtual void SetHeightClipZ( float z ) = 0;
  939. // Fog methods...
  940. virtual void FogMode( MaterialFogMode_t fogMode ) = 0;
  941. virtual void FogStart( float fStart ) = 0;
  942. virtual void FogEnd( float fEnd ) = 0;
  943. virtual void SetFogZ( float fogZ ) = 0;
  944. virtual MaterialFogMode_t GetFogMode( void ) = 0;
  945. virtual void FogColor3f( float r, float g, float b ) = 0;
  946. virtual void FogColor3fv( float const* rgb ) = 0;
  947. virtual void FogColor3ub( unsigned char r, unsigned char g, unsigned char b ) = 0;
  948. virtual void FogColor3ubv( unsigned char const* rgb ) = 0;
  949. virtual void GetFogColor( unsigned char *rgb ) = 0;
  950. // Sets the number of bones for skinning
  951. virtual void SetNumBoneWeights( int numBones ) = 0;
  952. // Creates/destroys Mesh
  953. virtual IMesh* CreateStaticMesh( VertexFormat_t fmt, const char *pTextureBudgetGroup, IMaterial * pMaterial = NULL ) = 0;
  954. virtual void DestroyStaticMesh( IMesh* mesh ) = 0;
  955. // Gets the dynamic mesh associated with the currently bound material
  956. // note that you've got to render the mesh before calling this function
  957. // a second time. Clients should *not* call DestroyStaticMesh on the mesh
  958. // returned by this call.
  959. // Use buffered = false if you want to not have the mesh be buffered,
  960. // but use it instead in the following pattern:
  961. // meshBuilder.Begin
  962. // meshBuilder.End
  963. // Draw partial
  964. // Draw partial
  965. // Draw partial
  966. // meshBuilder.Begin
  967. // meshBuilder.End
  968. // etc
  969. // Use Vertex or Index Override to supply a static vertex or index buffer
  970. // to use in place of the dynamic buffers.
  971. //
  972. // If you pass in a material in pAutoBind, it will automatically bind the
  973. // material. This can be helpful since you must bind the material you're
  974. // going to use BEFORE calling GetDynamicMesh.
  975. virtual IMesh* GetDynamicMesh(
  976. bool buffered = true,
  977. IMesh* pVertexOverride = 0,
  978. IMesh* pIndexOverride = 0,
  979. IMaterial *pAutoBind = 0 ) = 0;
  980. // ------------ New Vertex/Index Buffer interface ----------------------------
  981. // Do we need support for bForceTempMesh and bSoftwareVertexShader?
  982. // I don't think we use bSoftwareVertexShader anymore. .need to look into bForceTempMesh.
  983. virtual IVertexBuffer *CreateStaticVertexBuffer( VertexFormat_t fmt, int nVertexCount, const char *pTextureBudgetGroup ) = 0;
  984. virtual IIndexBuffer *CreateStaticIndexBuffer( MaterialIndexFormat_t fmt, int nIndexCount, const char *pTextureBudgetGroup ) = 0;
  985. virtual void DestroyVertexBuffer( IVertexBuffer * ) = 0;
  986. virtual void DestroyIndexBuffer( IIndexBuffer * ) = 0;
  987. // Do we need to specify the stream here in the case of locking multiple dynamic VBs on different streams?
  988. virtual IVertexBuffer *GetDynamicVertexBuffer( int streamID, VertexFormat_t vertexFormat, bool bBuffered = true ) = 0;
  989. virtual IIndexBuffer *GetDynamicIndexBuffer( MaterialIndexFormat_t fmt, bool bBuffered = true ) = 0;
  990. virtual void BindVertexBuffer( int streamID, IVertexBuffer *pVertexBuffer, int nOffsetInBytes, int nFirstVertex, int nVertexCount, VertexFormat_t fmt, int nRepetitions = 1 ) = 0;
  991. virtual void BindIndexBuffer( IIndexBuffer *pIndexBuffer, int nOffsetInBytes ) = 0;
  992. virtual void Draw( MaterialPrimitiveType_t primitiveType, int firstIndex, int numIndices ) = 0;
  993. // ------------ End ----------------------------
  994. // Selection mode methods
  995. virtual int SelectionMode( bool selectionMode ) = 0;
  996. virtual void SelectionBuffer( unsigned int* pBuffer, int size ) = 0;
  997. virtual void ClearSelectionNames( ) = 0;
  998. virtual void LoadSelectionName( int name ) = 0;
  999. virtual void PushSelectionName( int name ) = 0;
  1000. virtual void PopSelectionName() = 0;
  1001. // Sets the Clear Color for ClearBuffer....
  1002. virtual void ClearColor3ub( unsigned char r, unsigned char g, unsigned char b ) = 0;
  1003. virtual void ClearColor4ub( unsigned char r, unsigned char g, unsigned char b, unsigned char a ) = 0;
  1004. // Allows us to override the depth buffer setting of a material
  1005. virtual void OverrideDepthEnable( bool bEnable, bool bDepthEnable ) = 0;
  1006. // FIXME: This is a hack required for NVidia/XBox, can they fix in drivers?
  1007. virtual void DrawScreenSpaceQuad( IMaterial* pMaterial ) = 0;
  1008. // For debugging and building recording files. This will stuff a token into the recording file,
  1009. // then someone doing a playback can watch for the token.
  1010. virtual void SyncToken( const char *pToken ) = 0;
  1011. // FIXME: REMOVE THIS FUNCTION!
  1012. // The only reason why it's not gone is because we're a week from ship when I found the bug in it
  1013. // and everything's tuned to use it.
  1014. // It's returning values which are 2x too big (it's returning sphere diameter x2)
  1015. // Use ComputePixelDiameterOfSphere below in all new code instead.
  1016. virtual float ComputePixelWidthOfSphere( const Vector& origin, float flRadius ) = 0;
  1017. //
  1018. // Occlusion query support
  1019. //
  1020. // Allocate and delete query objects.
  1021. virtual OcclusionQueryObjectHandle_t CreateOcclusionQueryObject( void ) = 0;
  1022. virtual void DestroyOcclusionQueryObject( OcclusionQueryObjectHandle_t ) = 0;
  1023. // Bracket drawing with begin and end so that we can get counts next frame.
  1024. virtual void BeginOcclusionQueryDrawing( OcclusionQueryObjectHandle_t ) = 0;
  1025. virtual void EndOcclusionQueryDrawing( OcclusionQueryObjectHandle_t ) = 0;
  1026. // Get the number of pixels rendered between begin and end on an earlier frame.
  1027. // Calling this in the same frame is a huge perf hit!
  1028. virtual int OcclusionQuery_GetNumPixelsRendered( OcclusionQueryObjectHandle_t ) = 0;
  1029. virtual void SetFlashlightMode( bool bEnable ) = 0;
  1030. virtual void SetFlashlightState( const FlashlightState_t &state, const VMatrix &worldToTexture ) = 0;
  1031. // Gets the current height clip mode
  1032. virtual MaterialHeightClipMode_t GetHeightClipMode( ) = 0;
  1033. // This returns the diameter of the sphere in pixels based on
  1034. // the current model, view, + projection matrices and viewport.
  1035. virtual float ComputePixelDiameterOfSphere( const Vector& vecAbsOrigin, float flRadius ) = 0;
  1036. // By default, the material system applies the VIEW and PROJECTION matrices to the user clip
  1037. // planes (which are specified in world space) to generate projection-space user clip planes
  1038. // Occasionally (for the particle system in hl2, for example), we want to override that
  1039. // behavior and explictly specify a ViewProj transform for user clip planes
  1040. virtual void EnableUserClipTransformOverride( bool bEnable ) = 0;
  1041. virtual void UserClipTransform( const VMatrix &worldToView ) = 0;
  1042. virtual bool GetFlashlightMode() const = 0;
  1043. // Used to make the handle think it's never had a successful query before
  1044. virtual void ResetOcclusionQueryObject( OcclusionQueryObjectHandle_t ) = 0;
  1045. // FIXME: Remove
  1046. virtual void Unused3() {}
  1047. // Creates/destroys morph data associated w/ a particular material
  1048. virtual IMorph *CreateMorph( MorphFormat_t format, const char *pDebugName ) = 0;
  1049. virtual void DestroyMorph( IMorph *pMorph ) = 0;
  1050. // Binds the morph data for use in rendering
  1051. virtual void BindMorph( IMorph *pMorph ) = 0;
  1052. // Sets flexweights for rendering
  1053. virtual void SetFlexWeights( int nFirstWeight, int nCount, const MorphWeight_t* pWeights ) = 0;
  1054. // FIXME: Remove
  1055. virtual void Unused4() {};
  1056. virtual void Unused5() {};
  1057. virtual void Unused6() {};
  1058. virtual void Unused7() {};
  1059. virtual void Unused8() {};
  1060. // Read w/ stretch to a host-memory buffer
  1061. virtual void ReadPixelsAndStretch( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pBuffer, ImageFormat dstFormat, int nDstStride ) = 0;
  1062. // Gets the window size
  1063. virtual void GetWindowSize( int &width, int &height ) const = 0;
  1064. // This function performs a texture map from one texture map to the render destination, doing
  1065. // all the necessary pixel/texel coordinate fix ups. fractional values can be used for the
  1066. // src_texture coordinates to get linear sampling - integer values should produce 1:1 mappings
  1067. // for non-scaled operations.
  1068. virtual void DrawScreenSpaceRectangle(
  1069. IMaterial *pMaterial,
  1070. int destx, int desty,
  1071. int width, int height,
  1072. float src_texture_x0, float src_texture_y0, // which texel you want to appear at
  1073. // destx/y
  1074. float src_texture_x1, float src_texture_y1, // which texel you want to appear at
  1075. // destx+width-1, desty+height-1
  1076. int src_texture_width, int src_texture_height, // needed for fixup
  1077. void *pClientRenderable = NULL,
  1078. int nXDice = 1,
  1079. int nYDice = 1 )=0;
  1080. virtual void LoadBoneMatrix( int boneIndex, const matrix3x4_t& matrix ) = 0;
  1081. // This version will push the current rendertarget + current viewport onto the stack
  1082. virtual void PushRenderTargetAndViewport( ) = 0;
  1083. // This version will push a new rendertarget + a maximal viewport for that rendertarget onto the stack
  1084. virtual void PushRenderTargetAndViewport( ITexture *pTexture ) = 0;
  1085. // This version will push a new rendertarget + a specified viewport onto the stack
  1086. virtual void PushRenderTargetAndViewport( ITexture *pTexture, int nViewX, int nViewY, int nViewW, int nViewH ) = 0;
  1087. // This version will push a new rendertarget + a specified viewport onto the stack
  1088. virtual void PushRenderTargetAndViewport( ITexture *pTexture, ITexture *pDepthTexture, int nViewX, int nViewY, int nViewW, int nViewH ) = 0;
  1089. // This will pop a rendertarget + viewport
  1090. virtual void PopRenderTargetAndViewport( void ) = 0;
  1091. // Binds a particular texture as the current lightmap
  1092. virtual void BindLightmapTexture( ITexture *pLightmapTexture ) = 0;
  1093. // Blit a subrect of the current render target to another texture
  1094. virtual void CopyRenderTargetToTextureEx( ITexture *pTexture, int nRenderTargetID, Rect_t *pSrcRect, Rect_t *pDstRect = NULL ) = 0;
  1095. virtual void CopyTextureToRenderTargetEx( int nRenderTargetID, ITexture *pTexture, Rect_t *pSrcRect, Rect_t *pDstRect = NULL ) = 0;
  1096. // Special off-center perspective matrix for DoF, MSAA jitter and poster rendering
  1097. virtual void PerspectiveOffCenterX( double fovx, double aspect, double zNear, double zFar, double bottom, double top, double left, double right ) = 0;
  1098. // Rendering parameters control special drawing modes withing the material system, shader
  1099. // system, shaders, and engine. renderparm.h has their definitions.
  1100. virtual void SetFloatRenderingParameter(int parm_number, float value) = 0;
  1101. virtual void SetIntRenderingParameter(int parm_number, int value) = 0;
  1102. virtual void SetVectorRenderingParameter(int parm_number, Vector const &value) = 0;
  1103. // stencil buffer operations.
  1104. virtual void SetStencilEnable(bool onoff) = 0;
  1105. virtual void SetStencilFailOperation(StencilOperation_t op) = 0;
  1106. virtual void SetStencilZFailOperation(StencilOperation_t op) = 0;
  1107. virtual void SetStencilPassOperation(StencilOperation_t op) = 0;
  1108. virtual void SetStencilCompareFunction(StencilComparisonFunction_t cmpfn) = 0;
  1109. virtual void SetStencilReferenceValue(int ref) = 0;
  1110. virtual void SetStencilTestMask(uint32 msk) = 0;
  1111. virtual void SetStencilWriteMask(uint32 msk) = 0;
  1112. virtual void ClearStencilBufferRectangle(int xmin, int ymin, int xmax, int ymax,int value) =0;
  1113. virtual void SetRenderTargetEx( int nRenderTargetID, ITexture *pTexture ) = 0;
  1114. // rendering clip planes, beware that only the most recently pushed plane will actually be used in a sizeable chunk of hardware configurations
  1115. // and that changes to the clip planes mid-frame while UsingFastClipping() is true will result unresolvable depth inconsistencies
  1116. virtual void PushCustomClipPlane( const float *pPlane ) = 0;
  1117. virtual void PopCustomClipPlane( void ) = 0;
  1118. // Returns the number of vertices + indices we can render using the dynamic mesh
  1119. // Passing true in the second parameter will return the max # of vertices + indices
  1120. // we can use before a flush is provoked and may return different values
  1121. // if called multiple times in succession.
  1122. // Passing false into the second parameter will return
  1123. // the maximum possible vertices + indices that can be rendered in a single batch
  1124. virtual void GetMaxToRender( IMesh *pMesh, bool bMaxUntilFlush, int *pMaxVerts, int *pMaxIndices ) = 0;
  1125. // Returns the max possible vertices + indices to render in a single draw call
  1126. virtual int GetMaxVerticesToRender( IMaterial *pMaterial ) = 0;
  1127. virtual int GetMaxIndicesToRender( ) = 0;
  1128. virtual void DisableAllLocalLights() = 0;
  1129. virtual int CompareMaterialCombos( IMaterial *pMaterial1, IMaterial *pMaterial2, int lightMapID1, int lightMapID2 ) = 0;
  1130. virtual IMesh *GetFlexMesh() = 0;
  1131. virtual void SetFlashlightStateEx( const FlashlightState_t &state, const VMatrix &worldToTexture, ITexture *pFlashlightDepthTexture ) = 0;
  1132. // Returns the currently bound local cubemap
  1133. virtual ITexture *GetLocalCubemap( ) = 0;
  1134. // This is a version of clear buffers which will only clear the buffer at pixels which pass the stencil test
  1135. virtual void ClearBuffersObeyStencil( bool bClearColor, bool bClearDepth ) = 0;
  1136. //enables/disables all entered clipping planes, returns the input from the last time it was called.
  1137. virtual bool EnableClipping( bool bEnable ) = 0;
  1138. //get fog distances entered with FogStart(), FogEnd(), and SetFogZ()
  1139. virtual void GetFogDistances( float *fStart, float *fEnd, float *fFogZ ) = 0;
  1140. // Hooks for firing PIX events from outside the Material System...
  1141. virtual void BeginPIXEvent( unsigned long color, const char *szName ) = 0;
  1142. virtual void EndPIXEvent() = 0;
  1143. virtual void SetPIXMarker( unsigned long color, const char *szName ) = 0;
  1144. // Batch API
  1145. // from changelist 166623:
  1146. // - replaced obtuse material system batch usage with an explicit and easier to thread API
  1147. virtual void BeginBatch( IMesh* pIndices ) = 0;
  1148. virtual void BindBatch( IMesh* pVertices, IMaterial *pAutoBind = NULL ) = 0;
  1149. virtual void DrawBatch(int firstIndex, int numIndices ) = 0;
  1150. virtual void EndBatch() = 0;
  1151. // Raw access to the call queue, which can be NULL if not in a queued mode
  1152. virtual ICallQueue *GetCallQueue() = 0;
  1153. // Returns the world-space camera position
  1154. virtual void GetWorldSpaceCameraPosition( Vector *pCameraPos ) = 0;
  1155. virtual void GetWorldSpaceCameraVectors( Vector *pVecForward, Vector *pVecRight, Vector *pVecUp ) = 0;
  1156. // Tone mapping
  1157. virtual void ResetToneMappingScale( float monoscale) = 0; // set scale to monoscale instantly with no chasing
  1158. virtual void SetGoalToneMappingScale( float monoscale) = 0; // set scale to monoscale instantly with no chasing
  1159. // call TurnOnToneMapping before drawing the 3d scene to get the proper interpolated brightness
  1160. // value set.
  1161. virtual void TurnOnToneMapping() = 0;
  1162. // Set a linear vector color scale for all 3D rendering.
  1163. // A value of [1.0f, 1.0f, 1.0f] should match non-tone-mapped rendering.
  1164. virtual void SetToneMappingScaleLinear( const Vector &scale ) = 0;
  1165. virtual Vector GetToneMappingScaleLinear( void ) = 0;
  1166. virtual void SetShadowDepthBiasFactors( float fSlopeScaleDepthBias, float fDepthBias ) = 0;
  1167. // Apply stencil operations to every pixel on the screen without disturbing depth or color buffers
  1168. virtual void PerformFullScreenStencilOperation( void ) = 0;
  1169. // Sets lighting origin for the current model (needed to convert directional lights to points)
  1170. virtual void SetLightingOrigin( Vector vLightingOrigin ) = 0;
  1171. // Set scissor rect for rendering
  1172. virtual void SetScissorRect( const int nLeft, const int nTop, const int nRight, const int nBottom, const bool bEnableScissor ) = 0;
  1173. // Methods used to build the morph accumulator that is read from when HW morph<ing is enabled.
  1174. virtual void BeginMorphAccumulation() = 0;
  1175. virtual void EndMorphAccumulation() = 0;
  1176. virtual void AccumulateMorph( IMorph* pMorph, int nMorphCount, const MorphWeight_t* pWeights ) = 0;
  1177. virtual void PushDeformation( DeformationBase_t const *Deformation ) = 0;
  1178. virtual void PopDeformation( ) = 0;
  1179. virtual int GetNumActiveDeformations() const = 0;
  1180. virtual bool GetMorphAccumulatorTexCoord( Vector2D *pTexCoord, IMorph *pMorph, int nVertex ) = 0;
  1181. // Version of get dynamic mesh that specifies a specific vertex format
  1182. virtual IMesh* GetDynamicMeshEx( VertexFormat_t vertexFormat, bool bBuffered = true,
  1183. IMesh* pVertexOverride = 0, IMesh* pIndexOverride = 0, IMaterial *pAutoBind = 0 ) = 0;
  1184. virtual void FogMaxDensity( float flMaxDensity ) = 0;
  1185. #if defined( _X360 )
  1186. //Seems best to expose GPR allocation to scene rendering code. 128 total to split between vertex/pixel shaders (pixel will be set to 128 - vertex). Minimum value of 16. More GPR's = more threads.
  1187. virtual void PushVertexShaderGPRAllocation( int iVertexShaderCount = 64 ) = 0;
  1188. virtual void PopVertexShaderGPRAllocation( void ) = 0;
  1189. #endif
  1190. virtual IMaterial *GetCurrentMaterial() = 0;
  1191. virtual int GetCurrentNumBones() const = 0;
  1192. virtual void *GetCurrentProxy() = 0;
  1193. // Color correction related methods..
  1194. // Client cannot call IColorCorrectionSystem directly because it is not thread-safe
  1195. // FIXME: Make IColorCorrectionSystem threadsafe?
  1196. virtual void EnableColorCorrection( bool bEnable ) = 0;
  1197. virtual ColorCorrectionHandle_t AddLookup( const char *pName ) = 0;
  1198. virtual bool RemoveLookup( ColorCorrectionHandle_t handle ) = 0;
  1199. virtual void LockLookup( ColorCorrectionHandle_t handle ) = 0;
  1200. virtual void LoadLookup( ColorCorrectionHandle_t handle, const char *pLookupName ) = 0;
  1201. virtual void UnlockLookup( ColorCorrectionHandle_t handle ) = 0;
  1202. virtual void SetLookupWeight( ColorCorrectionHandle_t handle, float flWeight ) = 0;
  1203. virtual void ResetLookupWeights( ) = 0;
  1204. virtual void SetResetable( ColorCorrectionHandle_t handle, bool bResetable ) = 0;
  1205. //There are some cases where it's simply not reasonable to update the full screen depth texture (mostly on PC).
  1206. //Use this to mark it as invalid and use a dummy texture for depth reads.
  1207. virtual void SetFullScreenDepthTextureValidityFlag( bool bIsValid ) = 0;
  1208. // A special path used to tick the front buffer while loading on the 360
  1209. virtual void SetNonInteractivePacifierTexture( ITexture *pTexture, float flNormalizedX, float flNormalizedY, float flNormalizedSize ) = 0;
  1210. virtual void SetNonInteractiveTempFullscreenBuffer( ITexture *pTexture, MaterialNonInteractiveMode_t mode ) = 0;
  1211. virtual void EnableNonInteractiveMode( MaterialNonInteractiveMode_t mode ) = 0;
  1212. virtual void RefreshFrontBufferNonInteractive() = 0;
  1213. // Allocates temp render data. Renderdata goes out of scope at frame end in multicore
  1214. // Renderdata goes out of scope after refcount goes to zero in singlecore.
  1215. // Locking/unlocking increases + decreases refcount
  1216. virtual void * LockRenderData( int nSizeInBytes ) = 0;
  1217. virtual void UnlockRenderData( void *pData ) = 0;
  1218. // Typed version. If specified, pSrcData is copied into the locked memory.
  1219. template< class E > E* LockRenderDataTyped( int nCount, const E* pSrcData = NULL );
  1220. // Temp render data gets immediately freed after it's all unlocked in single core.
  1221. // This prevents it from being freed
  1222. virtual void AddRefRenderData() = 0;
  1223. virtual void ReleaseRenderData() = 0;
  1224. // Returns whether a pointer is render data. NOTE: passing NULL returns true
  1225. virtual bool IsRenderData( const void *pData ) const = 0;
  1226. virtual void PrintfVA( char *fmt, va_list vargs ) = 0;
  1227. virtual void Printf( PRINTF_FORMAT_STRING const char *fmt, ... ) = 0;
  1228. virtual float Knob( char *knobname, float *setvalue = NULL ) = 0;
  1229. // Allows us to override the alpha write setting of a material
  1230. virtual void OverrideAlphaWriteEnable( bool bEnable, bool bAlphaWriteEnable ) = 0;
  1231. virtual void OverrideColorWriteEnable( bool bOverrideEnable, bool bColorWriteEnable ) = 0;
  1232. virtual void ClearBuffersObeyStencilEx( bool bClearColor, bool bClearAlpha, bool bClearDepth ) = 0;
  1233. // Create a texture from the specified src render target, then call pRecipient->OnAsyncCreateComplete from the main thread.
  1234. // The texture will be created using the destination format, and will optionally have mipmaps generated.
  1235. // In case of error, the provided callback function will be called with the error texture.
  1236. virtual void AsyncCreateTextureFromRenderTarget( ITexture* pSrcRt, const char* pDstName, ImageFormat dstFmt, bool bGenMips, int nAdditionalCreationFlags, IAsyncTextureOperationReceiver* pRecipient, void* pExtraArgs ) = 0;
  1237. };
  1238. template< class E > inline E* IMatRenderContext::LockRenderDataTyped( int nCount, const E* pSrcData )
  1239. {
  1240. int nSizeInBytes = nCount * sizeof(E);
  1241. E *pDstData = (E*)LockRenderData( nSizeInBytes );
  1242. if ( pSrcData && pDstData )
  1243. {
  1244. memcpy( pDstData, pSrcData, nSizeInBytes );
  1245. }
  1246. return pDstData;
  1247. }
  1248. //-----------------------------------------------------------------------------
  1249. // Utility class for addreffing/releasing render data (prevents freeing on single core)
  1250. //-----------------------------------------------------------------------------
  1251. class CMatRenderDataReference
  1252. {
  1253. public:
  1254. CMatRenderDataReference();
  1255. CMatRenderDataReference( IMatRenderContext* pRenderContext );
  1256. ~CMatRenderDataReference();
  1257. void Lock( IMatRenderContext *pRenderContext );
  1258. void Release();
  1259. private:
  1260. IMatRenderContext *m_pRenderContext;
  1261. };
  1262. inline CMatRenderDataReference::CMatRenderDataReference()
  1263. {
  1264. m_pRenderContext = NULL;
  1265. }
  1266. inline CMatRenderDataReference::CMatRenderDataReference( IMatRenderContext* pRenderContext )
  1267. {
  1268. m_pRenderContext = NULL;
  1269. Lock( pRenderContext );
  1270. }
  1271. inline CMatRenderDataReference::~CMatRenderDataReference()
  1272. {
  1273. Release();
  1274. }
  1275. inline void CMatRenderDataReference::Lock( IMatRenderContext* pRenderContext )
  1276. {
  1277. if ( !m_pRenderContext )
  1278. {
  1279. m_pRenderContext = pRenderContext;
  1280. m_pRenderContext->AddRefRenderData( );
  1281. }
  1282. }
  1283. inline void CMatRenderDataReference::Release()
  1284. {
  1285. if ( m_pRenderContext )
  1286. {
  1287. m_pRenderContext->ReleaseRenderData( );
  1288. m_pRenderContext = NULL;
  1289. }
  1290. }
  1291. //-----------------------------------------------------------------------------
  1292. // Utility class for locking/unlocking render data
  1293. //-----------------------------------------------------------------------------
  1294. template< typename E >
  1295. class CMatRenderData
  1296. {
  1297. public:
  1298. CMatRenderData( IMatRenderContext* pRenderContext );
  1299. CMatRenderData( IMatRenderContext* pRenderContext, int nCount, const E *pSrcData = NULL );
  1300. ~CMatRenderData();
  1301. E* Lock( int nCount, const E* pSrcData = NULL );
  1302. void Release();
  1303. bool IsValid() const;
  1304. const E* Base() const;
  1305. E* Base();
  1306. const E& operator[]( int i ) const;
  1307. E& operator[]( int i );
  1308. private:
  1309. IMatRenderContext* m_pRenderContext;
  1310. E *m_pRenderData;
  1311. int m_nCount;
  1312. bool m_bNeedsUnlock;
  1313. };
  1314. template< typename E >
  1315. inline CMatRenderData<E>::CMatRenderData( IMatRenderContext* pRenderContext )
  1316. {
  1317. m_pRenderContext = pRenderContext;
  1318. m_nCount = 0;
  1319. m_pRenderData = 0;
  1320. m_bNeedsUnlock = false;
  1321. }
  1322. template< typename E >
  1323. inline CMatRenderData<E>::CMatRenderData( IMatRenderContext* pRenderContext, int nCount, const E* pSrcData )
  1324. {
  1325. m_pRenderContext = pRenderContext;
  1326. m_nCount = 0;
  1327. m_pRenderData = 0;
  1328. m_bNeedsUnlock = false;
  1329. Lock( nCount, pSrcData );
  1330. }
  1331. template< typename E >
  1332. inline CMatRenderData<E>::~CMatRenderData()
  1333. {
  1334. Release();
  1335. }
  1336. template< typename E >
  1337. inline bool CMatRenderData<E>::IsValid() const
  1338. {
  1339. return m_pRenderData != NULL;
  1340. }
  1341. template< typename E >
  1342. inline E* CMatRenderData<E>::Lock( int nCount, const E* pSrcData )
  1343. {
  1344. m_nCount = nCount;
  1345. if ( pSrcData && m_pRenderContext->IsRenderData( pSrcData ) )
  1346. {
  1347. // Yes, we're const-casting away, but that should be ok since
  1348. // the src data is render data
  1349. m_pRenderData = const_cast<E*>( pSrcData );
  1350. m_pRenderContext->AddRefRenderData();
  1351. m_bNeedsUnlock = false;
  1352. return m_pRenderData;
  1353. }
  1354. m_pRenderData = m_pRenderContext->LockRenderDataTyped<E>( nCount, pSrcData );
  1355. m_bNeedsUnlock = true;
  1356. return m_pRenderData;
  1357. }
  1358. template< typename E >
  1359. inline void CMatRenderData<E>::Release()
  1360. {
  1361. if ( m_pRenderContext && m_pRenderData )
  1362. {
  1363. if ( m_bNeedsUnlock )
  1364. {
  1365. m_pRenderContext->UnlockRenderData( m_pRenderData );
  1366. }
  1367. else
  1368. {
  1369. m_pRenderContext->ReleaseRenderData();
  1370. }
  1371. }
  1372. m_pRenderData = NULL;
  1373. m_nCount = 0;
  1374. m_bNeedsUnlock = false;
  1375. }
  1376. template< typename E >
  1377. inline E* CMatRenderData<E>::Base()
  1378. {
  1379. return m_pRenderData;
  1380. }
  1381. template< typename E >
  1382. inline const E* CMatRenderData<E>::Base() const
  1383. {
  1384. return m_pRenderData;
  1385. }
  1386. template< typename E >
  1387. inline E& CMatRenderData<E>::operator[]( int i )
  1388. {
  1389. Assert( ( i >= 0 ) && ( i < m_nCount ) );
  1390. return m_pRenderData[i];
  1391. }
  1392. template< typename E >
  1393. inline const E& CMatRenderData<E>::operator[]( int i ) const
  1394. {
  1395. Assert( ( i >= 0 ) && ( i < m_nCount ) );
  1396. return m_pRenderData[i];
  1397. }
  1398. //-----------------------------------------------------------------------------
  1399. class CMatRenderContextPtr : public CRefPtr<IMatRenderContext>
  1400. {
  1401. typedef CRefPtr<IMatRenderContext> BaseClass;
  1402. public:
  1403. CMatRenderContextPtr() {}
  1404. CMatRenderContextPtr( IMatRenderContext *pInit ) : BaseClass( pInit ) { if ( BaseClass::m_pObject ) BaseClass::m_pObject->BeginRender(); }
  1405. CMatRenderContextPtr( IMaterialSystem *pFrom ) : BaseClass( pFrom->GetRenderContext() ) { if ( BaseClass::m_pObject ) BaseClass::m_pObject->BeginRender(); }
  1406. ~CMatRenderContextPtr() { if ( BaseClass::m_pObject ) BaseClass::m_pObject->EndRender(); }
  1407. IMatRenderContext *operator=( IMatRenderContext *p ) { if ( p ) p->BeginRender(); return BaseClass::operator=( p ); }
  1408. void SafeRelease() { if ( BaseClass::m_pObject ) BaseClass::m_pObject->EndRender(); BaseClass::SafeRelease(); }
  1409. void AssignAddRef( IMatRenderContext *pFrom ) { if ( BaseClass::m_pObject ) BaseClass::m_pObject->EndRender(); BaseClass::AssignAddRef( pFrom ); BaseClass::m_pObject->BeginRender(); }
  1410. void GetFrom( IMaterialSystem *pFrom ) { AssignAddRef( pFrom->GetRenderContext() ); }
  1411. private:
  1412. CMatRenderContextPtr( const CMatRenderContextPtr &from );
  1413. void operator=( const CMatRenderContextPtr &from );
  1414. };
  1415. //-----------------------------------------------------------------------------
  1416. // Helper class for begin/end of pix event via constructor/destructor
  1417. //-----------------------------------------------------------------------------
  1418. #define PIX_VALVE_ORANGE 0xFFF5940F
  1419. class PIXEvent
  1420. {
  1421. public:
  1422. PIXEvent( IMatRenderContext *pRenderContext, const char *szName, unsigned long color = PIX_VALVE_ORANGE )
  1423. {
  1424. m_pRenderContext = pRenderContext;
  1425. Assert( m_pRenderContext );
  1426. Assert( szName );
  1427. m_pRenderContext->BeginPIXEvent( color, szName );
  1428. }
  1429. ~PIXEvent()
  1430. {
  1431. m_pRenderContext->EndPIXEvent();
  1432. }
  1433. private:
  1434. IMatRenderContext *m_pRenderContext;
  1435. };
  1436. // Also be sure to enable PIX_INSTRUMENTATION in shaderdevicedx8.h
  1437. //#define PIX_ENABLE 1 // set this to 1 and build engine/studiorender to enable pix events in the engine
  1438. #if PIX_ENABLE
  1439. # define PIXEVENT PIXEvent _pixEvent
  1440. #else
  1441. # define PIXEVENT
  1442. #endif
  1443. //-----------------------------------------------------------------------------
  1444. #ifdef MATERIAL_SYSTEM_DEBUG_CALL_QUEUE
  1445. #include "tier1/callqueue.h"
  1446. #include "tier1/fmtstr.h"
  1447. static void DoMatSysQueueMark( IMaterialSystem *pMaterialSystem, const char *psz )
  1448. {
  1449. CMatRenderContextPtr pRenderContext( pMaterialSystem );
  1450. if ( pRenderContext->GetCallQueue() )
  1451. pRenderContext->GetCallQueue()->QueueCall( Plat_DebugString, CUtlEnvelope<const char *>( psz ) );
  1452. }
  1453. #define MatSysQueueMark( pMaterialSystem, ...) DoMatSysQueueMark( pMaterialSystem, CFmtStr( __VA_ARGS__ ) )
  1454. #else
  1455. #define MatSysQueueMark( msg, ...) ((void)0)
  1456. #endif
  1457. //-----------------------------------------------------------------------------
  1458. extern IMaterialSystem *materials;
  1459. extern IMaterialSystem *g_pMaterialSystem;
  1460. #endif // IMATERIALSYSTEM_H