forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcmaterialsystem.cpp
5533 lines (4680 loc) · 179 KB
/
cmaterialsystem.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
//===========================================================================//
#include "pch_materialsystem.h"
#define MATSYS_INTERNAL
#include "cmaterialsystem.h"
#include "colorspace.h"
#include "materialsystem/materialsystem_config.h"
#include "IHardwareConfigInternal.h"
#include "shadersystem.h"
#include "texturemanager.h"
#include "shaderlib/ShaderDLL.h"
#include "tier1/callqueue.h"
#include "vstdlib/jobthread.h"
#include "cmatnullrendercontext.h"
#include "filesystem/IQueuedLoader.h"
#include "datacache/idatacache.h"
#include "materialsystem/imaterialproxy.h"
#include "vstdlib/IKeyValuesSystem.h"
#include "ctexturecompositor.h"
#if defined( _X360 )
#include "xbox/xbox_console.h"
#include "xbox/xbox_win32stubs.h"
#endif
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
#ifdef POSIX
#define _finite finite
#endif
// this is hooked into the engines convar
ConVar mat_debugalttab( "mat_debugalttab", "0", FCVAR_CHEAT );
ConVar mat_forcemanagedtextureintohardware( "mat_forcemanagedtextureintohardware", "1", FCVAR_HIDDEN | FCVAR_ALLOWED_IN_COMPETITIVE );
ConVar mat_supportflashlight( "mat_supportflashlight", "-1", FCVAR_HIDDEN, "0 - do not support flashlight (don't load flashlight shader combos), 1 - flashlight is supported" );
#ifdef OSX
#define CV_FRAME_SWAP_WORKAROUND_DEFAULT "1"
#else
#define CV_FRAME_SWAP_WORKAROUND_DEFAULT "0"
#endif
ConVar mat_texture_reload_frame_swap_workaround( "mat_texture_reload_frame_swap_workaround", CV_FRAME_SWAP_WORKAROUND_DEFAULT, FCVAR_INTERNAL_USE,
"Workaround certain GL drivers holding unnecessary amounts of data when loading many materials by forcing synthetic frame swaps" );
// This ConVar allows us to skip ~40% of our map load time, but it doesn't work on GPUs older
// than ~2005. We set it automatically and don't expose it to players.
ConVar mat_requires_rt_alloc_first( "mat_requires_rt_alloc_first", "0", FCVAR_HIDDEN );
// Make sure this convar gets created before videocfg.lib is initialized, so it can be driven by dxsupport.cfg
static ConVar mat_tonemapping_occlusion_use_stencil( "mat_tonemapping_occlusion_use_stencil", "0" );
#ifdef DX_TO_GL_ABSTRACTION
// In GL mode, we currently require mat_dxlevel to be between 90-92
static ConVar mat_dxlevel( "mat_dxlevel", "92", 0, "", true, 90, true, 92, NULL );
#else
static ConVar mat_dxlevel( "mat_dxlevel", "0", 0, "Current DirectX Level. Competitive play requires at least mat_dxlevel 90", false, 0, false, 0, true, 90, false, 0, NULL );
#endif
IMaterialInternal *g_pErrorMaterial = NULL;
CreateInterfaceFn g_fnMatSystemConnectCreateInterface = NULL;
static int ReadListFromFile(CUtlVector<char*>* outReplacementMaterials, const char *pszPathName);
//#define PERF_TESTING 1
//-----------------------------------------------------------------------------
// Implementational structures
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Singleton instance exposed to the engine
//-----------------------------------------------------------------------------
CMaterialSystem g_MaterialSystem;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CMaterialSystem, IMaterialSystem,
MATERIAL_SYSTEM_INTERFACE_VERSION, g_MaterialSystem );
// Expose this to the external shader DLLs
MaterialSystem_Config_t g_config;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( MaterialSystem_Config_t, MaterialSystem_Config_t, MATERIALSYSTEM_CONFIG_VERSION, g_config );
//-----------------------------------------------------------------------------
CThreadFastMutex g_MatSysMutex;
//-----------------------------------------------------------------------------
// Purpose: additional materialsystem information, internal use only
//-----------------------------------------------------------------------------
#ifndef _X360
struct MaterialSystem_Config_Internal_t
{
int r_waterforceexpensive;
};
MaterialSystem_Config_Internal_t g_config_internal;
#endif
//-----------------------------------------------------------------------------
// Necessary to allow the shader DLLs to get ahold of IMaterialSystemHardwareConfig
//-----------------------------------------------------------------------------
IHardwareConfigInternal* g_pHWConfig = 0;
static void *GetHardwareConfig()
{
if ( g_pHWConfig )
return (IMaterialSystemHardwareConfig*)g_pHWConfig;
// can't call QueryShaderAPI here because it calls a factory function
// and we end up in an infinite recursion
return NULL;
}
EXPOSE_INTERFACE_FN( GetHardwareConfig, IMaterialSystemHardwareConfig, MATERIALSYSTEM_HARDWARECONFIG_INTERFACE_VERSION );
//-----------------------------------------------------------------------------
// Necessary to allow the shader DLLs to get ahold of ICvar
//-----------------------------------------------------------------------------
static void *GetICVar()
{
return g_pCVar;
}
EXPOSE_INTERFACE_FN( GetICVar, ICVar, CVAR_INTERFACE_VERSION );
//-----------------------------------------------------------------------------
// Accessor to get at the material system
//-----------------------------------------------------------------------------
IMaterialSystemInternal *g_pInternalMaterialSystem = &g_MaterialSystem;
IShaderUtil *g_pShaderUtil = &g_MaterialSystem;
#if defined(USE_SDL)
#include "appframework/ilaunchermgr.h"
ILauncherMgr *g_pLauncherMgr = NULL; // set in CMaterialSystem::Connect
#endif
//-----------------------------------------------------------------------------
// Factory used to get at internal interfaces (used by shaderapi + shader dlls)
//-----------------------------------------------------------------------------
void *ShaderFactory( const char *pName, int *pReturnCode )
{
if (pReturnCode)
{
*pReturnCode = IFACE_OK;
}
if ( !Q_stricmp( pName, FILESYSTEM_INTERFACE_VERSION ))
return g_pFullFileSystem;
if ( !Q_stricmp( pName, QUEUEDLOADER_INTERFACE_VERSION ))
return g_pQueuedLoader;
if ( !Q_stricmp( pName, SHADER_UTIL_INTERFACE_VERSION ))
return g_pShaderUtil;
#ifdef USE_SDL
if ( !Q_stricmp( pName, "SDLMgrInterface001" /*SDLMGR_INTERFACE_VERSION*/ ))
return g_pLauncherMgr;
#endif
void * pInterface = g_MaterialSystem.QueryInterface( pName );
if ( pInterface )
return pInterface;
if ( pReturnCode )
{
*pReturnCode = IFACE_FAILED;
}
return NULL;
}
//-----------------------------------------------------------------------------
// Resource preloading for materials.
//-----------------------------------------------------------------------------
class CResourcePreloadMaterial : public CResourcePreload
{
virtual bool CreateResource( const char *pName )
{
IMaterial *pMaterial = g_MaterialSystem.FindMaterial( pName, TEXTURE_GROUP_WORLD, false );
IMaterialInternal *pMatInternal = static_cast< IMaterialInternal * >( pMaterial );
if ( pMatInternal )
{
// always work with the realtime material internally
pMatInternal = pMatInternal->GetRealTimeVersion();
// tag these for later identification (prevents an unwanted purge)
pMatInternal->MarkAsPreloaded( true );
if ( !pMatInternal->IsErrorMaterial() )
{
// force material's textures to create now
pMatInternal->Precache();
return true;
}
else
{
if ( IsPosix() )
{
printf("\n ##### CResourcePreloadMaterial::CreateResource can't find material %s\n", pName);
}
}
}
return false;
}
//-----------------------------------------------------------------------------
// Called before queued loader i/o jobs are actually performed. Must free up memory
// to ensure i/o requests have enough memory to succeed. The materials that were
// touched by the CreateResource() are inhibited from purging (as is their textures,
// by virtue of ref counts), all others are candidates. The preloaded materials
// are by definition zero ref'd until owned by the normal loading process. Any material
// that stays zero ref'd is a candidate for the post load purge.
//-----------------------------------------------------------------------------
virtual void PurgeUnreferencedResources()
{
bool bSpew = ( g_pQueuedLoader->GetSpewDetail() & LOADER_DETAIL_PURGES ) != 0;
bool bDidUncacheMaterial = false;
MaterialHandle_t hNext;
for ( MaterialHandle_t hMaterial = g_MaterialSystem.FirstMaterial(); hMaterial != g_MaterialSystem.InvalidMaterial(); hMaterial = hNext )
{
hNext = g_MaterialSystem.NextMaterial( hMaterial );
IMaterialInternal *pMatInternal = g_MaterialSystem.GetMaterialInternal( hMaterial );
Assert( pMatInternal->GetReferenceCount() >= 0 );
// preloaded materials are safe from this pre-purge
if ( !pMatInternal->IsPreloaded() )
{
// undo any possible artifical ref count
pMatInternal->ArtificialRelease();
if ( pMatInternal->GetReferenceCount() <= 0 )
{
if ( bSpew )
{
Msg( "CResourcePreloadMaterial: Purging: %s (%d)\n", pMatInternal->GetName(), pMatInternal->GetReferenceCount() );
}
bDidUncacheMaterial = true;
pMatInternal->Uncache();
pMatInternal->DeleteIfUnreferenced();
}
}
else
{
// clear the bit
pMatInternal->MarkAsPreloaded( false );
}
}
// purged materials unreference their textures
// purge any zero ref'd textures
TextureManager()->RemoveUnusedTextures();
// fixup any excluded textures, may cause some new batch requests
MaterialSystem()->UpdateExcludedTextures();
}
virtual void PurgeAll()
{
bool bSpew = ( g_pQueuedLoader->GetSpewDetail() & LOADER_DETAIL_PURGES ) != 0;
bool bDidUncacheMaterial = false;
MaterialHandle_t hNext;
for ( MaterialHandle_t hMaterial = g_MaterialSystem.FirstMaterial(); hMaterial != g_MaterialSystem.InvalidMaterial(); hMaterial = hNext )
{
hNext = g_MaterialSystem.NextMaterial( hMaterial );
IMaterialInternal *pMatInternal = g_MaterialSystem.GetMaterialInternal( hMaterial );
Assert( pMatInternal->GetReferenceCount() >= 0 );
pMatInternal->MarkAsPreloaded( false );
// undo any possible artifical ref count
pMatInternal->ArtificialRelease();
if ( pMatInternal->GetReferenceCount() <= 0 )
{
if ( bSpew )
{
Msg( "CResourcePreloadMaterial: Purging: %s (%d)\n", pMatInternal->GetName(), pMatInternal->GetReferenceCount() );
}
bDidUncacheMaterial = true;
pMatInternal->Uncache();
pMatInternal->DeleteIfUnreferenced();
}
}
// purged materials unreference their textures
// purge any zero ref'd textures
TextureManager()->RemoveUnusedTextures();
}
};
static CResourcePreloadMaterial s_ResourcePreloadMaterial;
//-----------------------------------------------------------------------------
// Resource preloading for cubemaps.
//-----------------------------------------------------------------------------
class CResourcePreloadCubemap : public CResourcePreload
{
virtual bool CreateResource( const char *pName )
{
ITexture *pTexture = g_MaterialSystem.FindTexture( pName, TEXTURE_GROUP_CUBE_MAP, true );
ITextureInternal *pTexInternal = static_cast< ITextureInternal * >( pTexture );
if ( pTexInternal )
{
// There can be cubemaps that are unbound by materials. To prevent an unwanted purge,
// mark and increase the ref count. Otherwise the pre-purge discards these zero
// ref'd textures, and then the normal loading process hitches on the miss.
// The zombie cubemaps DO get discarded after the normal loading process completes
// if no material references them.
pTexInternal->MarkAsPreloaded( true );
pTexInternal->IncrementReferenceCount();
if ( !IsErrorTexture( pTexInternal ) )
{
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// All valid cubemaps should have been owned by their materials. Undo the preloaded
// cubemap locks. Any zero ref'd cubemaps will be purged by the normal loading path conclusion.
//-----------------------------------------------------------------------------
virtual void OnEndMapLoading( bool bAbort )
{
int iIndex = -1;
for ( ;; )
{
ITextureInternal *pTexInternal;
iIndex = TextureManager()->FindNext( iIndex, &pTexInternal );
if ( iIndex == -1 || !pTexInternal )
{
// end of list
break;
}
if ( pTexInternal->IsPreloaded() )
{
// undo the artificial increase
pTexInternal->MarkAsPreloaded( false );
pTexInternal->DecrementReferenceCount();
}
}
}
};
static CResourcePreloadCubemap s_ResourcePreloadCubemap;
//-----------------------------------------------------------------------------
// Creates the debugging materials
//-----------------------------------------------------------------------------
void CMaterialSystem::CreateDebugMaterials()
{
if ( !m_pDrawFlatMaterial )
{
KeyValues *pVMTKeyValues = new KeyValues( "UnlitGeneric" );
pVMTKeyValues->SetInt( "$model", 1 );
pVMTKeyValues->SetFloat( "$decalscale", 0.05f );
pVMTKeyValues->SetString( "$basetexture", "error" ); // This is the "error texture"
g_pErrorMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___error.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "UnlitGeneric" );
pVMTKeyValues->SetInt( "$flat", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pDrawFlatMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___flat.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_NONE] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil0.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$clearcolor", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil1.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$clearalpha", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_ALPHA] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil2.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$clearcolor", 1 );
pVMTKeyValues->SetInt( "$clearalpha", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_ALPHA] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil3.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$cleardepth", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil4.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$cleardepth", 1 );
pVMTKeyValues->SetInt( "$clearcolor", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil5.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$cleardepth", 1 );
pVMTKeyValues->SetInt( "$clearalpha", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_ALPHA_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil6.vmt", pVMTKeyValues ))->GetRealTimeVersion();
pVMTKeyValues = new KeyValues( "BufferClearObeyStencil" );
pVMTKeyValues->SetInt( "$nocull", 1 );
pVMTKeyValues->SetInt( "$cleardepth", 1 );
pVMTKeyValues->SetInt( "$clearcolor", 1 );
pVMTKeyValues->SetInt( "$clearalpha", 1 );
pVMTKeyValues->SetInt( "$vertexcolor", 1 );
m_pBufferClearObeyStencil[BUFFER_CLEAR_COLOR_AND_ALPHA_AND_DEPTH] = static_cast<IMaterialInternal*>(CreateMaterial( "___buffer_clear_obey_stencil7.vmt", pVMTKeyValues ))->GetRealTimeVersion();
if ( IsX360() )
{
pVMTKeyValues = new KeyValues( "RenderTargetBlit_X360" );
m_pRenderTargetBlitMaterial = static_cast<IMaterialInternal*>(CreateMaterial( "___renderTargetBlit.vmt", pVMTKeyValues ))->GetRealTimeVersion();
}
ShaderSystem()->CreateDebugMaterials();
}
}
//-----------------------------------------------------------------------------
// Creates compositor materials
//-----------------------------------------------------------------------------
void CMaterialSystem::CreateCompositorMaterials()
{
// precache composite materials
for ( int i = ECO_FirstPrecacheMaterial; i < ECO_LastPrecacheMaterial; i++ )
{
const char *pszMaterial = GetCombinedMaterialName( ( ECombineOperation ) i );
if ( pszMaterial[ 0 ] == '\0' )
continue;
IMaterialInternal *pMatqf = assert_cast< IMaterialInternal* >( FindMaterial( pszMaterial, TEXTURE_GROUP_RUNTIME_COMPOSITE ) );
Assert( pMatqf );
//Assert( !pMatqf->IsErrorMaterial() );
IMaterialInternal *pMatrt = pMatqf->GetRealTimeVersion();
Assert( pMatrt );
pMatrt->IncrementReferenceCount(); // Hold a ref.
m_pCompositorMaterials.AddToTail( pMatrt );
}
}
//-----------------------------------------------------------------------------
// Cleanup compositor materials
//-----------------------------------------------------------------------------
void CMaterialSystem::CleanUpCompositorMaterials()
{
FOR_EACH_VEC( m_pCompositorMaterials, i )
{
if ( m_pCompositorMaterials[ i ] == NULL )
continue;
m_pCompositorMaterials[ i ]->DecrementReferenceCount();
RemoveMaterial( m_pCompositorMaterials[ i ] );
}
m_pCompositorMaterials.RemoveAll();
}
//-----------------------------------------------------------------------------
// Creates the debugging materials
//-----------------------------------------------------------------------------
void CMaterialSystem::CleanUpDebugMaterials()
{
if ( m_pDrawFlatMaterial )
{
m_pDrawFlatMaterial->DecrementReferenceCount();
RemoveMaterial( m_pDrawFlatMaterial );
m_pDrawFlatMaterial = NULL;
for ( int i = BUFFER_CLEAR_NONE; i < BUFFER_CLEAR_TYPE_COUNT; ++i )
{
m_pBufferClearObeyStencil[i]->DecrementReferenceCount();
RemoveMaterial( m_pBufferClearObeyStencil[i] );
m_pBufferClearObeyStencil[i] = NULL;
}
if ( IsX360() )
{
m_pRenderTargetBlitMaterial->DecrementReferenceCount();
RemoveMaterial( m_pRenderTargetBlitMaterial );
m_pRenderTargetBlitMaterial = NULL;
}
ShaderSystem()->CleanUpDebugMaterials();
}
}
void CMaterialSystem::CleanUpErrorMaterial()
{
// Destruction of g_pErrorMaterial is deferred until after CMaterialDict::Shutdown.
// The global g_pErrorMaterial is set to NULL so that IsErrorMaterial() will return false and
// RemoveMaterial() / DestroyMaterial() will delete it.
IMaterialInternal *pErrorMaterial = g_pErrorMaterial;
g_pErrorMaterial = NULL;
pErrorMaterial->DecrementReferenceCount();
RemoveMaterial( pErrorMaterial );
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CMaterialSystem::CMaterialSystem()
{
m_nRenderThreadID = (uintp)-1;
m_hAsyncLoadFileCache = NULL;
m_ShaderHInst = 0;
m_pMaterialProxyFactory = NULL;
m_nAdapter = 0;
m_nAdapterFlags = 0;
m_bRequestedEditorMaterials = false;
m_bCanUseEditorMaterials = false;
m_StandardTexturesAllocated = false;
m_bInFrame = false;
m_bThreadHasOwnership = false;
m_ThreadOwnershipID = 0;
m_pShaderDLL = NULL;
m_FullbrightLightmapTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_FullbrightBumpedLightmapTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_BlackTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_FlatNormalTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_GreyTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_GreyAlphaZeroTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_WhiteTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_LinearToGammaTableTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_LinearToGammaIdentityTableTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_MaxDepthTextureHandle = INVALID_SHADERAPI_TEXTURE_HANDLE;
m_bInStubMode = false;
m_pForcedTextureLoadPathID = NULL;
m_bAllocatingRenderTargets = false;
m_pRenderContext.Set( &m_HardwareRenderContext );
m_iCurQueuedContext = 0;
#if defined(DEDICATED)
m_bThreadingNotAvailable = true;
m_bForcedSingleThreaded = true;
m_bAllowQueuedRendering = false;
#else
m_bThreadingNotAvailable = false;
m_bForcedSingleThreaded = false;
m_bAllowQueuedRendering = true;
#endif
m_bGeneratedConfig = false;
m_pActiveAsyncJob = NULL;
m_pMatQueueThreadPool = NULL;
m_IdealThreadMode = m_ThreadMode = MATERIAL_SINGLE_THREADED;
m_nServiceThread = 0;
m_nRenderTargetFrameBufferHeightOverride = m_nRenderTargetFrameBufferWidthOverride = 0;
m_bReplacementFilesValid = false;
}
CMaterialSystem::~CMaterialSystem()
{
if (m_pShaderDLL)
{
delete[] m_pShaderDLL;
}
}
//-----------------------------------------------------------------------------
// Creates/destroys the shader implementation for the selected API
//-----------------------------------------------------------------------------
CreateInterfaceFn CMaterialSystem::CreateShaderAPI( char const* pShaderDLL )
{
if ( !pShaderDLL )
return 0;
// Clean up the old shader
DestroyShaderAPI();
// Load the new shader
m_ShaderHInst = Sys_LoadModule( pShaderDLL );
// Error loading the shader
if ( !m_ShaderHInst )
return 0;
// Get our class factory methods...
return Sys_GetFactory( m_ShaderHInst );
}
void CMaterialSystem::DestroyShaderAPI()
{
if (m_ShaderHInst)
{
// NOTE: By unloading the library, this will destroy m_pShaderAPI
Sys_UnloadModule( m_ShaderHInst );
g_pShaderAPI = 0;
g_pHWConfig = 0;
g_pShaderShadow = 0;
m_ShaderHInst = 0;
}
}
//-----------------------------------------------------------------------------
// Sets which shader we should be using. Has to be done before connect!
//-----------------------------------------------------------------------------
void CMaterialSystem::SetShaderAPI( char const *pShaderAPIDLL )
{
if ( m_ShaderAPIFactory )
{
Error( "Cannot set the shader API twice!\n" );
}
if ( !pShaderAPIDLL )
{
pShaderAPIDLL = "shaderapidx9";
}
// m_pShaderDLL is needed to spew driver info
Assert( pShaderAPIDLL );
int len = Q_strlen( pShaderAPIDLL ) + 1;
m_pShaderDLL = new char[len];
memcpy( m_pShaderDLL, pShaderAPIDLL, len );
m_ShaderAPIFactory = CreateShaderAPI( pShaderAPIDLL );
if ( !m_ShaderAPIFactory )
{
DestroyShaderAPI();
}
}
//-----------------------------------------------------------------------------
// Connect/disconnect
//-----------------------------------------------------------------------------
bool CMaterialSystem::Connect( CreateInterfaceFn factory )
{
// __stop__();
if ( !factory )
return false;
if ( !BaseClass::Connect( factory ) )
return false;
if ( !g_pFullFileSystem )
{
Warning( "The material system requires the filesystem to run!\n" );
return false;
}
// Get at the interfaces exported by the shader DLL
g_pShaderDeviceMgr = (IShaderDeviceMgr*)m_ShaderAPIFactory( SHADER_DEVICE_MGR_INTERFACE_VERSION, 0 );
if ( !g_pShaderDeviceMgr )
return false;
g_pHWConfig = (IHardwareConfigInternal*)m_ShaderAPIFactory( MATERIALSYSTEM_HARDWARECONFIG_INTERFACE_VERSION, 0 );
if ( !g_pHWConfig )
return false;
#if !defined(DEDICATED)
#if defined( USE_SDL )
g_pLauncherMgr = (ILauncherMgr *)factory( "SDLMgrInterface001" /*SDL_MGR_INTERFACE_VERSION*/, NULL );
if ( !g_pLauncherMgr )
{
return false;
}
#endif // USE_SDL
#endif // !DEDICATED
// FIXME: ShaderAPI, ShaderDevice, and ShaderShadow should only come in after setting mode
g_pShaderAPI = (IShaderAPI*)m_ShaderAPIFactory( SHADERAPI_INTERFACE_VERSION, 0 );
if ( !g_pShaderAPI )
return false;
g_pShaderDevice = (IShaderDevice*)m_ShaderAPIFactory( SHADER_DEVICE_INTERFACE_VERSION, 0 );
if ( !g_pShaderDevice )
return false;
g_pShaderShadow = (IShaderShadow*)m_ShaderAPIFactory( SHADERSHADOW_INTERFACE_VERSION, 0 );
if ( !g_pShaderShadow )
return false;
// Remember the factory for connect
g_fnMatSystemConnectCreateInterface = factory;
return g_pShaderDeviceMgr->Connect( ShaderFactory );
}
void CMaterialSystem::Disconnect()
{
// Forget the factory for connect
g_fnMatSystemConnectCreateInterface = NULL;
if ( g_pShaderDeviceMgr )
{
g_pShaderDeviceMgr->Disconnect();
g_pShaderDeviceMgr = NULL;
// Unload the DLL
DestroyShaderAPI();
}
g_pShaderAPI = NULL;
g_pHWConfig = NULL;
g_pShaderShadow = NULL;
g_pShaderDevice = NULL;
BaseClass::Disconnect();
}
//-----------------------------------------------------------------------------
// Used to enable editor materials. Must be called before Init.
//-----------------------------------------------------------------------------
void CMaterialSystem::EnableEditorMaterials()
{
m_bRequestedEditorMaterials = true;
}
//-----------------------------------------------------------------------------
// Method to get at interfaces supported by the SHADDERAPI
//-----------------------------------------------------------------------------
void *CMaterialSystem::QueryShaderAPI( const char *pInterfaceName )
{
// Returns various interfaces supported by the shader API dll
void *pInterface = NULL;
if (m_ShaderAPIFactory)
{
pInterface = m_ShaderAPIFactory( pInterfaceName, NULL );
}
return pInterface;
}
//-----------------------------------------------------------------------------
// Method to get at different interfaces supported by the material system
//-----------------------------------------------------------------------------
void *CMaterialSystem::QueryInterface( const char *pInterfaceName )
{
// Returns various interfaces supported by the shader API dll
void *pInterface = QueryShaderAPI( pInterfaceName );
if ( pInterface )
return pInterface;
CreateInterfaceFn factory = Sys_GetFactoryThis(); // This silly construction is necessary
return factory( pInterfaceName, NULL ); // to prevent the LTCG compiler from crashing.
}
//-----------------------------------------------------------------------------
// Must be called before Init(), if you're going to call it at all...
//-----------------------------------------------------------------------------
void CMaterialSystem::SetAdapter( int nAdapter, int nAdapterFlags )
{
m_nAdapter = nAdapter;
m_nAdapterFlags = nAdapterFlags;
}
//-----------------------------------------------------------------------------
// Initializes the color correction terms
//-----------------------------------------------------------------------------
void CMaterialSystem::InitColorCorrection( )
{
if ( ColorCorrectionSystem() )
{
ColorCorrectionSystem()->Init();
}
}
//-----------------------------------------------------------------------------
// Initialization + shutdown of the material system
//-----------------------------------------------------------------------------
InitReturnVal_t CMaterialSystem::Init()
{
InitReturnVal_t nRetVal = BaseClass::Init();
if ( nRetVal != INIT_OK )
return nRetVal;
// NOTE! : Overbright is 1.0 so that Hammer will work properly with the white bumped and unbumped lightmaps.
MathLib_Init( 2.2f, 2.2f, 0.0f, 2.0f );
g_pShaderDeviceMgr->SetAdapter( m_nAdapter, m_nAdapterFlags );
if ( g_pShaderDeviceMgr->Init( ) != INIT_OK )
{
DestroyShaderAPI();
return INIT_FAILED;
}
// Texture manager...
TextureManager()->Init( m_nAdapterFlags );
// Shader system!
ShaderSystem()->Init();
#if defined( WIN32 ) && !defined( _X360 )
// HACKHACK: <sigh> This horrible hack is possibly the only way to reliably detect an old
// version of hammer initializing the material system. We need to know this so that we set
// up the editor materials properly. If we don't do this, we never allocate the white lightmap,
// for example. We can remove this when we update the SDK!!
char szExeName[_MAX_PATH];
if ( ::GetModuleFileName( ( HINSTANCE )GetModuleHandle( NULL ), szExeName, sizeof( szExeName ) ) )
{
char szRight[20];
Q_StrRight( szExeName, 11, szRight, sizeof( szRight ) );
if ( !Q_stricmp( szRight, "\\hammer.exe" ) )
{
m_bRequestedEditorMaterials = true;
}
}
#endif // WIN32
m_bCanUseEditorMaterials = m_bRequestedEditorMaterials;
InitColorCorrection();
// Set up debug materials...
CreateDebugMaterials();
#if !defined(DEDICATED)
CreateCompositorMaterials();
#endif
if ( IsX360() )
{
g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_MATERIAL, &s_ResourcePreloadMaterial );
g_pQueuedLoader->InstallLoader( RESOURCEPRELOAD_CUBEMAP, &s_ResourcePreloadCubemap );
}
// Set up a default material system config
// GenerateConfigFromConfigKeyValues( &g_config, false );
// UpdateConfig( false );
// JAY: Added this command line parameter to force creating <32x32 mips
// to test for reported performance regressions on some systems
if ( CommandLine()->FindParm("-forceallmips") )
{
extern bool g_bForceTextureAllMips;
g_bForceTextureAllMips = true;
}
#if defined(DEDICATED)
m_bThreadingNotAvailable = true;
#else
for ( int i = 0; i < ARRAYSIZE( m_QueuedRenderContexts ); i++ )
{
if ( !m_QueuedRenderContexts[i].IsInitialized() )
{
if ( !m_QueuedRenderContexts[i].Init( this, &m_HardwareRenderContext ) )
{
m_bThreadingNotAvailable = true;
break;
}
}
}
#endif
return m_HardwareRenderContext.Init( this );
}
//-----------------------------------------------------------------------------
// For backwards compatability
//-----------------------------------------------------------------------------
static CreateInterfaceFn s_TempCVarFactory;
static CreateInterfaceFn s_TempFileSystemFactory;
void* TempCreateInterface( const char *pName, int *pReturnCode )
{
void *pRetVal = NULL;
if ( s_TempCVarFactory )
{
pRetVal = s_TempCVarFactory( pName, pReturnCode );
if (pRetVal)
return pRetVal;
}
pRetVal = s_TempFileSystemFactory( pName, pReturnCode );
if (pRetVal)
return pRetVal;
return NULL;
}
//-----------------------------------------------------------------------------
// Initializes and shuts down the shader API
//-----------------------------------------------------------------------------
CreateInterfaceFn CMaterialSystem::Init( char const* pShaderAPIDLL,
IMaterialProxyFactory *pMaterialProxyFactory,
CreateInterfaceFn fileSystemFactory,
CreateInterfaceFn cvarFactory )
{
SetShaderAPI( pShaderAPIDLL );
s_TempCVarFactory = cvarFactory;
s_TempFileSystemFactory = fileSystemFactory;
if ( !Connect( TempCreateInterface ) )
return 0;
if (Init() != INIT_OK)
return NULL;
// save the proxy factory
m_pMaterialProxyFactory = pMaterialProxyFactory;
return m_ShaderAPIFactory;
}
void CMaterialSystem::Shutdown( )
{
DestroyMatQueueThreadPool();
m_HardwareRenderContext.Shutdown();
// Clean up standard textures
ReleaseStandardTextures();
CleanUpCompositorMaterials();
// Clean up the debug materials
CleanUpDebugMaterials();
g_pMorphMgr->FreeMaterials();
g_pOcclusionQueryMgr->FreeOcclusionQueryObjects();
GetLightmaps()->Shutdown();
m_MaterialDict.Shutdown();
CleanUpErrorMaterial();
// Shader system!
ShaderSystem()->Shutdown();
// Texture manager...
TextureManager()->Shutdown();
if (g_pShaderDeviceMgr)
{
g_pShaderDeviceMgr->Shutdown();
}
BaseClass::Shutdown();
}
void CMaterialSystem::ModInit()
{
// Set up a default material system config
GenerateConfigFromConfigKeyValues( &g_config, false );
UpdateConfig( false );
// Shader system!
ShaderSystem()->ModInit();
}
void CMaterialSystem::ModShutdown()
{
// Shader system!
ShaderSystem()->ModShutdown();
// HACK - this is here to unhook ourselves from the client interface, since we're not actually notified when it happens
m_pMaterialProxyFactory = NULL;
}
//-----------------------------------------------------------------------------
// Returns the current adapter in use
//-----------------------------------------------------------------------------
IMaterialSystemHardwareConfig *CMaterialSystem::GetHardwareConfig( const char *pVersion, int *returnCode )
{
return ( IMaterialSystemHardwareConfig * )m_ShaderAPIFactory( pVersion, returnCode );
}
//-----------------------------------------------------------------------------
// Returns the current adapter in use
//-----------------------------------------------------------------------------
int CMaterialSystem::GetCurrentAdapter() const
{
return g_pShaderDevice->GetCurrentAdapter();
}
//-----------------------------------------------------------------------------
// Returns the device name for the current adapter
//-----------------------------------------------------------------------------
char *CMaterialSystem::GetDisplayDeviceName() const
{
return g_pShaderDevice->GetDisplayDeviceName();
}
//-----------------------------------------------------------------------------