Repository navigation
Expand file tree
/
Copy pathMaterialSystem.cs
More file actions
2048 lines (1629 loc) · 76.3 KB
/
Copy pathMaterialSystem.cs
File metadata and controls
2048 lines (1629 loc) · 76.3 KB
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
using CommunityToolkit.HighPerformance;
using Microsoft.Extensions.DependencyInjection;
using Source.Common;
using Source.Common.Bitmap;
using Source.Common.Commands;
using Source.Common.Engine;
using Source.Common.Filesystem;
using Source.Common.Formats.Keyvalues;
using Source.Common.GUI;
using Source.Common.Launcher;
using Source.Common.MaterialSystem;
using Source.Common.Mathematics;
using Source.Common.ShaderAPI;
using Source.MaterialSystem.Surface;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Source.MaterialSystem;
public static class MatSysBootstrap
{
public static T WithFullMaterialSystem<T>(this T services) where T : IServiceCollection {
services.AddSingleton<IMaterialSystem, MaterialSystem>();
services.AddSingleton<MatSystemSurface>();
services.AddSingleton<IMatSystemSurface>(x => x.GetRequiredService<MatSystemSurface>());
services.AddSingleton<ISurface>(x => x.GetRequiredService<MatSystemSurface>());
services.AddSingleton<ITextureManager, TextureManager>();
services.AddSingleton<MaterialSystem_Config>();
return services;
}
public static T WithStubMaterialSystem<T>(this T services) where T : IServiceCollection {
services.AddSingleton<IMaterialSystem, DummyMaterialSystem>();
services.AddSingleton<IMaterialSystemHardwareConfig, DummyHardwareConfig>();
return services;
}
}
public class MaterialSystem : IMaterialSystemInternal, IShaderUtil
{
public readonly MaterialDict MaterialDict;
nint graphics;
public IShaderUtil GetShaderUtil() => this;
readonly IServiceProvider services;
public readonly IFileSystem FileSystem;
public readonly TextureManager TextureSystem;
public readonly IShaderSystem ShaderSystem;
public IShaderDevice ShaderDevice;
public IShaderAPI ShaderAPI;
public readonly IMeshMgr MeshMgr;
public readonly IMaterialSystemHardwareConfig HardwareConfig;
public readonly ICommandLine CommandLine;
public readonly MaterialSystem_Config Config;
readonly static ConVar mat_vsync = new("mat_vsync", "0", 0, "Force sync to vertical retrace", 0, 1);
readonly static ConVar mat_forcehardwaresync = new("1", 0);
readonly static ConVar mat_trilinear = new("1", 0);
readonly static ConVar mat_forceaniso = new("16", FCvar.Archive); // 0 = Bilinear, 1 = Trilinear, 2+ = Aniso
readonly static ConVar mat_filterlightmaps = new("1", 0);
readonly static ConVar mat_filtertextures = new("1", 0);
readonly static ConVar mat_mipmaptextures = new("1", 0);
readonly static ConVar mat_vrmode_adapter = new("-1", 0);
readonly static ConVar mat_showmiplevels = new("0", FCvar.Cheat, "color-code miplevels 2: normalmaps, 1: everything else"); // , callback: mat_showmiplevels_Callback_f
readonly static ConVar mat_specular = new("1", 0, "Enable/Disable specularity for perf testing. Will cause a material reload upon change.");
readonly static ConVar mat_bumpmap = new("1", 0);
readonly static ConVar mat_phong = new("1", 0);
readonly static ConVar mat_parallaxmap = new("1", FCvar.Hidden | 0);
readonly static ConVar mat_reducefillrate = new("0", 0);
readonly static ConVar mat_picmip = new("0", FCvar.Archive, "", -1, 4);
readonly static ConVar mat_slopescaledepthbias_normal = new("0.0f", FCvar.Cheat);
readonly static ConVar mat_depthbias_normal = new("0.0f", FCvar.Cheat | 0);
readonly static ConVar mat_slopescaledepthbias_decal = new("-0.5", FCvar.Cheat); // Reciprocals of these biases sent to API
readonly static ConVar mat_depthbias_decal = new("-262144", FCvar.Cheat | 0);
readonly static ConVar mat_slopescaledepthbias_shadowmap = new("16", FCvar.Cheat);
readonly static ConVar mat_depthbias_shadowmap = new("0.0005", FCvar.Cheat);
readonly static ConVar mat_monitorgamma = new("2.2", FCvar.Archive, "monitor gamma (typically 2.2 for CRT and 1.7 for LCD)", 1.6f, 2.6f);
readonly static ConVar mat_monitorgamma_tv_range_min = new("16", 0);
readonly static ConVar mat_monitorgamma_tv_range_max = new("255", 0);
readonly static ConVar mat_monitorgamma_tv_exp = new("2.5", 0, "", 1.0f, 4.0f);
readonly static ConVar mat_monitorgamma_tv_enabled = new("0", FCvar.Archive, "");
readonly static ConVar mat_antialias = new("0", FCvar.Archive);
readonly static ConVar mat_aaquality = new("0", FCvar.Archive);
readonly static ConVar mat_diffuse = new("1", FCvar.Cheat);
readonly static ConVar mat_showlowresimage = new("0", FCvar.Cheat);
readonly static ConVar mat_fullbright = new("0", FCvar.Cheat);
readonly static ConVar mat_normalmaps = new("0", FCvar.Cheat);
readonly static ConVar mat_measurefillrate = new("0", FCvar.Cheat);
readonly static ConVar mat_fillrate = new("0", FCvar.Cheat);
readonly static ConVar mat_reversedepth = new("0", FCvar.Cheat);
readonly static ConVar mat_bufferprimitives = new("1", 0);
readonly static ConVar mat_drawflat = new("0", FCvar.Cheat);
readonly static ConVar mat_softwarelighting = new("0", 0);
readonly static ConVar mat_proxy = new("0", FCvar.Cheat, ""); // , callback: MatProxyCallback
readonly static ConVar mat_norendering = new("0", FCvar.Cheat);
readonly static ConVar mat_compressedtextures = new("1", 0);
readonly static ConVar mat_fastspecular = new("1", 0, "Enable/Disable specularity for visual testing. Will not reload materials and will not affect perf.");
readonly static ConVar mat_fastnobump = new("0", FCvar.Cheat); // Binds 1-texel normal map for quick internal testing
// These are not controlled by the material system, but are limited by settings in the material system
readonly static ConVar r_shadowrendertotexture = new("0", FCvar.Archive);
readonly static ConVar r_flashlightdepthtexture = new("1", 0);
readonly static ConVar r_waterforceexpensive = new("0", FCvar.Archive);
readonly static ConVar r_waterforcereflectentities = new("0", 0);
readonly static ConVar mat_motion_blur_enabled = new("0", FCvar.Archive);
public MaterialSystem(IServiceProvider services) {
MaterialDict = new(this);
this.services = services;
FileSystem = services.GetRequiredService<IFileSystem>();
ShaderAPI = services.GetRequiredService<IShaderAPI>()!;
ShaderDevice = services.GetRequiredService<IShaderDevice>();
TextureSystem = (services.GetRequiredService<ITextureManager>() as TextureManager)!;
MeshMgr = services.GetRequiredService<IMeshMgr>(); // todo: interface
HardwareConfig = services.GetRequiredService<IMaterialSystemHardwareConfig>(); // todo: interface
ShaderSystem = services.GetRequiredService<IShaderSystem>();
Config = services.GetRequiredService<MaterialSystem_Config>()!;
CommandLine = services.GetRequiredService<ICommandLine>()!;
HardwareRenderContext = new(this);
QueuedRenderContexts = [new(this), new(this)];
ExecuteQueuedContextJobs = [new(MatQueueJob.JobKind.ExecuteQueuedContext, QueuedRenderContexts[0]), new(MatQueueJob.JobKind.ExecuteQueuedContext, QueuedRenderContexts[1])];
MathLib.Init(IMaterialSystem.GAMMA, IMaterialSystem.TEXGAMMA, 0.0f, (int)IMaterialSystem.OVERBRIGHT);
// Link up
ShaderDevice.PreInit(this, services);
TextureSystem.MaterialSystem = this;
ShaderSystem.LoadAllShaderDLLs();
TextureSystem.Init();
ShaderSystem.Init();
CreateDebugMaterials();
MatLightmaps = new(this);
OcclusionQueryMgr = new(this);
}
ILauncherManager launcherMgr;
public void ModInit() {
launcherMgr = services.GetRequiredService<ILauncherManager>();
GenerateConfigFromConfigKeyValues(Config, false);
UpdateConfig(false);
}
public void GenerateConfigFromConfigKeyValues(MaterialSystem_Config config, bool overwriteCommandLineValues) {
config.Flags = 0;
launcherMgr.GetNativeDisplayInfo(-1, out uint width, out uint height, out uint refreshHz);
config.VideoMode.Width = (int)width;
config.VideoMode.Height = (int)height;
}
public bool UpdateConfig(bool forceUpdate) {
MaterialSystem_Config config = new();
Config.CopyInstantiatedReferenceTo(config);
ReadConfigFromConVars(config);
return OverrideConfig(config, forceUpdate);
}
public bool OverrideConfig(MaterialSystem_Config config, bool forceUpdate) {
bool redownloadLightmaps = false;
bool redownloadTextures = false;
bool recomputeSnapshots = false;
bool reloadMaterials = false;
bool resetAnisotropy = false;
bool setStandardVertexShaderConstants = false;
bool monitorGammaChanged = false;
bool videoModeChange = false;
bool resetTextureFilter = false;
if (!ShaderDevice.IsUsingGraphics()) {
// Config = config;
config.CopyInstantiatedReferenceTo(Config);
ColorSpace.SetGamma(2.2f, 2.2f, IMaterialSystem.OVERBRIGHT, Config.AllowCheats, false);
return redownloadLightmaps;
}
ShaderAPI.SetDefaultState();
if (config.HDREnabled() != Config.HDREnabled()) {
forceUpdate = true;
reloadMaterials = true;
}
if (config.ShadowDepthTexture != Config.ShadowDepthTexture) {
forceUpdate = true;
reloadMaterials = true;
recomputeSnapshots = true;
}
// Don't use compressed textures for the moment if we don't support them
if (!HardwareConfig.SupportsCompressedTextures())
config.CompressedTextures = false;
if (forceUpdate) {
MatLightmaps.EnableLightmapFiltering(config.FilterLightmaps);
recomputeSnapshots = true;
redownloadLightmaps = true;
redownloadTextures = true;
resetAnisotropy = true;
setStandardVertexShaderConstants = true;
}
// toggle bump mapping
if (config.DisableSpecular() != Config.DisableSpecular() || config.DisablePhong() != Config.DisablePhong()) {
recomputeSnapshots = true;
reloadMaterials = true;
resetAnisotropy = true;
}
// toggle specularity
if (config.DisableSpecular() != Config.DisableSpecular()) {
recomputeSnapshots = true;
reloadMaterials = true;
resetAnisotropy = true;
}
// toggle parallax mapping
if (config.EnableParallaxMapping() != Config.EnableParallaxMapping())
reloadMaterials = true;
// Reload materials if we want reduced fillrate
if (config.ReduceFillrate() != Config.ReduceFillrate())
reloadMaterials = true;
// toggle reverse depth
if (config.ReverseDepth != Config.ReverseDepth) {
recomputeSnapshots = true;
resetAnisotropy = true;
}
// toggle no transparency
if (config.NoTransparency != Config.NoTransparency) {
recomputeSnapshots = true;
resetAnisotropy = true;
}
// toggle lightmap filtering
if (config.FilterLightmaps != Config.FilterLightmaps)
MatLightmaps.EnableLightmapFiltering(config.FilterLightmaps);
// toggle software lighting
if (config.SoftwareLighting != Config.SoftwareLighting)
reloadMaterials = true;
// generic things that cause us to redownload textures
if (config.AllowCheats != Config.AllowCheats ||
config.SkipMipLevels != Config.SkipMipLevels ||
config.ShowMipLevels != Config.ShowMipLevels ||
((config.CompressedTextures != Config.CompressedTextures) && HardwareConfig.SupportsCompressedTextures()) ||
config.ShowLowResImage != Config.ShowLowResImage) {
redownloadTextures = true;
recomputeSnapshots = true;
resetAnisotropy = true;
}
if (config.ForceTrilinear() != Config.ForceTrilinear())
resetTextureFilter = true;
if (config.ForceAnisotropicLevel != Config.ForceAnisotropicLevel) {
resetAnisotropy = true;
resetTextureFilter = true;
}
if (config.MonitorGamma != Config.MonitorGamma || config.GammaTVRangeMin != Config.GammaTVRangeMin ||
config.GammaTVRangeMax != Config.GammaTVRangeMax || config.GammaTVExponent != Config.GammaTVExponent ||
config.GammaTVEnabled != Config.GammaTVEnabled)
monitorGammaChanged = true;
if (config.VideoMode.Width != Config.VideoMode.Width ||
config.VideoMode.Height != Config.VideoMode.Height ||
config.VideoMode.RefreshRate != Config.VideoMode.RefreshRate ||
config.AASamples != Config.AASamples ||
config.AAQuality != Config.AAQuality ||
config.Windowed() != Config.Windowed() ||
config.NoWindowBorder() != Config.NoWindowBorder() ||
config.Stencil() != Config.Stencil())
videoModeChange = true;
if (!config.Windowed() && (config.WaitForVSync() != Config.WaitForVSync()))
videoModeChange = true;
config.CopyInstantiatedReferenceTo(Config);
if (redownloadTextures || redownloadLightmaps)
ColorSpace.SetGamma(2.2f, 2.2f, IMaterialSystem.OVERBRIGHT, Config.AllowCheats, false);
if (resetAnisotropy || recomputeSnapshots || redownloadLightmaps ||
redownloadTextures || resetAnisotropy || videoModeChange ||
setStandardVertexShaderConstants || resetTextureFilter) {
ForceSingleThreaded();
}
if (reloadMaterials)
ReloadMaterials();
if (resetAnisotropy)
ShaderAPI.SetAnisotropicLevel(config.ForceAnisotropicLevel);
if (redownloadTextures) {
if (ShaderAPI.CanDownloadTextures()) {
TextureSystem.RestoreRenderTargets();
TextureSystem.RestoreNonRenderTargetTextures();
}
}
else if (resetTextureFilter) {
TextureSystem.ResetTextureFilteringState();
}
// Recompute all state snapshots
if (recomputeSnapshots)
RecomputeAllStateSnapshots();
// if (setStandardVertexShaderConstants)
// ShaderAPI.SetStandardVertexShaderConstants(IMaterialSystem.OVERBRIGHT);
if (monitorGammaChanged) {
// ShaderDevice.SetHardwareGammaRamp(config.MonitorGamma, config.GammaTVRangeMin, config.GammaTVRangeMax, config.GammaTVExponent, config.GammaTVEnabled);
}
if (videoModeChange) {
ConvertModeStruct(config, out ShaderDeviceInfo info);
ShaderAPI.ChangeVideoMode(info);
if (ShaderAPI.CanDownloadTextures())
TextureSystem.RestoreRenderTargets();
}
if (videoModeChange)
ForceSingleThreaded();
return redownloadLightmaps;
}
private void ReadConfigFromConVars(MaterialSystem_Config config) {
config.SetFlag(MaterialSystem_Config_Flags.NoWaitForVSync, !mat_vsync.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.ForceTrilinear, mat_trilinear.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.DisableSpecular, !mat_specular.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.DisableBumpmap, !mat_bumpmap.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.DisableBumpmap, !mat_phong.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.EnableParallaxMapping, mat_parallaxmap.GetBool());
config.SetFlag(MaterialSystem_Config_Flags.ReduceFillrate, mat_reducefillrate.GetBool());
config.ForceAnisotropicLevel = Math.Max(mat_forceaniso.GetInt(), 1);
config.SkipMipLevels = mat_picmip.GetInt();
config.SetFlag(MaterialSystem_Config_Flags.ForceHardwareSync, mat_forcehardwaresync.GetBool());
config.SlopeScaleDepthBias_Decal = mat_slopescaledepthbias_decal.GetFloat();
config.DepthBias_Decal = mat_depthbias_decal.GetFloat();
config.SlopeScaleDepthBias_Normal = mat_slopescaledepthbias_normal.GetFloat();
config.DepthBias_Normal = mat_depthbias_normal.GetFloat();
config.SlopeScaleDepthBias_ShadowMap = mat_slopescaledepthbias_shadowmap.GetFloat();
config.DepthBias_ShadowMap = mat_depthbias_shadowmap.GetFloat();
config.MonitorGamma = mat_monitorgamma.GetFloat();
config.GammaTVRangeMin = mat_monitorgamma_tv_range_min.GetFloat();
config.GammaTVRangeMax = mat_monitorgamma_tv_range_max.GetFloat();
config.GammaTVExponent = mat_monitorgamma_tv_exp.GetFloat();
config.GammaTVEnabled = mat_monitorgamma_tv_enabled.GetBool();
config.AASamples = mat_antialias.GetInt();
config.AAQuality = mat_aaquality.GetInt();
config.ShowDiffuse = mat_diffuse.GetBool();
config.ShowNormalMap = mat_normalmaps.GetBool();
config.ShowLowResImage = mat_showlowresimage.GetBool();
config.MeasureFillRate = mat_measurefillrate.GetBool();
config.VisualizeFillRate = mat_fillrate.GetBool();
config.FilterLightmaps = mat_filterlightmaps.GetBool();
config.FilterTextures = mat_filtertextures.GetBool();
config.MipMapTextures = mat_mipmaptextures.GetBool();
config.ShowMipLevels = (sbyte)mat_showmiplevels.GetInt();
config.ReverseDepth = mat_reversedepth.GetBool();
config.BufferPrimitives = mat_bufferprimitives.GetBool();
config.DrawFlat = mat_drawflat.GetBool();
config.SoftwareLighting = mat_softwarelighting.GetBool();
config.ProxiesTestMode = (byte)mat_proxy.GetInt();
config.SuppressRendering = mat_norendering.GetInt() != 0;
config.CompressedTextures = mat_compressedtextures.GetBool();
config.ShowSpecular = mat_fastspecular.GetBool();
config.Fullbright = (byte)mat_fullbright.GetInt();
config.FastNoBump = mat_fastnobump.GetInt() != 0;
config.MotionBlur = mat_motion_blur_enabled.GetBool();
config.SupportFlashlight = true; // mat_supportflashlight.GetBool();
config.ShadowDepthTexture = r_flashlightdepthtexture.GetBool();
config.SetFlag(MaterialSystem_Config_Flags.ENABLE_HDR, HardwareConfig.GetHDREnabled());
}
public uint GetDisplayAdapterCount() {
throw new NotImplementedException();
}
public uint GetCurrentAdapter() => (uint)ShaderDevice.GetCurrentAdapter();
public void ModShutdown() {
}
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
unsafe static void raylibSpew(int logLevel, sbyte* text, sbyte* args) {
//var message = Logging.GetLogMessage((nint)text, (nint)args);
/*Dbg._SpewMessage((TraceLogLevel)logLevel switch {
TraceLogLevel.Info => SpewType.Message,
TraceLogLevel.Trace => SpewType.Log,
TraceLogLevel.Debug => SpewType.Message,
TraceLogLevel.Warning => SpewType.Warning,
TraceLogLevel.Error => SpewType.Warning,
TraceLogLevel.Fatal => SpewType.Error,
_ => SpewType.Message,
}, "raylib", 1, new Color(255, 255, 255), message + "\n");*/
}
public uint DebugVarsSignature;
public ITexture GetErrorTexture() => TextureSystem.ErrorTexture();
public void BeginFrame(double frameTime) {
if (!ThreadInMainThread() || IsInFrame())
return;
DebugVarsSignature = (uint)(
((mat_specular.GetInt() != 0) ? 1 : 0)
+ (mat_normalmaps.GetInt() << 1)
+ (mat_fullbright.GetInt() << 2)
);
var renderContext = GetRenderContextInternal();
renderContext.MarkRenderDataUnused(true);
renderContext.BeginFrame();
renderContext.SetFrameTime(frameTime);
Assert(!InFrame);
InFrame = true;
}
bool InFrame = false;
private Matrix4x4 GetScreenMatrix() {
launcherMgr.DisplayedSize(out int screenWidth, out _);
int renderWidth = 0, renderHeight = 0;
launcherMgr.RenderedSize(false, ref renderWidth, ref renderHeight);
float scaleRatio = (float)renderWidth / (float)screenWidth;
MathLib.MatrixBuildScale(out Matrix4x4 m, scaleRatio, scaleRatio, 1);
return m;
}
public bool IsInFrame() => InFrame;
public void EndFrame() {
if (!ThreadInMainThread() || !IsInFrame())
return;
GetRenderContextInternal().EndFrame();
int convarThreadMode = mat_queue_mode.GetInt();
if (convarThreadMode == -2)
convarThreadMode = (int)MaterialThreadMode.QueuedThreaded;
if (convarThreadMode == (int)MaterialThreadMode.QueuedSingleThreaded)
convarThreadMode = (int)MaterialThreadMode.SingleThreaded;
MaterialThreadMode nextThreadMode = (convarThreadMode >= 0) ? (MaterialThreadMode)convarThreadMode : IdealThreadMode;
bool deviceReady = ShaderAPI.CanDownloadTextures();
if (!deviceReady || !AllowQueuedRendering)
nextThreadMode = MaterialThreadMode.SingleThreaded;
if (ForcedSingleThreaded) {
nextThreadMode = MaterialThreadMode.SingleThreaded;
ForcedSingleThreaded = false;
}
switch (ThreadMode) {
case MaterialThreadMode.SingleThreaded:
break;
case MaterialThreadMode.QueuedThreaded: {
if (!ThreadHasOwnership)
ThreadAcquire(true);
if (ActiveAsyncJob != null && !ActiveAsyncJob.IsFinished())
ActiveAsyncJob.WaitForFinish();
ActiveAsyncJob = null;
MatQueuedRenderContext prevContext = QueuedRenderContexts[CurQueuedContext];
CurQueuedContext = (CurQueuedContext + 1) % QueuedRenderContexts.Length;
QueuedRenderContexts[CurQueuedContext].BeginQueue(prevContext);
CurrentThreadRenderContext = QueuedRenderContexts[CurQueuedContext];
ActiveAsyncJob = ExecuteQueuedContextJobs[prevContext == QueuedRenderContexts[0] ? 0 : 1];
ActiveAsyncJob.Reset();
MatQueueThread.AddJob(ActiveAsyncJob);
break;
}
}
if (!deviceReady && nextThreadMode != MaterialThreadMode.SingleThreaded)
nextThreadMode = MaterialThreadMode.SingleThreaded;
if (ThreadMode != nextThreadMode) {
switch (ThreadMode) {
case MaterialThreadMode.SingleThreaded:
break;
case MaterialThreadMode.QueuedThreaded: {
if (ActiveAsyncJob != null) {
ActiveAsyncJob.WaitForFinish();
ActiveAsyncJob = null;
}
HardwareRenderContext.InitializeFrom(QueuedRenderContexts[CurQueuedContext]);
CurrentThreadRenderContext = HardwareRenderContext;
QueuedRenderContexts[CurQueuedContext].EndQueue(true);
ThreadRelease();
}
break;
}
ThreadMode = nextThreadMode;
switch (ThreadMode) {
case MaterialThreadMode.SingleThreaded:
CurrentThreadRenderContext = HardwareRenderContext;
for (int i = 0; i < QueuedRenderContexts.Length; i++)
QueuedRenderContexts[i].EndQueue(true);
break;
case MaterialThreadMode.QueuedThreaded: {
for (int i = 0; i < QueuedRenderContexts.Length; i++) {
if (!QueuedRenderContexts[i].IsInitialized())
QueuedRenderContexts[i].Init(HardwareRenderContext);
}
CurQueuedContext = 0;
QueuedRenderContexts[CurQueuedContext].BeginQueue(HardwareRenderContext);
CurrentThreadRenderContext = QueuedRenderContexts[CurQueuedContext];
ShaderAPI.ReleaseThreadOwnership();
MatQueueThread.AddJob(new MatQueueJob(MatQueueJob.JobKind.AcquireThreadOwnership));
ThreadHasOwnership = true;
ThreadOwnershipID = ThreadGetCurrentId();
}
break;
}
}
Assert(InFrame);
InFrame = false;
}
static readonly ConVar mat_queue_mode = new("mat_queue_mode", "-1", FCvar.Archive, "The queue/thread mode the material system should use: -1=default, 0=synchronous single thread, 2=queued multithreaded");
static readonly ConVar mat_queue_report = new("mat_queue_report", "0", FCvar.Archive, "Report thread stalls. Positive number will filter by stalls >= time in ms. -1 reports all locks.");
MaterialThreadMode IdealThreadMode = MaterialThreadMode.SingleThreaded;
int ServiceThread = -1;
bool AllowQueuedRendering;
bool ForcedSingleThreaded;
bool ThreadHasOwnership;
int ThreadOwnershipID;
readonly object MatSysMutex = new();
readonly MatQueuedRenderContext[] QueuedRenderContexts;
readonly MatQueueJob[] ExecuteQueuedContextJobs;
int CurQueuedContext;
MatQueueJob? ActiveAsyncJob;
MatQueueThread? matQueueThread;
MatQueueThread MatQueueThread => matQueueThread ??= new(this);
public void ForceSingleThreaded() {
if (!ThreadInMainThread())
Error("Can't force single thread from within thread!\n");
if (GetThreadMode() != MaterialThreadMode.SingleThreaded) {
if (ActiveAsyncJob != null && !ActiveAsyncJob.IsFinished())
ActiveAsyncJob.WaitForFinish();
ActiveAsyncJob = null;
ThreadRelease();
HardwareRenderContext.InitializeFrom(QueuedRenderContexts[CurQueuedContext]);
CurrentThreadRenderContext = HardwareRenderContext;
for (int i = 0; i < QueuedRenderContexts.Length; i++)
QueuedRenderContexts[i].EndQueue(true);
ThreadMode = MaterialThreadMode.SingleThreaded;
ForcedSingleThreaded = true;
}
}
internal void ExecuteJob(MatQueueJob job) {
switch (job.Kind) {
case MatQueueJob.JobKind.AcquireThreadOwnership:
ShaderAPI.AcquireThreadOwnership();
break;
case MatQueueJob.JobKind.ReleaseThreadOwnership:
ShaderAPI.ReleaseThreadOwnership();
break;
case MatQueueJob.JobKind.ExecuteQueuedContext:
ThreadExecuteQueuedContext(job.Context!);
break;
}
}
void ThreadExecuteQueuedContext(MatQueuedRenderContext context) {
RenderThreadID = (uint)ThreadGetCurrentId();
IMatRenderContextInternal? savedRenderContext = CurrentThreadRenderContext;
CurrentThreadRenderContext = HardwareRenderContext;
context.EndQueue(true);
CurrentThreadRenderContext = savedRenderContext;
RenderThreadID = 0xFFFFFFFF;
}
void ThreadRelease() {
if (!ThreadHasOwnership)
return;
double startTime = mat_queue_report.GetInt() != 0 ? Platform.Time : 0;
MatQueueJob job = new(MatQueueJob.JobKind.ReleaseThreadOwnership);
MatQueueThread.AddJob(job);
job.WaitForFinish();
double endThreadRelease = mat_queue_report.GetInt() != 0 ? Platform.Time : 0;
ShaderAPI.AcquireThreadOwnership();
ThreadHasOwnership = false;
ThreadOwnershipID = 0;
if (mat_queue_report.GetInt() != 0) {
double endTime = Platform.Time;
double result = (endTime - startTime) * 1000.0;
if (mat_queue_report.GetInt() == -1 || result > mat_queue_report.GetFloat())
ConColorMsg(new Color(200, 20, 20, 255), $"CMaterialSystem::ThreadRelease: {result:0.00}ms = Release:{(endThreadRelease - startTime) * 1000.0:0.00}ms + Acquire:{(endTime - endThreadRelease) * 1000.0:0.00}ms\n");
}
}
void ThreadAcquire(bool force) {
if (!force)
return;
double startTime = mat_queue_report.GetInt() != 0 ? Platform.Time : 0;
ShaderAPI.ReleaseThreadOwnership();
MatQueueThread.AddJob(new MatQueueJob(MatQueueJob.JobKind.AcquireThreadOwnership));
ThreadHasOwnership = true;
ThreadOwnershipID = ThreadGetCurrentId();
if (mat_queue_report.GetInt() != 0) {
double result = (Platform.Time - startTime) * 1000.0;
if (mat_queue_report.GetInt() == -1 || result > mat_queue_report.GetFloat())
ConColorMsg(new Color(200, 20, 20, 255), $"CMaterialSystem::ThreadAcquire: {result:0.00}ms\n");
}
}
ulong FrameNum;
public void SwapBuffers() {
GetRenderContextInternal().SwapBuffers();
FrameNum++;
}
public MaterialSystem_Config GetCurrentConfigForVideoCard() => Config;
[ThreadStatic] static IMatRenderContextInternal? CurrentThreadRenderContext;
readonly MatRenderContext HardwareRenderContext;
public IMatRenderContext GetRenderContext() {
ref IMatRenderContextInternal? result = ref CurrentThreadRenderContext;
result ??= HardwareRenderContext;
return result;
}
public bool SetMode(IWindow window, MaterialSystem_Config config) {
MaterialSystem MaterialSystem = (MaterialSystem)Singleton<IMaterialSystem>();
TextureManager TextureManager = (TextureManager)Singleton<ITextureManager>();
ShaderDeviceInfo info;
ConvertModeStruct(config, out info);
bool previouslyUsingGraphics = ShaderDevice.IsUsingGraphics();
bool bOk = ShaderAPI.SetMode(window, GetCurrentAdapter(), info);
if (!bOk)
return false;
int width = info.DisplayMode.Width;
int height = info.DisplayMode.Height;
launcherMgr.RenderedSize(true, ref width, ref height);
TextureManager.FreeStandardRenderTargets();
TextureManager.AllocateStandardRenderTargets();
if (!previouslyUsingGraphics) {
TextureManager.RestoreRenderTargets();
TextureManager.RestoreNonRenderTargetTextures();
if (MaterialSystem.CanUseEditorMaterials())
MathLib.Init(2.2f, 2.2f, 0.0f, (int)IMaterialSystem.OVERBRIGHT);
AllocateStandardTextures();
}
// Copy over that state which isn't stored currently in convars
Config.VideoMode = config.VideoMode;
Config.SetFlag(MaterialSystem_Config_Flags.Windowed, config.Windowed());
Config.SetFlag(MaterialSystem_Config_Flags.Stencil, config.Stencil());
Config.SetFlag(MaterialSystem_Config_Flags.VRMode, config.VRMode());
// WriteConfigIntoConVars(config);
return true;
}
public void AddModeChangeCallBack(ModeChangeCallbackFunc func) => ShaderDevice.AddModeChangeCallBack(func);
ShaderAPITextureHandle_t FullbrightLightmapTextureHandle;
ShaderAPITextureHandle_t FullbrightBumpedLightmapTextureHandle;
ShaderAPITextureHandle_t BlackTextureHandle;
ShaderAPITextureHandle_t FlatNormalTextureHandle;
ShaderAPITextureHandle_t GreyTextureHandle;
ShaderAPITextureHandle_t GreyAlphaZeroTextureHandle;
ShaderAPITextureHandle_t WhiteTextureHandle;
ShaderAPITextureHandle_t LinearToGammaTableTextureHandle;
ShaderAPITextureHandle_t LinearToGammaIdentityTableTextureHandle;
ShaderAPITextureHandle_t MaxDepthTextureHandle;
bool StandardTexturesAllocated = false;
private void AllocateStandardTextures() {
if (StandardTexturesAllocated)
return;
StandardTexturesAllocated = true;
float nominal_lightmap_value = 1.0f;
if (HardwareConfig.GetHDRType() == HDRType.Integer)
nominal_lightmap_value = 1.0f / 16.0f;
Span<byte> texel = stackalloc byte[4];
texel[3] = 255;
CreateTextureFlags tcFlags = CreateTextureFlags.Managed;
CreateTextureFlags tcFlagsSRGB = CreateTextureFlags.Managed | CreateTextureFlags.SRGB;
FullbrightLightmapTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlags, "[FULLBRIGHT_LIGHTMAP_TEXID]", TEXTURE_GROUP_LIGHTMAP);
ShaderAPI.ModifyTexture(FullbrightLightmapTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
Span<float> tmpVect = [nominal_lightmap_value, nominal_lightmap_value, nominal_lightmap_value];
ColorSpace.LinearToLightmap(texel, tmpVect);
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
BlackTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlagsSRGB, "[BLACK_TEXID]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(BlackTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = texel[1] = texel[2] = 0;
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
ShaderAPI.SetStandardTextureHandle(StandardTextureId.Black, BlackTextureHandle);
WhiteTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlagsSRGB, "[WHITE_TEXID]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(WhiteTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = texel[1] = texel[2] = 255;
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
ShaderAPI.SetStandardTextureHandle(StandardTextureId.White, WhiteTextureHandle);
GreyTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlagsSRGB, "[GREY_TEXID]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(GreyTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = texel[1] = texel[2] = 128;
texel[3] = 255;
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
ShaderAPI.SetStandardTextureHandle(StandardTextureId.Grey, GreyTextureHandle);
GreyAlphaZeroTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.RGBA8888, 1, 1, (int)tcFlagsSRGB, "[GREYALPHAZERO_TEXID]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(GreyAlphaZeroTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = texel[1] = texel[2] = 128;
texel[3] = 0;
ShaderAPI.TexImage2D(0, 0, ImageFormat.RGBA8888, 0, 1, 1, ImageFormat.RGBA8888, false, texel);
texel[3] = 255;
ShaderAPI.SetStandardTextureHandle(StandardTextureId.GreyAlphaZero, GreyAlphaZeroTextureHandle);
FlatNormalTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlags, "[FLAT_NORMAL_TEXTURE]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(FlatNormalTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = 255;
texel[1] = 127;
texel[2] = 127;
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
ShaderAPI.SetStandardTextureHandle(StandardTextureId.NormalMapFlat, FlatNormalTextureHandle);
FullbrightBumpedLightmapTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.BGRX8888, 1, 1, (int)tcFlags, "[FULLBRIGHT_BUMPED_LIGHTMAP_TEXID]", TEXTURE_GROUP_LIGHTMAP);
ShaderAPI.ModifyTexture(FullbrightBumpedLightmapTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
Span<float> linearColor = [nominal_lightmap_value, nominal_lightmap_value, nominal_lightmap_value];
Span<byte> dummy = stackalloc byte[3];
ColorSpace.LinearToBumpedLightmap(linearColor, linearColor, linearColor, linearColor, dummy, texel, dummy, dummy);
ShaderAPI.TexImage2D(0, 0, ImageFormat.BGRX8888, 0, 1, 1, ImageFormat.BGRX8888, false, texel);
ShaderAPI.SetStandardTextureHandle(StandardTextureId.LightmapBumpedFullbright, FullbrightBumpedLightmapTextureHandle);
{
CreateTextureFlags iGammaLookupFlags = tcFlags;
ImageFormat gammalookupfmt;
gammalookupfmt = ImageFormat.I8;
{
const int LINEAR_TO_GAMMA_TABLE_WIDTH = 512;
LinearToGammaTableTextureHandle = ShaderAPI.CreateTexture(LINEAR_TO_GAMMA_TABLE_WIDTH, 1, 1, gammalookupfmt, 1, 1, (int)iGammaLookupFlags, "[LINEAR_TO_GAMMA_LOOKUP_SRGBON_TEXID]", TEXTURE_GROUP_PIXEL_SHADERS);
ShaderAPI.ModifyTexture(LinearToGammaTableTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
ShaderAPI.TexWrap(TexCoordComponent.S, TexWrapMode.Clamp);
ShaderAPI.TexWrap(TexCoordComponent.T, TexWrapMode.Clamp);
ShaderAPI.TexWrap(TexCoordComponent.U, TexWrapMode.Clamp);
Span<float> pixelData = stackalloc float[LINEAR_TO_GAMMA_TABLE_WIDTH];
for (int i = 0; i != LINEAR_TO_GAMMA_TABLE_WIDTH; ++i) {
float fLookupResult = ((float)i) / ((float)(LINEAR_TO_GAMMA_TABLE_WIDTH - 1));
fLookupResult = ShaderAPI.LinearToGamma_HardwareSpecific(fLookupResult);
fLookupResult = ShaderAPI.LinearToGamma_HardwareSpecific(fLookupResult);
int iColor = MathLib.RoundFloatToInt(fLookupResult * 255.0f);
if (iColor > 255)
iColor = 255;
pixelData.Cast<float, byte>()[i] = (byte)iColor;
}
ShaderAPI.TexImage2D(0, 0, gammalookupfmt, 0, LINEAR_TO_GAMMA_TABLE_WIDTH, 1, gammalookupfmt, false, pixelData.Cast<float, byte>());
}
// generate the identity conversion table texture.
{
const int LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH = 256;
LinearToGammaIdentityTableTextureHandle = ShaderAPI.CreateTexture(LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH, 1, 1, gammalookupfmt, 1, 1, (int)tcFlags, "[LINEAR_TO_GAMMA_LOOKUP_SRGBOFF_TEXID]", TEXTURE_GROUP_PIXEL_SHADERS);
ShaderAPI.ModifyTexture(LinearToGammaIdentityTableTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
ShaderAPI.TexWrap(TexCoordComponent.S, TexWrapMode.Clamp);
ShaderAPI.TexWrap(TexCoordComponent.T, TexWrapMode.Clamp);
ShaderAPI.TexWrap(TexCoordComponent.U, TexWrapMode.Clamp);
Span<float> pixelData = stackalloc float[LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH];
for (int i = 0; i != LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH; ++i) {
float fLookupResult = ((float)i) / ((float)(LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH - 1));
//do an extra srgb conversion because we'll be converting back on texture read
fLookupResult = ShaderAPI.LinearToGamma_HardwareSpecific(fLookupResult);
int iColor = MathLib.RoundFloatToInt(fLookupResult * 255.0f);
if (iColor > 255)
iColor = 255;
pixelData.Cast<float, byte>()[i] = (byte)iColor;
}
ShaderAPI.TexImage2D(0, 0, gammalookupfmt, 0, LINEAR_TO_GAMMA_IDENTITY_TABLE_WIDTH, 1, gammalookupfmt, false, pixelData.Cast<float, byte>());
}
}
//create the maximum depth texture
{
MaxDepthTextureHandle = ShaderAPI.CreateTexture(1, 1, 1, ImageFormat.RGBA8888, 1, 1, (int)tcFlags, "[MAXDEPTH_TEXID]", TEXTURE_GROUP_OTHER);
ShaderAPI.ModifyTexture(MaxDepthTextureHandle);
ShaderAPI.TexMinFilter(TexFilterMode.Linear);
ShaderAPI.TexMagFilter(TexFilterMode.Linear);
texel[0] = texel[1] = texel[2] = 255;
texel[3] = 255;
ShaderAPI.TexImage2D(0, 0, ImageFormat.RGBA8888, 0, 1, 1, ImageFormat.RGBA8888, false, texel);
}
//only the shaderapi can handle switching between textures correctly, so pass off the textures to it.
ShaderAPI.SetLinearToGammaConversionTextures(LinearToGammaTableTextureHandle, LinearToGammaIdentityTableTextureHandle);
}
public void ReleaseStandardTextures() {
if (StandardTexturesAllocated) {
ShaderAPI.DeleteTexture(BlackTextureHandle);
ShaderAPI.DeleteTexture(WhiteTextureHandle);
ShaderAPI.DeleteTexture(GreyTextureHandle);
ShaderAPI.DeleteTexture(GreyAlphaZeroTextureHandle);
ShaderAPI.DeleteTexture(FullbrightLightmapTextureHandle);
ShaderAPI.DeleteTexture(FlatNormalTextureHandle);
ShaderAPI.DeleteTexture(FullbrightBumpedLightmapTextureHandle);
ShaderAPI.DeleteTexture(LinearToGammaTableTextureHandle);
ShaderAPI.DeleteTexture(LinearToGammaIdentityTableTextureHandle);
ShaderAPI.SetLinearToGammaConversionTextures(INVALID_SHADERAPI_TEXTURE_HANDLE, INVALID_SHADERAPI_TEXTURE_HANDLE);
ShaderAPI.DeleteTexture(MaxDepthTextureHandle);
StandardTexturesAllocated = false;
}
}
private void ConvertModeStruct(MaterialSystem_Config config, out ShaderDeviceInfo mode) {
mode = new ShaderDeviceInfo();
mode.DisplayMode.Width = config.VideoMode.Width;
mode.DisplayMode.Height = config.VideoMode.Height;
mode.DisplayMode.Format = config.Format;
mode.DisplayMode.RefreshRateNumerator = config.VideoMode.RefreshRate;
mode.DisplayMode.RefreshRateDenominator = config.VideoMode.RefreshRate >= 0 ? 1 : 0;
mode.BackBufferCount = 1;
mode.AASamples = config.AASamples;
mode.AAQuality = config.AAQuality;
mode.Driver = config.Driver;
mode.WindowedSizeLimitWidth = (int)config.WindowedSizeLimitWidth;
mode.WindowedSizeLimitHeight = (int)config.WindowedSizeLimitHeight;
mode.Windowed = config.Windowed();
mode.Borderless = config.NoWindowBorder();
mode.Resizing = config.Resizing();
mode.UseStencil = config.Stencil();
mode.LimitWindowedSize = config.LimitWindowedSize();
mode.WaitForVSync = config.WaitForVSync();
mode.ScaleToOutputResolution = config.ScaleToOutputResolution();
mode.UsingMultipleWindows = config.UsingMultipleWindows();
}
IMaterial IMaterialSystem.CreateMaterial(ReadOnlySpan<char> materialName, ReadOnlySpan<char> textureGroup, KeyValues keyValues) => CreateMaterial(materialName, textureGroup, keyValues);
IMaterial IMaterialSystem.CreateMaterial(ReadOnlySpan<char> materialName, KeyValues keyValues) => CreateMaterial(materialName, TEXTURE_GROUP_OTHER, keyValues);
public IMaterialInternal CreateMaterial(ReadOnlySpan<char> materialName, KeyValues? keyValues)
=> CreateMaterial(materialName, MaterialDefines.TEXTURE_GROUP_OTHER, keyValues);
public IMaterialInternal CreateMaterial(ReadOnlySpan<char> materialName, ReadOnlySpan<char> textureGroup, KeyValues? keyValues) {
IMaterialInternal material;
MaterialLock hMaterialLock = Lock();
lock (this) {
material = new Material(this, materialName, textureGroup, keyValues);
}
Unlock(hMaterialLock);
MaterialDict.AddMaterialToMaterialList(material);
return material;
}
public IMaterial? GetCurrentMaterial() {
return GetRenderContext().GetCurrentMaterial();
}
public void AddMaterialToMaterialList(IMaterialInternal? material) => MaterialDict.AddMaterialToMaterialList(material!);
public void RemoveMaterial(IMaterialInternal? material) => MaterialDict.RemoveMaterial(material!);
public void RemoveMaterialSubRect(IMaterialInternal? material) {
throw new NotImplementedException("Incomplete port of IMaterialSystemInternal");
}
public int GetLightmapWidth(int lightmap) => MatLightmaps.GetLightmapWidth(lightmap);
public int GetLightmapHeight(int lightmap) => MatLightmaps.GetLightmapHeight(lightmap);
public int GetLightmapPage() => GetRenderContextInternal().GetLightmapPage();
public ITexture? GetLocalCubemap() => GetRenderContextInternal().GetLocalCubemap();
public void ForceDepthFuncEquals(bool enable) => GetRenderContextInternal().ForceDepthFuncEquals(enable);
public MaterialHeightClipMode GetHeightClipMode() => GetRenderContextInternal().GetHeightClipMode();
public MatCallQueue? GetRenderCallQueue() => CurrentThreadRenderContext?.GetCallQueueInternal();
public void UnbindMaterial(IMaterial? material) {
Assert(material == null || ((IMaterialInternal)material).IsRealTimeVersion());
if (HardwareRenderContext.GetCurrentMaterial() == material)
HardwareRenderContext.Bind(errorMaterial, null);
}
uint RenderThreadID = 0xFFFFFFFF;
public uint GetRenderThreadId() => RenderThreadID;
public bool CanUseEditorMaterials() {
return false; //todo
}
public bool IsInStubMode() => false;
public bool OnDrawMesh(IMesh mesh, int firstIndex, int indexCount) {
if (IsInStubMode())
return false;