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.

5683 lines
187 KiB

  1. //===== Copyright (c) Valve Corporation, All rights reserved. ======//
  2. //
  3. // Purpose:
  4. //
  5. //===========================================================================//
  6. #include "pch_materialsystem.h"
  7. #ifndef _PS3
  8. #define MATSYS_INTERNAL
  9. #endif
  10. #include "cmaterialsystem.h"
  11. #include "colorspace.h"
  12. #include "materialsystem/materialsystem_config.h"
  13. #include "materialsystem/imaterialproxyfactory.h"
  14. #include "IHardwareConfigInternal.h"
  15. #include "shadersystem.h"
  16. #include "texturemanager.h"
  17. #include "shaderlib/ShaderDLL.h"
  18. #include "tier1/callqueue.h"
  19. #include "tier1/smartptr.h"
  20. #include "vstdlib/jobthread.h"
  21. #include "cmatnullrendercontext.h"
  22. #include "datacache/iresourceaccesscontrol.h"
  23. #include "filesystem/IQueuedLoader.h"
  24. #include "filesystem/IXboxInstaller.h"
  25. #include "cdll_int.h"
  26. #include "vjobs_interface.h"
  27. #include "ps3/ps3_sn.h"
  28. #include "shaderapidx9/imeshdx8.h"
  29. #include "tier0/perfstats.h"
  30. #if defined( _X360 )
  31. #include "xbox/xbox_console.h"
  32. #include "xbox/xbox_win32stubs.h"
  33. #elif defined(_PS3)
  34. #include "ps3/ps3_helpers.h"
  35. #include "ps3/ps3_console.h"
  36. #endif
  37. // NOTE: This must be the last file included!!!
  38. #include "tier0/memdbgon.h"
  39. #ifdef PLATFORM_POSIX
  40. #define _finite finite
  41. #endif
  42. // this is hooked into the engines convar
  43. ConVar mat_debugalttab( "mat_debugalttab", "0", FCVAR_CHEAT );
  44. ConVar gpu_level( "gpu_level", "3", 0, "GPU Level - Default: High" );
  45. ConVar mat_force_vertexfog( "mat_force_vertexfog", "0", FCVAR_DEVELOPMENTONLY );
  46. static ConVar mat_forcemanagedtextureintohardware( "mat_forcemanagedtextureintohardware", "1", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY );
  47. ConVar mat_supportflashlight( "mat_supportflashlight", "-1", FCVAR_CHEAT | FCVAR_DEVELOPMENTONLY, "0 - do not support flashlight (don't load flashlight shader combos), 1 - flashlight is supported" );
  48. // Default this to zero for the press playtest!
  49. static ConVar mat_forcehardwaresync( "mat_forcehardwaresync", /* IsPC() ? "1" : */ "0" );
  50. // Make sure this convar gets created before videocfg.lib is initialized, so it can be driven by dxsupport.cfg
  51. static ConVar mat_tonemapping_occlusion_use_stencil( "mat_tonemapping_occlusion_use_stencil", "0", FCVAR_DEVELOPMENTONLY );
  52. #if defined( DX_TO_GL_ABSTRACTION ) && !defined( _PS3 )
  53. static ConVar mat_dxlevel( "mat_dxlevel", "100", FCVAR_DEVELOPMENTONLY, "", true, 90, true, 100, NULL );
  54. //static ConVar mat_dxlevel( "mat_dxlevel", "95", FCVAR_DEVELOPMENTONLY, "", true, 95, true, 95, NULL );
  55. //static ConVar mat_dxlevel( "mat_dxlevel", "92", FCVAR_DEVELOPMENTONLY, "", true, 92, true, 92, NULL );
  56. #else
  57. static ConVar mat_dxlevel( "mat_dxlevel", "0", FCVAR_DEVELOPMENTONLY );
  58. #endif
  59. ConVar mat_queue_mode( "mat_queue_mode", "-1", FCVAR_RELEASE, "The queue/thread mode the material system should use: -1=default, 0=synchronous single thread, 1=queued single thread, 2=queued multithreaded" );
  60. ConVar mat_queue_report( "mat_queue_report", "0", FCVAR_ARCHIVE, "Report thread stalls. Positive number will filter by stalls >= time in ms. -1 reports all locks." );
  61. ConVar mat_queue_mode_force_allow( "mat_queue_mode_force_allow", IsPS3() ? "1" : "0", FCVAR_DEVELOPMENTONLY, "Whether QMS can be enabled on single threaded CPU" );
  62. ConVar mat_queue_priority("mat_queue_priority", "1", FCVAR_RELEASE);
  63. // FIXME: Would like to remove these, but what the hey.
  64. #if defined( DX_TO_GL_ABSTRACTION )
  65. static ConVar cpu_level( "cpu_level", "3", 0, "CPU Level - Default: High" );
  66. static ConVar gpu_mem_level( "gpu_mem_level", "3", 0, "Memory Level - Default: High" );
  67. #else
  68. static ConVar cpu_level( "cpu_level", "2", 0, "CPU Level - Default: High" );
  69. static ConVar mem_level( "mem_level", "2", 0, "Memory Level - Default: High" );
  70. static ConVar gpu_mem_level( "gpu_mem_level", "2", 0, "Memory Level - Default: High" );
  71. #endif
  72. static ConVar mat_picmip( "mat_picmip", "0", FCVAR_NONE, "", true, -10, true, 4 );
  73. ConVar csm_quality_level( "csm_quality_level", "0", 0, "Cascaded shadow map quality level, [0,3], 0=VERY_LOW, 3=HIGHEST" );
  74. // Moving this here (instead of in viewpostprocess.cpp) so videocfg.cpp can modify its value early during init based off whatever setting is in video.txt
  75. #if defined( CSTRIKE15 )
  76. ConVar mat_software_aa_strength( "mat_software_aa_strength", "-1.0", 0, "Software AA - perform a software anti-aliasing post-process (an alternative/supplement to MSAA). This value sets the strength of the effect: (0.0 - off), (1.0 - full)" );
  77. #else
  78. ConVar mat_software_aa_strength( "mat_software_aa_strength", IsPS3()? "0" : "-1.0", 0, "Software AA - perform a software anti-aliasing post-process (an alternative/supplement to MSAA). This value sets the strength of the effect: (0.0 - off), (1.0 - full)" );
  79. #endif
  80. ConVar mat_async_tex_maxtime_ms( "mat_async_tex_maxtime_ms", "0.5", FCVAR_DEVELOPMENTONLY, "Cutoff time (in ms) spent in ServiceAsyncTextureLoads" );
  81. // Material system console channel
  82. BEGIN_DEFINE_LOGGING_CHANNEL( LOG_MaterialSystemConsole, "MaterialSystemConsole", LCF_CONSOLE_ONLY );
  83. ADD_LOGGING_CHANNEL_TAG( "Console" );
  84. END_DEFINE_LOGGING_CHANNEL();
  85. IMaterialInternal *g_pErrorMaterial = NULL;
  86. #if defined( INCLUDE_SCALEFORM )
  87. extern IScaleformUI* g_pScaleformUI;
  88. #endif
  89. CreateInterfaceFn g_fnMatSystemConnectCreateInterface = NULL;
  90. #ifdef _PS3
  91. #define m_pRenderContext Ps3TlsMaterialSystemRenderContext
  92. #elif defined(_X360)
  93. IMatRenderContextInternal *CMaterialSystem::m_pRenderContexts[2];
  94. #define m_pRenderContext CMaterialSystem::m_pRenderContexts[(int)ThreadInMainThread()]
  95. #else
  96. CTHREADLOCALPTR(IMatRenderContextInternal) CMaterialSystem::m_pRenderContext;
  97. #endif
  98. #if defined( _X360 )
  99. static const unsigned int g_GamerpicSize = 64;
  100. static const ImageFormat g_GamerpicFormat = IMAGE_FORMAT_LINEAR_BGRA8888; // note that this format is intentionally BGRA instead of ARBB
  101. #endif // _X360
  102. //#define PERF_TESTING 1
  103. #ifdef DX_TO_GL_ABSTRACTION
  104. // Uncomment if you want the material queued system to run on its own thread pool
  105. // Otherwise it will use the global thread pool
  106. #define MAT_QUEUED_OWN_THREADPOOL
  107. #endif
  108. //-----------------------------------------------------------------------------
  109. // Implementational structures
  110. //-----------------------------------------------------------------------------
  111. #define MATERIAL_MAX_TREE_DEPTH 256
  112. //-----------------------------------------------------------------------------
  113. // Singleton instance exposed to the engine
  114. //-----------------------------------------------------------------------------
  115. CMaterialSystem g_MaterialSystem;
  116. EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CMaterialSystem, IMaterialSystem,
  117. MATERIAL_SYSTEM_INTERFACE_VERSION, g_MaterialSystem );
  118. // Expose this to the external shader DLLs
  119. MaterialSystem_Config_t g_config;
  120. EXPOSE_SINGLE_INTERFACE_GLOBALVAR( MaterialSystem_Config_t, MaterialSystem_Config_t, MATERIALSYSTEM_CONFIG_VERSION, g_config );
  121. //-----------------------------------------------------------------------------
  122. CThreadFastMutex g_MatSysMutex;
  123. //-----------------------------------------------------------------------------
  124. // Purpose: additional materialsystem information, internal use only
  125. //-----------------------------------------------------------------------------
  126. #ifndef _GAMECONSOLE
  127. struct MaterialSystem_Config_Internal_t
  128. {
  129. int gpu_level;
  130. };
  131. MaterialSystem_Config_Internal_t g_config_internal;
  132. #endif
  133. //-----------------------------------------------------------------------------
  134. // Necessary to allow the shader DLLs to get ahold of IMaterialSystemHardwareConfig
  135. //-----------------------------------------------------------------------------
  136. IHardwareConfigInternal* g_pHWConfig = 0;
  137. static void *GetHardwareConfig()
  138. {
  139. if ( g_pHWConfig )
  140. return (IMaterialSystemHardwareConfig*)g_pHWConfig;
  141. // can't call QueryShaderAPI here because it calls a factory function
  142. // and we end up in an infinite recursion
  143. return NULL;
  144. }
  145. EXPOSE_INTERFACE_FN( GetHardwareConfig, IMaterialSystemHardwareConfig, MATERIALSYSTEM_HARDWARECONFIG_INTERFACE_VERSION );
  146. //-----------------------------------------------------------------------------
  147. // Necessary to allow the shader DLLs to get ahold of ICvar
  148. //-----------------------------------------------------------------------------
  149. static void *GetICVar()
  150. {
  151. return g_pCVar;
  152. }
  153. EXPOSE_INTERFACE_FN( GetICVar, ICVar, CVAR_INTERFACE_VERSION );
  154. //-----------------------------------------------------------------------------
  155. // Accessor to get at the material system
  156. //-----------------------------------------------------------------------------
  157. IMaterialSystemInternal *g_pInternalMaterialSystem = &g_MaterialSystem;
  158. #ifndef _PS3
  159. IShaderUtil *g_pShaderUtil = &g_MaterialSystem;
  160. #endif
  161. IVJobs * g_pVJobs = NULL;
  162. #if defined( USE_SDL ) || defined( OSX )
  163. #include "appframework/ilaunchermgr.h"
  164. ILauncherMgr *g_pLauncherMgr = NULL; // set in CMaterialSystem::Connect
  165. #endif
  166. //-----------------------------------------------------------------------------
  167. // Factory used to get at internal interfaces (used by shaderapi + shader dlls)
  168. //-----------------------------------------------------------------------------
  169. void *ShaderFactory( const char *pName, int *pReturnCode )
  170. {
  171. if (pReturnCode)
  172. {
  173. *pReturnCode = IFACE_OK;
  174. }
  175. if ( !Q_stricmp( pName, FILESYSTEM_INTERFACE_VERSION ))
  176. return g_pFullFileSystem;
  177. if ( !Q_stricmp( pName, QUEUEDLOADER_INTERFACE_VERSION ))
  178. return g_pQueuedLoader;
  179. if ( !Q_stricmp( pName, VJOBS_INTERFACE_VERSION ) )
  180. return g_pVJobs;
  181. #if defined( _X360 )
  182. if ( !Q_stricmp( pName, XBOXINSTALLER_INTERFACE_VERSION ))
  183. return g_pXboxInstaller;
  184. #endif
  185. if ( !Q_stricmp( pName, SHADER_UTIL_INTERFACE_VERSION ))
  186. return g_pShaderUtil;
  187. #if defined( USE_SDL )
  188. if ( !Q_stricmp( pName, "SDLMgrInterface001" /*SDLMGR_INTERFACE_VERSION*/ ))
  189. return g_pLauncherMgr;
  190. #endif
  191. #if PLATFORM_OSX
  192. if ( !Q_stricmp( pName, "CocoaMgrInterface006" /*COCOAMGR_INTERFACE_VERSION*/ ))
  193. return g_pLauncherMgr;
  194. #endif
  195. void * pInterface = g_MaterialSystem.QueryInterface( pName );
  196. if ( pInterface )
  197. return pInterface;
  198. if ( pReturnCode )
  199. {
  200. *pReturnCode = IFACE_FAILED;
  201. }
  202. return NULL;
  203. }
  204. //-----------------------------------------------------------------------------
  205. // Resource preloading for materials.
  206. //-----------------------------------------------------------------------------
  207. class CResourcePreloadMaterial : public CResourcePreload
  208. {
  209. virtual bool CreateResource( const char *pName )
  210. {
  211. IMaterial *pMaterial = g_MaterialSystem.FindMaterial( pName, TEXTURE_GROUP_WORLD, false );
  212. IMaterialInternal *pMatInternal = static_cast< IMaterialInternal * >( pMaterial );
  213. if ( pMatInternal )
  214. {
  215. // always work with the realtime material internally
  216. pMatInternal = pMatInternal->GetRealTimeVersion();
  217. // tag these for later identification (prevents an unwanted purge)
  218. pMatInternal->MarkAsPreloaded( true );
  219. if ( !pMatInternal->IsErrorMaterial() )
  220. {
  221. // force material's textures to create now
  222. pMatInternal->Precache();
  223. return true;
  224. }
  225. else
  226. {
  227. if ( IsPosix() )
  228. {
  229. printf("\n ##### CResourcePreloadMaterial::CreateResource can't find material %s\n", pName);
  230. }
  231. }
  232. }
  233. return false;
  234. }
  235. //-----------------------------------------------------------------------------
  236. // Called before queued loader i/o jobs are actually performed. Must free up memory
  237. // to ensure i/o requests have enough memory to succeed. The materials that were
  238. // touched by the CreateResource() are inhibited from purging (as is their textures,
  239. // by virtue of ref counts), all others are candidates. The preloaded materials
  240. // are by definition zero ref'd until owned by the normal loading process. Any material
  241. // that stays zero ref'd is a candidate for the post load purge.
  242. //-----------------------------------------------------------------------------
  243. virtual void PurgeUnreferencedResources()
  244. {
  245. bool bSpew = ( g_pQueuedLoader->GetSpewDetail() & LOADER_DETAIL_PURGES ) != 0;
  246. bool bDidUncacheMaterial = false;
  247. MaterialHandle_t hNext;
  248. for ( MaterialHandle_t hMaterial = g_MaterialSystem.FirstMaterial(); hMaterial != g_MaterialSystem.InvalidMaterial(); hMaterial = hNext )
  249. {
  250. hNext = g_MaterialSystem.NextMaterial( hMaterial );
  251. IMaterialInternal *pMatInternal = g_MaterialSystem.GetMaterialInternal( hMaterial );
  252. Assert( pMatInternal->GetReferenceCount() >= 0 );
  253. // preloaded materials are safe from this pre-purge
  254. if ( !pMatInternal->IsPreloaded() )
  255. {
  256. // undo any possible artifical ref count
  257. pMatInternal->ArtificialRelease();
  258. if ( pMatInternal->GetReferenceCount() <= 0 )
  259. {
  260. if ( bSpew )
  261. {
  262. Msg( "CResourcePreloadMaterial: Purging: %s (%d)\n", pMatInternal->GetName(), pMatInternal->GetReferenceCount() );
  263. }
  264. bDidUncacheMaterial = true;
  265. pMatInternal->Uncache();
  266. pMatInternal->DeleteIfUnreferenced();
  267. }
  268. }
  269. else
  270. {
  271. // clear the bit
  272. pMatInternal->MarkAsPreloaded( false );
  273. }
  274. }
  275. // purged materials unreference their textures
  276. // purge any zero ref'd textures
  277. TextureManager()->RemoveUnusedTextures();
  278. // fixup any excluded textures, may cause some new batch requests
  279. MaterialSystem()->UpdateExcludedTextures();
  280. }
  281. virtual void PurgeAll()
  282. {
  283. bool bSpew = ( g_pQueuedLoader->GetSpewDetail() & LOADER_DETAIL_PURGES ) != 0;
  284. bool bDidUncacheMaterial = false;
  285. MaterialHandle_t hNext;
  286. for ( MaterialHandle_t hMaterial = g_MaterialSystem.FirstMaterial(); hMaterial != g_MaterialSystem.InvalidMaterial(); hMaterial = hNext )
  287. {
  288. hNext = g_MaterialSystem.NextMaterial( hMaterial );
  289. IMaterialInternal *pMatInternal = g_MaterialSystem.GetMaterialInternal( hMaterial );
  290. Assert( pMatInternal->GetReferenceCount() >= 0 );
  291. pMatInternal->MarkAsPreloaded( false );
  292. // undo any possible artifical ref count
  293. pMatInternal->ArtificialRelease();
  294. if ( pMatInternal->GetReferenceCount() <= 0 )
  295. {
  296. if ( bSpew )
  297. {
  298. Msg( "CResourcePreloadMaterial: Purging: %s (%d)\n", pMatInternal->GetName(), pMatInternal->GetReferenceCount() );
  299. }
  300. bDidUncacheMaterial = true;
  301. pMatInternal->Uncache();
  302. pMatInternal->DeleteIfUnreferenced();
  303. }
  304. }
  305. // purged materials unreference their textures
  306. // purge any zero ref'd textures
  307. TextureManager()->RemoveUnusedTextures();
  308. }
  309. void OnEndMapLoading( bool bAbort )
  310. {
  311. CMaterialDict *pDict = g_MaterialSystem.GetMaterialDict();
  312. for (MaterialHandle_t i = pDict->FirstMaterial(); i != pDict->InvalidMaterial(); i = pDict->NextMaterial(i) )
  313. {
  314. pDict->GetMaterialInternal(i)->CompactMaterialVars();
  315. }
  316. CompactMaterialVarHeap();
  317. }
  318. #if defined( _PS3 )
  319. virtual bool RequiresRendererLock()
  320. {
  321. return true;
  322. }
  323. #endif // _PS3
  324. };
  325. static CResourcePreloadMaterial s_ResourcePreloadMaterial;
  326. //-----------------------------------------------------------------------------
  327. // Resource preloading for cubemaps.
  328. //-----------------------------------------------------------------------------
  329. class CResourcePreloadCubemap : public CResourcePreload
  330. {
  331. virtual bool CreateResource( const char *pName )
  332. {
  333. ITexture *pTexture = g_MaterialSystem.FindTexture( pName, TEXTURE_GROUP_CUBE_MAP, true );
  334. ITextureInternal *pTexInternal = static_cast< ITextureInternal * >( pTexture );
  335. if ( pTexInternal )
  336. {
  337. // There can be cubemaps that are unbound by materials. To prevent an unwanted purge,
  338. // mark and increase the ref count. Otherwise the pre-purge discards these zero
  339. // ref'd textures, and then the normal loading process hitches on the miss.
  340. // The zombie cubemaps DO get discarded after the normal loading process completes
  341. // if no material references them.
  342. pTexInternal->MarkAsPreloaded( true );
  343. pTexInternal->IncrementReferenceCount();
  344. if ( !IsErrorTexture( pTexInternal ) )
  345. {
  346. return true;
  347. }
  348. }
  349. return false;
  350. }
  351. //-----------------------------------------------------------------------------
  352. // All valid cubemaps should have been owned by their materials. Undo the preloaded
  353. // cubemap locks. Any zero ref'd cubemaps will be purged by the normal loading path conclusion.
  354. //-----------------------------------------------------------------------------
  355. virtual void OnEndMapLoading( bool bAbort )
  356. {
  357. int iIndex = -1;
  358. for ( ;; )
  359. {
  360. ITextureInternal *pTexInternal;
  361. iIndex = TextureManager()->FindNext( iIndex, &pTexInternal );
  362. if ( iIndex == -1 || !pTexInternal )
  363. {
  364. // end of list
  365. break;
  366. }
  367. if ( pTexInternal->IsPreloaded() )
  368. {
  369. // undo the artificial increase
  370. pTexInternal->MarkAsPreloaded( false );
  371. pTexInternal->DecrementReferenceCount();
  372. }
  373. }
  374. }
  375. #if defined( _PS3 )
  376. virtual bool RequiresRendererLock()
  377. {
  378. return true;
  379. }
  380. #endif // _PS3
  381. };
  382. static CResourcePreloadCubemap s_ResourcePreloadCubemap;
  383. //-----------------------------------------------------------------------------
  384. // Creates the debugging materials
  385. //-----------------------------------------------------------------------------
  386. void CMaterialSystem::CreateDebugMaterials()
  387. {
  388. if ( !m_pDrawFlatMaterial )
  389. {
  390. KeyValues *pVMTKeyValues = new KeyValues( "UnlitGeneric" );
  391. pVMTKeyValues->SetInt( "$model", 1 );
  392. pVMTKeyValues->SetFloat( "$decalscale", 0.05f );
  393. pVMTKeyValues->SetString( "$basetexture", "error" ); // This is the "error texture"
  394. pVMTKeyValues->SetInt( "$gammacolorread", 1 );
  395. pVMTKeyValues->SetInt( "$linearwrite", 1 );
  396. g_pErrorMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___error.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  397. pVMTKeyValues = new KeyValues( "UnlitGeneric" );
  398. pVMTKeyValues->SetInt( "$flat", 1 );
  399. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  400. pVMTKeyValues->SetInt( "$gammacolorread", 1 );
  401. pVMTKeyValues->SetInt( "$linearwrite", 1 );
  402. m_pDrawFlatMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___flat.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  403. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  404. pVMTKeyValues->SetInt( "$nocull", 1 );
  405. m_pBufferClearObeyStencil[BUFFER_CLEAR_NONE] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil0.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  406. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  407. pVMTKeyValues->SetInt( "$nocull", 1 );
  408. pVMTKeyValues->SetInt( "$clearcolor", 1 );
  409. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  410. m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil1.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  411. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  412. pVMTKeyValues->SetInt( "$nocull", 1 );
  413. pVMTKeyValues->SetInt( "$clearalpha", 1 );
  414. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  415. m_pBufferClearObeyStencil[BUFFER_CLEAR_ALPHA] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil2.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  416. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  417. pVMTKeyValues->SetInt( "$nocull", 1 );
  418. pVMTKeyValues->SetInt( "$clearcolor", 1 );
  419. pVMTKeyValues->SetInt( "$clearalpha", 1 );
  420. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  421. m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_ALPHA] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil3.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  422. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  423. pVMTKeyValues->SetInt( "$nocull", 1 );
  424. pVMTKeyValues->SetInt( "$cleardepth", 1 );
  425. m_pBufferClearObeyStencil[BUFFER_CLEAR_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil4.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  426. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  427. pVMTKeyValues->SetInt( "$nocull", 1 );
  428. pVMTKeyValues->SetInt( "$cleardepth", 1 );
  429. pVMTKeyValues->SetInt( "$clearcolor", 1 );
  430. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  431. m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil5.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  432. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  433. pVMTKeyValues->SetInt( "$nocull", 1 );
  434. pVMTKeyValues->SetInt( "$cleardepth", 1 );
  435. pVMTKeyValues->SetInt( "$clearalpha", 1 );
  436. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  437. m_pBufferClearObeyStencil[BUFFER_CLEAR_ALPHA_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil6.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  438. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  439. pVMTKeyValues->SetInt( "$nocull", 1 );
  440. pVMTKeyValues->SetInt( "$cleardepth", 1 );
  441. pVMTKeyValues->SetInt( "$clearcolor", 1 );
  442. pVMTKeyValues->SetInt( "$clearalpha", 1 );
  443. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  444. m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_ALPHA_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil7.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  445. if ( IsPS3() )
  446. {
  447. pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
  448. pVMTKeyValues->SetInt( "$nocull", 1 );
  449. pVMTKeyValues->SetInt( "$cleardepth", 1 );
  450. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  451. pVMTKeyValues->SetInt( "$reloadzcull", 1 );
  452. m_pReloadZcullMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "__reload_zcull.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  453. }
  454. if ( IsX360() )
  455. {
  456. pVMTKeyValues = new KeyValues( "RenderTargetBlit_X360" );
  457. m_pRenderTargetBlitMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___renderTargetBlit.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  458. }
  459. // PORTAL2 - hack to make sure BINK shaders are always precached to avoid hitches at runtime
  460. if ( IsGameConsole() )
  461. {
  462. pVMTKeyValues = new KeyValues( "Bik" );
  463. pVMTKeyValues->SetInt( "$nofog", 1 );
  464. pVMTKeyValues->SetInt( "$spriteorientation", 3 );
  465. pVMTKeyValues->SetInt( "$translucent", 1 );
  466. pVMTKeyValues->SetInt( "$vertexcolor", 1 );
  467. pVMTKeyValues->SetInt( "$vertexalpha", 1 );
  468. pVMTKeyValues->SetInt( "$nolod", 1 );
  469. pVMTKeyValues->SetInt( "$nomip", 1 );
  470. pVMTKeyValues->SetInt( "$nobasetexture", 1 );
  471. m_pBIKPreloadMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___binkprecache.vmt", pVMTKeyValues ))->GetRealTimeVersion();
  472. }
  473. ShaderSystem()->CreateDebugMaterials();
  474. }
  475. }
  476. //-----------------------------------------------------------------------------
  477. // Deletes the debugging materials
  478. //-----------------------------------------------------------------------------
  479. void CMaterialSystem::CleanUpDebugMaterials()
  480. {
  481. if ( m_pDrawFlatMaterial )
  482. {
  483. m_pDrawFlatMaterial->DecrementReferenceCount();
  484. RemoveMaterial( m_pDrawFlatMaterial );
  485. m_pDrawFlatMaterial = NULL;
  486. for ( int i = BUFFER_CLEAR_NONE; i < BUFFER_CLEAR_TYPE_COUNT; ++i )
  487. {
  488. m_pBufferClearObeyStencil[i]->DecrementReferenceCount();
  489. RemoveMaterial( m_pBufferClearObeyStencil[i] );
  490. m_pBufferClearObeyStencil[i] = NULL;
  491. }
  492. if ( IsPS3() )
  493. {
  494. m_pReloadZcullMaterial->DecrementReferenceCount();
  495. RemoveMaterial( m_pReloadZcullMaterial );
  496. m_pReloadZcullMaterial = NULL;
  497. }
  498. if ( IsX360() )
  499. {
  500. m_pRenderTargetBlitMaterial->DecrementReferenceCount();
  501. RemoveMaterial( m_pRenderTargetBlitMaterial );
  502. m_pRenderTargetBlitMaterial = NULL;
  503. }
  504. // PORTAL2 - clean up preloaded bink shader
  505. if ( IsGameConsole() )
  506. {
  507. m_pBIKPreloadMaterial->DecrementReferenceCount();
  508. RemoveMaterial( m_pBIKPreloadMaterial );
  509. m_pBIKPreloadMaterial = NULL;
  510. }
  511. ShaderSystem()->CleanUpDebugMaterials();
  512. }
  513. }
  514. void CMaterialSystem::CleanUpErrorMaterial()
  515. {
  516. // Destruction of g_pErrorMaterial is deferred until after CMaterialDict::Shutdown.
  517. // The global g_pErrorMaterial is set to NULL so that IMaterialInternal::DestroyMaterial will delete it.
  518. IMaterialInternal *pErrorMaterial = g_pErrorMaterial;
  519. g_pErrorMaterial = NULL;
  520. pErrorMaterial->DecrementReferenceCount();
  521. IMaterialInternal::DestroyMaterial( pErrorMaterial );
  522. }
  523. //-----------------------------------------------------------------------------
  524. // Constructor
  525. //-----------------------------------------------------------------------------
  526. CMaterialSystem::CMaterialSystem()
  527. {
  528. m_nRenderThreadID = 0xFFFFFFFF;
  529. m_ShaderHInst = 0;
  530. m_pMaterialProxyFactory = NULL;
  531. m_pClientMaterialSystemInterface = NULL;
  532. m_nAdapter = 0;
  533. m_nAdapterFlags = 0;
  534. m_bRequestedEditorMaterials = false;
  535. m_bRequestedGBuffers = false;
  536. m_StandardTexturesAllocated = false;
  537. m_bRestoreManangedResources = true;
  538. m_bInFrame = false;
  539. m_bThreadHasOwnership = false;
  540. #ifdef DX_TO_GL_ABSTRACTION
  541. m_ThreadOwnershipID = 0;
  542. #endif
  543. m_pShaderDLL = NULL;
  544. m_FullbrightLightmapTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  545. m_FullbrightBumpedLightmapTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  546. m_BlackTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  547. m_BlackAlphaZeroTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  548. m_FlatNormalTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  549. m_FlatSSBumpTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  550. m_GreyTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  551. m_GreyAlphaZeroTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  552. m_WhiteTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  553. m_LinearToGammaTableTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  554. m_LinearToGammaIdentityTableTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  555. m_MaxDepthTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
  556. m_bInStubMode = false;
  557. m_pForcedTextureLoadPathID = NULL;
  558. m_bDisableRenderTargetAllocationForever = false;
  559. m_nAllocatingRenderTargets = false;
  560. m_pRenderContext = &m_HardwareRenderContext;
  561. m_iCurQueuedContext = 0;
  562. m_bGeneratedConfig = false;
  563. m_pMatQueueThreadPool = NULL;
  564. m_pActiveAsyncTextureLoad = NULL;
  565. #ifndef _PS3
  566. m_pActiveAsyncJob = NULL;
  567. #else
  568. m_bQMSJobSubmitted = false;
  569. #endif
  570. m_IdealThreadMode = m_ThreadMode = MATERIAL_SINGLE_THREADED;
  571. m_nServiceThread = 0;
  572. m_nConfigurationFlags = 0;
  573. m_bForcedSingleThreaded = true;
  574. m_bAllowQueuedRendering = false;
  575. m_bStereoBoolsInitialized = false;
  576. m_bIsStereoSupported = false;
  577. m_bIsStereoActiveThisFrame = false;
  578. m_bLevelLoadingComplete = false;
  579. m_pSubString = NULL;
  580. m_bDeferredMaterialReload = false;
  581. }
  582. CMaterialSystem::~CMaterialSystem()
  583. {
  584. if (m_pShaderDLL)
  585. {
  586. delete[] m_pShaderDLL;
  587. }
  588. if ( m_pSubString )
  589. {
  590. free( m_pSubString );
  591. m_pSubString = NULL;
  592. }
  593. }
  594. //-----------------------------------------------------------------------------
  595. // Creates/destroys the shader implementation for the selected API
  596. //-----------------------------------------------------------------------------
  597. CreateInterfaceFn CMaterialSystem::CreateShaderAPI( char const* pShaderDLL )
  598. {
  599. if ( !pShaderDLL )
  600. return 0;
  601. // Clean up the old shader
  602. DestroyShaderAPI();
  603. // Load the new shader
  604. m_ShaderHInst = Sys_LoadModule( pShaderDLL );
  605. // Error loading the shader
  606. if ( !m_ShaderHInst )
  607. return 0;
  608. // Get our class factory methods...
  609. return Sys_GetFactory( m_ShaderHInst );
  610. }
  611. void CMaterialSystem::DestroyShaderAPI()
  612. {
  613. if (m_ShaderHInst)
  614. {
  615. // NOTE: By unloading the library, this will destroy m_pShaderAPI
  616. Sys_UnloadModule( m_ShaderHInst );
  617. g_pShaderAPI = 0;
  618. g_pHWConfig = 0;
  619. g_pShaderShadow = 0;
  620. m_ShaderHInst = 0;
  621. }
  622. }
  623. //-----------------------------------------------------------------------------
  624. // Sets which shader we should be using. Has to be done before connect!
  625. //-----------------------------------------------------------------------------
  626. void CMaterialSystem::SetShaderAPI( char const *pShaderAPIDLL )
  627. {
  628. #if defined( _PS3 ) || defined( _OSX )
  629. return;
  630. #endif
  631. if ( m_ShaderAPIFactory )
  632. {
  633. Warning( "Cannot set the shader API twice!\n" );
  634. return;
  635. }
  636. if ( !pShaderAPIDLL )
  637. {
  638. pShaderAPIDLL = "shaderapidx9";
  639. }
  640. // m_pShaderDLL is needed to spew driver info
  641. Assert( pShaderAPIDLL );
  642. int len = Q_strlen( pShaderAPIDLL ) + 1;
  643. m_pShaderDLL = new char[len];
  644. memcpy( m_pShaderDLL, pShaderAPIDLL, len );
  645. m_ShaderAPIFactory = CreateShaderAPI( pShaderAPIDLL );
  646. if ( !m_ShaderAPIFactory )
  647. {
  648. DestroyShaderAPI();
  649. }
  650. }
  651. //-----------------------------------------------------------------------------
  652. // Connect/disconnect
  653. //-----------------------------------------------------------------------------
  654. bool CMaterialSystem::Connect( CreateInterfaceFn factory )
  655. {
  656. if ( !factory )
  657. return false;
  658. if ( !BaseClass::Connect( factory ) )
  659. return false;
  660. if ( !g_pFullFileSystem )
  661. {
  662. Warning( "The material system requires the filesystem to run!\n" );
  663. return false;
  664. }
  665. g_pVJobs = ( IVJobs* )factory( VJOBS_INTERFACE_VERSION, NULL );
  666. // Get at the interfaces exported by the shader DLL
  667. #ifndef _OSX
  668. g_pShaderDeviceMgr = (IShaderDeviceMgr*)m_ShaderAPIFactory( SHADER_DEVICE_MGR_INTERFACE_VERSION, 0 );
  669. if ( !g_pShaderDeviceMgr )
  670. return false;
  671. g_pHWConfig = (IHardwareConfigInternal*)m_ShaderAPIFactory( MATERIALSYSTEM_HARDWARECONFIG_INTERFACE_VERSION, 0 );
  672. if ( !g_pHWConfig )
  673. return false;
  674. #endif
  675. #ifndef DEDICATED
  676. #if defined( USE_SDL )
  677. #if !defined( LINUX )
  678. g_pHWConfig = g_pHardwareConfig;
  679. #endif
  680. g_pLauncherMgr = (ILauncherMgr *)factory( "SDLMgrInterface001", NULL );
  681. if ( !g_pLauncherMgr )
  682. return false;
  683. #elif defined( _PS3 )
  684. g_pHWConfig = g_pHardwareConfig;
  685. #elif defined( _OSX )
  686. g_pHWConfig = g_pHardwareConfig;
  687. // write a link to the Cocoa manager into the config record so the shader subsystem can get to it.
  688. // alas we can't include icocoamgr.h due to a header conflict in the SDK, so the interface name here is hardwired for now
  689. // /System/Library/Frameworks/CoreServices.framework/Frameworks/CarbonCore.framework/Headers/Threads.h:520:
  690. // error: declaration of C function ‘OSErr CreateThreadPool(ThreadStyle, SInt16, Size)’
  691. #define COCOAMGR_INTERFACE_VERSION "CocoaMgrInterface006"
  692. g_pLauncherMgr = (ILauncherMgr *)factory( COCOAMGR_INTERFACE_VERSION, NULL );
  693. if ( !g_pLauncherMgr )
  694. return false;
  695. #elif defined(_WIN32)
  696. #else
  697. #error
  698. #endif
  699. #endif // !DEDICATED
  700. #ifndef _OSX
  701. // FIXME: ShaderAPI, ShaderDevice, and ShaderShadow should only come in after setting mode
  702. g_pShaderAPI = (IShaderAPI*)m_ShaderAPIFactory( SHADERAPI_INTERFACE_VERSION, 0 );
  703. if ( !g_pShaderAPI )
  704. return false;
  705. g_pShaderDevice = (IShaderDevice*)m_ShaderAPIFactory( SHADER_DEVICE_INTERFACE_VERSION, 0 );
  706. if ( !g_pShaderDevice )
  707. return false;
  708. g_pShaderShadow = (IShaderShadow*)m_ShaderAPIFactory( SHADERSHADOW_INTERFACE_VERSION, 0 );
  709. if ( !g_pShaderShadow )
  710. return false;
  711. #endif
  712. // Remember the factory for connect
  713. g_fnMatSystemConnectCreateInterface = factory;
  714. #if defined( INCLUDE_SCALEFORM )
  715. g_pScaleformUI = ( IScaleformUI* ) factory( SCALEFORMUI_INTERFACE_VERSION, 0 );
  716. #endif
  717. return g_pShaderDeviceMgr->Connect( ShaderFactory );
  718. }
  719. void CMaterialSystem::Disconnect()
  720. {
  721. // Forget the factory for connect
  722. g_fnMatSystemConnectCreateInterface = NULL;
  723. if ( g_pShaderDeviceMgr )
  724. {
  725. g_pShaderDeviceMgr->Disconnect();
  726. g_pShaderDeviceMgr = NULL;
  727. // Unload the DLL
  728. DestroyShaderAPI();
  729. }
  730. #if !defined( _PS3 ) && !defined( _OSX )
  731. g_pShaderAPI = NULL;
  732. g_pHWConfig = NULL;
  733. g_pShaderShadow = NULL;
  734. g_pShaderDevice = NULL;
  735. #endif
  736. #if defined( INCLUDE_SCALEFORM )
  737. g_pScaleformUI = NULL;
  738. #endif
  739. BaseClass::Disconnect();
  740. }
  741. //-----------------------------------------------------------------------------
  742. // Used to enable editor materials. Must be called before Init.
  743. //-----------------------------------------------------------------------------
  744. void CMaterialSystem::EnableEditorMaterials()
  745. {
  746. m_bRequestedEditorMaterials = true;
  747. }
  748. void CMaterialSystem::EnableGBuffers()
  749. {
  750. m_bRequestedGBuffers = true;
  751. }
  752. //-----------------------------------------------------------------------------
  753. // Method to get at interfaces supported by the SHADDERAPI
  754. //-----------------------------------------------------------------------------
  755. void *CMaterialSystem::QueryShaderAPI( const char *pInterfaceName )
  756. {
  757. // Returns various interfaces supported by the shader API dll
  758. void *pInterface = NULL;
  759. if (m_ShaderAPIFactory)
  760. {
  761. pInterface = m_ShaderAPIFactory( pInterfaceName, NULL );
  762. }
  763. return pInterface;
  764. }
  765. //-----------------------------------------------------------------------------
  766. // Method to get at different interfaces supported by the material system
  767. //-----------------------------------------------------------------------------
  768. void *CMaterialSystem::QueryInterface( const char *pInterfaceName )
  769. {
  770. // Returns various interfaces supported by the shader API dll
  771. void *pInterface = QueryShaderAPI( pInterfaceName );
  772. if ( pInterface )
  773. return pInterface;
  774. CreateInterfaceFn factory = Sys_GetFactoryThis(); // This silly construction is necessary
  775. return factory( pInterfaceName, NULL ); // to prevent the LTCG compiler from crashing.
  776. }
  777. //-----------------------------------------------------------------------------
  778. // Must be called before Init(), if you're going to call it at all...
  779. //-----------------------------------------------------------------------------
  780. void CMaterialSystem::SetAdapter( int nAdapter, int nAdapterFlags )
  781. {
  782. m_nAdapter = nAdapter;
  783. m_nAdapterFlags = nAdapterFlags;
  784. g_pShaderDeviceMgr->GetCurrentModeInfo( &m_nAdapterInfo, m_nAdapter );
  785. }
  786. //-----------------------------------------------------------------------------
  787. // Initializes the color correction terms
  788. //-----------------------------------------------------------------------------
  789. void CMaterialSystem::InitColorCorrection( )
  790. {
  791. if ( ColorCorrectionSystem() )
  792. {
  793. ColorCorrectionSystem()->Init();
  794. }
  795. }
  796. #ifndef _PS3 // make some empty stubs so we can use IsPS3() instead of ifdefs
  797. static inline void PS3InitFontLibrary( unsigned fontFileCacheSizeInBytes, unsigned maxNumFonts ) {};
  798. static inline void PS3DumpFontLibrary(){}
  799. #define kPS3_DEFAULT_MAX_USER_FONTS 0
  800. #endif
  801. //-----------------------------------------------------------------------------
  802. // Initialization + shutdown of the material system
  803. //-----------------------------------------------------------------------------
  804. void AllocateScratchRSXMemory();
  805. InitReturnVal_t CMaterialSystem::Init()
  806. {
  807. InitReturnVal_t nRetVal = BaseClass::Init();
  808. if ( nRetVal != INIT_OK )
  809. return nRetVal;
  810. // NOTE! : Overbright is 1.0 so that Hammer will work properly with the white bumped and unbumped lightmaps.
  811. MathLib_Init( 2.2f, 2.2f, 0.0f, OVERBRIGHT );
  812. g_pShaderDeviceMgr->SetAdapter( m_nAdapter, m_nAdapterFlags );
  813. if ( g_pShaderDeviceMgr->Init( ) != INIT_OK )
  814. {
  815. DestroyShaderAPI();
  816. return INIT_FAILED;
  817. }
  818. mat_forcemanagedtextureintohardware.SetValue( HardwareConfig()->PreferTexturesInHWMemory() );
  819. mat_forcehardwaresync.SetValue( HardwareConfig()->PreferHardwareSync() );
  820. mat_dxlevel.SetValue( HardwareConfig()->GetDXSupportLevel() );
  821. // Texture manager...
  822. TextureManager()->Init( m_nAdapterFlags );
  823. // Shader system!
  824. ShaderSystem()->Init();
  825. #if defined( WIN32 ) && !defined( _X360 )
  826. // HACKHACK: <sigh> This horrible hack is possibly the only way to reliably detect an old
  827. // version of hammer initializing the material system. We need to know this so that we set
  828. // up the editor materials properly. If we don't do this, we never allocate the white lightmap,
  829. // for example. We can remove this when we update the SDK!!
  830. char szExeName[_MAX_PATH];
  831. if ( ::GetModuleFileName( ( HINSTANCE )GetModuleHandle( NULL ), szExeName, sizeof( szExeName ) ) )
  832. {
  833. char szRight[20];
  834. Q_StrRight( szExeName, 11, szRight, sizeof( szRight ) );
  835. if ( ( !Q_stricmp( szRight, "\\hammer.exe" ) ) || ( !Q_stricmp( szRight, "\\vmview.exe" ) ) )
  836. {
  837. m_bRequestedEditorMaterials = true;
  838. m_bRequestedGBuffers = true;
  839. }
  840. }
  841. // HACKHACK: This will go away when we get rid of tools mode in the first place.
  842. if ( CommandLine()->FindParm( "-foundrymode" ) != 0 )
  843. {
  844. m_bRequestedEditorMaterials = true;
  845. m_bRequestedGBuffers = true;
  846. }
  847. if ( CommandLine()->FindParm( "-tools" ) != 0 )
  848. {
  849. m_bRequestedGBuffers = true;
  850. }
  851. if ( CommandLine()->FindParm( "-buildcubemaps" ) || CommandLine()->FindParm( "-buildmodelforworld" ) )
  852. {
  853. mat_queue_mode.SetValue( 0 );
  854. }
  855. #endif // WIN32
  856. m_nConfigurationFlags = 0;
  857. if ( m_bRequestedEditorMaterials )
  858. {
  859. m_nConfigurationFlags |= MATCONFIG_FLAGS_SUPPORT_EDITOR;
  860. }
  861. if ( m_bRequestedGBuffers )
  862. {
  863. m_nConfigurationFlags |= MATCONFIG_FLAGS_SUPPORT_GBUFFER;
  864. }
  865. InitColorCorrection();
  866. // Set up debug materials...
  867. CreateDebugMaterials();
  868. if ( IsGameConsole() )
  869. {
  870. g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_MATERIAL, &s_ResourcePreloadMaterial );
  871. g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_CUBEMAP, &s_ResourcePreloadCubemap );
  872. }
  873. if ( IsPS3() )
  874. {
  875. InitializePS3Fonts();
  876. // load the font library and keep it resident forever.
  877. // for an alternative means, where you just load and unload
  878. // the library as needed, look at PS3FontLibraryRAII --
  879. // that's disabled at the moment because we evidently render
  880. // characters ad hoc each frame always.
  881. PS3InitFontLibrary( 256 * 1024, kPS3_DEFAULT_MAX_USER_FONTS ); // try a 256kb file cache
  882. }
  883. // Set up a default material system config
  884. // GenerateConfigFromConfigKeyValues( &g_config, false );
  885. // UpdateConfig( false );
  886. // JAY: Added this command line parameter to force creating <32x32 mips
  887. // to test for reported performance regressions on some systems
  888. if ( CommandLine()->FindParm("-forceallmips") )
  889. {
  890. extern bool g_bForceTextureAllMips;
  891. g_bForceTextureAllMips = true;
  892. }
  893. BeginRenderTargetAllocation();
  894. m_CompositeTextureGenerator.Init();
  895. EndRenderTargetAllocation();
  896. m_CustomMaterialManager.Init();
  897. return m_HardwareRenderContext.Init( this );
  898. }
  899. //-----------------------------------------------------------------------------
  900. // For backwards compatability
  901. //-----------------------------------------------------------------------------
  902. static CreateInterfaceFn s_TempCVarFactory;
  903. static CreateInterfaceFn s_TempFileSystemFactory;
  904. void* TempCreateInterface( const char *pName, int *pReturnCode )
  905. {
  906. void *pRetVal = NULL;
  907. if ( s_TempCVarFactory )
  908. {
  909. pRetVal = s_TempCVarFactory( pName, pReturnCode );
  910. if (pRetVal)
  911. return pRetVal;
  912. }
  913. pRetVal = s_TempFileSystemFactory( pName, pReturnCode );
  914. if (pRetVal)
  915. return pRetVal;
  916. return NULL;
  917. }
  918. //-----------------------------------------------------------------------------
  919. // Initializes and shuts down the shader API
  920. //-----------------------------------------------------------------------------
  921. CreateInterfaceFn CMaterialSystem::Init( char const* pShaderAPIDLL,
  922. IMaterialProxyFactory *pMaterialProxyFactory,
  923. CreateInterfaceFn fileSystemFactory,
  924. CreateInterfaceFn cvarFactory )
  925. {
  926. SetShaderAPI( pShaderAPIDLL );
  927. s_TempCVarFactory = cvarFactory;
  928. s_TempFileSystemFactory = fileSystemFactory;
  929. if ( !Connect( TempCreateInterface ) )
  930. return 0;
  931. if (Init() != INIT_OK)
  932. return NULL;
  933. // save the proxy factory
  934. m_pMaterialProxyFactory = pMaterialProxyFactory;
  935. return m_ShaderAPIFactory;
  936. }
  937. void CMaterialSystem::Shutdown( )
  938. {
  939. DestroyMatQueueThreadPool();
  940. m_CustomMaterialManager.Shutdown();
  941. m_CompositeTextureGenerator.Shutdown();
  942. m_HardwareRenderContext.Shutdown();
  943. // Clean up standard textures
  944. ReleaseStandardTextures();
  945. // Clean up the debug materials
  946. CleanUpDebugMaterials();
  947. g_pMorphMgr->FreeMaterials();
  948. g_pOcclusionQueryMgr->FreeOcclusionQueryObjects();
  949. GetLightmaps()->Shutdown();
  950. m_MaterialDict.Shutdown();
  951. CleanUpErrorMaterial();
  952. // Shader system!
  953. ShaderSystem()->Shutdown();
  954. // Texture manager...
  955. TextureManager()->Shutdown();
  956. if (g_pShaderDeviceMgr)
  957. {
  958. g_pShaderDeviceMgr->Shutdown();
  959. }
  960. #if defined( _PS3 )
  961. // this would have been called in g_pShaderDeviceMgr->Shutdown(), but since g_pShaderDeviceMgr is sometimes NULL, we'll clean up mesh manager once more, just in case
  962. MeshMgr()->Shutdown();
  963. #endif
  964. if ( IsPS3() )
  965. PS3DumpFontLibrary();
  966. BaseClass::Shutdown();
  967. }
  968. void CMaterialSystem::ModInit()
  969. {
  970. // Set up a default material system config
  971. GenerateConfigFromConfigKeyValues( &g_config, false );
  972. UpdateConfig( false );
  973. // Shader system!
  974. ShaderSystem()->ModInit();
  975. }
  976. void CMaterialSystem::ModShutdown()
  977. {
  978. // Shader system!
  979. ShaderSystem()->ModShutdown();
  980. // HACK - this is here to unhook ourselves from the client interface, since we're not actually notified when it happens
  981. m_pMaterialProxyFactory = NULL;
  982. m_pClientMaterialSystemInterface = NULL;
  983. }
  984. //-----------------------------------------------------------------------------
  985. // Returns the current adapter in use
  986. //-----------------------------------------------------------------------------
  987. IMaterialSystemHardwareConfig *CMaterialSystem::GetHardwareConfig( const char *pVersion, int *returnCode )
  988. {
  989. return ( IMaterialSystemHardwareConfig * )m_ShaderAPIFactory( pVersion, returnCode );
  990. }
  991. //-----------------------------------------------------------------------------
  992. // Returns the current adapter in use
  993. //-----------------------------------------------------------------------------
  994. int CMaterialSystem::GetCurrentAdapter() const
  995. {
  996. return g_pShaderDevice->GetCurrentAdapter();
  997. }
  998. //-----------------------------------------------------------------------------
  999. //
  1000. //-----------------------------------------------------------------------------
  1001. void CMaterialSystem::SetThreadMode( MaterialThreadMode_t nextThreadMode, int nServiceThread )
  1002. {
  1003. m_IdealThreadMode = nextThreadMode;
  1004. m_nServiceThread = nServiceThread;
  1005. }
  1006. MaterialThreadMode_t CMaterialSystem::GetThreadMode()
  1007. {
  1008. return m_ThreadMode;
  1009. }
  1010. bool CMaterialSystem::IsRenderThreadSafe( )
  1011. {
  1012. #if defined( WIN32 ) && !defined( DX_TO_GL_ABSTRACTION )
  1013. return true;
  1014. #else
  1015. return ( m_ThreadMode != MATERIAL_QUEUED_THREADED && ThreadInMainThread() ) ||
  1016. ( m_ThreadMode == MATERIAL_QUEUED_THREADED && m_nRenderThreadID == ThreadGetCurrentId() );
  1017. #endif
  1018. }
  1019. void CMaterialSystem::OnDebugEvent( const char * pEvent )
  1020. {
  1021. g_pShaderDevice->OnDebugEvent( pEvent );
  1022. }
  1023. bool CMaterialSystem::AllowThreading( bool bAllow, int nServiceThread )
  1024. {
  1025. if ( CommandLine()->ParmValue( "-threads", 2 ) < 2 ) // if -threads specified on command line to restrict all the pools then obey and not turn on QMS
  1026. bAllow = false;
  1027. bool bOldAllow = m_bAllowQueuedRendering;
  1028. if ( GetCPUInformation().m_nPhysicalProcessors >= 2 || mat_queue_mode_force_allow.GetBool() )
  1029. {
  1030. m_bAllowQueuedRendering = bAllow;
  1031. bool bQueued = m_IdealThreadMode != MATERIAL_SINGLE_THREADED;
  1032. if ( bAllow && !bQueued )
  1033. {
  1034. // go into queued mode
  1035. DevMsg( "Queued Material System: ENABLED!\n" );
  1036. OnDebugEvent( "Allow Threading");
  1037. SetThreadMode( MATERIAL_QUEUED_THREADED, nServiceThread );
  1038. }
  1039. else if ( !bAllow && bQueued )
  1040. {
  1041. // disabling queued mode just needs to stop the queuing of drawing
  1042. // but still allow other threaded access to the Material System
  1043. // flush the queue
  1044. DevMsg( "Queued Material System: DISABLED!\n" );
  1045. ForceSingleThreaded();
  1046. MaterialLock_t hMaterialLock = Lock();
  1047. SetThreadMode( MATERIAL_SINGLE_THREADED, -1 );
  1048. Unlock( hMaterialLock );
  1049. OnDebugEvent( "Disallow Threading" );
  1050. }
  1051. }
  1052. else
  1053. {
  1054. m_bAllowQueuedRendering = false;
  1055. }
  1056. return bOldAllow;
  1057. }
  1058. void CMaterialSystem::ExecuteQueued()
  1059. {
  1060. }
  1061. //-----------------------------------------------------------------------------
  1062. //
  1063. //-----------------------------------------------------------------------------
  1064. IMatRenderContext *CMaterialSystem::GetRenderContext()
  1065. {
  1066. IMatRenderContext *pResult = m_pRenderContext;
  1067. if ( !pResult )
  1068. {
  1069. pResult = &m_HardwareRenderContext;
  1070. m_pRenderContext = &m_HardwareRenderContext;
  1071. }
  1072. return RetAddRef( pResult );
  1073. }
  1074. //-----------------------------------------------------------------------------
  1075. //
  1076. //-----------------------------------------------------------------------------
  1077. IMatRenderContext *CMaterialSystem::CreateRenderContext( MaterialContextType_t type )
  1078. {
  1079. switch ( type )
  1080. {
  1081. case MATERIAL_HARDWARE_CONTEXT:
  1082. return NULL;
  1083. case MATERIAL_QUEUED_CONTEXT:
  1084. {
  1085. CMatQueuedRenderContext *pQueuedContext = new CMatQueuedRenderContext;
  1086. pQueuedContext->Init( this, &m_HardwareRenderContext );
  1087. pQueuedContext->BeginQueue( &m_HardwareRenderContext );
  1088. return pQueuedContext;
  1089. }
  1090. case MATERIAL_NULL_CONTEXT:
  1091. {
  1092. CMatRenderContextBase *pNullContext = CreateNullRenderContext();
  1093. pNullContext->Init();
  1094. pNullContext->InitializeFrom( &m_HardwareRenderContext );
  1095. return pNullContext;
  1096. }
  1097. }
  1098. Assert(0);
  1099. return NULL;
  1100. }
  1101. //-----------------------------------------------------------------------------
  1102. //
  1103. //-----------------------------------------------------------------------------
  1104. IMatRenderContext *CMaterialSystem::SetRenderContext( IMatRenderContext *pNewContext )
  1105. {
  1106. IMatRenderContext *pOldContext = m_pRenderContext;
  1107. if ( pNewContext )
  1108. {
  1109. pNewContext->AddRef();
  1110. m_pRenderContext = ( assert_cast<IMatRenderContextInternal *>(pNewContext) );
  1111. }
  1112. else
  1113. {
  1114. m_pRenderContext = NULL;
  1115. }
  1116. return pOldContext;
  1117. }
  1118. //-----------------------------------------------------------------------------
  1119. // Get/Set Material proxy factory
  1120. //-----------------------------------------------------------------------------
  1121. IMaterialProxyFactory* CMaterialSystem::GetMaterialProxyFactory()
  1122. {
  1123. return m_pMaterialProxyFactory;
  1124. }
  1125. void CMaterialSystem::SetMaterialProxyFactory( IMaterialProxyFactory* pFactory )
  1126. {
  1127. // Changing the factory requires an uncaching of all materials
  1128. // since the factory may contain different proxies
  1129. UncacheAllMaterials();
  1130. m_pMaterialProxyFactory = pFactory;
  1131. }
  1132. IClientMaterialSystem *CMaterialSystem::GetClientMaterialSystemInterface()
  1133. {
  1134. if ( m_pClientMaterialSystemInterface )
  1135. return m_pClientMaterialSystemInterface;
  1136. if ( !m_pMaterialProxyFactory )
  1137. return NULL;
  1138. CreateInterfaceFn pClientFactory = m_pMaterialProxyFactory->GetFactory();
  1139. if ( !pClientFactory )
  1140. return NULL;
  1141. m_pClientMaterialSystemInterface = (IClientMaterialSystem *)pClientFactory( VCLIENTMATERIALSYSTEM_INTERFACE_VERSION, NULL );
  1142. return m_pClientMaterialSystemInterface;
  1143. }
  1144. void CMaterialSystem::RefreshFrontBufferNonInteractive()
  1145. {
  1146. #ifdef _PS3
  1147. extern bool IsItSafeToRefreshFrontBufferNonInteractivePs3();
  1148. if ( !IsItSafeToRefreshFrontBufferNonInteractivePs3() )
  1149. #else
  1150. if ( !ThreadInMainThread() )
  1151. #endif
  1152. return;
  1153. CMatRenderContextPtr pRenderContext( materials );
  1154. pRenderContext->RefreshFrontBufferNonInteractive();
  1155. }
  1156. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  1157. static CThreadFastMutex s_mtFrameTimestamps;
  1158. static double s_flMstThreadBeginTimestamp = 0.0f;
  1159. static double s_flTotalFrameBeginTimestamp = 0.0f;
  1160. static ApplicationPerformanceCountersInfo_t s_apci;
  1161. void OnFrameTimestampAvailableMain( float ms )
  1162. {
  1163. AUTO_LOCK( s_mtFrameTimestamps );
  1164. s_apci.msMain = ms;
  1165. }
  1166. void OnFrameTimestampAvailableMST( float ms )
  1167. {
  1168. AUTO_LOCK( s_mtFrameTimestamps );
  1169. if ( !ms )
  1170. {
  1171. s_flMstThreadBeginTimestamp = Plat_FloatTime();
  1172. }
  1173. else
  1174. {
  1175. double flMstThreadFrameTimeSec = Plat_FloatTime() - s_flMstThreadBeginTimestamp;
  1176. s_apci.msMST = flMstThreadFrameTimeSec*1000.0f;
  1177. }
  1178. }
  1179. void OnFrameTimestampAvailableRsx( float ms )
  1180. {
  1181. AUTO_LOCK( s_mtFrameTimestamps );
  1182. s_apci.msGPU = ms;
  1183. }
  1184. void OnFrameTimestampAvailableTotal( float ms )
  1185. {
  1186. AUTO_LOCK( s_mtFrameTimestamps );
  1187. s_apci.msTotal = ms;
  1188. }
  1189. #ifdef _X360
  1190. static LARGE_INTEGER s_gpuStartTime;
  1191. static LARGE_INTEGER s_gpuTime;
  1192. void OnGpuStartFrame(uint32 context)
  1193. {
  1194. QueryPerformanceCounter( &s_gpuStartTime );
  1195. }
  1196. void OnGpuEndFrame(uint32 context)
  1197. {
  1198. LARGE_INTEGER current_time;
  1199. QueryPerformanceCounter( &current_time );
  1200. s_gpuTime.QuadPart = current_time.QuadPart - s_gpuStartTime.QuadPart;
  1201. }
  1202. #endif
  1203. #endif
  1204. uint32 CMaterialSystem::GetFrameTimestamps( ApplicationPerformanceCountersInfo_t &apci, ApplicationInstantCountersInfo_t & aici )
  1205. {
  1206. #if defined (_X360) && X360_ALLOW_TIMESTAMPS
  1207. LARGE_INTEGER freq;
  1208. QueryPerformanceFrequency(&freq);
  1209. s_apci.msGPU = 1000.0f * ((double)s_gpuTime.QuadPart / (double)(freq.QuadPart));
  1210. #endif
  1211. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  1212. AUTO_LOCK( s_mtFrameTimestamps );
  1213. V_memcpy( &apci, &s_apci, sizeof( s_apci ) );
  1214. return 1000;
  1215. #else
  1216. return 0;
  1217. #endif
  1218. }
  1219. bool CMaterialSystem::CanDownloadTextures() const
  1220. {
  1221. return g_pShaderAPI->CanDownloadTextures();
  1222. }
  1223. int CMaterialSystem::GetConfigurationFlags( void ) const
  1224. {
  1225. return m_nConfigurationFlags;
  1226. }
  1227. //-----------------------------------------------------------------------------
  1228. // Can we use editor materials?
  1229. //-----------------------------------------------------------------------------
  1230. bool CMaterialSystem::CanUseEditorMaterials( void ) const
  1231. {
  1232. return GetConfigurationFlags() & MATCONFIG_FLAGS_SUPPORT_EDITOR;
  1233. }
  1234. //-----------------------------------------------------------------------------
  1235. // Methods related to mode setting...
  1236. //-----------------------------------------------------------------------------
  1237. // Gets the number of adapters...
  1238. int CMaterialSystem::GetDisplayAdapterCount() const
  1239. {
  1240. return g_pShaderDeviceMgr->GetAdapterCount( );
  1241. }
  1242. // Returns info about each adapter
  1243. void CMaterialSystem::GetDisplayAdapterInfo( int adapter, MaterialAdapterInfo_t& info ) const
  1244. {
  1245. g_pShaderDeviceMgr->GetAdapterInfo( adapter, info );
  1246. }
  1247. // Returns the number of modes
  1248. int CMaterialSystem::GetModeCount( int adapter ) const
  1249. {
  1250. return g_pShaderDeviceMgr->GetModeCount( adapter );
  1251. }
  1252. //-----------------------------------------------------------------------------
  1253. // Compatability function, should go away eventually
  1254. //-----------------------------------------------------------------------------
  1255. static void ConvertModeStruct( ShaderDeviceInfo_t *pMode, const MaterialSystem_Config_t &config )
  1256. {
  1257. pMode->m_DisplayMode.m_nWidth = config.m_VideoMode.m_Width;
  1258. pMode->m_DisplayMode.m_nHeight = config.m_VideoMode.m_Height;
  1259. pMode->m_DisplayMode.m_Format = config.m_VideoMode.m_Format;
  1260. pMode->m_DisplayMode.m_nRefreshRateNumerator = config.m_VideoMode.m_RefreshRate;
  1261. pMode->m_DisplayMode.m_nRefreshRateDenominator = config.m_VideoMode.m_RefreshRate ? 1 : 0;
  1262. pMode->m_nBackBufferCount = ( config.m_bWantTripleBuffered && config.WaitForVSync() && !config.Windowed() ) ? 2 : 1; // Only used in ShaderAPIDX10
  1263. pMode->m_nAASamples = config.m_nAASamples;
  1264. pMode->m_nAAQuality = config.m_nAAQuality;
  1265. pMode->m_nDXLevel = config.dxSupportLevel;
  1266. pMode->m_nWindowedSizeLimitWidth = (int)config.m_WindowedSizeLimitWidth;
  1267. pMode->m_nWindowedSizeLimitHeight = (int)config.m_WindowedSizeLimitHeight;
  1268. pMode->m_bWindowed = config.Windowed();
  1269. pMode->m_bResizing = config.Resizing();
  1270. pMode->m_bUseStencil = config.Stencil();
  1271. pMode->m_bLimitWindowedSize = config.LimitWindowedSize();
  1272. pMode->m_bWaitForVSync = config.WaitForVSync();
  1273. pMode->m_bScaleToOutputResolution = config.ScaleToOutputResolution();
  1274. pMode->m_bUsingMultipleWindows = config.UsingMultipleWindows();
  1275. }
  1276. static void ConvertModeStruct( MaterialVideoMode_t *pMode, const ShaderDisplayMode_t &info )
  1277. {
  1278. pMode->m_Width = info.m_nWidth;
  1279. pMode->m_Height = info.m_nHeight;
  1280. pMode->m_Format = info.m_Format;
  1281. pMode->m_RefreshRate = info.m_nRefreshRateNumerator / info.m_nRefreshRateDenominator;
  1282. }
  1283. //-----------------------------------------------------------------------------
  1284. // Returns mode information..
  1285. //-----------------------------------------------------------------------------
  1286. void CMaterialSystem::GetModeInfo( int nAdapter, int nMode, MaterialVideoMode_t& info ) const
  1287. {
  1288. ShaderDisplayMode_t shaderInfo;
  1289. g_pShaderDeviceMgr->GetModeInfo( &shaderInfo, nAdapter, nMode );
  1290. ConvertModeStruct( &info, shaderInfo );
  1291. }
  1292. //-----------------------------------------------------------------------------
  1293. // Returns the mode info for the current display device
  1294. //-----------------------------------------------------------------------------
  1295. void CMaterialSystem::GetDisplayMode( MaterialVideoMode_t& info ) const
  1296. {
  1297. ShaderDisplayMode_t shaderInfo;
  1298. g_pShaderDeviceMgr->GetCurrentModeInfo( &shaderInfo, m_nAdapter );
  1299. ConvertModeStruct( &info, shaderInfo );
  1300. }
  1301. void CMaterialSystem::ForceSingleThreaded()
  1302. {
  1303. if ( !ThreadInMainThread() )
  1304. {
  1305. Error("Can't force single thread from within thread!\n");
  1306. }
  1307. if ( GetThreadMode() != MATERIAL_SINGLE_THREADED )
  1308. {
  1309. #ifndef _PS3
  1310. if ( m_pActiveAsyncJob && !m_pActiveAsyncJob->IsFinished() )
  1311. {
  1312. m_pActiveAsyncJob->WaitForFinish();
  1313. }
  1314. SafeRelease( m_pActiveAsyncJob );
  1315. #else
  1316. if (m_bQMSJobSubmitted)
  1317. {
  1318. g_pGcmSharedData->WaitForQMS();
  1319. m_bQMSJobSubmitted = 0;
  1320. }
  1321. #endif
  1322. #ifdef MAT_QUEUED_OWN_THREADPOOL
  1323. ThreadRelease();
  1324. #else
  1325. g_pShaderAPI->AcquireThreadOwnership();
  1326. #endif
  1327. g_pShaderAPI->EnableShaderShaderMutex( false );
  1328. m_pRenderContext = &m_HardwareRenderContext;
  1329. for ( int i = 0; i < ARRAYSIZE( m_QueuedRenderContexts ); i++ )
  1330. {
  1331. Assert( m_QueuedRenderContexts[i].IsInitialized() );
  1332. m_QueuedRenderContexts[i].EndQueue(true);
  1333. m_QueuedRenderContexts[i].Shutdown();
  1334. }
  1335. if( mat_debugalttab.GetBool() )
  1336. {
  1337. Warning("Forcing queued mode off!\n");
  1338. }
  1339. // NOTE: Must happen after EndQueue or proxies get bound again, which is bad.
  1340. m_ThreadMode = MATERIAL_SINGLE_THREADED;
  1341. m_bForcedSingleThreaded = true;
  1342. }
  1343. }
  1344. //-----------------------------------------------------------------------------
  1345. // Sets the mode...
  1346. //-----------------------------------------------------------------------------
  1347. bool CMaterialSystem::SetMode( void* hwnd, const MaterialSystem_Config_t &config )
  1348. {
  1349. Assert( m_bGeneratedConfig );
  1350. ForceSingleThreaded();
  1351. ShaderDeviceInfo_t info;
  1352. ConvertModeStruct( &info, config );
  1353. bool bPreviouslyUsingGraphics = g_pShaderDevice->IsUsingGraphics();
  1354. bool bOk = g_pShaderAPI->SetMode( hwnd, m_nAdapter, info );
  1355. if ( !bOk )
  1356. return false;
  1357. AllocateScratchRSXMemory();
  1358. TextureManager()->FreeStandardRenderTargets();
  1359. TextureManager()->AllocateStandardRenderTargets();
  1360. // FIXME: There's gotta be a better way of doing this?
  1361. // After the first mode set, make sure to download any textures created
  1362. // before the first mode set. After the first mode set, all textures
  1363. // will be reloaded via the reaquireresources call. Same goes for procedural materials
  1364. if ( !bPreviouslyUsingGraphics )
  1365. {
  1366. if ( IsPC() )
  1367. {
  1368. TextureManager()->RestoreRenderTargets();
  1369. TextureManager()->RestoreNonRenderTargetTextures();
  1370. if ( MaterialSystem()->CanUseEditorMaterials() )
  1371. {
  1372. // We are in Hammer. Allocate these here since we aren't going to allocate
  1373. // lightmaps.
  1374. // HACK!
  1375. // NOTE! : Overbright is 1.0 so that Hammer will work properly with the white bumped and unbumped lightmaps.
  1376. MathLib_Init( 2.2f, 2.2f, 0.0f, OVERBRIGHT );
  1377. AllocateStandardTextures();
  1378. }
  1379. }
  1380. if ( IsX360() || IsPS3() )
  1381. {
  1382. // shaderapi was not viable at init time, it is now
  1383. TextureManager()->ReloadTextures();
  1384. AllocateStandardTextures();
  1385. }
  1386. }
  1387. g_pShaderDevice->SetHardwareGammaRamp( config.m_fMonitorGamma, config.m_fGammaTVRangeMin, config.m_fGammaTVRangeMax,
  1388. config.m_fGammaTVExponent, config.m_bGammaTVEnabled );
  1389. // Copy over that state which isn't stored currently in convars
  1390. g_config.m_VideoMode = config.m_VideoMode;
  1391. g_config.SetFlag( MATSYS_VIDCFG_FLAGS_WINDOWED, config.Windowed() );
  1392. g_config.SetFlag( MATSYS_VIDCFG_FLAGS_STENCIL, config.Stencil() );
  1393. WriteConfigIntoConVars( config );
  1394. extern void SetupDirtyDiskReportFunc();
  1395. SetupDirtyDiskReportFunc();
  1396. return true;
  1397. }
  1398. // Creates/ destroys a child window
  1399. bool CMaterialSystem::AddView( void* hwnd )
  1400. {
  1401. return g_pShaderDevice->AddView( hwnd );
  1402. }
  1403. void CMaterialSystem::RemoveView( void* hwnd )
  1404. {
  1405. g_pShaderDevice->RemoveView( hwnd );
  1406. }
  1407. // Activates a view
  1408. void CMaterialSystem::SetView( void* hwnd )
  1409. {
  1410. g_pShaderDevice->SetView( hwnd );
  1411. }
  1412. //-----------------------------------------------------------------------------
  1413. // Installs a function to be called when we need to release vertex buffers
  1414. //-----------------------------------------------------------------------------
  1415. void CMaterialSystem::AddReleaseFunc( MaterialBufferReleaseFunc_t func )
  1416. {
  1417. // Shouldn't have two copies in our list
  1418. Assert( m_ReleaseFunc.Find( func ) == -1 );
  1419. m_ReleaseFunc.AddToTail( func );
  1420. }
  1421. void CMaterialSystem::RemoveReleaseFunc( MaterialBufferReleaseFunc_t func )
  1422. {
  1423. int i = m_ReleaseFunc.Find( func );
  1424. if( i != -1 )
  1425. m_ReleaseFunc.Remove(i);
  1426. }
  1427. //-----------------------------------------------------------------------------
  1428. // Installs a function to be called when we need to restore vertex buffers
  1429. //-----------------------------------------------------------------------------
  1430. void CMaterialSystem::AddRestoreFunc( MaterialBufferRestoreFunc_t func )
  1431. {
  1432. // Shouldn't have two copies in our list
  1433. Assert( m_RestoreFunc.Find( func ) == -1 );
  1434. m_RestoreFunc.AddToTail( func );
  1435. }
  1436. void CMaterialSystem::RemoveRestoreFunc( MaterialBufferRestoreFunc_t func )
  1437. {
  1438. int i = m_RestoreFunc.Find( func );
  1439. Assert( i != -1 );
  1440. m_RestoreFunc.Remove(i);
  1441. }
  1442. //-----------------------------------------------------------------------------
  1443. // Installs a function to be called when we need to release vertex buffers
  1444. //-----------------------------------------------------------------------------
  1445. void CMaterialSystem::AddEndFrameCleanupFunc( EndFrameCleanupFunc_t func )
  1446. {
  1447. // Shouldn't have two copies in our list
  1448. Assert( m_EndFrameCleanupFunc.Find( func ) == -1 );
  1449. m_EndFrameCleanupFunc.AddToTail( func );
  1450. }
  1451. void CMaterialSystem::RemoveEndFrameCleanupFunc( EndFrameCleanupFunc_t func )
  1452. {
  1453. int i = m_EndFrameCleanupFunc.Find( func );
  1454. if( i != -1 )
  1455. {
  1456. m_EndFrameCleanupFunc.Remove(i);
  1457. }
  1458. }
  1459. // Gets called when the level is shuts down, will call the registered callback
  1460. void CMaterialSystem::OnLevelShutdown()
  1461. {
  1462. // changing contexts away from gameplay
  1463. m_bLevelLoadingComplete = false;
  1464. int nSize = m_OnLevelShutdownFuncs.Count();
  1465. for (int i = 0 ; i < nSize ; ++i)
  1466. {
  1467. COnLevelShutdownFunc & instance = m_OnLevelShutdownFuncs[i];
  1468. instance.m_Func(instance.m_pUserData);
  1469. }
  1470. }
  1471. // Installs a function to be called when the level is shuts down
  1472. bool CMaterialSystem::AddOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData )
  1473. {
  1474. COnLevelShutdownFunc instance(func, pUserData);
  1475. int i = m_OnLevelShutdownFuncs.Find( instance );
  1476. if (i != -1)
  1477. {
  1478. return false;
  1479. }
  1480. m_OnLevelShutdownFuncs.AddToTail(instance);
  1481. return true;
  1482. }
  1483. bool CMaterialSystem::RemoveOnLevelShutdownFunc( OnLevelShutdownFunc_t func, void * pUserData )
  1484. {
  1485. COnLevelShutdownFunc instance(func, pUserData);
  1486. int i = m_OnLevelShutdownFuncs.Find( instance );
  1487. if (i == -1)
  1488. {
  1489. return false;
  1490. }
  1491. m_OnLevelShutdownFuncs.Remove(i);
  1492. return true;
  1493. }
  1494. //-----------------------------------------------------------------------------
  1495. // // Installs a function to be called when we need to perform operation before next rendering context is started
  1496. //-----------------------------------------------------------------------------
  1497. void CMaterialSystem::AddEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func )
  1498. {
  1499. // Shouldn't have two copies in our list
  1500. Assert( m_EndFramePriorToNextContextFunc.Find( func ) == m_EndFramePriorToNextContextFunc.InvalidIndex() );
  1501. m_EndFramePriorToNextContextFunc.AddToTail( func );
  1502. }
  1503. void CMaterialSystem::RemoveEndFramePriorToNextContextFunc( EndFramePriorToNextContextFunc_t func )
  1504. {
  1505. int i = m_EndFramePriorToNextContextFunc.Find( func );
  1506. if( i != m_EndFramePriorToNextContextFunc.InvalidIndex() )
  1507. {
  1508. m_EndFramePriorToNextContextFunc.Remove(i);
  1509. }
  1510. }
  1511. ICustomMaterialManager *CMaterialSystem::GetCustomMaterialManager()
  1512. {
  1513. return &m_CustomMaterialManager;
  1514. }
  1515. ICompositeTextureGenerator *CMaterialSystem::GetCompositeTextureGenerator()
  1516. {
  1517. return &m_CompositeTextureGenerator;
  1518. }
  1519. void CMaterialSystem::OnLevelLoadingComplete()
  1520. {
  1521. // called from engine when level has loaded and gameplay is expected to commence
  1522. m_bLevelLoadingComplete = true;
  1523. }
  1524. //-----------------------------------------------------------------------------
  1525. // Called by the shader API when it's just about to lose video memory
  1526. //-----------------------------------------------------------------------------
  1527. void CMaterialSystem::ReleaseShaderObjects( int nChangeFlags )
  1528. {
  1529. if( mat_debugalttab.GetBool() )
  1530. {
  1531. Warning( "mat_debugalttab: CMaterialSystem::ReleaseShaderObjects\n" );
  1532. }
  1533. Flush( false );
  1534. m_HardwareRenderContext.OnReleaseShaderObjects();
  1535. if ( ( nChangeFlags & MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED ) == 0 )
  1536. {
  1537. g_pOcclusionQueryMgr->FreeOcclusionQueryObjects();
  1538. // If we're in an alt+tab event don't release managed resources
  1539. bool bReleaseManaged = ( nChangeFlags & MATERIAL_RESTORE_RELEASE_MANAGED_RESOURCES ) ? true : false;
  1540. m_bRestoreManangedResources = bReleaseManaged;
  1541. TextureManager()->ReleaseTextures( bReleaseManaged );
  1542. ReleaseStandardTextures();
  1543. if ( bReleaseManaged )
  1544. {
  1545. GetLightmaps()->ReleaseLightmapPages();
  1546. }
  1547. }
  1548. for (int i = 0; i < m_ReleaseFunc.Count(); ++i)
  1549. {
  1550. m_ReleaseFunc[i]( nChangeFlags );
  1551. }
  1552. }
  1553. void CMaterialSystem::RestoreShaderObjects( CreateInterfaceFn shaderFactory, int nChangeFlags )
  1554. {
  1555. #if !defined( _PS3 ) && !defined( _OSX )
  1556. if ( shaderFactory )
  1557. {
  1558. g_pShaderAPI = (IShaderAPI*)shaderFactory( SHADERAPI_INTERFACE_VERSION, NULL );
  1559. g_pShaderDevice = (IShaderDevice*)shaderFactory( SHADER_DEVICE_INTERFACE_VERSION, NULL );
  1560. g_pShaderShadow = (IShaderShadow*)shaderFactory( SHADERSHADOW_INTERFACE_VERSION, NULL );
  1561. }
  1562. #endif
  1563. for( MaterialHandle_t i = m_MaterialDict.FirstMaterial(); i != m_MaterialDict.InvalidMaterial(); i = m_MaterialDict.NextMaterial( i ) )
  1564. {
  1565. IMaterialInternal *pMat = m_MaterialDict.GetMaterialInternal( i );
  1566. if ( pMat )
  1567. {
  1568. pMat->ReportVarChanged( NULL );
  1569. }
  1570. }
  1571. if ( mat_debugalttab.GetBool() )
  1572. {
  1573. Warning( "mat_debugalttab: CMaterialSystem::RestoreShaderObjects\n" );
  1574. }
  1575. // Shader API sets this to the max value the card supports when it resets
  1576. // the state, so restore this value.
  1577. g_pShaderAPI->SetAnisotropicLevel( GetCurrentConfigForVideoCard().m_nForceAnisotropicLevel );
  1578. if ( ( nChangeFlags & MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED ) == 0 )
  1579. {
  1580. // NOTE: render targets must be restored first, then vb/ibs, then managed textures
  1581. // FIXME: Gotta restore lightmap pages + standard textures before restore funcs are called
  1582. // because they use them both.
  1583. TextureManager()->RestoreRenderTargets();
  1584. AllocateStandardTextures();
  1585. if ( m_bRestoreManangedResources )
  1586. {
  1587. GetLightmaps()->RestoreLightmapPages();
  1588. }
  1589. g_pOcclusionQueryMgr->AllocOcclusionQueryObjects();
  1590. }
  1591. for (int i = 0; i < m_RestoreFunc.Count(); ++i)
  1592. {
  1593. m_RestoreFunc[i]( nChangeFlags );
  1594. }
  1595. if ( ( nChangeFlags & MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED ) == 0 && m_bRestoreManangedResources )
  1596. {
  1597. TextureManager()->RestoreNonRenderTargetTextures();
  1598. // Reset the restore to true in the odd case that we get a RestoreShaderObjects without a ReleaseShaderObjects
  1599. m_bRestoreManangedResources = true;
  1600. }
  1601. }
  1602. //-----------------------------------------------------------------------------
  1603. // Use this to spew information about the 3D layer
  1604. //-----------------------------------------------------------------------------
  1605. void CMaterialSystem::SpewDriverInfo() const
  1606. {
  1607. Warning( "ShaderAPI: %s\n", m_pShaderDLL );
  1608. g_pShaderDevice->SpewDriverInfo();
  1609. }
  1610. //-----------------------------------------------------------------------------
  1611. // Color converting blitter
  1612. //-----------------------------------------------------------------------------
  1613. bool CMaterialSystem::ConvertImageFormat( unsigned char *src, enum ImageFormat srcImageFormat,
  1614. unsigned char *dst, enum ImageFormat dstImageFormat,
  1615. int width, int height, int srcStride, int dstStride )
  1616. {
  1617. return ImageLoader::ConvertImageFormat( src, srcImageFormat,
  1618. dst, dstImageFormat, width, height, srcStride, dstStride );
  1619. }
  1620. //-----------------------------------------------------------------------------
  1621. // Figures out the amount of memory needed by a bitmap
  1622. //-----------------------------------------------------------------------------
  1623. int CMaterialSystem::GetMemRequired( int width, int height, int depth, ImageFormat format, bool mipmap )
  1624. {
  1625. return ImageLoader::GetMemRequired( width, height, depth, format, mipmap );
  1626. }
  1627. ShaderAPITextureHandle_t CMaterialSystem::GetShaderAPITextureBindHandle( ITexture *pTexture, int nFrameVar, int nTextureChannel )
  1628. {
  1629. return ShaderSystem()->GetShaderAPITextureBindHandle( pTexture, nFrameVar, nTextureChannel );
  1630. }
  1631. //-----------------------------------------------------------------------------
  1632. // Method to allow clients access to the MaterialSystem_Config
  1633. //-----------------------------------------------------------------------------
  1634. MaterialSystem_Config_t& CMaterialSystem::GetConfig()
  1635. {
  1636. Assert( m_bGeneratedConfig );
  1637. return g_config;
  1638. }
  1639. //-----------------------------------------------------------------------------
  1640. // Gets image format info
  1641. //-----------------------------------------------------------------------------
  1642. ImageFormatInfo_t const& CMaterialSystem::ImageFormatInfo( ImageFormat fmt) const
  1643. {
  1644. return ImageLoader::ImageFormatInfo(fmt);
  1645. }
  1646. //-----------------------------------------------------------------------------
  1647. // Reads keyvalues for information
  1648. //-----------------------------------------------------------------------------
  1649. static void ReadInt( KeyValues *pGroup, const char *pName, int nDefaultVal, int nUndefinedVal, int *pDest )
  1650. {
  1651. *pDest = pGroup->GetInt( pName, nDefaultVal );
  1652. // Warning( "\t%s = %d\n", pName, *pDest );
  1653. Assert( *pDest != nUndefinedVal );
  1654. }
  1655. static void ReadFlt( KeyValues *pGroup, const char *pName, float flDefaultVal, float flUndefinedVal, float *pDest )
  1656. {
  1657. *pDest = pGroup->GetFloat( pName, flDefaultVal );
  1658. // Warning( "\t%s = %f\n", pName, *pDest );
  1659. Assert( *pDest != flUndefinedVal );
  1660. }
  1661. static void LoadFlags( KeyValues *pGroup, const char *pName, bool bDefaultValue, unsigned int nFlag, unsigned int *pFlags )
  1662. {
  1663. int nValue = pGroup->GetInt( pName, bDefaultValue ? 1 : 0 );
  1664. // Warning( "\t%s = %s\n", pName, nValue ? "true" : "false" );
  1665. if ( nValue )
  1666. {
  1667. *pFlags |= nFlag;
  1668. }
  1669. }
  1670. //-----------------------------------------------------------------------------
  1671. // This is called when the config changes
  1672. //-----------------------------------------------------------------------------
  1673. void CMaterialSystem::GenerateConfigFromConfigKeyValues( MaterialSystem_Config_t *pConfig, bool bOverwriteCommandLineValues )
  1674. {
  1675. KeyValues *pKeyValues = new KeyValues( "config" );
  1676. if ( !pKeyValues )
  1677. return;
  1678. if ( IsPC() && !GetRecommendedVideoConfig( pKeyValues ) )
  1679. {
  1680. pKeyValues->deleteThis();
  1681. return;
  1682. }
  1683. float flAspectRatio;
  1684. pConfig->m_Flags = 0;
  1685. ReadInt( pKeyValues, "setting.defaultres", 640, -1, &pConfig->m_VideoMode.m_Width );
  1686. ReadInt( pKeyValues, "setting.defaultresheight", 480, -1, &pConfig->m_VideoMode.m_Height );
  1687. ReadFlt( pKeyValues, "setting.aspectratio", ( 4.0f / 3.0f ), -1, &flAspectRatio );
  1688. int nUnsupported = 0;
  1689. ReadInt( pKeyValues, "setting.unsupported", 0, -1, &nUnsupported );
  1690. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_UNSUPPORTED, nUnsupported != 0 );
  1691. #ifdef LINUX
  1692. uint width = 0;
  1693. uint height = 0;
  1694. uint refreshHz = 0; // Not used
  1695. // query backbuffer size (window size whether FS or windowed)
  1696. if( g_pLauncherMgr )
  1697. {
  1698. g_pLauncherMgr->GetNativeDisplayInfo( -1, width, height, refreshHz );
  1699. }
  1700. pConfig->m_VideoMode.m_Width = width;
  1701. pConfig->m_VideoMode.m_Height = height;
  1702. #elif defined( _X360 )
  1703. pConfig->m_VideoMode.m_Width = GetSystemMetrics( SM_CXSCREEN );
  1704. pConfig->m_VideoMode.m_Height = GetSystemMetrics( SM_CYSCREEN );
  1705. // We can afford better aniso in standard def
  1706. if ( pConfig->m_VideoMode.m_Width == 640 )
  1707. {
  1708. static ConVarRef mat_forceaniso( "mat_forceaniso" );
  1709. mat_forceaniso.SetValue( 8 );
  1710. }
  1711. #elif defined( _PS3 )
  1712. // Shader API does the dirty work of querying cellVideo libraries for screen res, so just piggy back on it
  1713. ShaderDisplayMode_t info;
  1714. g_pShaderDeviceMgr->GetModeInfo( &info, 0, 0 );
  1715. pConfig->m_VideoMode.m_Width = info.m_nWidth;
  1716. pConfig->m_VideoMode.m_Height = info.m_nHeight;
  1717. // We can afford better aniso in standard def
  1718. if ( pConfig->m_VideoMode.m_Width == 640 )
  1719. {
  1720. static ConVarRef mat_forceaniso( "mat_forceaniso" );
  1721. mat_forceaniso.SetValue( 8 );
  1722. }
  1723. #endif
  1724. // Destroy the keys.
  1725. pKeyValues->deleteThis();
  1726. m_bGeneratedConfig = true;
  1727. }
  1728. //-----------------------------------------------------------------------------
  1729. // If mat_proxy goes to 0, we need to reload all materials, because their shader
  1730. // params might have been messed with.
  1731. //-----------------------------------------------------------------------------
  1732. static void MatProxyCallback( IConVar *pConVar, const char *old, float flOldValue )
  1733. {
  1734. ConVarRef var( pConVar );
  1735. int oldVal = (int)flOldValue;
  1736. if ( var.GetInt() == 0 && oldVal != 0 )
  1737. {
  1738. g_MaterialSystem.ReloadMaterials();
  1739. }
  1740. }
  1741. //-----------------------------------------------------------------------------
  1742. // Convars that control the config record
  1743. //-----------------------------------------------------------------------------
  1744. ConVar mat_vsync( "mat_vsync", IsGameConsole() ? "1" : "0", FCVAR_NONE, "Force sync to vertical retrace", true, 0.0, true, 1.0 );
  1745. // Texture-related
  1746. static ConVar mat_forceaniso( "mat_forceaniso", "1" ); // 0 = Bilinear, 1 = Trilinear, 2+ = Aniso
  1747. static ConVar mat_filterlightmaps( "mat_filterlightmaps", "1" );
  1748. static ConVar mat_filtertextures( "mat_filtertextures", "1" );
  1749. static ConVar mat_mipmaptextures( "mat_mipmaptextures", "1" );
  1750. static void mat_showmiplevels_Callback_f( IConVar *var, const char *pOldValue, float flOldValue )
  1751. {
  1752. // turn off texture filtering if we are showing mip levels.
  1753. mat_filtertextures.SetValue( ( ( ConVar * )var )->GetInt() == 0 );
  1754. }
  1755. // Debugging textures
  1756. static ConVar mat_showmiplevels( "mat_showmiplevels", "0", FCVAR_CHEAT, "color-code miplevels 2: normalmaps, 1: everything else", mat_showmiplevels_Callback_f );
  1757. static ConVar mat_specular( "mat_specular", "1", 0, "Enable/Disable specularity for perf testing. Will cause a material reload upon change." );
  1758. static ConVar mat_bumpmap( "mat_bumpmap", "1" );
  1759. static ConVar mat_detail_tex( "mat_detail_tex", "1" );
  1760. static ConVar mat_phong( "mat_phong", "1" );
  1761. static ConVar mat_parallaxmap( "mat_parallaxmap", "1" );
  1762. static ConVar mat_reducefillrate( "mat_reducefillrate", "0" );
  1763. // moved up: static ConVar mat_picmip( "mat_picmip", "0", FCVAR_NONE, "", true, -10, true, 4 );
  1764. static ConVar mat_monitorgamma( "mat_monitorgamma", "2.2", FCVAR_ARCHIVE | FCVAR_ARCHIVE_GAMECONSOLE, "monitor gamma (typically 2.2 for CRT and 1.7 for LCD)", true, 1.6f, true, 2.6f );
  1765. static ConVar mat_monitorgamma_tv_range_min( "mat_monitorgamma_tv_range_min", "16" );
  1766. static ConVar mat_monitorgamma_tv_range_max( "mat_monitorgamma_tv_range_max", "235" );
  1767. // TV's generally have a 2.5 gamma, so we need to convert our 2.2 frame buffer into a 2.5 frame buffer for display on a TV
  1768. static ConVar mat_monitorgamma_tv_exp( "mat_monitorgamma_tv_exp", "2.5", 0, "", true, 1.0f, true, 4.0f );
  1769. static ConVar mat_monitorgamma_tv_enabled( "mat_monitorgamma_tv_enabled", IsGameConsole() ? "1" : "0", FCVAR_ARCHIVE | FCVAR_ARCHIVE_GAMECONSOLE, "" );
  1770. static ConVar mat_triplebuffered( "mat_triplebuffered", "0", 0, "This means we want triple buffering if we are fullscreen and vsync'd" );
  1771. static ConVar mat_antialias( "mat_antialias", "0" );
  1772. static ConVar mat_aaquality( "mat_aaquality", "0" );
  1773. static ConVar mat_diffuse( "mat_diffuse", "1" );
  1774. static ConVar mat_showlowresimage( "mat_showlowresimage", "0", FCVAR_CHEAT );
  1775. static ConVar mat_fullbright( "mat_fullbright","0", FCVAR_CHEAT );
  1776. static ConVar mat_normalmaps( "mat_normalmaps", "0", FCVAR_CHEAT );
  1777. static ConVar mat_measurefillrate( "mat_measurefillrate", "0", FCVAR_CHEAT );
  1778. static ConVar mat_fillrate( "mat_fillrate", "0", FCVAR_CHEAT );
  1779. static ConVar mat_reversedepth( "mat_reversedepth", "0", FCVAR_CHEAT );
  1780. #if defined( PLATFORM_POSIX ) && !defined( _PS3 )
  1781. static ConVar mat_bufferprimitives( "mat_bufferprimitives", "0" ); // I'm not seeing any benefit speed wise for buffered primitives on GLM/POSIX (checked via TF2 timedemo) - default to zero
  1782. #else
  1783. static ConVar mat_bufferprimitives( "mat_bufferprimitives", "1" );
  1784. #endif
  1785. static ConVar mat_drawflat( "mat_drawflat","0", FCVAR_CHEAT );
  1786. static ConVar mat_softwarelighting( "mat_softwarelighting", "0" );
  1787. static ConVar mat_proxy( "mat_proxy", "0", FCVAR_CHEAT, "", MatProxyCallback );
  1788. static ConVar mat_norendering( "mat_norendering", "0", FCVAR_CHEAT );
  1789. static ConVar mat_compressedtextures( "mat_compressedtextures", "1" );
  1790. static ConVar mat_fastspecular( "mat_fastspecular", "1", 0, "Enable/Disable specularity for visual testing. Will not reload materials and will not affect perf." );
  1791. static ConVar mat_fastnobump( "mat_fastnobump", "0", FCVAR_CHEAT ); // Binds 1-texel normal map for quick internal testing
  1792. static ConVar mat_drawgray( "mat_drawgray","0", FCVAR_CHEAT );
  1793. // These are not controlled by the material system, but are limited by settings in the material system
  1794. static ConVar r_shadowrendertotexture( "r_shadowrendertotexture", "0" );
  1795. #if ( defined( CSTRIKE15 ) && defined( _PS3) )
  1796. static ConVar r_flashlightdepthtexture( "r_flashlightdepthtexture", "1" );
  1797. #else
  1798. static ConVar r_flashlightdepthtexture( "r_flashlightdepthtexture", "1" );
  1799. #endif
  1800. // On non-gameconsoles mat_motion_blur_enabled now comes from video.txt/videodefaults.txt
  1801. static ConVar mat_motion_blur_enabled( "mat_motion_blur_enabled", IsGameConsole() ? "1" : "0" );
  1802. static ConVar mat_paint_enabled( "mat_paint_enabled", "0" );
  1803. uint32 g_nDebugVarsSignature = 0;
  1804. //-----------------------------------------------------------------------------
  1805. // This is called when the config changes
  1806. //-----------------------------------------------------------------------------
  1807. void CMaterialSystem::ReadConfigFromConVars( MaterialSystem_Config_t *pConfig )
  1808. {
  1809. if ( !g_pCVar )
  1810. return;
  1811. // video panel config items
  1812. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_NO_WAIT_FOR_VSYNC, !mat_vsync.GetBool() );
  1813. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_DISABLE_SPECULAR, !mat_specular.GetBool() );
  1814. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_DISABLE_BUMPMAP, !mat_bumpmap.GetBool() );
  1815. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_DISABLE_DETAIL, !mat_detail_tex.GetBool() );
  1816. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_DISABLE_PHONG, !mat_phong.GetBool() );
  1817. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_ENABLE_PARALLAX_MAPPING, mat_parallaxmap.GetBool() );
  1818. pConfig->m_nForceAnisotropicLevel = MAX( mat_forceaniso.GetInt(), 1 );
  1819. // special handling for mat_dxlevel since it must be clamped to allowable values
  1820. int nDxLevel = clamp( mat_dxlevel.GetInt(), g_pMaterialSystemHardwareConfig->GetMinDXSupportLevel(), g_pMaterialSystemHardwareConfig->GetMaxDXSupportLevel() );
  1821. pConfig->dxSupportLevel = nDxLevel;
  1822. mat_dxlevel.SetValue( nDxLevel );
  1823. pConfig->skipMipLevels = mat_picmip.GetInt();
  1824. pConfig->m_fMonitorGamma = mat_monitorgamma.GetFloat();
  1825. pConfig->m_fGammaTVRangeMin = mat_monitorgamma_tv_range_min.GetFloat();
  1826. pConfig->m_fGammaTVRangeMax = mat_monitorgamma_tv_range_max.GetFloat();
  1827. pConfig->m_fGammaTVExponent = mat_monitorgamma_tv_exp.GetFloat();
  1828. pConfig->m_bGammaTVEnabled = mat_monitorgamma_tv_enabled.GetBool();
  1829. pConfig->m_bWantTripleBuffered = mat_triplebuffered.GetBool();
  1830. pConfig->m_nAASamples = mat_antialias.GetInt();
  1831. pConfig->m_nAAQuality = mat_aaquality.GetInt();
  1832. pConfig->bShowDiffuse = mat_diffuse.GetBool();
  1833. // pConfig->bAllowCheats = false; // hack
  1834. pConfig->bShowNormalMap = mat_normalmaps.GetBool();
  1835. pConfig->bShowLowResImage = mat_showlowresimage.GetBool();
  1836. pConfig->bMeasureFillRate = mat_measurefillrate.GetBool();
  1837. pConfig->bVisualizeFillRate = mat_fillrate.GetBool();
  1838. pConfig->bFilterLightmaps = mat_filterlightmaps.GetBool();
  1839. pConfig->bFilterTextures = mat_filtertextures.GetBool();
  1840. pConfig->bMipMapTextures = mat_mipmaptextures.GetBool();
  1841. pConfig->nShowMipLevels = mat_showmiplevels.GetInt();
  1842. pConfig->bReverseDepth = mat_reversedepth.GetBool();
  1843. pConfig->bBufferPrimitives = mat_bufferprimitives.GetBool();
  1844. pConfig->bDrawFlat = mat_drawflat.GetBool();
  1845. pConfig->bSoftwareLighting = mat_softwarelighting.GetBool();
  1846. pConfig->proxiesTestMode = mat_proxy.GetInt();
  1847. pConfig->m_bSuppressRendering = mat_norendering.GetBool();
  1848. pConfig->bCompressedTextures = mat_compressedtextures.GetBool();
  1849. pConfig->bShowSpecular = mat_fastspecular.GetBool();
  1850. pConfig->nFullbright = mat_fullbright.GetInt();
  1851. pConfig->m_bFastNoBump = mat_fastnobump.GetBool();
  1852. pConfig->m_bMotionBlur = mat_motion_blur_enabled.GetBool();
  1853. pConfig->m_bSupportFlashlight = mat_supportflashlight.GetBool();
  1854. pConfig->m_bShadowDepthTexture = r_flashlightdepthtexture.GetBool();
  1855. pConfig->bDrawGray = mat_drawgray.GetBool();
  1856. // PAINT
  1857. pConfig->m_bPaintInGame = mat_paint_enabled.GetBool();
  1858. pConfig->m_bPaintInMap = GetPaintmaps()->IsEnabled();
  1859. ConVarRef csm_quality_level( "csm_quality_level" );
  1860. pConfig->m_nCSMQuality = (CSMQualityMode_t)clamp( csm_quality_level.GetInt(), CSMQUALITY_VERY_LOW, (int)CSMQUALITY_TOTAL_MODES - 1 );
  1861. pConfig->SetFlag( MATSYS_VIDCFG_FLAGS_ENABLE_HDR, HardwareConfig() && HardwareConfig()->GetHDREnabled() );
  1862. }
  1863. //-----------------------------------------------------------------------------
  1864. // This is called when the config changes
  1865. //-----------------------------------------------------------------------------
  1866. void CMaterialSystem::WriteConfigIntoConVars( const MaterialSystem_Config_t &config )
  1867. {
  1868. if ( !g_pCVar )
  1869. return;
  1870. mat_vsync.SetValue( config.WaitForVSync() );
  1871. mat_specular.SetValue( config.UseSpecular() );
  1872. mat_bumpmap.SetValue( config.UseBumpmapping() );
  1873. mat_detail_tex.SetValue( config.UseDetailTexturing() );
  1874. mat_parallaxmap.SetValue( config.UseParallaxMapping() );
  1875. mat_forceaniso.SetValue( config.m_nForceAnisotropicLevel );
  1876. mat_dxlevel.SetValue( config.dxSupportLevel );
  1877. mat_picmip.SetValue( config.skipMipLevels );
  1878. mat_phong.SetValue( config.UsePhong() );
  1879. mat_monitorgamma.SetValue( config.m_fMonitorGamma );
  1880. mat_monitorgamma_tv_range_min.SetValue( config.m_fGammaTVRangeMin );
  1881. mat_monitorgamma_tv_range_max.SetValue( config.m_fGammaTVRangeMax );
  1882. mat_monitorgamma_tv_exp.SetValue( config.m_fGammaTVExponent );
  1883. mat_monitorgamma_tv_enabled.SetValue( config.m_bGammaTVEnabled );
  1884. mat_triplebuffered.SetValue( config.m_bWantTripleBuffered ? 1 : 0 );
  1885. mat_antialias.SetValue( config.m_nAASamples );
  1886. mat_aaquality.SetValue( config.m_nAAQuality );
  1887. mat_diffuse.SetValue( config.bShowDiffuse ? 1 : 0 );
  1888. // config.bAllowCheats = false; // hack
  1889. mat_normalmaps.SetValue( config.bShowNormalMap ? 1 : 0 );
  1890. mat_showlowresimage.SetValue( config.bShowLowResImage ? 1 : 0 );
  1891. mat_measurefillrate.SetValue( config.bMeasureFillRate ? 1 : 0 );
  1892. mat_fillrate.SetValue( config.bVisualizeFillRate ? 1 : 0 );
  1893. mat_filterlightmaps.SetValue( config.bFilterLightmaps ? 1 : 0 );
  1894. mat_filtertextures.SetValue( config.bFilterTextures ? 1 : 0 );
  1895. mat_mipmaptextures.SetValue( config.bMipMapTextures ? 1 : 0 );
  1896. mat_showmiplevels.SetValue( config.nShowMipLevels );
  1897. mat_reversedepth.SetValue( config.bReverseDepth ? 1 : 0 );
  1898. mat_bufferprimitives.SetValue( config.bBufferPrimitives ? 1 : 0 );
  1899. mat_drawflat.SetValue( config.bDrawFlat ? 1 : 0 );
  1900. mat_softwarelighting.SetValue( config.bSoftwareLighting ? 1 : 0 );
  1901. mat_proxy.SetValue( config.proxiesTestMode );
  1902. mat_norendering.SetValue( config.m_bSuppressRendering ? 1 : 0 );
  1903. mat_compressedtextures.SetValue( config.bCompressedTextures ? 1 : 0 );
  1904. mat_fastspecular.SetValue( config.bShowSpecular ? 1 : 0 );
  1905. mat_fullbright.SetValue( config.nFullbright );
  1906. mat_fastnobump.SetValue( config.m_bFastNoBump ? 1 : 0 );
  1907. bool hdre = config.HDREnabled();
  1908. HardwareConfig()->SetHDREnabled( hdre );
  1909. r_flashlightdepthtexture.SetValue( config.m_bShadowDepthTexture ? 1 : 0 );
  1910. mat_motion_blur_enabled.SetValue( config.m_bMotionBlur ? 1 : 0 );
  1911. mat_supportflashlight.SetValue( config.m_bSupportFlashlight ? 1 : 0 );
  1912. mat_drawgray.SetValue( config.bDrawGray ? 1 : 0 );
  1913. ConVarRef csm_quality_level( "csm_quality_level" );
  1914. csm_quality_level.SetValue( clamp<int>( config.m_nCSMQuality, CSMQUALITY_VERY_LOW, CSMQUALITY_TOTAL_MODES - 1 ) );
  1915. }
  1916. //-----------------------------------------------------------------------------
  1917. // This is called constantly to catch for config changes
  1918. //-----------------------------------------------------------------------------
  1919. bool CMaterialSystem::OverrideConfig( const MaterialSystem_Config_t &_config, bool forceUpdate )
  1920. {
  1921. Assert( m_bGeneratedConfig );
  1922. // internal config settings
  1923. #ifndef _GAMECONSOLE
  1924. MaterialSystem_Config_Internal_t config_internal;
  1925. config_internal.gpu_level = gpu_level.GetInt();
  1926. #endif
  1927. if (
  1928. !memcmp( &_config, &g_config, sizeof(_config) )
  1929. #ifndef _GAMECONSOLE
  1930. && !memcmp( &config_internal, &g_config_internal, sizeof(config_internal) )
  1931. #endif
  1932. )
  1933. return false;
  1934. MaterialLock_t hLock = Lock();
  1935. MaterialSystem_Config_t config = _config;
  1936. // It's illegal to create a window larger than the screen resolution
  1937. if ( config.Windowed() )
  1938. {
  1939. config.m_VideoMode.m_Width = clamp( config.m_VideoMode.m_Width, 0, m_nAdapterInfo.m_nWidth );
  1940. config.m_VideoMode.m_Height = clamp( config.m_VideoMode.m_Height, 0, m_nAdapterInfo.m_nHeight );
  1941. }
  1942. bool bRedownloadLightmaps = false;
  1943. bool bRedownloadTextures = false;
  1944. bool recomputeSnapshots = false;
  1945. bool bReloadMaterials = false;
  1946. bool bResetAnisotropy = false;
  1947. bool bSetStandardVertexShaderConstants = false;
  1948. bool bMonitorGammaChanged = false;
  1949. bool bVideoModeChange = false;
  1950. bool bResetTextureFilter = false;
  1951. bool bForceAltTab = false;
  1952. if ( !g_pShaderDevice->IsUsingGraphics() )
  1953. {
  1954. g_config = config;
  1955. #ifndef _GAMECONSOLE
  1956. g_config_internal = config_internal;
  1957. #endif
  1958. // Shouldn't call this more than once.
  1959. ColorSpace::SetGamma( 2.2f, 2.2f, OVERBRIGHT, g_config.bAllowCheats, false );
  1960. Unlock( hLock );
  1961. return bRedownloadLightmaps;
  1962. }
  1963. // set the default state since we might be changing the number of
  1964. // texture units, etc. (i.e. we don't want to leave unit 2 in overbright mode
  1965. // if it isn't going to be reset upon each SetDefaultState because there is
  1966. // effectively only one texture unit.)
  1967. g_pShaderAPI->SetDefaultState();
  1968. // toggle dx emulation level
  1969. if ( config.dxSupportLevel != g_config.dxSupportLevel )
  1970. {
  1971. if ( mat_debugalttab.GetBool() )
  1972. {
  1973. Warning( "mat_debugalttab: Setting bReloadMaterials because new dxlevel = %d and old dxlevel = %d\n",
  1974. ( int )config.dxSupportLevel, g_config.dxSupportLevel );
  1975. }
  1976. // Necessary for DXSupportLevelChanged to work
  1977. g_config.dxSupportLevel = config.dxSupportLevel;
  1978. // This will reset config to match whatever the dxlevel wants
  1979. g_pShaderAPI->DXSupportLevelChanged( config.dxSupportLevel );
  1980. bReloadMaterials = true;
  1981. }
  1982. if ( config.m_nCSMQuality != g_config.m_nCSMQuality )
  1983. {
  1984. //forceUpdate = true;
  1985. bReloadMaterials = true;
  1986. recomputeSnapshots = true;
  1987. }
  1988. if ( config.HDREnabled() != g_config.HDREnabled() )
  1989. {
  1990. if ( mat_debugalttab.GetBool() )
  1991. {
  1992. Warning( "mat_debugalttab: Setting forceUpdate, bReloadMaterials, and bForceAltTab because new hdr level = %d and old hdr level = %d\n",
  1993. ( int )config.HDREnabled(), g_config.HDREnabled() );
  1994. }
  1995. forceUpdate = true;
  1996. bReloadMaterials = true;
  1997. bForceAltTab = true;
  1998. }
  1999. if ( config.ShadowDepthTexture() != g_config.ShadowDepthTexture() )
  2000. {
  2001. if ( mat_debugalttab.GetBool() )
  2002. {
  2003. Warning( "mat_debugalttab: Setting forceUpdate, bReloadMaterials and recomputeSnapshots (ShadowDepthTexture changed: %d -> %d)\n",
  2004. g_config.ShadowDepthTexture() ? 1 : 0, config.ShadowDepthTexture() ? 1 : 0 );
  2005. }
  2006. if ( !IsGameConsole() )
  2007. {
  2008. // On the 360, we don't actually destroy or recreate any render targets when r_shadowdepthtexture changes,
  2009. // so we don't have to do any of this stuff
  2010. forceUpdate = true;
  2011. bReloadMaterials = true;
  2012. recomputeSnapshots = true;
  2013. }
  2014. }
  2015. if ( forceUpdate )
  2016. {
  2017. if ( mat_debugalttab.GetBool() )
  2018. {
  2019. Warning( "mat_debugalttab: forceUpdate is true, therefore setting recomputeSnapshots, bRedownloadLightmaps, bRedownloadTextures, bResetAnisotropy, and bSetStandardVertexShaderConstants\n" );
  2020. }
  2021. GetLightmaps()->EnableLightmapFiltering( config.bFilterLightmaps );
  2022. recomputeSnapshots = true;
  2023. bRedownloadLightmaps = true;
  2024. bRedownloadTextures = true;
  2025. bResetAnisotropy = true;
  2026. bSetStandardVertexShaderConstants = true;
  2027. }
  2028. // toggle bump mapping
  2029. if ( config.UseBumpmapping() != g_config.UseBumpmapping() )
  2030. {
  2031. if( mat_debugalttab.GetBool() )
  2032. {
  2033. Warning( "mat_debugalttab: forceUpdate is true, therefore setting recomputeSnapshots, bRedownloadLightmaps, bRedownloadTextures, bResetAnisotropy, and bSetStandardVertexShaderConstants\n" );
  2034. }
  2035. recomputeSnapshots = true;
  2036. bReloadMaterials = true;
  2037. bResetAnisotropy = true;
  2038. }
  2039. // toggle detail texturing
  2040. if ( config.UseDetailTexturing() != g_config.UseDetailTexturing() )
  2041. {
  2042. if( mat_debugalttab.GetBool() )
  2043. {
  2044. Warning( "mat_debugalttab: forceUpdate is true, therefore setting recomputeSnapshots, bRedownloadLightmaps, bRedownloadTextures, bResetAnisotropy, and bSetStandardVertexShaderConstants\n" );
  2045. }
  2046. recomputeSnapshots = true;
  2047. bReloadMaterials = true;
  2048. bResetAnisotropy = true;
  2049. }
  2050. // toggle specularity
  2051. if ( config.UseSpecular() != g_config.UseSpecular() )
  2052. {
  2053. if( mat_debugalttab.GetBool() )
  2054. {
  2055. Warning( "mat_debugalttab: new usespecular=%d, old usespecular=%d, setting recomputeSnapshots, bReloadMaterials, and bResetAnisotropy\n",
  2056. ( int )config.UseSpecular(), ( int )g_config.UseSpecular() );
  2057. }
  2058. recomputeSnapshots = true;
  2059. bReloadMaterials = true;
  2060. bResetAnisotropy = true;
  2061. }
  2062. // toggle parallax mapping
  2063. if ( config.UseParallaxMapping() != g_config.UseParallaxMapping() )
  2064. {
  2065. if ( mat_debugalttab.GetBool() )
  2066. {
  2067. Warning( "mat_debugalttab: new UseParallaxMapping=%d, old UseParallaxMapping=%d, setting bReloadMaterials\n",
  2068. ( int )config.UseParallaxMapping(), ( int )g_config.UseParallaxMapping() );
  2069. }
  2070. bReloadMaterials = true;
  2071. }
  2072. // toggle phong
  2073. if ( config.UsePhong() != g_config.UsePhong() )
  2074. {
  2075. if ( mat_debugalttab.GetBool() )
  2076. {
  2077. Warning( "mat_debugalttab: new UsePhong=%d, old UsePhong=%d, setting bReloadMaterials\n",
  2078. ( int )config.UsePhong(), ( int )g_config.UsePhong() );
  2079. }
  2080. bReloadMaterials = true;
  2081. }
  2082. // toggle reverse depth
  2083. if ( config.bReverseDepth != g_config.bReverseDepth )
  2084. {
  2085. if( mat_debugalttab.GetBool() )
  2086. {
  2087. Warning( "mat_debugalttab: new ReduceFillrate=%d, old ReduceFillrate=%d, setting bReloadMaterials\n",
  2088. ( int )config.bReverseDepth, ( int )g_config.bReverseDepth );
  2089. }
  2090. recomputeSnapshots = true;
  2091. bResetAnisotropy = true;
  2092. }
  2093. // toggle no transparency
  2094. if ( config.bNoTransparency != g_config.bNoTransparency )
  2095. {
  2096. if ( mat_debugalttab.GetBool() )
  2097. {
  2098. Warning( "mat_debugalttab: new bNoTransparency=%d, old bNoTransparency=%d, setting recomputeSnapshots and bResetAnisotropy\n",
  2099. ( int )config.bNoTransparency, ( int )g_config.bNoTransparency );
  2100. }
  2101. recomputeSnapshots = true;
  2102. bResetAnisotropy = true;
  2103. }
  2104. // toggle lightmap filtering
  2105. if ( config.bFilterLightmaps != g_config.bFilterLightmaps )
  2106. {
  2107. if ( mat_debugalttab.GetBool() )
  2108. {
  2109. Warning( "mat_debugalttab: new bFilterLightmaps=%d, old bFilterLightmaps=%d, setting EnableLightmapFiltering\n",
  2110. ( int )config.bFilterLightmaps, ( int )g_config.bFilterLightmaps );
  2111. }
  2112. GetLightmaps()->EnableLightmapFiltering( config.bFilterLightmaps );
  2113. }
  2114. // toggle software lighting
  2115. if ( config.bSoftwareLighting != g_config.bSoftwareLighting )
  2116. {
  2117. if( mat_debugalttab.GetBool() )
  2118. {
  2119. Warning( "mat_debugalttab: new bSoftwareLighting=%d, old bSoftwareLighting=%d, setting bReloadMaterials\n",
  2120. ( int )config.bFilterLightmaps, ( int )g_config.bFilterLightmaps );
  2121. }
  2122. bReloadMaterials = true;
  2123. }
  2124. #ifndef _GAMECONSOLE
  2125. if ( config_internal.gpu_level != g_config_internal.gpu_level )
  2126. {
  2127. if ( mat_debugalttab.GetBool() )
  2128. {
  2129. Warning( "mat_debugalttab: new gpu_level=%d, old gpu_level=%d, setting bReloadMaterials\n",
  2130. ( int )config_internal.gpu_level, ( int )g_config_internal.gpu_level );
  2131. }
  2132. bReloadMaterials = true;
  2133. }
  2134. #endif
  2135. // generic things that cause us to redownload lightmaps
  2136. if ( config.bAllowCheats != g_config.bAllowCheats )
  2137. {
  2138. if ( mat_debugalttab.GetBool() )
  2139. {
  2140. Warning( "mat_debugalttab: new bAllowCheats=%d, old bAllowCheats=%d, setting bRedownloadLightmaps\n",
  2141. ( int )config.bAllowCheats, ( int )g_config.bAllowCheats );
  2142. }
  2143. bRedownloadLightmaps = true;
  2144. }
  2145. // generic things that cause us to redownload textures
  2146. if ( config.bAllowCheats != g_config.bAllowCheats ||
  2147. config.skipMipLevels != g_config.skipMipLevels ||
  2148. config.nShowMipLevels != g_config.nShowMipLevels ||
  2149. ( config.bCompressedTextures != g_config.bCompressedTextures ) ||
  2150. config.bShowLowResImage != g_config.bShowLowResImage ||
  2151. config.bDrawGray != g_config.bDrawGray
  2152. )
  2153. {
  2154. if ( mat_debugalttab.GetBool() )
  2155. {
  2156. Warning( "mat_debugalttab: setting bRedownloadTextures, recomputeSnapshots, and bResetAnisotropy\n" );
  2157. }
  2158. bRedownloadTextures = true;
  2159. recomputeSnapshots = true;
  2160. bResetAnisotropy = true;
  2161. }
  2162. if ( config.m_nForceAnisotropicLevel != g_config.m_nForceAnisotropicLevel )
  2163. {
  2164. if( mat_debugalttab.GetBool() )
  2165. {
  2166. Warning( "mat_debugalttab: new m_nForceAnisotropicLevel: %d, old m_nForceAnisotropicLevel: %d, setting bResetAnisotropy and bResetTextureFilter\n",
  2167. ( int )config.m_nForceAnisotropicLevel, ( int )g_config.m_nForceAnisotropicLevel );
  2168. }
  2169. bResetAnisotropy = true;
  2170. bResetTextureFilter = true;
  2171. }
  2172. if ( config.m_fMonitorGamma != g_config.m_fMonitorGamma || config.m_fGammaTVRangeMin != g_config.m_fGammaTVRangeMin ||
  2173. config.m_fGammaTVRangeMax != g_config.m_fGammaTVRangeMax || config.m_fGammaTVExponent != g_config.m_fGammaTVExponent ||
  2174. config.m_bGammaTVEnabled != g_config.m_bGammaTVEnabled )
  2175. {
  2176. if( mat_debugalttab.GetBool() )
  2177. {
  2178. Warning( "mat_debugalttab: new monitorgamma: %f, old monitorgamma: %f, setting bMonitorGammaChanged\n",
  2179. config.m_fMonitorGamma, g_config.m_fMonitorGamma );
  2180. }
  2181. bMonitorGammaChanged = true;
  2182. }
  2183. if ( config.m_VideoMode.m_Width != g_config.m_VideoMode.m_Width ||
  2184. config.m_VideoMode.m_Height != g_config.m_VideoMode.m_Height ||
  2185. config.m_VideoMode.m_RefreshRate != g_config.m_VideoMode.m_RefreshRate ||
  2186. config.m_nAASamples != g_config.m_nAASamples ||
  2187. config.m_nAAQuality != g_config.m_nAAQuality ||
  2188. config.Windowed() != g_config.Windowed() ||
  2189. config.NoWindowBorder() != g_config.NoWindowBorder() ||
  2190. config.Stencil() != g_config.Stencil() )
  2191. {
  2192. if( mat_debugalttab.GetBool() )
  2193. {
  2194. Warning( "mat_debugalttab: video mode changed for one of various reasons\n" );
  2195. }
  2196. bVideoModeChange = true;
  2197. }
  2198. // Toggle triple buffering
  2199. if ( config.m_bWantTripleBuffered != g_config.m_bWantTripleBuffered )
  2200. {
  2201. // Only force a video mode change if we are fullscreen and vsync'd
  2202. if ( ( IsGameConsole() || !config.Windowed() ) && ( config.WaitForVSync() ) )
  2203. {
  2204. if ( mat_debugalttab.GetBool() )
  2205. {
  2206. Warning( "mat_debugalttab: video mode changed because triple buffering changed\n" );
  2207. }
  2208. bVideoModeChange = true;
  2209. }
  2210. }
  2211. // toggle wait for vsync
  2212. if ( (IsGameConsole() || !config.Windowed()) && (config.WaitForVSync() != g_config.WaitForVSync()) )
  2213. {
  2214. # if ( !defined( _X360 ) )
  2215. {
  2216. if ( mat_debugalttab.GetBool() )
  2217. {
  2218. Warning( "mat_debugalttab: video mode changed due to toggle of wait for vsync\n" );
  2219. }
  2220. bVideoModeChange = true;
  2221. }
  2222. # else
  2223. {
  2224. g_pShaderAPI->EnableVSync_360( config.WaitForVSync() );
  2225. }
  2226. # endif
  2227. }
  2228. g_config = config;
  2229. #ifndef _GAMECONSOLE
  2230. g_config_internal = config_internal;
  2231. #endif
  2232. if ( bRedownloadTextures || bRedownloadLightmaps )
  2233. {
  2234. // Get rid of this?
  2235. ColorSpace::SetGamma( 2.2f, 2.2f, OVERBRIGHT, g_config.bAllowCheats, false );
  2236. }
  2237. // 360 does not support various configuration changes and cannot reload materials
  2238. if ( !IsGameConsole() )
  2239. {
  2240. if ( bResetAnisotropy || recomputeSnapshots || bRedownloadLightmaps ||
  2241. bRedownloadTextures || bResetAnisotropy || bVideoModeChange ||
  2242. bSetStandardVertexShaderConstants || bResetTextureFilter )
  2243. {
  2244. Unlock( hLock );
  2245. ForceSingleThreaded();
  2246. hLock = Lock();
  2247. }
  2248. }
  2249. if ( bReloadMaterials && !IsGameConsole() )
  2250. {
  2251. if ( mat_debugalttab.GetBool() )
  2252. {
  2253. Warning( "mat_debugalttab: ReloadMaterials\n" );
  2254. }
  2255. ReloadMaterials();
  2256. }
  2257. // 360 does not support various configuration changes and cannot reload textures
  2258. // 360 has no reason to reload textures, it's unnecessary and massively expensive
  2259. // 360 does not use this path as an init affect to get its textures into memory
  2260. if ( bRedownloadTextures && !IsGameConsole() )
  2261. {
  2262. if ( mat_debugalttab.GetBool() )
  2263. {
  2264. Warning( "mat_debugalttab: redownloading textures\n" );
  2265. }
  2266. if ( CanDownloadTextures() )
  2267. {
  2268. TextureManager()->RestoreRenderTargets();
  2269. TextureManager()->RestoreNonRenderTargetTextures();
  2270. }
  2271. }
  2272. else if ( bResetTextureFilter )
  2273. {
  2274. if( mat_debugalttab.GetBool() )
  2275. {
  2276. Warning( "mat_debugalttab: ResetTextureFilteringState\n" );
  2277. }
  2278. TextureManager()->ResetTextureFilteringState();
  2279. }
  2280. // Recompute all state snapshots
  2281. if ( recomputeSnapshots )
  2282. {
  2283. if( mat_debugalttab.GetBool() )
  2284. {
  2285. Warning( "mat_debugalttab: RecomputeAllStateSnapshots\n" );
  2286. }
  2287. RecomputeAllStateSnapshots();
  2288. }
  2289. if ( bResetAnisotropy )
  2290. {
  2291. if( mat_debugalttab.GetBool() )
  2292. {
  2293. Warning( "mat_debugalttab: SetAnisotropicLevel\n" );
  2294. }
  2295. g_pShaderAPI->SetAnisotropicLevel( config.m_nForceAnisotropicLevel );
  2296. }
  2297. if ( bSetStandardVertexShaderConstants )
  2298. {
  2299. if ( mat_debugalttab.GetBool() )
  2300. {
  2301. Warning( "mat_debugalttab: SetStandardVertexShaderConstants\n" );
  2302. }
  2303. g_pShaderAPI->SetStandardVertexShaderConstants( OVERBRIGHT );
  2304. }
  2305. if ( bMonitorGammaChanged )
  2306. {
  2307. if( mat_debugalttab.GetBool() )
  2308. {
  2309. Warning( "mat_debugalttab: SetHardwareGammaRamp\n" );
  2310. }
  2311. g_pShaderDevice->SetHardwareGammaRamp( config.m_fMonitorGamma, config.m_fGammaTVRangeMin, config.m_fGammaTVRangeMax,
  2312. config.m_fGammaTVExponent, config.m_bGammaTVEnabled );
  2313. }
  2314. if ( bVideoModeChange )
  2315. {
  2316. if ( mat_debugalttab.GetBool() )
  2317. {
  2318. Warning( "mat_debugalttab: ChangeVideoMode\n" );
  2319. }
  2320. ShaderDeviceInfo_t info;
  2321. ConvertModeStruct( &info, config );
  2322. g_pShaderAPI->ChangeVideoMode( info );
  2323. }
  2324. if ( bForceAltTab )
  2325. {
  2326. // Simulate an Alt-Tab
  2327. // g_pShaderAPI->ReleaseResources();
  2328. // g_pShaderAPI->ReacquireResources();
  2329. }
  2330. Unlock( hLock );
  2331. if ( bVideoModeChange )
  2332. {
  2333. ForceSingleThreaded();
  2334. }
  2335. return bRedownloadLightmaps;
  2336. }
  2337. //-----------------------------------------------------------------------------
  2338. // This is called when the config changes
  2339. //-----------------------------------------------------------------------------
  2340. bool CMaterialSystem::UpdateConfig( bool forceUpdate )
  2341. {
  2342. int nUpdateFlags = 0;
  2343. if ( g_pCVar && g_pCVar->HasQueuedMaterialThreadConVarSets() )
  2344. {
  2345. ForceSingleThreaded();
  2346. nUpdateFlags = g_pCVar->ProcessQueuedMaterialThreadConVarSets();
  2347. }
  2348. MaterialSystem_Config_t config = g_config;
  2349. #ifndef DEDICATED
  2350. ReadConfigFromConVars( &config );
  2351. #endif
  2352. return OverrideConfig( config, forceUpdate );
  2353. }
  2354. void CMaterialSystem::ReleaseResources()
  2355. {
  2356. if ( mat_debugalttab.GetBool() )
  2357. {
  2358. Warning( "mat_debugalttab: CMaterialSystem::ReleaseResources\n" );
  2359. }
  2360. g_pShaderDevice->ReleaseResources();
  2361. #if defined( FEATURE_SUBD_SUPPORT )
  2362. g_pSubDMgr->ReleaseResources();
  2363. #endif
  2364. }
  2365. void CMaterialSystem::ReacquireResources()
  2366. {
  2367. if ( mat_debugalttab.GetBool() )
  2368. {
  2369. Warning( "mat_debugalttab: CMaterialSystem::ReacquireResources\n" );
  2370. }
  2371. g_pShaderDevice->ReacquireResources();
  2372. #if defined( FEATURE_SUBD_SUPPORT )
  2373. g_pSubDMgr->ReacquireResources();
  2374. #endif
  2375. }
  2376. //-----------------------------------------------------------------------------
  2377. //
  2378. //-----------------------------------------------------------------------------
  2379. bool CMaterialSystem::OnDrawMesh( IMesh *pMesh, int firstIndex, int numIndices )
  2380. {
  2381. if ( IsInStubMode() )
  2382. {
  2383. return false;
  2384. }
  2385. return GetRenderContextInternal()->OnDrawMesh( pMesh, firstIndex, numIndices );
  2386. }
  2387. bool CMaterialSystem::OnDrawMesh( IMesh *pMesh, CPrimList *pLists, int nLists )
  2388. {
  2389. if ( IsInStubMode() )
  2390. return false;
  2391. return GetRenderContextInternal()->OnDrawMesh( pMesh, pLists, nLists );
  2392. }
  2393. bool CMaterialSystem::OnDrawMeshModulated( IMesh *pMesh, const Vector4D &diffuseModulation, int firstIndex, int numIndices )
  2394. {
  2395. if ( IsInStubMode() )
  2396. return false;
  2397. return GetRenderContextInternal()->OnDrawMeshModulated( pMesh, diffuseModulation, firstIndex, numIndices );
  2398. }
  2399. void CMaterialSystem::OnThreadEvent( uint32 threadEvent )
  2400. {
  2401. m_threadEvents.AddToTail( threadEvent );
  2402. }
  2403. //-----------------------------------------------------------------------------
  2404. // Creates a procedural texture
  2405. //-----------------------------------------------------------------------------
  2406. ITexture *CMaterialSystem::CreateProceduralTexture(
  2407. const char *pTextureName,
  2408. const char *pTextureGroupName,
  2409. int w,
  2410. int h,
  2411. ImageFormat fmt,
  2412. int nFlags )
  2413. {
  2414. ITextureInternal* pTex = TextureManager()->CreateProceduralTexture( pTextureName, pTextureGroupName, w, h, 1, fmt, nFlags );
  2415. return pTex;
  2416. }
  2417. #if defined( _X360 )
  2418. //-----------------------------------------------------------------------------
  2419. // Create a texture for displaying gamerpics.
  2420. // This function allocates the texture in the correct gamerpic format, but it does not fill in the gamerpic data.
  2421. //-----------------------------------------------------------------------------
  2422. ITexture *CMaterialSystem::CreateGamerpicTexture(
  2423. const char *pTextureName,
  2424. const char *pTextureGroupName,
  2425. int nFlags )
  2426. {
  2427. return CreateProceduralTexture( pTextureName, pTextureGroupName, g_GamerpicSize, g_GamerpicSize, g_GamerpicFormat, nFlags );
  2428. }
  2429. //-----------------------------------------------------------------------------
  2430. // Update the given texture with the player gamerpic for the local player at the given index.
  2431. // Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
  2432. //-----------------------------------------------------------------------------
  2433. bool CMaterialSystem::UpdateLocalGamerpicTexture(
  2434. ITexture *pTexture,
  2435. DWORD userIndex )
  2436. {
  2437. Assert( pTexture != NULL );
  2438. Assert( pTexture->GetActualWidth() == g_GamerpicSize && pTexture->GetActualHeight() == g_GamerpicSize );
  2439. Assert( pTexture->GetImageFormat() == g_GamerpicFormat );
  2440. Assert( userIndex >= 0 && userIndex < 4 );
  2441. // lock
  2442. CPixelWriter writer;
  2443. g_pShaderAPI->ModifyTexture( ((ITextureInternal*)pTexture)->GetTextureHandle( 0 ) );
  2444. g_pShaderAPI->TexLock( 0, 0, 0, 0, g_GamerpicSize, g_GamerpicSize, writer );
  2445. // Write the gamerpic to the texture.
  2446. BYTE *pBuf = (BYTE*)writer.GetPixelMemory();
  2447. DWORD retVal = XUserReadGamerPicture( userIndex, FALSE, pBuf, g_GamerpicSize * writer.GetPixelSize(), g_GamerpicSize * writer.GetPixelSize(), NULL );
  2448. // unlock
  2449. g_pShaderAPI->TexUnlock();
  2450. return (retVal == ERROR_SUCCESS);
  2451. }
  2452. //-----------------------------------------------------------------------------
  2453. // Update the given texture with a remote player's gamerpic.
  2454. // Note: this texture must be the correct size and format. Use CreateGamerpicTexture.
  2455. //-----------------------------------------------------------------------------
  2456. bool CMaterialSystem::UpdateRemoteGamerpicTexture(
  2457. ITexture *pTexture,
  2458. XUID xuid )
  2459. {
  2460. Assert( pTexture != NULL );
  2461. Assert( pTexture->GetActualWidth() == g_GamerpicSize && pTexture->GetActualHeight() == g_GamerpicSize );
  2462. Assert( pTexture->GetImageFormat() == g_GamerpicFormat );
  2463. //
  2464. // Read the remote player's profile.
  2465. //
  2466. const DWORD xuidCount = 1;
  2467. XUID xuids[xuidCount];
  2468. xuids[0] = xuid;
  2469. const DWORD settingIdCount = 1;
  2470. DWORD settingIds[settingIdCount];
  2471. settingIds[0] = XPROFILE_GAMERCARD_PICTURE_KEY;
  2472. // Get the size of the results.
  2473. DWORD resultsSize = 0;
  2474. DWORD retVal = XUserReadProfileSettingsByXuid( 0, XBX_GetPrimaryUserId(), xuidCount, xuids, settingIdCount, settingIds, &resultsSize, 0, 0 );
  2475. if ( retVal != ERROR_INSUFFICIENT_BUFFER )
  2476. {
  2477. return false;
  2478. }
  2479. Assert( resultsSize > 0 );
  2480. // Get the profile with the correct results size.
  2481. CArrayAutoPtr<unsigned char> spResultsBuffer( new unsigned char[resultsSize] );
  2482. XUSER_READ_PROFILE_SETTING_RESULT *pResults = (XUSER_READ_PROFILE_SETTING_RESULT*)spResultsBuffer.Get();
  2483. retVal = XUserReadProfileSettingsByXuid( 0, 0, xuidCount, xuids, settingIdCount, settingIds, &resultsSize, pResults, 0 );
  2484. if ( retVal != ERROR_SUCCESS || pResults->dwSettingsLen == 0 )
  2485. {
  2486. return false;
  2487. }
  2488. // lock
  2489. CPixelWriter writer;
  2490. g_pShaderAPI->ModifyTexture( ((ITextureInternal*)pTexture)->GetTextureHandle( 0 ) );
  2491. g_pShaderAPI->TexLock( 0, 0, 0, 0, g_GamerpicSize, g_GamerpicSize, writer );
  2492. // Write the gamerpic to the texture.
  2493. BYTE *pBuf = (BYTE*)writer.GetPixelMemory();
  2494. retVal = XUserReadGamerPictureByKey( &(pResults->pSettings[0].data), FALSE, pBuf, g_GamerpicSize * writer.GetPixelSize(), g_GamerpicSize * writer.GetPixelSize(), NULL );
  2495. // unlock
  2496. g_pShaderAPI->TexUnlock();
  2497. return (retVal == ERROR_SUCCESS);
  2498. }
  2499. #endif // _X360
  2500. //-----------------------------------------------------------------------------
  2501. // Create new materials (currently only used by the editor!)
  2502. //-----------------------------------------------------------------------------
  2503. IMaterial *CMaterialSystem::CreateMaterial( const char *pMaterialName, KeyValues *pVMTKeyValues )
  2504. {
  2505. // For not, just create a material with no default settings
  2506. IMaterialInternal* pMaterial = IMaterialInternal::CreateMaterial( pMaterialName, TEXTURE_GROUP_OTHER, pVMTKeyValues );
  2507. pMaterial->IncrementReferenceCount();
  2508. AddMaterialToMaterialList( pMaterial );
  2509. return pMaterial->GetQueueFriendlyVersion();
  2510. }
  2511. //-----------------------------------------------------------------------------
  2512. // Finds or creates a procedural material
  2513. //-----------------------------------------------------------------------------
  2514. IMaterial *CMaterialSystem::FindProceduralMaterial( const char *pMaterialName, const char *pTextureGroupName, KeyValues *pVMTKeyValues )
  2515. {
  2516. // We need lower-case symbols for this to work
  2517. int nLen = Q_strlen( pMaterialName ) + 1;
  2518. char *pTemp = (char*)stackalloc( nLen );
  2519. Q_strncpy( pTemp, pMaterialName, nLen );
  2520. Q_strlower( pTemp );
  2521. Q_FixSlashes( pTemp, '/' );
  2522. // 'true' causes the search to find procedural materials
  2523. IMaterialInternal *pMaterial = m_MaterialDict.FindMaterial( pTemp, true );
  2524. if ( pMaterial )
  2525. {
  2526. if ( pVMTKeyValues != NULL )
  2527. {
  2528. pVMTKeyValues->deleteThis();
  2529. }
  2530. }
  2531. else
  2532. {
  2533. if ( pVMTKeyValues != NULL )
  2534. {
  2535. pMaterial = IMaterialInternal::CreateMaterial( pMaterialName, pTextureGroupName, pVMTKeyValues );
  2536. AddMaterialToMaterialList( static_cast<IMaterialInternal*>( pMaterial ) );
  2537. }
  2538. else
  2539. {
  2540. pMaterial = g_pErrorMaterial;
  2541. }
  2542. }
  2543. return pMaterial->GetQueueFriendlyVersion();
  2544. }
  2545. //-----------------------------------------------------------------------------
  2546. // Search by name
  2547. //-----------------------------------------------------------------------------
  2548. IMaterial* CMaterialSystem::FindMaterial( char const *pMaterialName, const char *pTextureGroupName, bool bComplain, const char *pComplainPrefix )
  2549. {
  2550. if ( g_pResourceAccessControl )
  2551. {
  2552. if ( !g_pResourceAccessControl->IsAccessAllowed( RESOURCE_MATERIAL, pMaterialName ) )
  2553. return g_pErrorMaterial->GetRealTimeVersion();
  2554. }
  2555. if ( !pMaterialName )
  2556. {
  2557. return g_pErrorMaterial->GetQueueFriendlyVersion();
  2558. }
  2559. // We need lower-case symbols for this to work
  2560. int nLen = Q_strlen( pMaterialName ) + 1;
  2561. char *pFixedNameTemp = (char*)stackalloc( nLen );
  2562. char *pTemp = (char*)stackalloc( nLen );
  2563. Q_strncpy( pFixedNameTemp, pMaterialName, nLen );
  2564. Q_strlower( pFixedNameTemp );
  2565. #ifdef PLATFORM_POSIX
  2566. // strip extensions needs correct slashing for the OS, so fix it up early for Posix
  2567. Q_FixSlashes( pFixedNameTemp, '/' );
  2568. #endif
  2569. Q_StripExtension( pFixedNameTemp, pTemp, nLen );
  2570. #ifndef PLATFORM_POSIX
  2571. Q_FixSlashes( pTemp, '/' );
  2572. #endif
  2573. Assert( nLen >= Q_strlen( pTemp ) + 1 );
  2574. IMaterialInternal *pExistingMaterial = m_MaterialDict.FindMaterial( pTemp, false ); // 'false' causes the search to find only file-created materials
  2575. if ( pExistingMaterial )
  2576. return pExistingMaterial->GetQueueFriendlyVersion();
  2577. #if defined( DEVELOPMENT_ONLY ) || defined( ALLOW_TEXT_MODE )
  2578. static bool s_bTextMode = CommandLine()->HasParm( "-textmode" );
  2579. if ( s_bTextMode )
  2580. return g_pErrorMaterial->GetQueueFriendlyVersion();
  2581. #endif
  2582. // if ( !m_MaterialDict.IsMissing(pTemp) )
  2583. {
  2584. // It hasn't been seen yet, so let's check to see if it's in the filesystem.
  2585. nLen = Q_strlen( "materials/" ) + Q_strlen( pTemp ) + Q_strlen( ".vmt" ) + 1;
  2586. char *vmtName = (char *)stackalloc( nLen );
  2587. // Check to see if this is a UNC-specified material name
  2588. bool bIsUNC = pTemp[0] == '/' && pTemp[1] == '/' && pTemp[2] != '/';
  2589. if ( !bIsUNC )
  2590. {
  2591. Q_strncpy( vmtName, "materials/", nLen );
  2592. Q_strncat( vmtName, pTemp, nLen, COPY_ALL_CHARACTERS );
  2593. }
  2594. else
  2595. {
  2596. Q_strncpy( vmtName, pTemp, nLen );
  2597. }
  2598. //Q_strncat( vmtName, ".vmt", nLen, COPY_ALL_CHARACTERS );
  2599. Assert( nLen >= (int)Q_strlen( vmtName ) + 1 );
  2600. CUtlVector<FileNameHandle_t> includes;
  2601. KeyValues *pKeyValues = new KeyValues("vmt");
  2602. KeyValues *pPatchKeyValues = new KeyValues( "vmt_patches" );
  2603. if ( !LoadVMTFile( *pKeyValues, *pPatchKeyValues, vmtName, true, &includes ) )
  2604. {
  2605. pKeyValues->deleteThis();
  2606. pKeyValues = NULL;
  2607. pPatchKeyValues->deleteThis();
  2608. pPatchKeyValues = NULL;
  2609. }
  2610. else
  2611. {
  2612. char *matNameWithExtension;
  2613. nLen = Q_strlen( pTemp ) + Q_strlen( ".vmt" ) + 1;
  2614. matNameWithExtension = (char *)stackalloc( nLen );
  2615. Q_strncpy( matNameWithExtension, pTemp, nLen );
  2616. Q_strncat( matNameWithExtension, ".vmt", nLen, COPY_ALL_CHARACTERS );
  2617. IMaterialInternal *pMat = NULL;
  2618. if ( !Q_stricmp( pKeyValues->GetName(), "subrect" ) )
  2619. {
  2620. pMat = m_MaterialDict.AddMaterialSubRect( matNameWithExtension, pTextureGroupName, pKeyValues, pPatchKeyValues );
  2621. }
  2622. else
  2623. {
  2624. pMat = m_MaterialDict.AddMaterial( matNameWithExtension, pTextureGroupName );
  2625. if ( g_pShaderDevice->IsUsingGraphics() )
  2626. {
  2627. if ( !bIsUNC )
  2628. {
  2629. m_pForcedTextureLoadPathID = "GAME";
  2630. }
  2631. pMat->PrecacheVars( pKeyValues, pPatchKeyValues, &includes );
  2632. m_pForcedTextureLoadPathID = NULL;
  2633. }
  2634. }
  2635. pKeyValues->deleteThis();
  2636. pPatchKeyValues->deleteThis();
  2637. return pMat->GetQueueFriendlyVersion();
  2638. }
  2639. if ( bComplain )
  2640. {
  2641. Assert( pTemp );
  2642. // convert to lowercase
  2643. nLen = Q_strlen(pTemp) + 1 ;
  2644. char *name = (char*)stackalloc( nLen );
  2645. Q_strncpy( name, pTemp, nLen );
  2646. Q_strlower( name );
  2647. if ( m_MaterialDict.NoteMissing( name ) )
  2648. {
  2649. if ( pComplainPrefix )
  2650. {
  2651. DevWarning( "%s", pComplainPrefix );
  2652. }
  2653. DevWarning( "material \"%s\" not found.\n", name );
  2654. }
  2655. }
  2656. }
  2657. return g_pErrorMaterial->GetQueueFriendlyVersion();
  2658. }
  2659. bool CMaterialSystem::LoadKeyValuesFromVMTFile( KeyValues &vmtKeyValues, const char *pMaterialName, bool bUsesUNCFilename )
  2660. {
  2661. CUtlVector<FileNameHandle_t> includes;
  2662. KeyValues *pPatchKeyValues = new KeyValues( "vmt_patches" );
  2663. bool bResult = LoadVMTFile( vmtKeyValues, *pPatchKeyValues, pMaterialName, bUsesUNCFilename, &includes );
  2664. // we don't need these, they were applied to vmtKeyValues
  2665. pPatchKeyValues->deleteThis();
  2666. pPatchKeyValues = NULL;
  2667. return bResult;
  2668. }
  2669. static char const *TextureAliases[] =
  2670. {
  2671. // this table is only here for backwards compatibility where a render target change was made,
  2672. // and we wish to redirect an existing old client.dll for hl2 to reference this texture. It's
  2673. // not meant as a general texture aliasing system.
  2674. "_rt_FullFrameFB1", "_rt_FullScreen"
  2675. };
  2676. ITexture *CMaterialSystem::FindTexture( char const *pTextureName, const char *pTextureGroupName, bool bComplain /* = false */, int nAdditionalCreationFlags /* = 0 */ )
  2677. {
  2678. ITextureInternal *pTexture = TextureManager()->FindOrLoadTexture( pTextureName, pTextureGroupName, nAdditionalCreationFlags );
  2679. Assert( pTexture );
  2680. if ( pTexture->IsError() && !CommandLine()->HasParm( "-textmode" ) )
  2681. {
  2682. if ( IsPC() )
  2683. {
  2684. for ( int i=0; i<NELEMS( TextureAliases ); i+=2 )
  2685. {
  2686. if ( !Q_stricmp( pTextureName, TextureAliases[i] ) )
  2687. {
  2688. return FindTexture( TextureAliases[i+1], pTextureGroupName, bComplain, nAdditionalCreationFlags );
  2689. }
  2690. }
  2691. }
  2692. if ( bComplain )
  2693. {
  2694. DevWarning( "Texture '%s' not found.\n", pTextureName );
  2695. }
  2696. }
  2697. return pTexture;
  2698. }
  2699. bool CMaterialSystem::IsTextureLoaded( char const* pTextureName ) const
  2700. {
  2701. return TextureManager()->IsTextureLoaded( pTextureName );
  2702. }
  2703. bool CMaterialSystem::GetTextureInformation( char const *szTextureName, MaterialTextureInfo_t &info ) const
  2704. {
  2705. return TextureManager()->GetTextureInformation( szTextureName, info );
  2706. }
  2707. void CMaterialSystem::AddTextureAlias( const char *pAlias, const char *pRealName )
  2708. {
  2709. TextureManager()->AddTextureAlias( pAlias, pRealName );
  2710. }
  2711. void CMaterialSystem::RemoveTextureAlias( const char *pAlias )
  2712. {
  2713. TextureManager()->RemoveTextureAlias( pAlias );
  2714. }
  2715. void CMaterialSystem::SetExcludedTextures( const char *pScriptName, bool bUsingWeaponModelCache )
  2716. {
  2717. TextureManager()->SetExcludedTextures( pScriptName, bUsingWeaponModelCache );
  2718. }
  2719. void CMaterialSystem::UpdateExcludedTextures( void )
  2720. {
  2721. TextureManager()->UpdateExcludedTextures();
  2722. // Have to re-setup the representative textures since they may have been removed out from under us by the queued loader.
  2723. for ( MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial( i ) )
  2724. {
  2725. GetMaterialInternal( i )->FindRepresentativeTexture();
  2726. GetMaterialInternal( i )->PrecacheMappingDimensions();
  2727. }
  2728. }
  2729. void CMaterialSystem::ClearForceExcludes( void )
  2730. {
  2731. TextureManager()->ClearForceExcludes();
  2732. }
  2733. //-----------------------------------------------------------------------------
  2734. // Recomputes state snapshots for all materials
  2735. //-----------------------------------------------------------------------------
  2736. void CMaterialSystem::RecomputeAllStateSnapshots()
  2737. {
  2738. g_pShaderAPI->ClearSnapshots();
  2739. for (MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
  2740. {
  2741. GetMaterialInternal(i)->RecomputeStateSnapshots();
  2742. }
  2743. g_pShaderAPI->ResetRenderState();
  2744. }
  2745. //-----------------------------------------------------------------------------
  2746. // Uncache all materials
  2747. //-----------------------------------------------------------------------------
  2748. void CMaterialSystem::UncacheAllMaterials()
  2749. {
  2750. MaterialLock_t hLock = Lock();
  2751. Flush( true );
  2752. for ( MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial( i ) )
  2753. {
  2754. Assert( GetMaterialInternal(i)->GetReferenceCount() >= 0 );
  2755. GetMaterialInternal(i)->Uncache();
  2756. }
  2757. TextureManager()->RemoveUnusedTextures();
  2758. Unlock( hLock );
  2759. }
  2760. //-----------------------------------------------------------------------------
  2761. // Uncache unused materials
  2762. //-----------------------------------------------------------------------------
  2763. void CMaterialSystem::UncacheUnusedMaterials( bool bRecomputeStateSnapshots )
  2764. {
  2765. MaterialLock_t hLock = Lock();
  2766. Flush( true );
  2767. // We need two loops to make sure we don't reset the snapshots if nothing got removed,
  2768. // otherwise the snapshot recomputation is expensive and avoided at load time
  2769. bool bDidUncacheMaterial = false;
  2770. for ( MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
  2771. {
  2772. IMaterialInternal *pMatInternal = GetMaterialInternal( i );
  2773. Assert( pMatInternal->GetReferenceCount() >= 0 );
  2774. if ( pMatInternal->GetReferenceCount() <= 0 )
  2775. {
  2776. bDidUncacheMaterial = true;
  2777. pMatInternal->Uncache();
  2778. }
  2779. }
  2780. if ( IsX360() && bRecomputeStateSnapshots )
  2781. {
  2782. // Always recompute snapshots because the queued loading process skips it during pre-purge,
  2783. // allowing it to happen just once, here.
  2784. bDidUncacheMaterial = true;
  2785. }
  2786. if ( bDidUncacheMaterial && bRecomputeStateSnapshots )
  2787. {
  2788. // Clear the state snapshots since we are going to rebuild all of them.
  2789. g_pShaderAPI->ClearSnapshots();
  2790. g_pShaderAPI->ClearVertexAndPixelShaderRefCounts();
  2791. for ( MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
  2792. {
  2793. IMaterialInternal *pMatInternal = GetMaterialInternal(i);
  2794. if ( pMatInternal->GetReferenceCount() > 0 )
  2795. {
  2796. // Recompute the state snapshots for the materials that we are keeping
  2797. // since we blew all of them away above.
  2798. pMatInternal->RecomputeStateSnapshots();
  2799. }
  2800. }
  2801. g_pShaderAPI->PurgeUnusedVertexAndPixelShaders();
  2802. }
  2803. if ( bRecomputeStateSnapshots )
  2804. {
  2805. // kick out all per material context datas
  2806. for( MaterialHandle_t i = m_MaterialDict.FirstMaterial(); i != m_MaterialDict.InvalidMaterial(); i = m_MaterialDict.NextMaterial( i ) )
  2807. {
  2808. GetMaterialInternal(i)->ClearContextData();
  2809. }
  2810. }
  2811. TextureManager()->RemoveUnusedTextures();
  2812. Unlock( hLock );
  2813. }
  2814. //-----------------------------------------------------------------------------
  2815. // Release temporary HW memory...
  2816. //-----------------------------------------------------------------------------
  2817. void CMaterialSystem::ResetTempHWMemory( bool bExitingLevel )
  2818. {
  2819. if( !IsPS3() )
  2820. {
  2821. // Doing this on map transitions is not beneficial on PS3 (in fact it may fragment our RSX allocator)
  2822. g_pShaderAPI->DestroyVertexBuffers( bExitingLevel );
  2823. }
  2824. TextureManager()->ReleaseTempRenderTargetBits();
  2825. }
  2826. //-----------------------------------------------------------------------------
  2827. // Get GPU memory usage stats
  2828. //-----------------------------------------------------------------------------
  2829. void CMaterialSystem::GetGPUMemoryStats( GPUMemoryStats &stats )
  2830. {
  2831. g_pShaderAPI->GetGPUMemoryStats( stats );
  2832. }
  2833. bool CMaterialSystem::IsLevelLoadingComplete() const
  2834. {
  2835. return m_bLevelLoadingComplete;
  2836. }
  2837. void CMaterialSystem::OnAsyncTextureDataComplete( AsyncTextureContext_t *pContext, void *pData, int nNumReadBytes, AsyncTextureLoadError_t loadError )
  2838. {
  2839. // queue the async loaded texture data, cannot deal with update the texture data until end-of-frame on the main thread
  2840. AsyncTextureLoad_t textureLoad;
  2841. textureLoad.m_pContext = pContext;
  2842. textureLoad.m_pData = pData;
  2843. textureLoad.m_nNumReadBytes = nNumReadBytes;
  2844. textureLoad.m_LoadError = loadError;
  2845. m_QueuedAsyncTextureLoads.PushItem( textureLoad );
  2846. }
  2847. void CMaterialSystem::ServiceAsyncTextureLoads()
  2848. {
  2849. if ( !m_QueuedAsyncTextureLoads.Count() && !m_pActiveAsyncTextureLoad )
  2850. {
  2851. // nothing to do
  2852. return;
  2853. }
  2854. // We don't necessarily process all the elements in the queue in order to avoid
  2855. // large spikes on the main thread
  2856. // Spreading the cost of creating the async textures across multiple frames
  2857. double flStartTime = Plat_FloatTime();
  2858. float flRemainingMaxTimeMs = mat_async_tex_maxtime_ms.GetFloat();
  2859. // Resume FinishAsyncDownload() that was interrupted on the previous frame
  2860. // Need to do it first (before processing any other async textures from the queue)
  2861. // otherwise the VTF texture created on the previous frame will be invalid !
  2862. if ( m_pActiveAsyncTextureLoad )
  2863. {
  2864. m_pActiveAsyncTextureLoad->m_pContext->m_pTexture->FinishAsyncDownload(
  2865. m_pActiveAsyncTextureLoad->m_pContext,
  2866. m_pActiveAsyncTextureLoad->m_pData,
  2867. m_pActiveAsyncTextureLoad->m_nNumReadBytes,
  2868. !m_bLevelLoadingComplete || (m_pActiveAsyncTextureLoad->m_LoadError != ASYNCTEXTURE_LOADERROR_NONE),
  2869. flRemainingMaxTimeMs );
  2870. m_pActiveAsyncTextureLoad = NULL;
  2871. // Limit the amount of time spent creating D3D resources
  2872. float flElapsedMs = (Plat_FloatTime() - flStartTime) * 1000.0f;
  2873. flRemainingMaxTimeMs = mat_async_tex_maxtime_ms.GetFloat() - flElapsedMs;
  2874. if (flRemainingMaxTimeMs < 0.0f)
  2875. {
  2876. return;
  2877. }
  2878. }
  2879. // async texture loads are only valid AFTER the level has completed loading
  2880. // abort data incorrectly delivered during loading or on any data error
  2881. while ( m_QueuedAsyncTextureLoads.PopItem( &m_AsyncTextureLoad ) )
  2882. {
  2883. bool bDownloadCompleted = m_AsyncTextureLoad.m_pContext->m_pTexture->FinishAsyncDownload(
  2884. m_AsyncTextureLoad.m_pContext,
  2885. m_AsyncTextureLoad.m_pData,
  2886. m_AsyncTextureLoad.m_nNumReadBytes,
  2887. !m_bLevelLoadingComplete || ( m_AsyncTextureLoad.m_LoadError != ASYNCTEXTURE_LOADERROR_NONE ),
  2888. flRemainingMaxTimeMs );
  2889. if ( !bDownloadCompleted )
  2890. {
  2891. // FinishAsyncDownload has been interrupted and need to resume at the next frame
  2892. m_pActiveAsyncTextureLoad = &m_AsyncTextureLoad;
  2893. break;
  2894. }
  2895. else
  2896. {
  2897. m_pActiveAsyncTextureLoad = NULL;
  2898. }
  2899. // Limit the amount of time spent creating D3D resources
  2900. float flElapsedMs = ( Plat_FloatTime() - flStartTime ) * 1000.0f;
  2901. flRemainingMaxTimeMs = mat_async_tex_maxtime_ms.GetFloat() - flElapsedMs;
  2902. if ( flRemainingMaxTimeMs < 0.0f )
  2903. {
  2904. break;
  2905. }
  2906. }
  2907. }
  2908. //#define SPEW_SERVICE_END_FRAME_TIME
  2909. void CMaterialSystem::ServiceEndFramePriorToNextContext()
  2910. {
  2911. #if !defined( _CERT ) && defined( SPEW_SERVICE_END_FRAME_TIME )
  2912. double flStartTime = Plat_FloatTime();
  2913. #endif
  2914. // All these callers are highly specialized handlers aware of
  2915. // this precise calling state. These handlers all need to perform some
  2916. // operation that must be on the main thread while no rendering
  2917. // is concurrent.
  2918. bool bDataProcessed = false;
  2919. volatile int nLastCallIndex;
  2920. volatile EndFramePriorToNextContextFunc_t pLastCallSite;
  2921. for ( int i = 0; i < m_EndFramePriorToNextContextFunc.Count(); ++i )
  2922. {
  2923. nLastCallIndex = i;
  2924. pLastCallSite = m_EndFramePriorToNextContextFunc[ i ];
  2925. bDataProcessed |= m_EndFramePriorToNextContextFunc[ i ]();
  2926. }
  2927. if ( !bDataProcessed )
  2928. {
  2929. // Because this is at the main thread frame boundary, the async texture loading can simply be delayed until the next frame,
  2930. // to lighten the amount of a burst of main thread work. The async texture loading is tolerant of getting delayed because
  2931. // it's only driving a resident texture to a higher/lower resolution. This is more of a specific assist because the above caller
  2932. // is known to be the modelloader handling of weapon meshes eviction/restore.
  2933. ServiceAsyncTextureLoads();
  2934. }
  2935. #if !defined( _CERT ) && defined( SPEW_SERVICE_END_FRAME_TIME )
  2936. float flElapsed = ( Plat_FloatTime() - flStartTime ) * 1000.0f;
  2937. if ( flElapsed > 1.0f )
  2938. {
  2939. DevWarning( "ServiceEndFramePriorToNextContext: %.2f ms\n", flElapsed );
  2940. }
  2941. #endif
  2942. bool bDeviceReady = g_pShaderAPI->CanDownloadTextures();
  2943. if ( m_bDeferredMaterialReload && bDeviceReady)
  2944. {
  2945. m_bDeferredMaterialReload = false;
  2946. char *pReloadSubString = m_pSubString;
  2947. m_pSubString = NULL;
  2948. ReloadMaterials( pReloadSubString );
  2949. if ( pReloadSubString )
  2950. {
  2951. free( pReloadSubString );
  2952. }
  2953. }
  2954. }
  2955. //-----------------------------------------------------------------------------
  2956. // Cache used materials
  2957. //-----------------------------------------------------------------------------
  2958. void CMaterialSystem::CacheUsedMaterials( )
  2959. {
  2960. IMatRenderContextInternal *pRenderContext = GetRenderContextInternal();
  2961. pRenderContext->EvictManagedResources();
  2962. for (MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
  2963. {
  2964. IMaterialInternal* pMat = GetMaterialInternal(i);
  2965. Assert( pMat->GetReferenceCount() >= 0 );
  2966. if( pMat->GetReferenceCount() > 0 )
  2967. {
  2968. pMat->Precache();
  2969. }
  2970. }
  2971. if( mat_forcemanagedtextureintohardware.GetBool() )
  2972. {
  2973. TextureManager()->ForceAllTexturesIntoHardware();
  2974. }
  2975. }
  2976. //-----------------------------------------------------------------------------
  2977. // Reloads textures + materials
  2978. //-----------------------------------------------------------------------------
  2979. void CMaterialSystem::ReloadTextures( void )
  2980. {
  2981. ForceSingleThreaded();
  2982. // 360 should not have gotten here
  2983. Assert( !IsX360() );
  2984. TextureManager()->RestoreRenderTargets();
  2985. TextureManager()->RestoreNonRenderTargetTextures();
  2986. }
  2987. void CMaterialSystem::ReloadMaterials( const char *pSubString )
  2988. {
  2989. bool bDeviceReady = g_pShaderAPI->CanDownloadTextures();
  2990. if ( !bDeviceReady )
  2991. {
  2992. if ( m_bDeferredMaterialReload && !m_pSubString )
  2993. return; // ignore request, all materials already pending a reload (otherwise malicious user can request only a subset of materials to reload)
  2994. if ( m_pSubString )
  2995. {
  2996. free( m_pSubString );
  2997. m_pSubString = NULL;
  2998. }
  2999. if ( pSubString )
  3000. {
  3001. m_pSubString = strdup( pSubString );
  3002. }
  3003. m_bDeferredMaterialReload = true;
  3004. return;
  3005. }
  3006. ForceSingleThreaded();
  3007. bool bVertexFormatChanged = false;
  3008. if( pSubString == NULL )
  3009. {
  3010. bVertexFormatChanged = true;
  3011. UncacheAllMaterials();
  3012. CacheUsedMaterials();
  3013. }
  3014. else
  3015. {
  3016. Flush( false );
  3017. char const chMultiDelim = '*';
  3018. CUtlVector< char > arrSearchSubString;
  3019. CUtlVector< char const * > arrSearchItems;
  3020. if ( strchr( pSubString, chMultiDelim ) )
  3021. {
  3022. arrSearchSubString.SetCount( strlen( pSubString ) + 1 );
  3023. strcpy( arrSearchSubString.Base(), pSubString );
  3024. for ( char * pch = arrSearchSubString.Base(); pch; )
  3025. {
  3026. char *pchEnd = strchr( pch, chMultiDelim );
  3027. pchEnd ? *( pchEnd ++ ) = 0 : 0;
  3028. arrSearchItems.AddToTail( pch );
  3029. pch = pchEnd;
  3030. }
  3031. }
  3032. for (MaterialHandle_t i = FirstMaterial(); i != InvalidMaterial(); i = NextMaterial(i) )
  3033. {
  3034. if( GetMaterialInternal(i)->GetReferenceCount() <= 0 )
  3035. continue;
  3036. char const *szMatName = GetMaterialInternal(i)->GetName();
  3037. if ( arrSearchItems.Count() > 1 )
  3038. {
  3039. bool bMatched = false;
  3040. for ( int k = 0; !bMatched && ( k < arrSearchItems.Count() ); ++ k )
  3041. if( Q_stristr( szMatName, arrSearchItems[k] ) )
  3042. bMatched = true;
  3043. if ( !bMatched )
  3044. continue;
  3045. }
  3046. else
  3047. {
  3048. if( !Q_stristr( szMatName, pSubString ) )
  3049. continue;
  3050. }
  3051. if ( !GetMaterialInternal(i)->IsPrecached() )
  3052. {
  3053. if ( GetMaterialInternal(i)->IsPrecachedVars() )
  3054. {
  3055. GetMaterialInternal(i)->Uncache( );
  3056. }
  3057. }
  3058. else
  3059. {
  3060. VertexFormat_t oldVertexFormat = GetMaterialInternal(i)->GetVertexFormat();
  3061. GetMaterialInternal(i)->Uncache();
  3062. GetMaterialInternal(i)->Precache();
  3063. GetMaterialInternal(i)->ReloadTextures();
  3064. if( GetMaterialInternal(i)->GetVertexFormat() != oldVertexFormat )
  3065. {
  3066. bVertexFormatChanged = true;
  3067. }
  3068. }
  3069. }
  3070. }
  3071. if( bVertexFormatChanged )
  3072. {
  3073. // Reloading materials could cause a vertex format change, so
  3074. // we need to release and restore
  3075. // NOTE: Not calling ReleaseShaderObjects/RestoreShaderObjects
  3076. // because we don't want to free anything other than vbs
  3077. // FIXME: Should I add a flags to the release func? Probably.
  3078. ReleaseShaderObjects( MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED );
  3079. RestoreShaderObjects( NULL, MATERIAL_RESTORE_VERTEX_FORMAT_CHANGED );
  3080. }
  3081. }
  3082. #define NOMINAL_LIGHTMAP 1.0f
  3083. //-----------------------------------------------------------------------------
  3084. // Allocates the standard textures used by the material system
  3085. //-----------------------------------------------------------------------------
  3086. void CMaterialSystem::AllocateStandardTextures()
  3087. {
  3088. if ( m_StandardTexturesAllocated )
  3089. return;
  3090. m_StandardTexturesAllocated = true;
  3091. // This texture is where subdivision patch list goes
  3092. #if defined( FEATURE_SUBD_SUPPORT )
  3093. if ( g_pSubDMgr->ShouldAllocateTextures() )
  3094. {
  3095. g_pSubDMgr->AllocateTextures();
  3096. }
  3097. #endif
  3098. float nominal_lightmap_value = NOMINAL_LIGHTMAP;
  3099. if ( HardwareConfig()->GetHDRType() == HDR_TYPE_INTEGER )
  3100. {
  3101. nominal_lightmap_value = NOMINAL_LIGHTMAP/16.0;
  3102. }
  3103. unsigned char texel[4];
  3104. texel[3] = 255;
  3105. // using a pixel writer to hide platform endian issues
  3106. // the PC passes through, the 360 has endian swapped formats
  3107. // NOTE: the IMAGE_FORMAT_BGRA8888 is used when expecting a IMAGE_FORMAT_BGRX8888 to ensure the alpha component gets converted/swapped
  3108. CPixelWriter pixelWriter;
  3109. unsigned char outTexel[4];
  3110. int tcFlags = TEXTURE_CREATE_MANAGED;
  3111. int tcFlagsSRGB = TEXTURE_CREATE_MANAGED | (IsPS3()?0:TEXTURE_CREATE_SRGB);
  3112. if ( IsX360() )
  3113. {
  3114. // during init time, ok to allow any pixel conversion operations
  3115. tcFlags |= TEXTURE_CREATE_CANCONVERTFORMAT;
  3116. tcFlagsSRGB |= TEXTURE_CREATE_CANCONVERTFORMAT;
  3117. }
  3118. // allocate a black single texel texture
  3119. m_BlackTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_BGRX8888, 1, 1, tcFlags, "[BLACK_TEXID]", TEXTURE_GROUP_OTHER );
  3120. g_pShaderAPI->ModifyTexture( m_BlackTextureHandle );
  3121. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3122. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3123. texel[0] = texel[1] = texel[2] = 0;
  3124. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3125. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3126. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_BGRX8888, false, outTexel );
  3127. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_BLACK, m_BlackTextureHandle );
  3128. // allocate a fully white single texel texture
  3129. m_WhiteTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_BGRX8888, 1, 1, tcFlags, "[WHITE_TEXID]", TEXTURE_GROUP_OTHER );
  3130. g_pShaderAPI->ModifyTexture( m_WhiteTextureHandle );
  3131. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3132. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3133. texel[0] = texel[1] = texel[2] = 255;
  3134. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3135. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3136. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_BGRX8888, false, outTexel );
  3137. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_WHITE, m_WhiteTextureHandle );
  3138. // allocate a grey single texel texture with an alpha of zero (for mat_fullbright 2)
  3139. m_GreyTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_BGRX8888, 1, 1, tcFlagsSRGB, "[GREY_TEXID]", TEXTURE_GROUP_OTHER );
  3140. g_pShaderAPI->ModifyTexture( m_GreyTextureHandle );
  3141. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3142. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3143. texel[0] = texel[1] = texel[2] = 128;
  3144. texel[3] = 255; // needs to be 255 so that mat_fullbright 2 stuff isn't translucent.
  3145. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3146. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3147. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_BGRX8888, false, outTexel );
  3148. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_GREY, m_GreyTextureHandle );
  3149. // allocate a grey single texel texture with an alpha of zero (for mat_fullbright 2)
  3150. m_GreyAlphaZeroTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_RGBA8888, 1, 1, tcFlagsSRGB, "[GREYALPHAZERO_TEXID]", TEXTURE_GROUP_OTHER );
  3151. g_pShaderAPI->ModifyTexture( m_GreyAlphaZeroTextureHandle );
  3152. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3153. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3154. texel[0] = texel[1] = texel[2] = 128;
  3155. texel[3] = 0; // needs to be 0 so that self-illum doens't affect mat_fullbright 2
  3156. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3157. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3158. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_RGBA8888, false, outTexel );
  3159. texel[3] = 255; // set back to default value so we don't affect the rest of this code.
  3160. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_GREY_ALPHA_ZERO, m_GreyAlphaZeroTextureHandle );
  3161. // allocate a black single texel texture with an alpha of zero ( for paintmap not allocated or not enabled )
  3162. m_BlackAlphaZeroTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_RGBA8888, 1, 1, tcFlags, "[BLACKALPHAZERO_TEXID]", TEXTURE_GROUP_OTHER );
  3163. g_pShaderAPI->ModifyTexture( m_BlackAlphaZeroTextureHandle );
  3164. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3165. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3166. texel[0] = texel[1] = texel[2] = texel[3] = 0;
  3167. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3168. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3169. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_RGBA8888, false, outTexel );
  3170. texel[3] = 255; // set back to default value so we don't affect the rest of this code.
  3171. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_GREY_ALPHA_ZERO, m_BlackAlphaZeroTextureHandle );
  3172. // allocate a white, single texel texture for the fullbright lightmap
  3173. // note: make sure and redo this when changing gamma, etc.
  3174. // don't mipmap lightmaps
  3175. // 360 expects RGBE encoded lightmaps, PC does not
  3176. ImageFormat targetFormat = IsX360() ? IMAGE_FORMAT_BGRA8888 : IMAGE_FORMAT_BGRX8888;
  3177. m_FullbrightLightmapTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, targetFormat, 1, 1, tcFlagsSRGB, "[FULLBRIGHT_LIGHTMAP_TEXID]", TEXTURE_GROUP_LIGHTMAP );
  3178. g_pShaderAPI->ModifyTexture( m_FullbrightLightmapTextureHandle );
  3179. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3180. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3181. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3182. if ( HardwareConfig()->GetHDREnabled() )
  3183. {
  3184. // We use 4.12 fixed point lightmaps on all platforms currently.
  3185. // Since we are using an eight-bit texture, here, the closest representation to one is:
  3186. // ~( 1.0/16.0 * 255 )
  3187. texel[0] = texel[1] = texel[2] = clamp( 256.0f / g_pShaderAPI->GetLightMapScaleFactor(), 0, 255 );
  3188. }
  3189. else
  3190. {
  3191. float tmpVect[3] = { nominal_lightmap_value, nominal_lightmap_value, nominal_lightmap_value };
  3192. ColorSpace::LinearToLightmap( texel, tmpVect );
  3193. }
  3194. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3195. g_pShaderAPI->TexImage2D( 0, 0, targetFormat, 0, 1, 1, targetFormat, false, outTexel );
  3196. // allocate a single texel flat normal texture
  3197. m_FlatNormalTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_BGRX8888, 1, 1, tcFlags, "[FLAT_NORMAL_TEXTURE]", TEXTURE_GROUP_OTHER );
  3198. g_pShaderAPI->ModifyTexture( m_FlatNormalTextureHandle );
  3199. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3200. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3201. texel[0] = 127; // R
  3202. texel[1] = 127; // G
  3203. texel[2] = 255; // B
  3204. // using pixel writer to hide platform endian issues
  3205. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3206. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3207. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_BGRX8888, false, outTexel );
  3208. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_NORMALMAP_FLAT, m_FlatNormalTextureHandle );
  3209. // allocate a single texel flat normal ssbump texture
  3210. m_FlatSSBumpTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_BGRX8888, 1, 1, tcFlags, "[FLAT_SSBUMP_TEXTURE]", TEXTURE_GROUP_OTHER );
  3211. g_pShaderAPI->ModifyTexture( m_FlatSSBumpTextureHandle );
  3212. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3213. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3214. texel[0] = 85; // 1/3*255
  3215. texel[1] = 85; // 1/3*255
  3216. texel[2] = 85; // 1/3*255
  3217. // using pixel writer to hide platform endian issues
  3218. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3219. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3220. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_BGRX8888, 0, 1, 1, IMAGE_FORMAT_BGRX8888, false, outTexel );
  3221. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_SSBUMP_FLAT, m_FlatSSBumpTextureHandle );
  3222. // allocate a single texel fullbright 1 lightmap for use with bump textures
  3223. targetFormat = IsX360() ? IMAGE_FORMAT_BGRA8888 : IMAGE_FORMAT_BGRX8888;
  3224. m_FullbrightBumpedLightmapTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, targetFormat, 1, 1, tcFlags, "[FULLBRIGHT_BUMPED_LIGHTMAP_TEXID]", TEXTURE_GROUP_LIGHTMAP );
  3225. g_pShaderAPI->ModifyTexture( m_FullbrightBumpedLightmapTextureHandle );
  3226. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3227. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3228. // using pixel writer to hide platform endian issues
  3229. if ( HardwareConfig()->GetHDREnabled() )
  3230. {
  3231. // We use 4.12 fixed point lightmaps on all platforms currently.
  3232. // Since we are using an eight-bit texture, here, the closest representation to one is:
  3233. // ~( 1.0/16.0 * 255 )
  3234. texel[0] = texel[1] = texel[2] = clamp( 256.0f / g_pShaderAPI->GetLightMapScaleFactor(), 0, 255 );
  3235. }
  3236. else
  3237. {
  3238. float linearColor[3] = { nominal_lightmap_value, nominal_lightmap_value, nominal_lightmap_value };
  3239. unsigned char dummy[3];
  3240. ColorSpace::LinearToBumpedLightmap( linearColor, linearColor, linearColor, linearColor,
  3241. dummy, texel, dummy, dummy );
  3242. }
  3243. pixelWriter.SetPixelMemory( IMAGE_FORMAT_BGRA8888, outTexel, 0 );
  3244. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3245. g_pShaderAPI->TexImage2D( 0, 0, targetFormat, 0, 1, 1, targetFormat, false, outTexel );
  3246. g_pShaderAPI->SetStandardTextureHandle( TEXTURE_LIGHTMAP_BUMPED_FULLBRIGHT, m_FullbrightBumpedLightmapTextureHandle );
  3247. #if defined( GAMMA_TEX1D_LOOKUP )
  3248. {
  3249. int iGammaLookupFlags = tcFlags;
  3250. ImageFormat gammalookupfmt;
  3251. gammalookupfmt = IMAGE_FORMAT_I8;
  3252. // generate the linear->gamma conversion table texture.
  3253. {
  3254. const int LINEAR_TO_GAMMA_TABLE_WIDTH = 512;
  3255. m_LinearToGammaTableTextureHandle = g_pShaderAPI->CreateTexture( LINEAR_TO_GAMMA_TABLE_WIDTH, 1, 1, gammalookupfmt, 1, 1, iGammaLookupFlags, "[LINEAR_TO_GAMMA_LOOKUP_SRGBON_TEXID]", TEXTURE_GROUP_PIXEL_SHADERS );
  3256. g_pShaderAPI->ModifyTexture( m_LinearToGammaTableTextureHandle );
  3257. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3258. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3259. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_S, SHADER_TEXWRAPMODE_CLAMP );
  3260. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_T, SHADER_TEXWRAPMODE_CLAMP );
  3261. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_U, SHADER_TEXWRAPMODE_CLAMP );
  3262. float pixelData[LINEAR_TO_GAMMA_TABLE_WIDTH]; //sometimes used as float, sometimes as uint8, sizeof(float) > sizeof(uint8)
  3263. for( int i = 0; i != LINEAR_TO_GAMMA_TABLE_WIDTH; ++i )
  3264. {
  3265. float fLookupResult = ((float)i) / ((float)(LINEAR_TO_GAMMA_TABLE_WIDTH - 1));
  3266. fLookupResult = g_pShaderAPI->LinearToGamma_HardwareSpecific( fLookupResult );
  3267. //do an extra srgb conversion because we'll be converting back on texture read
  3268. fLookupResult = g_pShaderAPI->LinearToGamma_HardwareSpecific( fLookupResult ); //that's right, linear->gamma->gamma2x so that that gamma->linear srgb read still ends up in gamma
  3269. int iColor = RoundFloatToInt( fLookupResult * 255.0f );
  3270. if( iColor > 255 )
  3271. iColor = 255;
  3272. ((uint8 *)pixelData)[i] = (uint8)iColor;
  3273. }
  3274. g_pShaderAPI->TexImage2D( 0, 0, gammalookupfmt, 0, LINEAR_TO_GAMMA_TABLE_WIDTH, 1, gammalookupfmt, false, (void *)pixelData );
  3275. }
  3276. // generate the identity conversion table texture.
  3277. {
  3278. const int LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH = 256;
  3279. m_LinearToGammaIdentityTableTextureHandle = g_pShaderAPI->CreateTexture( LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH, 1, 1, gammalookupfmt, 1, 1, tcFlags, "[LINEAR_TO_GAMMA_LOOKUP_SRGBOFF_TEXID]", TEXTURE_GROUP_PIXEL_SHADERS );
  3280. g_pShaderAPI->ModifyTexture( m_LinearToGammaIdentityTableTextureHandle );
  3281. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3282. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3283. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_S, SHADER_TEXWRAPMODE_CLAMP );
  3284. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_T, SHADER_TEXWRAPMODE_CLAMP );
  3285. g_pShaderAPI->TexWrap( SHADER_TEXCOORD_U, SHADER_TEXWRAPMODE_CLAMP );
  3286. float pixelData[LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH]; //sometimes used as float, sometimes as uint8, sizeof(float) > sizeof(uint8)
  3287. for( int i = 0; i != LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH; ++i )
  3288. {
  3289. float fLookupResult = ((float)i) / ((float)(LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH - 1));
  3290. //do an extra srgb conversion because we'll be converting back on texture read
  3291. fLookupResult = g_pShaderAPI->LinearToGamma_HardwareSpecific( fLookupResult );
  3292. int iColor = RoundFloatToInt( fLookupResult * 255.0f );
  3293. if ( iColor > 255 )
  3294. iColor = 255;
  3295. ((uint8 *)pixelData)[i] = (uint8)iColor;
  3296. }
  3297. g_pShaderAPI->TexImage2D( 0, 0, gammalookupfmt, 0, LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH, 1, gammalookupfmt, false, (void *)pixelData );
  3298. }
  3299. }
  3300. //only the shaderapi can handle switching between textures correctly, so pass off the textures to it.
  3301. g_pShaderAPI->SetLinearToGammaConversionTextures( m_LinearToGammaTableTextureHandle, m_LinearToGammaIdentityTableTextureHandle );
  3302. #endif
  3303. // create the maximum depth texture
  3304. m_MaxDepthTextureHandle = g_pShaderAPI->CreateTexture( 1, 1, 1, IMAGE_FORMAT_RGBA8888, 1, 1, tcFlags, "[MAXDEPTH_TEXID]", TEXTURE_GROUP_OTHER );
  3305. g_pShaderAPI->ModifyTexture( m_MaxDepthTextureHandle );
  3306. g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
  3307. g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
  3308. // 360 gets depth out of the red channel (which doubles as depth in D24S8) and may be 0/1 depending on REVERSE_DEPTH_ON_X360
  3309. // PC gets depth out of the alpha channel
  3310. texel[0] = texel[1] = texel[2] = ReverseDepthOnX360() ? 0 : 255;
  3311. texel[3] = 255;
  3312. pixelWriter.SetPixelMemory( IMAGE_FORMAT_RGBA8888, outTexel, 0 );
  3313. pixelWriter.WritePixelNoAdvance( texel[0], texel[1], texel[2], texel[3] );
  3314. g_pShaderAPI->TexImage2D( 0, 0, IMAGE_FORMAT_RGBA8888, 0, 1, 1, IMAGE_FORMAT_RGBA8888, false, outTexel );
  3315. }
  3316. void CMaterialSystem::ReleaseStandardTextures()
  3317. {
  3318. if ( m_StandardTexturesAllocated )
  3319. {
  3320. g_pShaderAPI->DeleteTexture( m_WhiteTextureHandle );
  3321. g_pShaderAPI->DeleteTexture( m_BlackTextureHandle );
  3322. g_pShaderAPI->DeleteTexture( m_BlackAlphaZeroTextureHandle );
  3323. g_pShaderAPI->DeleteTexture( m_GreyTextureHandle );
  3324. g_pShaderAPI->DeleteTexture( m_GreyAlphaZeroTextureHandle );
  3325. #if defined( FEATURE_SUBD_SUPPORT )
  3326. g_pSubDMgr->FreeTextures();
  3327. #endif
  3328. g_pShaderAPI->DeleteTexture( m_FullbrightLightmapTextureHandle );
  3329. g_pShaderAPI->DeleteTexture( m_FlatNormalTextureHandle );
  3330. g_pShaderAPI->DeleteTexture( m_FlatSSBumpTextureHandle );
  3331. g_pShaderAPI->DeleteTexture( m_FullbrightBumpedLightmapTextureHandle );
  3332. #if defined( GAMMA_TEX1D_LOOKUP )
  3333. g_pShaderAPI->DeleteTexture( m_LinearToGammaTableTextureHandle );
  3334. g_pShaderAPI->DeleteTexture( m_LinearToGammaIdentityTableTextureHandle );
  3335. g_pShaderAPI->SetLinearToGammaConversionTextures( INVALID_SHADERAPI_TEXTURE_HANDLE, INVALID_SHADERAPI_TEXTURE_HANDLE );
  3336. #endif
  3337. g_pShaderAPI->DeleteTexture( m_MaxDepthTextureHandle );
  3338. m_StandardTexturesAllocated = false;
  3339. }
  3340. }
  3341. //-----------------------------------------------------------------------------
  3342. //
  3343. //-----------------------------------------------------------------------------
  3344. void CMaterialSystem::BeginFrame( float frameTime )
  3345. {
  3346. // Safety measure (calls should only come from the main thread, also check correct pairing)
  3347. if ( !ThreadInMainThread() || IsInFrame() )
  3348. return;
  3349. // check debug vars. we will use these to setup g_nDebugVarsSignature so that materials will
  3350. // rebuild their draw lists when debug modes changed.
  3351. g_nDebugVarsSignature = (
  3352. (mat_specular.GetInt() != 0 ) + ( mat_normalmaps.GetInt() << 1 ) +
  3353. ( mat_fullbright.GetInt() << 2 ) + ( mat_fastnobump.GetInt() << 4 ) + ( mat_fastspecular.GetInt() << 5 ) ) << 24;
  3354. Assert( m_bGeneratedConfig );
  3355. VPROF_BUDGET( "CMaterialSystem::BeginFrame", VPROF_BUDGETGROUP_SWAP_BUFFERS );
  3356. IMatRenderContextInternal *pRenderContext = GetRenderContextInternal();
  3357. if ( mat_forcehardwaresync.GetBool() && (IsPC() || m_ThreadMode != MATERIAL_QUEUED_THREADED) )
  3358. {
  3359. pRenderContext->ForceHardwareSync();
  3360. }
  3361. pRenderContext->MarkRenderDataUnused( true );
  3362. pRenderContext->BeginFrame();
  3363. pRenderContext->SetFrameTime( frameTime );
  3364. pRenderContext->SetToneMappingScaleLinear( Vector( 1,1,1) );
  3365. //g_pMDLCache->UpdateCombiner();
  3366. Assert( !m_bInFrame );
  3367. m_bInFrame = true;
  3368. }
  3369. bool CMaterialSystem::IsInFrame( ) const
  3370. {
  3371. return m_bInFrame;
  3372. }
  3373. void CMaterialSystem::ThreadExecuteQueuedContext( CMatQueuedRenderContext *pContext )
  3374. {
  3375. #ifdef _PS3
  3376. #if GCM_ALLOW_NULL_FLIPS
  3377. extern void Ps3NullFlipsStartSceneTime();
  3378. Ps3NullFlipsStartSceneTime();
  3379. #endif
  3380. // This function takes up a lot of global thread pool time in GPU-bound levels, and it's convenient
  3381. // to have it as a bar in snTuner profiler. Making it PS3-only to avoid polluting X360 bars
  3382. VPROF_BUDGET( "ThreadExecuteQueuedContext", "All Threaded Rendering" );
  3383. #endif
  3384. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3385. OnFrameTimestampAvailableMST( 0.0f ); // signals frame start
  3386. #endif
  3387. m_nRenderThreadID = ThreadGetCurrentId();
  3388. IMatRenderContextInternal* pSavedRenderContext = m_pRenderContext;
  3389. m_pRenderContext = &m_HardwareRenderContext;
  3390. pContext->EndQueue( true );
  3391. for (int i = 0; i < m_EndFrameCleanupFunc.Count(); ++i)
  3392. {
  3393. m_EndFrameCleanupFunc[ i ]();
  3394. }
  3395. m_pRenderContext = pSavedRenderContext;
  3396. m_nRenderThreadID = 0xFFFFFFFF;
  3397. }
  3398. IThreadPool *CMaterialSystem::CreateMatQueueThreadPool()
  3399. {
  3400. if( IsX360() )
  3401. {
  3402. return g_pThreadPool;
  3403. }
  3404. else if( !m_pMatQueueThreadPool )
  3405. {
  3406. ThreadPoolStartParams_t startParams;
  3407. startParams.nThreads = 1;
  3408. startParams.nStackSize = 256*1024;
  3409. startParams.fDistribute = TRS_TRUE;
  3410. // The rendering thread has the GL context and the main thread is coming in and
  3411. // "helping" finish jobs - that breaks OpenGL, which requires TLS. This flag states
  3412. // that only the threadpool threads should execute these jobs.
  3413. startParams.bExecOnThreadPoolThreadsOnly = true;
  3414. m_pMatQueueThreadPool = CreateNewThreadPool();
  3415. m_pMatQueueThreadPool->Start( startParams, "MatQueue" );
  3416. }
  3417. return m_pMatQueueThreadPool;
  3418. }
  3419. void CMaterialSystem::DestroyMatQueueThreadPool()
  3420. {
  3421. if( m_pMatQueueThreadPool )
  3422. {
  3423. m_pMatQueueThreadPool->Stop();
  3424. delete m_pMatQueueThreadPool;
  3425. m_pMatQueueThreadPool = NULL;
  3426. }
  3427. }
  3428. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3429. static double s_flMainThreadBeginTimestampSec = 0.0f;
  3430. #endif
  3431. //
  3432. // On OSX, Forced Single Threaded needs to last for more frames than windows that the window resizing/switch to
  3433. // and from fullscreen don't force GL calls at the same time as the render thread.
  3434. //
  3435. #if defined ( OSX )
  3436. static void CheckOsxForcedNextThreadMode( MaterialThreadMode_t* pNextThreadMode, bool* pbForcedSingleThreaded )
  3437. {
  3438. const int nOsxFramesAtSingleThreaded = 2;
  3439. static int nOsxFrames = nOsxFramesAtSingleThreaded;
  3440. if ( *pbForcedSingleThreaded )
  3441. {
  3442. *pNextThreadMode = MATERIAL_SINGLE_THREADED;
  3443. if ( nOsxFrames == 0 )
  3444. {
  3445. *pbForcedSingleThreaded = false;
  3446. nOsxFrames = nOsxFramesAtSingleThreaded;
  3447. }
  3448. else
  3449. {
  3450. nOsxFrames--;
  3451. }
  3452. }
  3453. else
  3454. {
  3455. nOsxFrames = nOsxFramesAtSingleThreaded;
  3456. }
  3457. }
  3458. #endif
  3459. void CMaterialSystem::EndFrame( void )
  3460. {
  3461. SNPROF("CMaterialSystem::EndFrame");
  3462. // Safety measure (calls should only come from the main thread, also check correct pairing)
  3463. if ( !ThreadInMainThread() || !IsInFrame() )
  3464. return;
  3465. Assert( m_bGeneratedConfig );
  3466. VPROF_BUDGET( "CMaterialSystem::EndFrame", VPROF_BUDGETGROUP_SWAP_BUFFERS );
  3467. GetRenderContextInternal()->EndFrame();
  3468. //-------------------------------------------------------------
  3469. UpdateConfig( false );
  3470. int iConVarThreadMode = mat_queue_mode.GetInt();
  3471. MaterialThreadMode_t nextThreadMode = ( iConVarThreadMode >= 0 ) ? (MaterialThreadMode_t)iConVarThreadMode : m_IdealThreadMode;
  3472. // note: This is a hack because there is no explicit query for the device being deactivated due to device lost.
  3473. // however, that is all the current implementation of CanDownloadTextures actually does.
  3474. bool bDeviceReady = g_pShaderAPI->CanDownloadTextures();
  3475. if ( !bDeviceReady || !m_bAllowQueuedRendering )
  3476. {
  3477. nextThreadMode = MATERIAL_SINGLE_THREADED;
  3478. }
  3479. #if !defined ( OSX )
  3480. if ( m_bForcedSingleThreaded )
  3481. {
  3482. nextThreadMode = MATERIAL_SINGLE_THREADED;
  3483. m_bForcedSingleThreaded = false;
  3484. }
  3485. #else
  3486. CheckOsxForcedNextThreadMode(&nextThreadMode, &m_bForcedSingleThreaded );
  3487. #endif
  3488. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3489. {
  3490. // This is called on the main thread and here the main thread is finished
  3491. double flMainThreadEndTimestampSec = Plat_FloatTime();
  3492. double flMainThreadTimeInSeconds = flMainThreadEndTimestampSec - s_flMainThreadBeginTimestampSec;
  3493. OnFrameTimestampAvailableMain( flMainThreadTimeInSeconds*1000.0f );
  3494. }
  3495. #endif
  3496. switch ( m_ThreadMode )
  3497. {
  3498. case MATERIAL_SINGLE_THREADED:
  3499. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3500. {
  3501. double flCurrentTime = Plat_FloatTime();
  3502. OnFrameTimestampAvailableTotal( (flCurrentTime-s_flTotalFrameBeginTimestamp)*1000.0f );
  3503. s_flTotalFrameBeginTimestamp = flCurrentTime;
  3504. OnFrameTimestampAvailableMST( 0.0f ); // signals frame start
  3505. }
  3506. #endif
  3507. ServiceEndFramePriorToNextContext();
  3508. g_pfnSwapBufferMarker();
  3509. break;
  3510. #ifndef _PS3
  3511. case MATERIAL_QUEUED_THREADED:
  3512. {
  3513. VPROF_BUDGET( "Mat_ThreadedEndframe", "Mat_ThreadedEndframe" );
  3514. {
  3515. TM_ZONE_PLOT( TELEMETRY_LEVEL1, "Endframe_Wait", TELEMETRY_ZONE_PLOT_SLOT_3 );
  3516. PERF_STATS_BLOCK( "Endframe_Wait", PERF_STATS_SLOT_END_FRAME );
  3517. while ( m_pActiveAsyncJob && !m_pActiveAsyncJob->IsFinished() )
  3518. {
  3519. // [jason]
  3520. // Potential fix for a deadlock on threaded rendering: we were occasionally seeing deadlocks on the main thread,
  3521. // waiting for work to be completed on the rendering job threads. Every time we break into this with the debugger,
  3522. // there are no job threads that are stalled - everything is waiting for new work to be sent down. I suspect that
  3523. // in the gap between the main thread determining there is still outstanding work and the main thread locking, we
  3524. // occasionally get a context switch to the job thread that completes its work. When we switch back to the main
  3525. // thread, we begin to wait on a thread that will never signal (because it's already done working) so we deadlock.
  3526. // The fix is to break this infinite wait into a busy loop of 1/2 second waits - either the worker thread will signal
  3527. // and we'll resume processing, or at worst we'll wait 1/2 second and then double-check there is actually work running
  3528. // on the job queue and find there is nothing left to wait for.
  3529. // [Michael Dorgan]
  3530. // Alas, the thread system ignores the timeout value passed in right now and always does a Sleep(0)
  3531. // Still, a Sleep(0) yield does seem to fix this, so removed the 500 param.
  3532. m_pActiveAsyncJob->WaitForFinish();
  3533. if ( !m_pActiveAsyncJob->IsFinished() )
  3534. DevMsg( "CMaterialSystem::EndFrame - waiting on additional threaded work for MatQueuedThreaded.\n" );
  3535. if ( !IsPC() && mat_forcehardwaresync.GetBool() )
  3536. {
  3537. g_pShaderAPI->ForceHardwareSync();
  3538. }
  3539. }
  3540. }
  3541. SafeRelease( m_pActiveAsyncJob );
  3542. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3543. {
  3544. double flCurrentTime = Plat_FloatTime();
  3545. OnFrameTimestampAvailableTotal( (flCurrentTime-s_flTotalFrameBeginTimestamp)*1000.0f );
  3546. s_flTotalFrameBeginTimestamp = flCurrentTime;
  3547. }
  3548. #endif
  3549. ServiceEndFramePriorToNextContext();
  3550. g_pfnSwapBufferMarker();
  3551. CMatQueuedRenderContext *pPrevContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3552. #ifdef MAT_QUEUED_OWN_THREADPOOL
  3553. // Needs to be done after calling ServiceEndFramePriorToNextContext to ensure the render thread
  3554. // will have ownership, as ServiceEndFramePriorToNextContext could locking the material system
  3555. // => RenderThread would then lose ownership
  3556. if ( !m_bThreadHasOwnership )
  3557. {
  3558. ThreadAcquire();
  3559. }
  3560. #endif
  3561. #ifndef MAT_QUEUED_OWN_THREADPOOL
  3562. m_QueuedRenderContexts[m_iCurQueuedContext].GetCallQueueInternal()->QueueCall( g_pShaderAPI, &IShaderAPI::ReleaseThreadOwnership );
  3563. #endif
  3564. m_iCurQueuedContext = ( ( m_iCurQueuedContext + 1 ) % ARRAYSIZE( m_QueuedRenderContexts) );
  3565. m_QueuedRenderContexts[m_iCurQueuedContext].BeginQueue( pPrevContext );
  3566. #ifndef MAT_QUEUED_OWN_THREADPOOL
  3567. m_QueuedRenderContexts[m_iCurQueuedContext].GetCallQueueInternal()->QueueCall( g_pShaderAPI, &IShaderAPI::AcquireThreadOwnership );
  3568. #endif
  3569. m_pRenderContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3570. m_pActiveAsyncJob = new CFunctorJob( CreateFunctor( this, &CMaterialSystem::ThreadExecuteQueuedContext, pPrevContext ) );
  3571. if ( !IsPC() )
  3572. {
  3573. if ( m_nServiceThread >= 0 )
  3574. {
  3575. m_pActiveAsyncJob->SetServiceThread( m_nServiceThread );
  3576. }
  3577. }
  3578. if ( mat_queue_priority.GetBool() )
  3579. {
  3580. m_pActiveAsyncJob->SetFlags( m_pActiveAsyncJob->GetFlags() | JF_QUEUE );
  3581. }
  3582. #ifdef MAT_QUEUED_OWN_THREADPOOL
  3583. IThreadPool *pThreadPool = CreateMatQueueThreadPool();
  3584. #else
  3585. IThreadPool *pThreadPool = g_pThreadPool;
  3586. #endif
  3587. pThreadPool->AddJob( m_pActiveAsyncJob );
  3588. break;
  3589. }
  3590. #else
  3591. case MATERIAL_QUEUED_THREADED:
  3592. {
  3593. // Wait for previous submitted QMS run
  3594. if (m_bQMSJobSubmitted)
  3595. {
  3596. g_pGcmSharedData->WaitForQMS();
  3597. m_bQMSJobSubmitted = 0;
  3598. if ( !IsPC() && mat_forcehardwaresync.GetBool() )
  3599. {
  3600. g_pShaderAPI->ForceHardwareSync();
  3601. }
  3602. }
  3603. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3604. {
  3605. double flCurrentTime = Plat_FloatTime();
  3606. OnFrameTimestampAvailableTotal( (flCurrentTime-s_flTotalFrameBeginTimestamp)*1000.0f );
  3607. s_flTotalFrameBeginTimestamp = flCurrentTime;
  3608. }
  3609. #endif
  3610. ServiceEndFramePriorToNextContext();
  3611. g_pfnSwapBufferMarker();
  3612. // Switch Render Contexts
  3613. CMatQueuedRenderContext *pPrevContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3614. m_QueuedRenderContexts[m_iCurQueuedContext].GetCallQueueInternal()->QueueCall( g_pShaderAPI, &IShaderAPI::ReleaseThreadOwnership );
  3615. m_iCurQueuedContext = ( ( m_iCurQueuedContext + 1 ) % ARRAYSIZE( m_QueuedRenderContexts) );
  3616. m_QueuedRenderContexts[m_iCurQueuedContext].BeginQueue( pPrevContext );
  3617. m_QueuedRenderContexts[m_iCurQueuedContext].GetCallQueueInternal()->QueueCall( g_pShaderAPI, &IShaderAPI::AcquireThreadOwnership );
  3618. m_pRenderContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3619. // Run QMS on prevContext
  3620. g_pGcmSharedData->RunQMS(&RunQMS, (void*)this, (void*)pPrevContext);
  3621. m_bQMSJobSubmitted = 1;
  3622. break;
  3623. }
  3624. #endif
  3625. case MATERIAL_QUEUED_SINGLE_THREADED:
  3626. {
  3627. VPROF_BUDGET( "Mat_ThreadedEndframe", "Mat_QueuedEndframe" );
  3628. g_pShaderAPI->SetDisallowAccess( false );
  3629. m_pRenderContext = &m_HardwareRenderContext;
  3630. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3631. OnFrameTimestampAvailableMST( 0.0f ); // signals frame start
  3632. #endif
  3633. m_QueuedRenderContexts[m_iCurQueuedContext].CallQueued();
  3634. // Set up for next frame, we don't cycle through m_iCurQueuedContext though
  3635. m_QueuedRenderContexts[m_iCurQueuedContext].CycleDynamicBuffers();
  3636. m_pRenderContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3637. g_pShaderAPI->SetDisallowAccess( true );
  3638. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3639. double flCurrentTime = Plat_FloatTime();
  3640. OnFrameTimestampAvailableTotal( (flCurrentTime-s_flTotalFrameBeginTimestamp)*1000.0f );
  3641. s_flTotalFrameBeginTimestamp = flCurrentTime;
  3642. #endif
  3643. ServiceEndFramePriorToNextContext();
  3644. g_pfnSwapBufferMarker();
  3645. break;
  3646. }
  3647. }
  3648. // Tick perfstats. We measure the main thread time from the point just after we finish waiting
  3649. // for the render thread.
  3650. g_PerfStats.Tick();
  3651. #if GCM_ALLOW_TIMESTAMPS || X360_ALLOW_TIMESTAMPS
  3652. s_flMainThreadBeginTimestampSec = Plat_FloatTime();
  3653. #endif
  3654. bool bRelease = false;
  3655. if ( !bDeviceReady )
  3656. {
  3657. if ( nextThreadMode != MATERIAL_SINGLE_THREADED )
  3658. {
  3659. Assert( nextThreadMode == MATERIAL_SINGLE_THREADED );
  3660. bRelease = true;
  3661. nextThreadMode = MATERIAL_SINGLE_THREADED;
  3662. if( mat_debugalttab.GetBool() )
  3663. {
  3664. Warning("Handling alt-tab in queued mode!\n");
  3665. }
  3666. }
  3667. }
  3668. if ( m_threadEvents.Count() )
  3669. {
  3670. nextThreadMode = MATERIAL_SINGLE_THREADED;
  3671. }
  3672. if ( m_ThreadMode != nextThreadMode )
  3673. {
  3674. // Shut down the current mode & set new mode
  3675. switch ( m_ThreadMode )
  3676. {
  3677. case MATERIAL_SINGLE_THREADED:
  3678. break;
  3679. case MATERIAL_QUEUED_THREADED:
  3680. {
  3681. #ifndef _PS3
  3682. if ( m_pActiveAsyncJob )
  3683. {
  3684. m_pActiveAsyncJob->WaitForFinish();
  3685. SafeRelease( m_pActiveAsyncJob );
  3686. }
  3687. #else
  3688. if (m_bQMSJobSubmitted)
  3689. {
  3690. g_pGcmSharedData->WaitForQMS();
  3691. m_bQMSJobSubmitted = 0;
  3692. }
  3693. #endif
  3694. // We have a queued context set here, need hardware to flush the queue if the job isn't active
  3695. m_pRenderContext = &m_HardwareRenderContext;
  3696. m_QueuedRenderContexts[m_iCurQueuedContext].EndQueue( true );
  3697. #ifdef MAT_QUEUED_OWN_THREADPOOL
  3698. ThreadRelease();
  3699. #else
  3700. g_pShaderAPI->AcquireThreadOwnership();
  3701. #endif
  3702. }
  3703. break;
  3704. case MATERIAL_QUEUED_SINGLE_THREADED:
  3705. {
  3706. g_pShaderAPI->SetDisallowAccess( false );
  3707. // We have a queued context set here, need hardware to flush the queue if the job isn't active
  3708. m_pRenderContext = &m_HardwareRenderContext;
  3709. m_QueuedRenderContexts[m_iCurQueuedContext].EndQueue( true );
  3710. break;
  3711. }
  3712. }
  3713. m_ThreadMode = nextThreadMode;
  3714. #ifndef DX_TO_GL_ABSTRACTION
  3715. Assert( g_MatSysMutex.GetOwnerId() == 0 );
  3716. #endif
  3717. g_pShaderAPI->EnableShaderShaderMutex( m_ThreadMode != MATERIAL_SINGLE_THREADED ); // use mutex even for queued to allow "disalow access" to function properly
  3718. g_pShaderAPI->EnableBuffer2FramesAhead( true );
  3719. switch ( m_ThreadMode )
  3720. {
  3721. case MATERIAL_SINGLE_THREADED:
  3722. m_pRenderContext = &m_HardwareRenderContext;
  3723. for ( int i = 0; i < ARRAYSIZE( m_QueuedRenderContexts ); i++ )
  3724. {
  3725. Assert( m_QueuedRenderContexts[i].IsInitialized() );
  3726. m_QueuedRenderContexts[i].Shutdown();
  3727. }
  3728. g_pScaleformUI->SetSingleThreadedMode(true);
  3729. break;
  3730. case MATERIAL_QUEUED_SINGLE_THREADED:
  3731. case MATERIAL_QUEUED_THREADED:
  3732. for ( int i = 0; i < ARRAYSIZE( m_QueuedRenderContexts ); i++ )
  3733. {
  3734. if ( !m_QueuedRenderContexts[i].IsInitialized() )
  3735. {
  3736. m_QueuedRenderContexts[i].Init( this, &m_HardwareRenderContext );
  3737. }
  3738. }
  3739. m_iCurQueuedContext = 0;
  3740. m_QueuedRenderContexts[m_iCurQueuedContext].BeginQueue( &m_HardwareRenderContext );
  3741. m_pRenderContext = &m_QueuedRenderContexts[m_iCurQueuedContext];
  3742. if ( m_ThreadMode == MATERIAL_QUEUED_SINGLE_THREADED )
  3743. {
  3744. g_pShaderAPI->SetDisallowAccess( true );
  3745. g_pScaleformUI->SetSingleThreadedMode(true);
  3746. }
  3747. else
  3748. {
  3749. #ifdef MAT_QUEUED_OWN_THREADPOOL
  3750. ThreadAcquire();
  3751. #else
  3752. g_pShaderAPI->ReleaseThreadOwnership();
  3753. m_QueuedRenderContexts[m_iCurQueuedContext].GetCallQueueInternal()->QueueCall( g_pShaderAPI, &IShaderAPI::AcquireThreadOwnership );
  3754. #endif
  3755. g_pScaleformUI->SetSingleThreadedMode(false);
  3756. }
  3757. break;
  3758. }
  3759. }
  3760. if ( m_ThreadMode == MATERIAL_SINGLE_THREADED )
  3761. {
  3762. for ( int i = 0; i < m_threadEvents.Count(); i++ )
  3763. {
  3764. g_pShaderDevice->HandleThreadEvent(m_threadEvents[i]);
  3765. }
  3766. m_threadEvents.RemoveAll();
  3767. }
  3768. if ( m_ThreadMode == MATERIAL_SINGLE_THREADED || m_ThreadMode == MATERIAL_QUEUED_SINGLE_THREADED )
  3769. {
  3770. for (int i = 0; i < m_EndFrameCleanupFunc.Count(); ++i)
  3771. {
  3772. m_EndFrameCleanupFunc[ i ]();
  3773. }
  3774. }
  3775. Assert( m_bInFrame );
  3776. m_bInFrame = false;
  3777. }
  3778. void CMaterialSystem::SetInStubMode( bool bInStubMode )
  3779. {
  3780. m_bInStubMode = bInStubMode;
  3781. }
  3782. bool CMaterialSystem::IsInStubMode()
  3783. {
  3784. return m_bInStubMode;
  3785. }
  3786. void CMaterialSystem::Flush( bool flushHardware )
  3787. {
  3788. GetRenderContextInternal()->Flush( flushHardware );
  3789. }
  3790. uint32 CMaterialSystem::GetCurrentFrameCount()
  3791. {
  3792. return g_FrameNum;
  3793. }
  3794. //-----------------------------------------------------------------------------
  3795. // Flushes managed textures from the texture cacher
  3796. //-----------------------------------------------------------------------------
  3797. void CMaterialSystem::EvictManagedResources()
  3798. {
  3799. g_pShaderAPI->EvictManagedResources();
  3800. }
  3801. int __cdecl MaterialNameCompareFunc( const void *elem1, const void *elem2 )
  3802. {
  3803. IMaterialInternal *pMaterialA = g_MaterialSystem.GetMaterialInternal( *(MaterialHandle_t *)elem1 );
  3804. IMaterialInternal *pMaterialB = g_MaterialSystem.GetMaterialInternal( *(MaterialHandle_t *)elem2 );
  3805. // case insensitive to group similar named materials
  3806. return stricmp( pMaterialA->GetName(), pMaterialB->GetName() );
  3807. }
  3808. void CMaterialSystem::DebugPrintUsedMaterials( const char *pSearchSubString, bool bVerbose )
  3809. {
  3810. MaterialHandle_t h;
  3811. int i;
  3812. int nNumCached;
  3813. int nRefCount;
  3814. int nSortedMaterials;
  3815. int nNumErrors;
  3816. // build a mapping to sort the material names
  3817. MaterialHandle_t *pSorted = (MaterialHandle_t*)stackalloc( GetNumMaterials() * sizeof(MaterialHandle_t) );
  3818. nSortedMaterials = 0;
  3819. for (h = FirstMaterial(); h != InvalidMaterial(); h = NextMaterial(h) )
  3820. {
  3821. pSorted[nSortedMaterials++] = h;
  3822. }
  3823. qsort( pSorted, nSortedMaterials, sizeof(MaterialHandle_t), MaterialNameCompareFunc );
  3824. nNumCached = 0;
  3825. nNumErrors = 0;
  3826. for (i = 0; i < nSortedMaterials; i++)
  3827. {
  3828. // iterate using sort mapping
  3829. IMaterialInternal *pMaterial = GetMaterialInternal(pSorted[i]);
  3830. nRefCount = pMaterial->GetReferenceCount();
  3831. if ( nRefCount < 0 )
  3832. {
  3833. nNumErrors++;
  3834. continue;
  3835. }
  3836. if (!nRefCount)
  3837. {
  3838. if (pMaterial->IsPrecached() || pMaterial->IsPrecachedVars())
  3839. {
  3840. nNumErrors++;
  3841. }
  3842. continue;
  3843. }
  3844. // nonzero reference count
  3845. // tally the valid ones
  3846. nNumCached++;
  3847. if( pSearchSubString )
  3848. {
  3849. if( !Q_stristr( pMaterial->GetName(), pSearchSubString ) &&
  3850. (!pMaterial->GetShader() || !Q_stristr( pMaterial->GetShader()->GetName(), pSearchSubString )) )
  3851. {
  3852. continue;
  3853. }
  3854. }
  3855. DevMsg( "%s (shader: %s) refCount: %d.\n", pMaterial->GetName(),
  3856. pMaterial->GetShader() ? pMaterial->GetShader()->GetName() : "unknown\n", nRefCount );
  3857. if( !bVerbose )
  3858. continue;
  3859. if( !pMaterial->IsPrecached() )
  3860. continue;
  3861. if( !pMaterial->GetShader() )
  3862. continue;
  3863. for( int j = 0; j < pMaterial->GetShader()->GetParamCount(); j++ )
  3864. {
  3865. IMaterialVar *var;
  3866. var = pMaterial->GetShaderParams()[j];
  3867. if( !var )
  3868. continue;
  3869. switch( var->GetType() )
  3870. {
  3871. case MATERIAL_VAR_TYPE_TEXTURE:
  3872. {
  3873. ITextureInternal *texture = static_cast<ITextureInternal *>( var->GetTextureValue() );
  3874. if( !texture )
  3875. {
  3876. DevWarning( "Programming error: CMaterialSystem::DebugPrintUsedMaterialsCallback: NULL texture\n" );
  3877. continue;
  3878. }
  3879. if( IsTextureInternalEnvCubemap( texture ) )
  3880. {
  3881. DevMsg( " \"%s\" \"env_cubemap\"\n", var->GetName() );
  3882. }
  3883. else
  3884. {
  3885. DevMsg( " \"%s\" \"%s\"\n",
  3886. var->GetName(),
  3887. texture->GetName() );
  3888. DevMsg( " %dx%d refCount: %d numframes: %d\n", texture->GetActualWidth(), texture->GetActualHeight(),
  3889. texture->GetReferenceCount(), texture->GetNumAnimationFrames() );
  3890. }
  3891. }
  3892. break;
  3893. case MATERIAL_VAR_TYPE_UNDEFINED:
  3894. break;
  3895. default:
  3896. DevMsg( " \"%s\" \"%s\"\n", var->GetName(), var->GetStringValue() );
  3897. break;
  3898. }
  3899. }
  3900. }
  3901. // list the critical errors after, otherwise the console log scrolls them away
  3902. if (nNumErrors)
  3903. {
  3904. for (i = 0; i < nSortedMaterials; i++)
  3905. {
  3906. // iterate using sort mapping
  3907. IMaterialInternal *pMaterial = GetMaterialInternal(pSorted[i]);
  3908. nRefCount = pMaterial->GetReferenceCount();
  3909. if ( nRefCount < 0 )
  3910. {
  3911. // reference counts should not be negative
  3912. DevWarning( "DebugPrintUsedMaterials: refCount (%d) < 0 for material: \"%s\"\n",
  3913. nRefCount, pMaterial->GetName() );
  3914. }
  3915. else if (!nRefCount)
  3916. {
  3917. // ensure that it stayed uncached after the post loading uncache
  3918. // this is effectively a coding bug thats needs to be fixed
  3919. // a material is being precached without incrementing its reference
  3920. if (pMaterial->IsPrecached() || pMaterial->IsPrecachedVars())
  3921. {
  3922. DevWarning( "DebugPrintUsedMaterials: material: \"%s\" didn't unache\n",
  3923. pMaterial->GetName() );
  3924. }
  3925. }
  3926. }
  3927. DevWarning( "%d Errors\n", nNumErrors );
  3928. }
  3929. if (!pSearchSubString)
  3930. {
  3931. DevMsg( "%d Cached, %d Total Materials\n", nNumCached, GetNumMaterials() );
  3932. }
  3933. }
  3934. void CMaterialSystem::DebugPrintUsedTextures( void )
  3935. {
  3936. TextureManager()->DebugPrintUsedTextures();
  3937. }
  3938. #if defined( _X360 ) || defined( _PS3 )
  3939. void CMaterialSystem::ListUsedMaterials( void )
  3940. {
  3941. int numMaterials = GetNumMaterials();
  3942. xMaterialList_t* pMaterialList = (xMaterialList_t *)stackalloc( numMaterials * sizeof( xMaterialList_t ) );
  3943. numMaterials = 0;
  3944. for ( MaterialHandle_t hMaterial = FirstMaterial(); hMaterial != InvalidMaterial(); hMaterial = NextMaterial( hMaterial ) )
  3945. {
  3946. IMaterialInternal *pMaterial = GetMaterialInternal( hMaterial );
  3947. pMaterialList[numMaterials].pName = pMaterial->GetName();
  3948. pMaterialList[numMaterials].pShaderName = pMaterial->GetShader() ? pMaterial->GetShader()->GetName() : "???";
  3949. pMaterialList[numMaterials].refCount = pMaterial->GetReferenceCount();
  3950. numMaterials++;
  3951. }
  3952. XBX_rMaterialList( numMaterials, pMaterialList );
  3953. }
  3954. #endif
  3955. void CMaterialSystem::ToggleSuppressMaterial( char const* pMaterialName )
  3956. {
  3957. /*
  3958. // This version suppresses all but the material
  3959. IMaterial *pMaterial = GetFirstMaterial();
  3960. while (pMaterial)
  3961. {
  3962. if (stricmp(pMaterial->GetName(), pMaterialName))
  3963. {
  3964. IMaterialInternal* pMatInt = static_cast<IMaterialInternal*>(pMaterial);
  3965. pMatInt->ToggleSuppression();
  3966. }
  3967. pMaterial = GetNextMaterial();
  3968. }
  3969. */
  3970. // Note: if we use this function a lot, we'll want to do something else, like have them
  3971. // pass in a texture group or reuse whatever texture group the material already had.
  3972. // As it is, this is rarely used, so if it's not in TEXTURE_GROUP_OTHER, it'll go in
  3973. // TEXTURE_GROUP_SHARED.
  3974. IMaterial* pMaterial = FindMaterial( pMaterialName, TEXTURE_GROUP_OTHER, true, NULL );
  3975. if ( !IsErrorMaterial( pMaterial ) )
  3976. {
  3977. IMaterialInternal* pMatInt = static_cast<IMaterialInternal*>(pMaterial);
  3978. pMatInt = pMatInt->GetRealTimeVersion(); //always work with the realtime material internally
  3979. pMatInt->ToggleSuppression();
  3980. }
  3981. }
  3982. void CMaterialSystem::ToggleDebugMaterial( char const* pMaterialName )
  3983. {
  3984. // Note: if we use this function a lot, we'll want to do something else, like have them
  3985. // pass in a texture group or reuse whatever texture group the material already had.
  3986. // As it is, this is rarely used, so if it's not in TEXTURE_GROUP_OTHER, it'll go in
  3987. // TEXTURE_GROUP_SHARED.
  3988. IMaterial* pMaterial = FindMaterial( pMaterialName, TEXTURE_GROUP_OTHER, false, NULL );
  3989. if ( !IsErrorMaterial( pMaterial ) )
  3990. {
  3991. IMaterialInternal* pMatInt = static_cast<IMaterialInternal*>(pMaterial);
  3992. pMatInt = pMatInt->GetRealTimeVersion(); //always work with the realtime material internally
  3993. pMatInt->ToggleDebugTrace();
  3994. }
  3995. else
  3996. {
  3997. Warning("Unknown material %s\n", pMaterialName );
  3998. }
  3999. }
  4000. //-----------------------------------------------------------------------------
  4001. // Used to iterate over all shaders for editing purposes
  4002. //-----------------------------------------------------------------------------
  4003. int CMaterialSystem::ShaderCount() const
  4004. {
  4005. return ShaderSystem()->ShaderCount();
  4006. }
  4007. int CMaterialSystem::GetShaders( int nFirstShader, int nMaxCount, IShader **ppShaderList ) const
  4008. {
  4009. return ShaderSystem()->GetShaders( nFirstShader, nMaxCount, ppShaderList );
  4010. }
  4011. //-----------------------------------------------------------------------------
  4012. // FIXME: Is there a better way of doing this?
  4013. // Returns shader flag names for editors to be able to edit them
  4014. //-----------------------------------------------------------------------------
  4015. int CMaterialSystem::ShaderFlagCount() const
  4016. {
  4017. return ShaderSystem()->ShaderStateCount( );
  4018. }
  4019. const char *CMaterialSystem::ShaderFlagName( int nIndex ) const
  4020. {
  4021. return ShaderSystem()->ShaderStateString( nIndex );
  4022. }
  4023. //-----------------------------------------------------------------------------
  4024. // Returns the currently active shader fallback for a particular shader
  4025. //-----------------------------------------------------------------------------
  4026. void CMaterialSystem::GetShaderFallback( const char *pShaderName, char *pFallbackShader, int nFallbackLength )
  4027. {
  4028. // FIXME: This is pretty much a hack. We need a better way for the
  4029. // editor to get ahold of shader fallbacks
  4030. int nCount = ShaderCount();
  4031. IShader** ppShaderList = (IShader**)stackalloc( nCount * sizeof(IShader) );
  4032. GetShaders( 0, nCount, ppShaderList );
  4033. do
  4034. {
  4035. int i;
  4036. for ( i = 0; i < nCount; ++i )
  4037. {
  4038. if ( !Q_stricmp( pShaderName, ppShaderList[i]->GetName() ) )
  4039. break;
  4040. }
  4041. // Didn't find a match!
  4042. if ( i == nCount )
  4043. {
  4044. Q_strncpy( pFallbackShader, "wireframe", nFallbackLength );
  4045. return;
  4046. }
  4047. // Found a match
  4048. // FIXME: Theoretically, getting fallbacks should require a param list
  4049. // In practice, it looks rare or maybe even neved done
  4050. const char *pFallback = ppShaderList[i]->GetFallbackShader( NULL );
  4051. if ( !pFallback )
  4052. {
  4053. Q_strncpy( pFallbackShader, pShaderName, nFallbackLength );
  4054. return;
  4055. }
  4056. else
  4057. {
  4058. pShaderName = pFallback;
  4059. }
  4060. } while (true);
  4061. }
  4062. //-----------------------------------------------------------------------------
  4063. // Triggers OpenGL shader preloading at game startup
  4064. //-----------------------------------------------------------------------------
  4065. #if defined( DX_TO_GL_ABSTRACTION ) && !defined( _GAMECONSOLE )
  4066. void CMaterialSystem::DoStartupShaderPreloading( void )
  4067. {
  4068. GetRenderContextInternal()->DoStartupShaderPreloading();
  4069. }
  4070. #endif
  4071. void CMaterialSystem::SwapBuffers( void )
  4072. {
  4073. VPROF_BUDGET( "CMaterialSystem::SwapBuffers", VPROF_BUDGETGROUP_SWAP_BUFFERS );
  4074. GetRenderContextInternal()->SwapBuffers();
  4075. g_FrameNum++;
  4076. }
  4077. bool CMaterialSystem::InEditorMode() const
  4078. {
  4079. Assert( m_bGeneratedConfig );
  4080. return g_config.bEditMode && CanUseEditorMaterials();
  4081. }
  4082. void CMaterialSystem::NoteAnisotropicLevel( int currentLevel )
  4083. {
  4084. Assert( m_bGeneratedConfig );
  4085. g_config.m_nForceAnisotropicLevel = currentLevel;
  4086. }
  4087. // Get the current config for this video card (as last set by control panel or the default if not)
  4088. const MaterialSystem_Config_t &CMaterialSystem::GetCurrentConfigForVideoCard() const
  4089. {
  4090. Assert( m_bGeneratedConfig );
  4091. return g_config;
  4092. }
  4093. // Does the device support the given MSAA level?
  4094. bool CMaterialSystem::SupportsMSAAMode( int nNumSamples )
  4095. {
  4096. return g_pShaderAPI->SupportsMSAAMode( nNumSamples );
  4097. }
  4098. void CMaterialSystem::ReloadFilesInList( IFileList *pFilesToReload )
  4099. {
  4100. if ( IsPC() )
  4101. {
  4102. // We have to flush the materials in 2 steps because they have recursive dependencies. The problem case
  4103. // is if you have two materials, A and B, that depend on C. You tell A to reload and it also reloads C. Then
  4104. // the filesystem thinks C doesn't need to be reloaded anymore. So when you get to B, it decides not to reload
  4105. // either since C doesn't need to be reloaded. To fix this, we ask all materials if they want to reload in
  4106. // one stage, then in the next stage we actually reload the appropriate ones.
  4107. MaterialHandle_t hNext;
  4108. for ( MaterialHandle_t h=m_MaterialDict.FirstMaterial(); h != m_MaterialDict.InvalidMaterial(); h=hNext )
  4109. {
  4110. hNext = m_MaterialDict.NextMaterial( h );
  4111. IMaterialInternal *pMat = m_MaterialDict.GetMaterialInternal( h );
  4112. pMat->DecideShouldReloadFromWhitelist( pFilesToReload );
  4113. }
  4114. // Now reload the materials that wanted to be reloaded.
  4115. for ( MaterialHandle_t h=m_MaterialDict.FirstMaterial(); h != m_MaterialDict.InvalidMaterial(); h=hNext )
  4116. {
  4117. hNext = m_MaterialDict.NextMaterial( h );
  4118. IMaterialInternal *pMat = m_MaterialDict.GetMaterialInternal( h );
  4119. pMat->ReloadFromWhitelistIfMarked();
  4120. }
  4121. // Flush out necessary textures.
  4122. TextureManager()->ReloadFilesInList( pFilesToReload );
  4123. }
  4124. }
  4125. // Does the device support the given CSAA level?
  4126. bool CMaterialSystem::SupportsCSAAMode( int nNumSamples, int nQualityLevel )
  4127. {
  4128. return g_pShaderAPI->SupportsCSAAMode( nNumSamples, nQualityLevel );
  4129. }
  4130. void CMaterialSystem::SetShadowDepthBiasFactors( float fShadowSlopeScaleDepthBias, float fShadowDepthBias )
  4131. {
  4132. g_pShaderAPI->SetShadowDepthBiasFactors( fShadowSlopeScaleDepthBias, fShadowDepthBias );
  4133. }
  4134. void CMaterialSystem::FlipCulling( bool bFlipCulling )
  4135. {
  4136. g_pShaderAPI->FlipCulling( bFlipCulling );
  4137. }
  4138. bool CMaterialSystem::SupportsHDRMode( HDRType_t nHDRMode )
  4139. {
  4140. return HardwareConfig()->SupportsHDRMode( nHDRMode );
  4141. }
  4142. bool CMaterialSystem::UsesSRGBCorrectBlending( void ) const
  4143. {
  4144. return HardwareConfig()->UsesSRGBCorrectBlending();
  4145. }
  4146. // Get video card identitier
  4147. const MaterialSystemHardwareIdentifier_t &CMaterialSystem::GetVideoCardIdentifier( void ) const
  4148. {
  4149. static MaterialSystemHardwareIdentifier_t foo;
  4150. Assert( 0 );
  4151. return foo;
  4152. }
  4153. void CMaterialSystem::AddModeChangeCallBack( ModeChangeCallbackFunc_t func )
  4154. {
  4155. g_pShaderDeviceMgr->AddModeChangeCallback( func );
  4156. }
  4157. void CMaterialSystem::RemoveModeChangeCallBack( ModeChangeCallbackFunc_t func )
  4158. {
  4159. g_pShaderDeviceMgr->RemoveModeChangeCallback( func );
  4160. }
  4161. //-----------------------------------------------------------------------------
  4162. // Gets configuration information associated with the display card.
  4163. // It will return a list of key values to set.
  4164. //-----------------------------------------------------------------------------
  4165. bool CMaterialSystem::GetRecommendedVideoConfig( KeyValues *pKeyValues )
  4166. {
  4167. MaterialLock_t hLock = Lock();
  4168. bool bResult = g_pShaderDeviceMgr->GetRecommendedVideoConfig( m_nAdapter, pKeyValues );
  4169. Unlock( hLock );
  4170. return bResult;
  4171. }
  4172. //-----------------------------------------------------------------------------
  4173. // Gets configuration information associated with a particular DX level.
  4174. // It will return a list of key values to set.
  4175. //-----------------------------------------------------------------------------
  4176. bool CMaterialSystem::GetRecommendedConfigurationInfo( int nDXLevel, KeyValues *pKeyValues )
  4177. {
  4178. MaterialLock_t hLock = Lock();
  4179. bool bResult = g_pShaderDeviceMgr->GetRecommendedConfigurationInfo( m_nAdapter, nDXLevel, pKeyValues );
  4180. Unlock( hLock );
  4181. return bResult;
  4182. }
  4183. //-----------------------------------------------------------------------------
  4184. // For dealing with device lost in cases where SwapBuffers isn't called all the time (Hammer)
  4185. //-----------------------------------------------------------------------------
  4186. void CMaterialSystem::HandleDeviceLost()
  4187. {
  4188. if ( IsGameConsole() )
  4189. return;
  4190. g_pShaderAPI->HandleDeviceLost();
  4191. }
  4192. bool CMaterialSystem::UsingFastClipping( void )
  4193. {
  4194. return (HardwareConfig()->UseFastClipping() || (HardwareConfig()->MaxUserClipPlanes() < 1));
  4195. };
  4196. int CMaterialSystem::StencilBufferBits( void )
  4197. {
  4198. return HardwareConfig()->StencilBufferBits();
  4199. }
  4200. ITexture* CMaterialSystem::CreateRenderTargetTexture(
  4201. int w,
  4202. int h,
  4203. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  4204. ImageFormat format,
  4205. MaterialRenderTargetDepth_t depth )
  4206. {
  4207. return CreateNamedRenderTargetTextureEx( NULL, w, h, sizeMode, format, depth, TEXTUREFLAGS_CLAMPS|TEXTUREFLAGS_CLAMPT, 0 );
  4208. }
  4209. ITexture* CMaterialSystem::CreateNamedRenderTargetTexture(
  4210. const char *pRTName,
  4211. int w,
  4212. int h,
  4213. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  4214. ImageFormat format,
  4215. MaterialRenderTargetDepth_t depth,
  4216. bool bClampTexCoords,
  4217. bool bAutoMipMap )
  4218. {
  4219. unsigned int textureFlags = 0;
  4220. if ( bClampTexCoords )
  4221. {
  4222. textureFlags |= TEXTUREFLAGS_CLAMPS | TEXTUREFLAGS_CLAMPT;
  4223. }
  4224. unsigned int renderTargetFlags = 0;
  4225. if ( bAutoMipMap )
  4226. {
  4227. renderTargetFlags |= CREATERENDERTARGETFLAGS_AUTOMIPMAP;
  4228. }
  4229. return CreateNamedRenderTargetTextureEx( pRTName, w, h, sizeMode, format, depth, textureFlags, renderTargetFlags );
  4230. }
  4231. inline RenderTargetType_t DepthTypeToRenderTargetType( MaterialRenderTargetDepth_t depth )
  4232. {
  4233. // GR - determine RT type based on depth buffer requirements
  4234. switch ( depth )
  4235. {
  4236. case MATERIAL_RT_DEPTH_SEPARATE:
  4237. // using own depth buffer
  4238. return RENDER_TARGET_WITH_DEPTH;
  4239. case MATERIAL_RT_DEPTH_NONE:
  4240. // no depth buffer
  4241. return RENDER_TARGET_NO_DEPTH;
  4242. case MATERIAL_RT_DEPTH_ONLY:
  4243. // only depth buffer
  4244. return RENDER_TARGET_ONLY_DEPTH;
  4245. case MATERIAL_RT_DEPTH_SHARED:
  4246. default:
  4247. // using shared depth buffer
  4248. return RENDER_TARGET;
  4249. }
  4250. }
  4251. ITexture* CMaterialSystem::CreateNamedRenderTargetTextureEx(
  4252. const char *pRTName,
  4253. int w,
  4254. int h,
  4255. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  4256. ImageFormat format,
  4257. MaterialRenderTargetDepth_t depth,
  4258. unsigned int textureFlags,
  4259. unsigned int renderTargetFlags )
  4260. {
  4261. if ( !m_nAllocatingRenderTargets )
  4262. {
  4263. Warning( "Tried to create render target outside of CMaterialSystem::BeginRenderTargetAllocation/EndRenderTargetAllocation block\n" );
  4264. return NULL;
  4265. }
  4266. RenderTargetType_t rtType = DepthTypeToRenderTargetType( depth );
  4267. ITextureInternal* pTex = TextureManager()->CreateRenderTargetTexture( pRTName, w, h, sizeMode, format, rtType, textureFlags, renderTargetFlags, false );
  4268. pTex->IncrementReferenceCount();
  4269. #if defined( _X360 )
  4270. if ( !( renderTargetFlags & CREATERENDERTARGETFLAGS_NOEDRAM ) )
  4271. {
  4272. // create the EDRAM surface that is bound to the RT Texture
  4273. pTex->CreateRenderTargetSurface( 0, 0, IMAGE_FORMAT_UNKNOWN, true );
  4274. }
  4275. #endif
  4276. return pTex;
  4277. }
  4278. //-----------------------------------------------------------------------------------------------------
  4279. // New version which must be called inside BeginRenderTargetAllocation-EndRenderTargetAllocation block
  4280. //-----------------------------------------------------------------------------------------------------
  4281. ITexture *CMaterialSystem::CreateNamedRenderTargetTextureEx2(
  4282. const char *pRTName,
  4283. int w,
  4284. int h,
  4285. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  4286. ImageFormat format,
  4287. MaterialRenderTargetDepth_t depth,
  4288. unsigned int textureFlags,
  4289. unsigned int renderTargetFlags )
  4290. {
  4291. // Only proceed if we are between BeginRenderTargetAllocation and EndRenderTargetAllocation
  4292. if ( !m_nAllocatingRenderTargets )
  4293. {
  4294. Warning( "Tried to create render target outside of CMaterialSystem::BeginRenderTargetAllocation/EndRenderTargetAllocation block\n" );
  4295. return NULL;
  4296. }
  4297. ITexture* pTexture = CreateNamedRenderTargetTextureEx( pRTName, w, h, sizeMode, format, depth, textureFlags, renderTargetFlags );
  4298. pTexture->DecrementReferenceCount(); // Follow the same convention as CTextureManager::LoadTexture (return refcount of 0).
  4299. return pTexture;
  4300. }
  4301. ITexture *CMaterialSystem::CreateNamedMultiRenderTargetTexture(
  4302. const char *pRTName,
  4303. int w,
  4304. int h,
  4305. RenderTargetSizeMode_t sizeMode, // Controls how size is generated (and regenerated on video mode change).
  4306. ImageFormat format,
  4307. MaterialRenderTargetDepth_t depth,
  4308. unsigned int textureFlags,
  4309. unsigned int renderTargetFlags )
  4310. {
  4311. // Only proceed if we are between BeginRenderTargetAllocation and EndRenderTargetAllocation
  4312. if ( !m_nAllocatingRenderTargets )
  4313. {
  4314. Warning( "Tried to create render target outside of CMaterialSystem::BeginRenderTargetAllocation/EndRenderTargetAllocation block\n" );
  4315. return NULL;
  4316. }
  4317. RenderTargetType_t rtType = DepthTypeToRenderTargetType( depth );
  4318. ITextureInternal* pTex =TextureManager()->CreateRenderTargetTexture( pRTName, w, h, sizeMode, format, rtType, textureFlags, renderTargetFlags, true );
  4319. #if defined( _X360 )
  4320. if ( !( renderTargetFlags & CREATERENDERTARGETFLAGS_NOEDRAM ) )
  4321. {
  4322. // create the EDRAM surface that is bound to the RT Texture
  4323. pTex->CreateRenderTargetSurface( 0, 0, IMAGE_FORMAT_UNKNOWN, true );
  4324. }
  4325. #endif
  4326. return pTex; //ref count is 0
  4327. }
  4328. void CMaterialSystem::BeginRenderTargetAllocation( void )
  4329. {
  4330. if ( m_bDisableRenderTargetAllocationForever )
  4331. {
  4332. Warning( "Tried BeginRenderTargetAllocation after game startup. If I let you do this, all users would suffer.\n" );
  4333. return;
  4334. }
  4335. m_nAllocatingRenderTargets++;
  4336. }
  4337. void CMaterialSystem::EndRenderTargetAllocation( void )
  4338. {
  4339. if ( m_bDisableRenderTargetAllocationForever )
  4340. return;
  4341. m_nAllocatingRenderTargets--;
  4342. if ( ! m_nAllocatingRenderTargets )
  4343. {
  4344. if ( IsPC() && CanDownloadTextures() )
  4345. {
  4346. // Simulate an Alt-Tab...will cause RTs to be allocated first
  4347. g_pShaderDevice->ReleaseResources();
  4348. g_pShaderDevice->ReacquireResources();
  4349. }
  4350. TextureManager()->CacheExternalStandardRenderTargets();
  4351. }
  4352. }
  4353. void CMaterialSystem::FinishRenderTargetAllocation( void )
  4354. {
  4355. // disable all future render target allocation to prevent re-load bugs from creeping in.
  4356. if (
  4357. ( CommandLine()->CheckParm( "-tools" ) == NULL ) &&
  4358. ( ! m_bRequestedEditorMaterials ) )
  4359. {
  4360. m_bDisableRenderTargetAllocationForever = true;
  4361. }
  4362. }
  4363. void CMaterialSystem::ReEnableRenderTargetAllocation_IRealizeIfICallThisAllTexturesWillBeUnloadedAndLoadTimeWillSufferHorribly( void )
  4364. {
  4365. m_bDisableRenderTargetAllocationForever = false;
  4366. }
  4367. //-----------------------------------------------------------------------------------------------------
  4368. //
  4369. //-----------------------------------------------------------------------------------------------------
  4370. void CMaterialSystem::UpdateLightmap( int lightmapPageID, int lightmapSize[2],
  4371. int offsetIntoLightmapPage[2],
  4372. float *pFloatImage, float *pFloatImageBump1,
  4373. float *pFloatImageBump2, float *pFloatImageBump3 )
  4374. {
  4375. CMatCallQueue *pCallQueue = GetRenderCallQueue();
  4376. if ( !pCallQueue )
  4377. {
  4378. m_Lightmaps.UpdateLightmap( lightmapPageID, lightmapSize, offsetIntoLightmapPage, pFloatImage, pFloatImageBump1, pFloatImageBump2, pFloatImageBump3 );
  4379. }
  4380. else
  4381. {
  4382. ExecuteOnce( DebuggerBreakIfDebugging() );
  4383. }
  4384. }
  4385. void CMaterialSystem::UpdatePaintmap( int paintmap, BYTE* pPaintData, int numRects, Rect_t* pRects )
  4386. {
  4387. CMatCallQueue *pCallQueue = GetRenderCallQueue();
  4388. if ( !pCallQueue )
  4389. {
  4390. m_Paintmaps.UpdatePaintmap( paintmap, pPaintData, numRects, pRects );
  4391. }
  4392. else
  4393. {
  4394. ExecuteOnce( DebuggerBreakIfDebugging() );
  4395. }
  4396. }
  4397. //-----------------------------------------------------------------------------------------------------
  4398. // NVIDIA stereo
  4399. //-----------------------------------------------------------------------------------------------------
  4400. void CMaterialSystem::NVStereoUpdate()
  4401. {
  4402. g_pShaderAPI->UpdateStereoTexture( TextureManager()->StereoParamTexture()->GetTextureHandle( 0 ), &m_bIsStereoActiveThisFrame );
  4403. }
  4404. bool CMaterialSystem::IsStereoSupported()
  4405. {
  4406. if ( !m_bStereoBoolsInitialized )
  4407. {
  4408. m_bIsStereoSupported = g_pShaderAPI->IsStereoSupported();
  4409. m_bStereoBoolsInitialized = true;
  4410. }
  4411. return m_bIsStereoSupported;
  4412. }
  4413. bool CMaterialSystem::IsStereoActiveThisFrame() const
  4414. {
  4415. // NOTE: This is updated in NVStereoUpdate above
  4416. return m_bIsStereoActiveThisFrame;
  4417. }
  4418. //-----------------------------------------------------------------------------------------------------
  4419. // 360 TTF Font Support
  4420. //-----------------------------------------------------------------------------------------------------
  4421. #if defined( _X360 )
  4422. HXUIFONT CMaterialSystem::OpenTrueTypeFont( const char *pFontname, int tall, int style )
  4423. {
  4424. MaterialLock_t hLock = Lock();
  4425. HXUIFONT result = g_pShaderAPI->OpenTrueTypeFont( pFontname, tall, style );
  4426. Unlock( hLock );
  4427. return result;
  4428. }
  4429. void CMaterialSystem::CloseTrueTypeFont( HXUIFONT hFont )
  4430. {
  4431. MaterialLock_t hLock = Lock();
  4432. g_pShaderAPI->CloseTrueTypeFont( hFont );
  4433. Unlock( hLock );
  4434. }
  4435. bool CMaterialSystem::GetTrueTypeFontMetrics( HXUIFONT hFont, wchar_t wchFirst, wchar_t wchLast, XUIFontMetrics *pFontMetrics, XUICharMetrics *pCharMetrics )
  4436. {
  4437. MaterialLock_t hLock = Lock();
  4438. bool result = g_pShaderAPI->GetTrueTypeFontMetrics( hFont, wchFirst, wchLast, pFontMetrics, pCharMetrics );
  4439. Unlock( hLock );
  4440. return result;
  4441. }
  4442. bool CMaterialSystem::GetTrueTypeGlyphs( HXUIFONT hFont, int numChars, wchar_t *pWch, int *pOffsetX, int *pOffsetY, int *pWidth, int *pHeight, unsigned char *pRGBA, int *pRGBAOffset )
  4443. {
  4444. MaterialLock_t hLock = Lock();
  4445. bool result = g_pShaderAPI->GetTrueTypeGlyphs( hFont, numChars, pWch, pOffsetX, pOffsetY, pWidth, pHeight, pRGBA, pRGBAOffset );
  4446. Unlock( hLock );
  4447. return result;
  4448. }
  4449. #endif
  4450. //-----------------------------------------------------------------------------------------------------
  4451. // 360 Back Buffer access. Due to hardware, RT data must be blitted from EDRAM
  4452. // and converted.
  4453. //-----------------------------------------------------------------------------------------------------
  4454. #if defined( _X360 )
  4455. void CMaterialSystem::ReadBackBuffer( Rect_t *pSrcRect, Rect_t *pDstRect, unsigned char *pDstData, ImageFormat dstFormat, int dstStride )
  4456. {
  4457. Assert( pSrcRect && pDstRect && pDstData );
  4458. int fbWidth, fbHeight;
  4459. g_pShaderAPI->GetBackBufferDimensions( fbWidth, fbHeight );
  4460. if ( pDstRect->width > fbWidth || pDstRect->height > fbHeight )
  4461. {
  4462. Assert( 0 );
  4463. return;
  4464. }
  4465. // intermediate results will be placed at (0,0)
  4466. Rect_t rect;
  4467. rect.x = 0;
  4468. rect.y = 0;
  4469. rect.width = pDstRect->width;
  4470. rect.height = pDstRect->height;
  4471. ITexture *pTempRT;
  4472. bool bStretch = ( pSrcRect->width != pDstRect->width || pSrcRect->height != pDstRect->height );
  4473. if ( !bStretch )
  4474. {
  4475. // hijack an unused RT (no surface required) for 1:1 resolve work, fastest path
  4476. pTempRT = FindTexture( "_rt_FullFrameFB", TEXTURE_GROUP_RENDER_TARGET );
  4477. }
  4478. else
  4479. {
  4480. // hijack an unused RT (with surface abilities) for stretch work, slower path
  4481. pTempRT = FindTexture( "_rt_WaterReflection", TEXTURE_GROUP_RENDER_TARGET );
  4482. }
  4483. Assert( !pTempRT->IsError() && pDstRect->width <= pTempRT->GetActualWidth() && pDstRect->height <= pTempRT->GetActualHeight() );
  4484. GetRenderContextInternal()->CopyRenderTargetToTextureEx( pTempRT, 0, pSrcRect, &rect );
  4485. // access the RT bits
  4486. CPixelWriter writer;
  4487. g_pShaderAPI->ModifyTexture( ((ITextureInternal*)pTempRT)->GetTextureHandle( 0 ) );
  4488. if ( !g_pShaderAPI->TexLock( 0, 0, 0, 0, pTempRT->GetActualWidth(), pTempRT->GetActualHeight(), writer ) )
  4489. return;
  4490. // this will be adequate for non-block formats
  4491. int srcStride = pTempRT->GetActualWidth() * ImageLoader::SizeInBytes( pTempRT->GetImageFormat() );
  4492. // untile intermediate RT in place to achieve linear access
  4493. XGUntileTextureLevel(
  4494. pTempRT->GetActualWidth(),
  4495. pTempRT->GetActualHeight(),
  4496. 0,
  4497. XGGetGpuFormat( ImageLoader::ImageFormatToD3DFormat( pTempRT->GetImageFormat() ) ),
  4498. 0,
  4499. (char*)writer.GetPixelMemory(),
  4500. srcStride,
  4501. NULL,
  4502. writer.GetPixelMemory(),
  4503. NULL );
  4504. // swap back to x86 order as expected by image conversion
  4505. ImageLoader::ByteSwapImageData( (unsigned char*)writer.GetPixelMemory(), srcStride*pTempRT->GetActualHeight(), pTempRT->GetImageFormat() );
  4506. // convert to callers format
  4507. Assert( dstFormat == IMAGE_FORMAT_RGB888 );
  4508. ImageLoader::ConvertImageFormat( (unsigned char*)writer.GetPixelMemory(), pTempRT->GetImageFormat(), pDstData, dstFormat, pDstRect->width, pDstRect->height, srcStride, dstStride );
  4509. g_pShaderAPI->TexUnlock();
  4510. }
  4511. #endif
  4512. #if defined( _X360 )
  4513. void CMaterialSystem::PersistDisplay()
  4514. {
  4515. g_pShaderAPI->PersistDisplay();
  4516. }
  4517. #endif
  4518. #if defined( _X360 )
  4519. void *CMaterialSystem::GetD3DDevice()
  4520. {
  4521. return g_pShaderAPI->GetD3DDevice();
  4522. }
  4523. #endif
  4524. #if defined( _X360 )
  4525. bool CMaterialSystem::OwnGPUResources( bool bEnable )
  4526. {
  4527. return g_pShaderAPI->OwnGPUResources( bEnable );
  4528. }
  4529. #endif
  4530. //-----------------------------------------------------------------------------------------------------
  4531. //
  4532. //-----------------------------------------------------------------------------------------------------
  4533. class CThreadRelease : public CJob
  4534. {
  4535. virtual JobStatus_t DoExecute()
  4536. {
  4537. g_pShaderAPI->ReleaseThreadOwnership();
  4538. return JOB_OK;
  4539. }
  4540. };
  4541. void CMaterialSystem::ThreadRelease( )
  4542. {
  4543. if ( !m_bThreadHasOwnership )
  4544. {
  4545. return;
  4546. }
  4547. double flStartTime, flEndThreadRelease, flEndTime;
  4548. if ( mat_queue_report.GetInt() )
  4549. {
  4550. flStartTime = Plat_FloatTime();
  4551. }
  4552. CJob *pActiveAsyncJob = new CThreadRelease();
  4553. CreateMatQueueThreadPool()->AddJob( pActiveAsyncJob );
  4554. pActiveAsyncJob->WaitForFinish();
  4555. SafeRelease( pActiveAsyncJob );
  4556. if ( mat_queue_report.GetInt() )
  4557. {
  4558. flEndThreadRelease = Plat_FloatTime();
  4559. }
  4560. g_pShaderAPI->AcquireThreadOwnership();
  4561. m_bThreadHasOwnership = false;
  4562. if ( mat_queue_report.GetInt() )
  4563. {
  4564. flEndTime = Plat_FloatTime();
  4565. double flResult = ( flEndTime - flStartTime ) * 1000.0;
  4566. if ( mat_queue_report.GetInt() == -1 || flResult > mat_queue_report.GetFloat() )
  4567. {
  4568. Color red( 200, 20, 20, 255 );
  4569. ConColorMsg( red, "CMaterialSystem::ThreadRelease: %0.2fms = Release:%0.2fms + Acquire:%0.2fms\n", flResult, ( flEndThreadRelease - flStartTime ) * 1000.0, ( flEndTime - flEndThreadRelease ) * 1000.0 );
  4570. }
  4571. }
  4572. }
  4573. class CThreadAcquire : public CJob
  4574. {
  4575. virtual JobStatus_t DoExecute()
  4576. {
  4577. g_pShaderAPI->AcquireThreadOwnership();
  4578. return JOB_OK;
  4579. }
  4580. };
  4581. void CMaterialSystem::ThreadAcquire( )
  4582. {
  4583. double flStartTime, flEndTime;
  4584. if ( mat_queue_report.GetInt() )
  4585. {
  4586. flStartTime = Plat_FloatTime();
  4587. }
  4588. g_pShaderAPI->ReleaseThreadOwnership();
  4589. CJob *pActiveAsyncJob = new CThreadAcquire();
  4590. CreateMatQueueThreadPool()->AddJob( pActiveAsyncJob );
  4591. // while we could wait for this job to finish, there's no reason too
  4592. // pActiveAsyncJob->WaitForFinish();
  4593. SafeRelease( pActiveAsyncJob );
  4594. m_bThreadHasOwnership = true;
  4595. if ( mat_queue_report.GetInt() )
  4596. {
  4597. flEndTime = Plat_FloatTime();
  4598. double flResult = ( flEndTime - flStartTime ) * 1000.0;
  4599. if ( mat_queue_report.GetInt() == -1 || flResult > mat_queue_report.GetFloat() )
  4600. {
  4601. Color red( 200, 20, 20, 255 );
  4602. ConColorMsg( red, "CMaterialSystem::ThreadAcquire: %0.2fms\n", flResult );
  4603. }
  4604. }
  4605. }
  4606. //-----------------------------------------------------------------------------------------------------
  4607. //
  4608. //-----------------------------------------------------------------------------------------------------
  4609. MaterialLock_t CMaterialSystem::Lock()
  4610. {
  4611. IMatRenderContextInternal *pCurContext = GetRenderContextInternal();
  4612. #ifdef _X360
  4613. // use this to help catch synchronization blocks in PIX timing captures
  4614. PIXEVENT( pCurContext, "CMaterialSystem::Lock" );
  4615. #endif
  4616. #ifndef _PS3
  4617. if ( pCurContext != &m_HardwareRenderContext && m_pActiveAsyncJob )
  4618. {
  4619. m_pActiveAsyncJob->WaitForFinishAndRelease();
  4620. m_pActiveAsyncJob = NULL;
  4621. }
  4622. #else
  4623. if ( pCurContext != &m_HardwareRenderContext && m_bQMSJobSubmitted )
  4624. {
  4625. g_pGcmSharedData->WaitForQMS();
  4626. m_bQMSJobSubmitted = 0;
  4627. }
  4628. #endif
  4629. g_MatSysMutex.Lock();
  4630. MaterialLock_t hMaterialLock = (MaterialLock_t)pCurContext;
  4631. m_pRenderContext = &m_HardwareRenderContext;
  4632. if ( m_ThreadMode != MATERIAL_SINGLE_THREADED )
  4633. {
  4634. g_pShaderAPI->SetDisallowAccess( false );
  4635. if ( pCurContext->GetCallQueueInternal() )
  4636. {
  4637. #ifdef MAT_QUEUED_OWN_THREADPOOL
  4638. ThreadRelease();
  4639. #else
  4640. g_pShaderAPI->AcquireThreadOwnership();
  4641. #endif
  4642. }
  4643. }
  4644. g_pShaderAPI->ShaderLock();
  4645. return hMaterialLock;
  4646. }
  4647. //-----------------------------------------------------------------------------------------------------
  4648. //
  4649. //-----------------------------------------------------------------------------------------------------
  4650. void CMaterialSystem::Unlock( MaterialLock_t hMaterialLock )
  4651. {
  4652. IMatRenderContextInternal *pRenderContext = (IMatRenderContextInternal *)hMaterialLock;
  4653. m_pRenderContext = pRenderContext ;
  4654. g_pShaderAPI->ShaderUnlock();
  4655. if ( m_ThreadMode == MATERIAL_QUEUED_SINGLE_THREADED )
  4656. {
  4657. g_pShaderAPI->SetDisallowAccess( true );
  4658. }
  4659. else if ( m_ThreadMode == MATERIAL_QUEUED_THREADED )
  4660. {
  4661. if ( pRenderContext->GetCallQueueInternal() )
  4662. {
  4663. #ifndef MAT_QUEUED_OWN_THREADPOOL
  4664. g_pShaderAPI->ReleaseThreadOwnership();
  4665. #endif
  4666. }
  4667. }
  4668. g_MatSysMutex.Unlock();
  4669. }
  4670. //-----------------------------------------------------------------------------------------------------
  4671. //
  4672. //-----------------------------------------------------------------------------------------------------
  4673. CMatCallQueue *CMaterialSystem::GetRenderCallQueue()
  4674. {
  4675. IMatRenderContextInternal *pRenderContext = m_pRenderContext;
  4676. return pRenderContext ? pRenderContext->GetCallQueueInternal() : NULL;
  4677. }
  4678. void CMaterialSystem::UnbindMaterial( IMaterial *pMaterial )
  4679. {
  4680. Assert( (pMaterial == NULL) || ((IMaterialInternal *)pMaterial)->IsRealTimeVersion() );
  4681. if ( m_HardwareRenderContext.GetCurrentMaterial() == pMaterial )
  4682. {
  4683. m_HardwareRenderContext.Bind( g_pErrorMaterial, NULL );
  4684. }
  4685. }
  4686. //-----------------------------------------------------------------------------
  4687. //
  4688. //-----------------------------------------------------------------------------
  4689. void CMaterialSystem::CompactMemory()
  4690. {
  4691. for ( int i = 0; i < ARRAYSIZE(m_QueuedRenderContexts); i++)
  4692. {
  4693. m_QueuedRenderContexts[i].CompactMemory();
  4694. }
  4695. }
  4696. //-----------------------------------------------------------------------------
  4697. // Material + texture related commands
  4698. //-----------------------------------------------------------------------------
  4699. void CMaterialSystem::DebugPrintUsedMaterials( const CCommand &args )
  4700. {
  4701. if( args.ArgC() == 1 )
  4702. {
  4703. DebugPrintUsedMaterials( NULL, false );
  4704. }
  4705. else
  4706. {
  4707. DebugPrintUsedMaterials( args[ 1 ], false );
  4708. }
  4709. }
  4710. void CMaterialSystem::DebugPrintUsedMaterialsVerbose( const CCommand &args )
  4711. {
  4712. if( args.ArgC() == 1 )
  4713. {
  4714. DebugPrintUsedMaterials( NULL, true );
  4715. }
  4716. else
  4717. {
  4718. DebugPrintUsedMaterials( args[ 1 ], true );
  4719. }
  4720. }
  4721. void CMaterialSystem::DebugPrintAspectRatioInfo( const CCommand &args )
  4722. {
  4723. int width, height;
  4724. GetBackBufferDimensions( width, height );
  4725. const AspectRatioInfo_t &aspectRatioInfo = GetAspectRatioInfo();
  4726. DevMsg( "========================\n" );
  4727. DevMsg( "m_bIsWidescreen: %s\n", aspectRatioInfo.m_bIsWidescreen ? "true" : "false" );
  4728. DevMsg( "m_bIsHidef: %s\n", aspectRatioInfo.m_bIsHidef ? "true" : "false" );
  4729. DevMsg( "m_flFrameBufferAspectRatio: %f\n", aspectRatioInfo.m_flFrameBufferAspectRatio );
  4730. DevMsg( "m_flPhysicalAspectRatio: %f\n", aspectRatioInfo.m_flPhysicalAspectRatio );
  4731. DevMsg( "m_flFrameBuffertoPhysicalScalar: %f\n", aspectRatioInfo.m_flFrameBuffertoPhysicalScalar );
  4732. DevMsg( "fb width: %d fb height: %d\n", width, height );
  4733. DevMsg( "========================\n" );
  4734. }
  4735. void CMaterialSystem::DebugPrintUsedTextures( const CCommand &args )
  4736. {
  4737. DebugPrintUsedTextures();
  4738. }
  4739. #if defined( _X360 ) || defined( _PS3 )
  4740. void CMaterialSystem::ListUsedMaterials( const CCommand &args )
  4741. {
  4742. ListUsedMaterials();
  4743. }
  4744. #endif // !_X360
  4745. void CMaterialSystem::ReloadAllMaterials( const CCommand &args )
  4746. {
  4747. ReloadMaterials( NULL );
  4748. }
  4749. void CMaterialSystem::ReloadMaterials( const CCommand &args )
  4750. {
  4751. if( args.ArgC() != 2 )
  4752. {
  4753. Log_Warning( LOG_MaterialSystemConsole, "Usage: mat_reloadmaterial material_name_substring\n"
  4754. " or mat_reloadmaterial substring1*substring2*...*substringN\n" );
  4755. return;
  4756. }
  4757. ReloadMaterials( args[ 1 ] );
  4758. }
  4759. void CMaterialSystem::ReloadTextures( const CCommand &args )
  4760. {
  4761. ReloadTextures();
  4762. }
  4763. #ifdef _PS3
  4764. //void CMaterialSystem::GetVRAMScreenShotInfo( char **pointerToRawImageData, uint32 *uWidth, uint32 *uHeight, uint32 *uPitch, VRAMScreenShotInfoColor_t *colour )
  4765. void CMaterialSystem::TransmitScreenshotToVX()
  4766. {
  4767. extern char *GetScreenShotInfoForVX( IDirect3DDevice9 *pDevice, uint32 *uWidth, uint32 *uHeight, uint32 *uPitch, uint32 *colour );
  4768. uint32 uWidth, uHeight, uPitch, uColor;
  4769. char *pFrameBuffer = GetScreenShotInfoForVX( Dx9Device(), &uWidth, &uHeight, &uPitch, &uColor );
  4770. if ( pFrameBuffer )
  4771. {
  4772. g_pValvePS3Console->TransmitScreenshot( pFrameBuffer, uWidth, uHeight, uPitch, uColor );
  4773. }
  4774. //return GetVRAMScreenShotInfoGCM( pointerToRawImageData, Dx9Device(), uWidth, uHeight, uPitch, colour);
  4775. }
  4776. void CMaterialSystem::CompactRsxLocalMemory( char const *szReason )
  4777. {
  4778. extern void Ps3gcmLocalMemoryAllocator_CompactWithReason( char const *szReason );
  4779. Ps3gcmLocalMemoryAllocator_CompactWithReason( szReason );
  4780. }
  4781. void CMaterialSystem::SetFlipPresentFrequency( int nNumVBlanks )
  4782. {
  4783. extern void Ps3gcmFlip_SetFlipPresentFrequency( int nNumVBlanks );
  4784. // 7ltodo Ps3gcmFlip_SetFlipPresentFrequency( nNumVBlanks );
  4785. }
  4786. #endif
  4787. void CMaterialSystem::SpinPresent( uint nFrames )
  4788. {
  4789. for( uint i = 0; i < nFrames; ++i )
  4790. {
  4791. // BeginScene(); // do we need this?
  4792. g_pShaderAPI->ClearColor3ub( 0, 0, 0 );
  4793. g_pShaderAPI->ClearBuffers( true, true, true, -1, -1 );
  4794. g_pShaderDevice->Present();
  4795. // EndScene(); // do we need this?
  4796. }
  4797. }
  4798. CON_COMMAND( mat_hdr_enabled, "Report if HDR is enabled for debugging" )
  4799. {
  4800. if( HardwareConfig() && HardwareConfig()->GetHDREnabled() )
  4801. {
  4802. Log_Warning( LOG_MaterialSystemConsole, "HDR Enabled\n" );
  4803. }
  4804. else
  4805. {
  4806. Log_Warning( LOG_MaterialSystemConsole, "HDR Disabled\n" );
  4807. }
  4808. }
  4809. #ifdef _PS3
  4810. #include "shaderutil_ps3nonvirt.inl"
  4811. #endif