forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shadersystem.cpp
2071 lines (1746 loc) · 63.8 KB
/
shadersystem.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 "shadersystem.h"
#include <stdlib.h>
#include "materialsystem_global.h"
#include "filesystem.h"
#include "tier1/utldict.h"
#include "shaderlib/ShaderDLL.h"
#include "texturemanager.h"
#include "itextureinternal.h"
#include "IHardwareConfigInternal.h"
#include "tier1/utlstack.h"
#include "tier1/utlbuffer.h"
#include "mathlib/vmatrix.h"
#include "imaterialinternal.h"
#include "tier1/strtools.h"
#include "tier0/icommandline.h"
#include "shaderlib/cshader.h"
#include "tier1/convar.h"
#include "tier1/KeyValues.h"
#include "shader_dll_verify.h"
#include "tier0/vprof.h"
// NOTE: This must be the last file included!
#include "tier0/memdbgon.h"
#include "mat_stub.h"
//#define DEBUG_DEPTH 1
CDummyTextureInternal g_BitchCubemapTexture("bitch_cubemap");
//-----------------------------------------------------------------------------
// Lovely convars
//-----------------------------------------------------------------------------
static ConVar mat_showenvmapmask( "mat_showenvmapmask", "0" );
static ConVar mat_debugdepth( "mat_debugdepth", "0" );
extern ConVar mat_supportflashlight;
//-----------------------------------------------------------------------------
// Implementation of the shader system
//-----------------------------------------------------------------------------
class CShaderSystem : public IShaderSystemInternal
{
public:
CShaderSystem();
// Methods of IShaderSystem
virtual ShaderAPITextureHandle_t GetShaderAPITextureBindHandle( ITexture *pTexture, int nFrameVar, int nTextureChannel = 0 );
virtual void BindTexture( Sampler_t sampler1, ITexture *pTexture, int nFrame = 0 );
virtual void BindTexture( Sampler_t sampler1, Sampler_t sampler2, ITexture *pTexture, int nFrame = 0 );
virtual void TakeSnapshot( );
virtual void DrawSnapshot( bool bMakeActualDrawCall = true );
virtual bool IsUsingGraphics() const;
virtual bool CanUseEditorMaterials() const;
// Methods of IShaderSystemInternal
virtual void Init();
virtual void Shutdown();
virtual void ModInit();
virtual void ModShutdown();
virtual bool LoadShaderDLL( const char *pFullPath );
virtual bool LoadShaderDLL( const char *pFullPath, const char *pPathID, bool bModShaderDLL );
virtual void UnloadShaderDLL( const char *pFullPath );
virtual IShader* FindShader( char const* pShaderName );
virtual void CreateDebugMaterials();
virtual void CleanUpDebugMaterials();
virtual char const* ShaderStateString( int i ) const;
virtual int ShaderStateCount( ) const;
virtual void InitShaderParameters( IShader *pShader, IMaterialVar **params, const char *pMaterialName );
virtual void InitShaderInstance( IShader *pShader, IMaterialVar **params, const char *pMaterialName, const char *pTextureGroupName );
virtual bool InitRenderState( IShader *pShader, int numParams, IMaterialVar **params, ShaderRenderState_t* pRenderState, char const* pMaterialName );
virtual void CleanupRenderState( ShaderRenderState_t* pRenderState );
virtual void DrawElements( IShader *pShader, IMaterialVar **params, ShaderRenderState_t* pShaderState, VertexCompressionType_t vertexCompression, uint32 nVarChangeID );
// Used to iterate over all shaders for editing purposes
virtual int ShaderCount() const;
virtual int GetShaders( int nFirstShader, int nMaxCount, IShader **ppShaderList ) const;
// Methods of IShaderInit
virtual void LoadTexture( IMaterialVar *pTextureVar, const char *pTextureGroupName, int nAdditionalCreationFlags = 0 );
virtual void LoadBumpMap( IMaterialVar *pTextureVar, const char *pTextureGroupName );
virtual void LoadCubeMap( IMaterialVar **ppParams, IMaterialVar *pTextureVar, int nAdditionalCreationFlags = 0 );
// Used to prevent re-entrant rendering from warning messages
void BufferSpew( SpewType_t spewType, const Color &c, const char *pMsg );
virtual void LockSpew(bool lock) { m_bLockSpew = lock; }
private:
struct ShaderDLLInfo_t
{
char *m_pFileName;
CSysModule *m_hInstance;
IShaderDLLInternal *m_pShaderDLL;
ShaderDLL_t m_hShaderDLL;
// True if this is a mod's shader DLL, in which case it's not allowed to
// override any existing shader names.
bool m_bModShaderDLL;
CUtlDict< IShader *, unsigned short > m_ShaderDict;
};
private:
// hackhack: remove this when VAC2 is online.
void VerifyBaseShaderDLL( CSysModule *pModule );
// Load up the shader DLLs...
void LoadAllShaderDLLs();
// Load the "mshader_" DLLs.
void LoadModShaderDLLs( int dxSupportLevel );
// Unload all the shader DLLs...
void UnloadAllShaderDLLs();
// Sets up the shader dictionary.
void SetupShaderDictionary( int nShaderDLLIndex );
// Cleans up the shader dictionary.
void CleanupShaderDictionary( int nShaderDLLIndex );
// Finds an already loaded shader DLL
int FindShaderDLL( const char *pFullPath );
// Unloads a particular shader DLL
void UnloadShaderDLL( int nShaderDLLIndex );
// Sets up the current ShaderState_t for rendering
void PrepForShaderDraw( IShader *pShader, IMaterialVar** ppParams,
ShaderRenderState_t* pRenderState, int modulation );
void DoneWithShaderDraw();
// Initializes state snapshots
void InitStateSnapshots( IShader *pShader, IMaterialVar **params, ShaderRenderState_t* pRenderState );
// Compute snapshots for all combinations of alpha + color modulation
void InitRenderStateFlags( ShaderRenderState_t* pRenderState, int numParams, IMaterialVar **params );
// Computes flags from a particular snapshot
void ComputeRenderStateFlagsFromSnapshot( ShaderRenderState_t* pRenderState );
// Computes vertex format + usage from a particular snapshot
bool ComputeVertexFormatFromSnapshot( IMaterialVar **params, ShaderRenderState_t* pRenderState );
// Used to prevent re-entrant rendering from warning messages
void PrintBufferedSpew( void );
// Gets at the current snapshot
StateSnapshot_t CurrentStateSnapshot();
// Draws using a particular material..
void DrawUsingMaterial( IMaterialInternal *pMaterial, VertexCompressionType_t vertexCompression );
// Copies material vars
void CopyMaterialVarToDebugShader( IMaterialInternal *pDebugMaterial, IShader *pShader, IMaterialVar **ppParams, const char *pSrcVarName, const char *pDstVarName = NULL );
// Debugging draw methods...
void DrawMeasureFillRate( ShaderRenderState_t* pRenderState, int mod, VertexCompressionType_t vertexCompression );
void DrawNormalMap( IShader *pShader, IMaterialVar **ppParams, VertexCompressionType_t vertexCompression );
bool DrawEnvmapMask( IShader *pShader, IMaterialVar **ppParams, ShaderRenderState_t* pRenderState, VertexCompressionType_t vertexCompression );
int GetModulationSnapshotCount( IMaterialVar **params );
private:
bool m_bLockSpew;
bool m_bOrigLock;
// List of all DLLs containing shaders
CUtlVector< ShaderDLLInfo_t > m_ShaderDLLs;
// Used to prevent re-entrant rendering from warning messages
SpewOutputFunc_t m_SaveSpewOutput;
CUtlBuffer m_StoredSpew;
// Render state we're drawing with
ShaderRenderState_t* m_pRenderState;
unsigned short m_hShaderDLL;
unsigned char m_nModulation;
unsigned char m_nRenderPass;
// Debugging materials
// If you add to this, add to the list of debug shader names (s_pDebugShaderName) below
enum
{
MATERIAL_FILL_RATE = 0,
MATERIAL_DEBUG_NORMALMAP,
MATERIAL_DEBUG_ENVMAPMASK,
MATERIAL_DEBUG_DEPTH,
MATERIAL_DEBUG_DEPTH_DECAL,
MATERIAL_DEBUG_WIREFRAME,
MATERIAL_DEBUG_COUNT,
};
IMaterialInternal* m_pDebugMaterials[MATERIAL_DEBUG_COUNT];
static const char *s_pDebugShaderName[MATERIAL_DEBUG_COUNT];
bool m_bForceUsingGraphicsReturnTrue;
};
//-----------------------------------------------------------------------------
// Singleton
//-----------------------------------------------------------------------------
static CShaderSystem s_ShaderSystem;
IShaderSystemInternal *g_pShaderSystem = &s_ShaderSystem;
EXPOSE_SINGLE_INTERFACE_GLOBALVAR( CShaderSystem, IShaderSystem,
SHADERSYSTEM_INTERFACE_VERSION, s_ShaderSystem );
//-----------------------------------------------------------------------------
// Debugging shader names
//-----------------------------------------------------------------------------
const char *CShaderSystem::s_pDebugShaderName[MATERIAL_DEBUG_COUNT] =
{
"FillRate",
"DebugNormalMap",
"DebugDrawEnvmapMask",
"DebugDepth",
"DebugDepth",
"Wireframe_DX9"
};
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CShaderSystem::CShaderSystem() : m_StoredSpew( 0, 512, 0 ), m_bForceUsingGraphicsReturnTrue( false )
{
}
//-----------------------------------------------------------------------------
// Initialization, shutdown
//-----------------------------------------------------------------------------
void CShaderSystem::Init()
{
m_SaveSpewOutput = NULL;
m_bForceUsingGraphicsReturnTrue = false;
if ( CommandLine()->FindParm( "-noshaderapi" ) ||
CommandLine()->FindParm( "-makereslists" ) )
{
m_bForceUsingGraphicsReturnTrue = true;
}
for ( int i = 0; i < MATERIAL_DEBUG_COUNT; ++i )
{
m_pDebugMaterials[i] = NULL;
}
LoadAllShaderDLLs();
}
void CShaderSystem::Shutdown()
{
UnloadAllShaderDLLs();
}
//-----------------------------------------------------------------------------
// Load/unload mod-specific shader DLLs
//-----------------------------------------------------------------------------
void CShaderSystem::ModInit()
{
// Load up standard shader DLLs...
int dxSupportLevel = HardwareConfig()->GetMaxDXSupportLevel();
Assert( dxSupportLevel >= 60 );
dxSupportLevel /= 10;
LoadModShaderDLLs( dxSupportLevel );
}
void CShaderSystem::ModShutdown()
{
// Unload only MOD dlls
for ( int i = m_ShaderDLLs.Count(); --i >= 0; )
{
if ( m_ShaderDLLs[i].m_bModShaderDLL )
{
UnloadShaderDLL(i);
delete[] m_ShaderDLLs[i].m_pFileName;
m_ShaderDLLs.Remove( i );
}
}
}
//-----------------------------------------------------------------------------
// Load up the shader DLLs...
//-----------------------------------------------------------------------------
void CShaderSystem::LoadAllShaderDLLs( )
{
UnloadAllShaderDLLs();
GetShaderDLLInternal()->Connect( Sys_GetFactoryThis(), true );
// Loads local defined or statically linked shaders
int i = m_ShaderDLLs.AddToHead();
m_ShaderDLLs[i].m_pFileName = new char[1];
m_ShaderDLLs[i].m_pFileName[0] = 0;
m_ShaderDLLs[i].m_hInstance = NULL;
m_ShaderDLLs[i].m_pShaderDLL = GetShaderDLLInternal();
m_ShaderDLLs[i].m_bModShaderDLL = false;
// Add the shaders to the dictionary of shaders...
SetupShaderDictionary( i );
// 360 has the the debug shaders in its dx9 dll
if ( IsPC() || !IsX360() )
{
// Always need the debug shaders
LoadShaderDLL( "stdshader_dbg" DLL_EXT_STRING );
}
// Load up standard shader DLLs...
int dxSupportLevel = HardwareConfig()->GetMaxDXSupportLevel();
Assert( dxSupportLevel >= 60 );
dxSupportLevel /= 10;
// 360 only supports its dx9 dll
int dxStart = IsX360() ? 9 : 6;
char buf[32];
for ( i = dxStart; i <= dxSupportLevel; ++i )
{
Q_snprintf( buf, sizeof( buf ), "stdshader_dx%d%s", i, DLL_EXT_STRING );
LoadShaderDLL( buf );
}
const char *pShaderName = NULL;
#ifdef _DEBUG
pShaderName = CommandLine()->ParmValue( "-shader" );
#endif
if ( !pShaderName )
{
pShaderName = HardwareConfig()->GetHWSpecificShaderDLLName();
}
if ( pShaderName )
{
LoadShaderDLL( pShaderName );
}
#ifdef _DEBUG
// For fast-iteration debugging
if ( CommandLine()->FindParm( "-testshaders" ) )
{
LoadShaderDLL( "shader_test" DLL_EXT_STRING );
}
#endif
}
const char *COM_GetModDirectory()
{
static char modDir[MAX_PATH];
if ( Q_strlen( modDir ) == 0 )
{
const char *gamedir = CommandLine()->ParmValue("-game", CommandLine()->ParmValue( "-defaultgamedir", "hl2" ) );
Q_strncpy( modDir, gamedir, sizeof(modDir) );
if ( strchr( modDir, '/' ) || strchr( modDir, '\\' ) )
{
Q_StripLastDir( modDir, sizeof(modDir) );
int dirlen = Q_strlen( modDir );
Q_strncpy( modDir, gamedir + dirlen, sizeof(modDir) - dirlen );
}
}
return modDir;
}
void CShaderSystem::LoadModShaderDLLs( int dxSupportLevel )
{
if ( IsX360() )
return;
// Don't do this for Valve mods. They don't need them, and attempting to load them is an opportunity for cheaters to get their code into the process
const char *pGameDir = COM_GetModDirectory();
if ( !Q_stricmp( pGameDir, "hl2" ) || !Q_stricmp( pGameDir, "cstrike" ) || !Q_stricmp( pGameDir, "cstrike_beta" ) ||
!Q_stricmp( pGameDir, "hl2mp" ) || !Q_stricmp( pGameDir, "lostcoast" ) || !Q_stricmp( pGameDir, "episodic" ) ||
!Q_stricmp( pGameDir, "portal" ) || !Q_stricmp( pGameDir, "ep2" ) || !Q_stricmp( pGameDir, "dod" ) ||
!Q_stricmp( pGameDir, "tf" ) || !Q_stricmp( pGameDir, "tf_beta" ) || !Q_stricmp( pGameDir, "hl1" ) )
{
return;
}
const char *pModShaderPathID = "GAMEBIN";
// First load the ones with dx_ prefix.
char buf[256];
int dxStart = 6;
for ( int i = dxStart; i <= dxSupportLevel; ++i )
{
Q_snprintf( buf, sizeof( buf ), "game_shader_dx%d%s", i, DLL_EXT_STRING );
LoadShaderDLL( buf, pModShaderPathID, true );
}
// Now load the ones with any dx_ prefix.
FileFindHandle_t findHandle;
const char *pFilename = g_pFullFileSystem->FindFirstEx( "game_shader_generic*", pModShaderPathID, &findHandle );
while ( pFilename )
{
Q_snprintf( buf, sizeof( buf ), "%s%s", pFilename, DLL_EXT_STRING );
LoadShaderDLL( buf, pModShaderPathID, true );
pFilename = g_pFullFileSystem->FindNext( findHandle );
}
}
//-----------------------------------------------------------------------------
// Unload all the shader DLLs...
//-----------------------------------------------------------------------------
void CShaderSystem::UnloadAllShaderDLLs()
{
if ( m_ShaderDLLs.Count() == 0 )
return;
for ( int i = m_ShaderDLLs.Count(); --i >= 0; )
{
UnloadShaderDLL(i);
delete[] m_ShaderDLLs[i].m_pFileName;
}
m_ShaderDLLs.RemoveAll();
}
bool CShaderSystem::LoadShaderDLL( const char *pFullPath )
{
return LoadShaderDLL( pFullPath, NULL, false );
}
// HACKHACK: remove me when VAC2 is online.
#if defined( _WIN32 ) && !defined( _X360 )
// Instead of including windows.h
extern "C"
{
extern void * __stdcall GetProcAddress( void *hModule, const char *pszProcName );
};
#endif
void CShaderSystem::VerifyBaseShaderDLL( CSysModule *pModule )
{
//#if defined( _WIN32 ) && !defined( _X360 )
#if 0
const char *pErrorStr = "Corrupt save data settings.";
unsigned char *testData1 = new unsigned char[SHADER_DLL_VERIFY_DATA_LEN1];
ShaderDLLVerifyFn fn = (ShaderDLLVerifyFn)GetProcAddress( (void *)pModule, SHADER_DLL_FNNAME_1 );
if ( !fn )
Error( pErrorStr );
IShaderDLLVerification *pVerify;
char *pPtr = (char*)(void*)&pVerify;
pPtr -= SHADER_DLL_VERIFY_DATA_PTR_OFFSET;
fn( pPtr );
// Test the first CRC.
CRC32_t testCRC;
CRC32_Init( &testCRC );
CRC32_ProcessBuffer( &testCRC, testData1, SHADER_DLL_VERIFY_DATA_LEN1 );
CRC32_ProcessBuffer( &testCRC, &pModule, 4 );
CRC32_ProcessBuffer( &testCRC, &pVerify, 4 );
CRC32_Final( &testCRC );
if ( testCRC != pVerify->Function1( testData1 - SHADER_DLL_VERIFY_DATA_PTR_OFFSET ) )
Error( pErrorStr );
// Test the next one.
unsigned char digest[MD5_DIGEST_LENGTH];
MD5Context_t md5Context;
MD5Init( &md5Context );
MD5Update( &md5Context, testData1 + SHADER_DLL_VERIFY_DATA_PTR_OFFSET, SHADER_DLL_VERIFY_DATA_LEN1 - SHADER_DLL_VERIFY_DATA_PTR_OFFSET );
MD5Final( digest, &md5Context );
pVerify->Function2( 2, 3, 3 ); // fn2 is supposed to place the result in testData1.
if ( memcmp( digest, testData1, MD5_DIGEST_LENGTH ) != 0 )
Error( pErrorStr );
pVerify->Function5();
delete [] testData1;
#endif
}
//-----------------------------------------------------------------------------
// Methods related to reading in shader DLLs
//-----------------------------------------------------------------------------
bool CShaderSystem::LoadShaderDLL( const char *pFullPath, const char *pPathID, bool bModShaderDLL )
{
if ( !pFullPath && !pFullPath[0] )
return true;
// Load the new shader
bool bValidatedDllOnly = true;
if ( bModShaderDLL )
bValidatedDllOnly = false;
CSysModule *hInstance = g_pFullFileSystem->LoadModule( pFullPath, pPathID, bValidatedDllOnly );
if ( !hInstance )
return false;
// Get at the shader DLL interface
CreateInterfaceFn factory = Sys_GetFactory( hInstance );
if (!factory)
{
g_pFullFileSystem->UnloadModule( hInstance );
return false;
}
IShaderDLLInternal *pShaderDLL = (IShaderDLLInternal*)factory( SHADER_DLL_INTERFACE_VERSION, NULL );
if ( !pShaderDLL )
{
g_pFullFileSystem->UnloadModule( hInstance );
return false;
}
// Make sure it's a valid base shader DLL if necessary.
//HACKHACK get rid of this when VAC2 comes online.
if ( !bModShaderDLL )
{
VerifyBaseShaderDLL( hInstance );
}
// Allow the DLL to try to connect to interfaces it needs
if ( !pShaderDLL->Connect( Sys_GetFactoryThis(), false ) )
{
g_pFullFileSystem->UnloadModule( hInstance );
return false;
}
// FIXME: We need to do some sort of shader validation here for anticheat.
// Now replace any existing shader
int nShaderDLLIndex = FindShaderDLL( pFullPath );
if ( nShaderDLLIndex >= 0 )
{
UnloadShaderDLL( nShaderDLLIndex );
}
else
{
nShaderDLLIndex = m_ShaderDLLs.AddToTail();
int nLen = Q_strlen(pFullPath) + 1;
m_ShaderDLLs[nShaderDLLIndex].m_pFileName = new char[ nLen ];
Q_strncpy( m_ShaderDLLs[nShaderDLLIndex].m_pFileName, pFullPath, nLen );
}
// Ok, the shader DLL's good!
m_ShaderDLLs[nShaderDLLIndex].m_hInstance = hInstance;
m_ShaderDLLs[nShaderDLLIndex].m_pShaderDLL = pShaderDLL;
m_ShaderDLLs[nShaderDLLIndex].m_bModShaderDLL = bModShaderDLL;
// Add the shaders to the dictionary of shaders...
SetupShaderDictionary( nShaderDLLIndex );
// FIXME: Fix up existing materials that were using shaders that have
// been reloaded?
return true;
}
//-----------------------------------------------------------------------------
// Finds an already loaded shader DLL
//-----------------------------------------------------------------------------
int CShaderSystem::FindShaderDLL( const char *pFullPath )
{
for ( int i = m_ShaderDLLs.Count(); --i >= 0; )
{
if ( !Q_stricmp( pFullPath, m_ShaderDLLs[i].m_pFileName ) )
return i;
}
return -1;
}
//-----------------------------------------------------------------------------
// Unloads a particular shader DLL
//-----------------------------------------------------------------------------
void CShaderSystem::UnloadShaderDLL( int nShaderDLLIndex )
{
if ( nShaderDLLIndex < 0 )
return;
// FIXME: Do some sort of fixup of materials to determine which
// materials are referencing shaders in this DLL?
CleanupShaderDictionary( nShaderDLLIndex );
IShaderDLLInternal *pShaderDLL = m_ShaderDLLs[nShaderDLLIndex].m_pShaderDLL;
pShaderDLL->Disconnect( pShaderDLL == GetShaderDLLInternal() );
if ( m_ShaderDLLs[nShaderDLLIndex].m_hInstance )
{
g_pFullFileSystem->UnloadModule( m_ShaderDLLs[nShaderDLLIndex].m_hInstance );
}
}
//-----------------------------------------------------------------------------
// Unloads a particular shader DLL
//-----------------------------------------------------------------------------
void CShaderSystem::UnloadShaderDLL( const char *pFullPath )
{
int nShaderDLLIndex = FindShaderDLL( pFullPath );
if ( nShaderDLLIndex >= 0 )
{
UnloadShaderDLL( nShaderDLLIndex );
delete[] m_ShaderDLLs[nShaderDLLIndex].m_pFileName;
m_ShaderDLLs.Remove( nShaderDLLIndex );
}
}
//-----------------------------------------------------------------------------
// Make sure these match the bits in imaterial.h
//-----------------------------------------------------------------------------
static const char* s_pShaderStateString[] =
{
"$debug",
"$no_fullbright",
"$no_draw",
"$use_in_fillrate_mode",
"$vertexcolor",
"$vertexalpha",
"$selfillum",
"$additive",
"$alphatest",
"$multipass",
"$znearer",
"$model",
"$flat",
"$nocull",
"$nofog",
"$ignorez",
"$decal",
"$envmapsphere",
"$noalphamod",
"$envmapcameraspace",
"$basealphaenvmapmask",
"$translucent",
"$normalmapalphaenvmapmask",
"$softwareskin",
"$opaquetexture",
"$envmapmode",
"$nodecal",
"$halflambert",
"$wireframe",
"$allowalphatocoverage",
"" // last one must be null
};
//-----------------------------------------------------------------------------
// returns strings associated with the shader state flags...
// If you modify this, make sure and modify MaterialVarFlags_t in imaterial.h
//-----------------------------------------------------------------------------
int CShaderSystem::ShaderStateCount( ) const
{
return sizeof( s_pShaderStateString ) / sizeof( char* ) - 1;
}
//-----------------------------------------------------------------------------
// returns strings associated with the shader state flags...
// If you modify this, make sure and modify MaterialVarFlags_t in imaterial.h
//-----------------------------------------------------------------------------
char const* CShaderSystem::ShaderStateString( int i ) const
{
return s_pShaderStateString[i];
}
//-----------------------------------------------------------------------------
// Sets up the shader dictionary.
//-----------------------------------------------------------------------------
void CShaderSystem::SetupShaderDictionary( int nShaderDLLIndex )
{
// We could have put the shader dictionary into each shader DLL
// I'm not sure if that makes this system any less secure than it already is
int i;
ShaderDLLInfo_t &info = m_ShaderDLLs[nShaderDLLIndex];
int nCount = info.m_pShaderDLL->ShaderCount();
for ( i = 0; i < nCount; ++i )
{
IShader *pShader = info.m_pShaderDLL->GetShader( i );
const char *pShaderName = pShader->GetName();
#ifdef POSIX
if (CommandLine()->FindParm("-glmspew"))
printf("CShaderSystem::SetupShaderDictionary: %s", pShaderName );
#endif
// Make sure it doesn't try to override another shader DLL's names.
if ( info.m_bModShaderDLL )
{
for ( int iTestDLL=0; iTestDLL < m_ShaderDLLs.Count(); iTestDLL++ )
{
ShaderDLLInfo_t *pTestDLL = &m_ShaderDLLs[iTestDLL];
if ( !pTestDLL->m_bModShaderDLL )
{
if ( pTestDLL->m_ShaderDict.Find( pShaderName ) != pTestDLL->m_ShaderDict.InvalidIndex() )
{
Error( "Game shader '%s' trying to override a base shader '%s'.", info.m_pFileName, pShaderName );
}
}
}
}
info.m_ShaderDict.Insert( pShaderName, pShader );
}
}
//-----------------------------------------------------------------------------
// Cleans up the shader dictionary.
//-----------------------------------------------------------------------------
void CShaderSystem::CleanupShaderDictionary( int nShaderDLLIndex )
{
}
//-----------------------------------------------------------------------------
// Finds a shader in the shader dictionary
//-----------------------------------------------------------------------------
IShader* CShaderSystem::FindShader( char const* pShaderName )
{
// FIXME: What kind of search order should we use here?
// I'm currently assuming last added, first searched.
for (int i = m_ShaderDLLs.Count(); --i >= 0; )
{
ShaderDLLInfo_t &info = m_ShaderDLLs[i];
unsigned short idx = info.m_ShaderDict.Find( pShaderName );
if ( idx != info.m_ShaderDict.InvalidIndex() )
{
return info.m_ShaderDict[idx];
}
}
return NULL;
}
//-----------------------------------------------------------------------------
// Used to iterate over all shaders for editing purposes
//-----------------------------------------------------------------------------
int CShaderSystem::ShaderCount() const
{
return GetShaders( 0, 65536, NULL );
}
int CShaderSystem::GetShaders( int nFirstShader, int nMaxCount, IShader **ppShaderList ) const
{
CUtlSymbolTable uniqueNames( 0, 512, true );
int nCount = 0;
int nActualCount = 0;
for ( int i = m_ShaderDLLs.Count(); --i >= 0; )
{
const ShaderDLLInfo_t &info = m_ShaderDLLs[i];
for ( unsigned short j = info.m_ShaderDict.First();
j != info.m_ShaderDict.InvalidIndex();
j = info.m_ShaderDict.Next( j ) )
{
// Don't add shaders twice
const char *pShaderName = info.m_ShaderDict.GetElementName( j );
if ( uniqueNames.Find( pShaderName ) != UTL_INVAL_SYMBOL )
continue;
// Indicate we've seen this shader
uniqueNames.AddString( pShaderName );
++nActualCount;
if ( nActualCount > nFirstShader )
{
if ( ppShaderList )
{
ppShaderList[ nCount ] = info.m_ShaderDict[j];
}
++nCount;
if ( nCount >= nMaxCount )
return nCount;
}
}
}
return nCount;
}
//-----------------------------------------------------------------------------
//
// Methods of IShaderInit lie below
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Gets at the render pass info for this pass...
//-----------------------------------------------------------------------------
inline StateSnapshot_t CShaderSystem::CurrentStateSnapshot()
{
Assert( m_pRenderState );
Assert( m_nRenderPass < MAX_RENDER_PASSES );
Assert( m_nRenderPass < m_pRenderState->m_pSnapshots[m_nModulation].m_nPassCount );
return m_pRenderState->m_pSnapshots[m_nModulation].m_Snapshot[m_nRenderPass];
}
//-----------------------------------------------------------------------------
// Create debugging materials
//-----------------------------------------------------------------------------
void CShaderSystem::CreateDebugMaterials()
{
if (m_pDebugMaterials[0])
return;
KeyValues *pVMTKeyValues[MATERIAL_DEBUG_COUNT];
int i;
for ( i = 0; i < MATERIAL_DEBUG_COUNT; ++i )
{
pVMTKeyValues[i] = new KeyValues( s_pDebugShaderName[i] );
}
pVMTKeyValues[MATERIAL_DEBUG_DEPTH_DECAL]->SetInt( "$decal", 1 );
for ( i = 0; i < MATERIAL_DEBUG_COUNT; ++i )
{
char shaderName[64];
Q_snprintf( shaderName, sizeof( shaderName ), "___%s_%d.vmt", s_pDebugShaderName[i], i );
m_pDebugMaterials[i] = static_cast<IMaterialInternal*>(MaterialSystem()->CreateMaterial( shaderName, pVMTKeyValues[i] ));
if( m_pDebugMaterials[i] )
m_pDebugMaterials[i] = m_pDebugMaterials[i]->GetRealTimeVersion();
}
}
//-----------------------------------------------------------------------------
// Cleans up the debugging materials
//-----------------------------------------------------------------------------
void CShaderSystem::CleanUpDebugMaterials()
{
if (m_pDebugMaterials[0])
{
for ( int i = 0; i < MATERIAL_DEBUG_COUNT; ++i )
{
m_pDebugMaterials[i]->DecrementReferenceCount();
if ( m_pDebugMaterials[i]->InMaterialPage() )
{
MaterialSystem()->RemoveMaterialSubRect( m_pDebugMaterials[i] );
}
else
{
MaterialSystem()->RemoveMaterial( m_pDebugMaterials[i] );
}
m_pDebugMaterials[i] = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Deal with buffering of spew while doing shader draw so that we don't get
// recursive spew during precache due to fonts not being loaded, etc.
//-----------------------------------------------------------------------------
CThreadFastMutex g_StgoredSpewMutex;
void CShaderSystem::BufferSpew( SpewType_t spewType, const Color &c, const char *pMsg )
{
AUTO_LOCK( g_StgoredSpewMutex );
m_StoredSpew.PutInt( spewType );
m_StoredSpew.PutChar( c.r() );
m_StoredSpew.PutChar( c.g() );
m_StoredSpew.PutChar( c.b() );
m_StoredSpew.PutChar( c.a() );
m_StoredSpew.PutString( pMsg );
}
void CShaderSystem::PrintBufferedSpew( void )
{
AUTO_LOCK( g_StgoredSpewMutex );
while ( m_StoredSpew.GetBytesRemaining() > 0 )
{
SpewType_t spewType = (SpewType_t)m_StoredSpew.GetInt();
unsigned char r, g, b, a;
r = m_StoredSpew.GetChar();
g = m_StoredSpew.GetChar();
b = m_StoredSpew.GetChar();
a = m_StoredSpew.GetChar();
Color c( r, g, b, a );
int nLen = m_StoredSpew.PeekStringLength();
if ( nLen )
{
char *pBuf = (char*)_alloca( nLen );
m_StoredSpew.GetStringManualCharCount( pBuf, nLen );
ColorSpewMessage( spewType, &c, "%s", pBuf );
}
else
{
break;
}
}
m_StoredSpew.Clear();
}
static SpewRetval_t MySpewOutputFunc( SpewType_t spewType, char const *pMsg )
{
AUTO_LOCK( g_StgoredSpewMutex );
Color c = *GetSpewOutputColor();
s_ShaderSystem.BufferSpew( spewType, c, pMsg );
switch( spewType )
{
case SPEW_MESSAGE:
case SPEW_WARNING:
case SPEW_LOG:
return SPEW_CONTINUE;
case SPEW_ASSERT:
case SPEW_ERROR:
default:
return SPEW_DEBUGGER;
}
}
//-----------------------------------------------------------------------------
// Deals with shader draw
//-----------------------------------------------------------------------------
void CShaderSystem::PrepForShaderDraw( IShader *pShader,
IMaterialVar** ppParams, ShaderRenderState_t* pRenderState, int nModulation )
{
Assert( !m_pRenderState );
// 360 runs the console remotely, spew cannot cause the matsys to be reentrant
// 360 sidesteps the other negative affect that *all* buffered spew redirects as warning text
m_bOrigLock = GetLockOutputFunc();
if ( (IsPC() || !IsX360()) )
{
Assert( !m_SaveSpewOutput );
m_SaveSpewOutput = GetSpewOutputFunc();
if (!m_bOrigLock)
{
SpewOutputFunc(MySpewOutputFunc);
}
}
m_pRenderState = pRenderState;
m_nModulation = nModulation;
m_nRenderPass = 0;
}
void CShaderSystem::DoneWithShaderDraw()
{
if ( (IsPC() || !IsX360()))
{
SpewOutputFunc( m_SaveSpewOutput );
if (!m_bOrigLock)
{
PrintBufferedSpew();
}
m_SaveSpewOutput = NULL;
}
m_pRenderState = NULL;
}
//-----------------------------------------------------------------------------
// Call the SHADER_PARAM_INIT block of the shaders
//-----------------------------------------------------------------------------
void CShaderSystem::InitShaderParameters( IShader *pShader, IMaterialVar **params, const char *pMaterialName )
{
// Let the derived class do its thing
PrepForShaderDraw( pShader, params, 0, 0 );
pShader->InitShaderParams( params, pMaterialName );
DoneWithShaderDraw();
// Set up color + alpha defaults
if (!params[COLOR]->IsDefined())
{
params[COLOR]->SetVecValue( 1.0f, 1.0f, 1.0f );
}
if (!params[ALPHA]->IsDefined())
{
params[ALPHA]->SetFloatValue( 1.0f );
}
// Initialize all shader params based on their type...
int i;