-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathsdl_glimp.cpp
More file actions
3033 lines (2497 loc) · 92.4 KB
/
sdl_glimp.cpp
File metadata and controls
3033 lines (2497 loc) · 92.4 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
/*
===========================================================================
Copyright (C) 1999-2005 Id Software, Inc.
This file is part of Daemon source code.
Daemon source code is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of the License,
or (at your option) any later version.
Daemon source code is distributed in the hope that it will be
useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Daemon source code; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
===========================================================================
*/
#include "qcommon/q_shared.h" // Include before SDL.h due to M_PI issue...
#include <SDL.h>
#ifdef USE_SMP
#include <SDL_thread.h>
#endif
#include "renderer/tr_local.h"
#include "renderer/DetectGLVendors.h"
#pragma warning(push)
#pragma warning(disable : 4125) // "decimal digit terminates octal escape sequence"
#include "sdl_icon.h"
#pragma warning(pop)
#include "SDL_syswm.h"
#include "framework/CommandSystem.h"
#include "framework/CvarSystem.h"
static Log::Logger logger("glconfig", "", Log::Level::NOTICE);
static Cvar::Modified<Cvar::Cvar<bool>> r_noBorder(
"r_noBorder", "draw window without border", Cvar::ARCHIVE, false);
static Cvar::Modified<Cvar::Range<Cvar::Cvar<int>>> r_swapInterval(
"r_swapInterval", "enable vsync on every Nth frame, negative for apdative", Cvar::ARCHIVE, 0, -5, 5 );
static Cvar::Cvar<std::string> r_glForceDriver(
"r_glForceDriver", "treat the OpenGL driver type as: 'icd' 'standalone' or 'opengl3'", Cvar::NONE, "");
static Cvar::Cvar<std::string> r_glForceHardware(
"r_glForceHardware", "treat the GPU type as: 'r300' or 'generic'", Cvar::NONE, "");
static Cvar::Cvar<std::string> r_availableModes(
"r_availableModes", "list of available resolutions", Cvar::ROM, "");
static Cvar::Range<Cvar::Cvar<int>> r_glDebugSeverity(
"r_glDebugSeverity",
"minimum severity of r_glDebugProfile messages (1=NOTIFICATION, 2=LOW, 3=MEDIUM, 4=HIGH)",
Cvar::NONE, 2, 1, 4);
// OpenGL extension cvars.
/* Driver bug: Mesa versions > 24.0.9 produce garbage rendering when bindless textures are enabled,
and the shader compiler crashes with material shaders
24.0.9 is the latest known working version, 24.1.1 is the earliest known broken version
So this defaults to disabled */
static Cvar::Cvar<bool> r_arb_bindless_texture( "r_arb_bindless_texture",
"Use GL_ARB_bindless_texture if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_buffer_storage( "r_arb_buffer_storage",
"Use GL_ARB_buffer_storage if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_compute_shader( "r_arb_compute_shader",
"Use GL_ARB_compute_shader if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_direct_state_access( "r_arb_direct_state_access",
"Use GL_ARB_direct_state_access if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_framebuffer_object( "r_arb_framebuffer_object",
"Use GL_ARB_framebuffer_object if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_explicit_uniform_location( "r_arb_explicit_uniform_location",
"Use GL_ARB_explicit_uniform_location if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_gpu_shader5( "r_arb_gpu_shader5",
"Use GL_ARB_gpu_shader5 if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_half_float_pixel( "r_arb_half_float_pixel",
"Use GL_ARB_half_float_pixel if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_half_float_vertex( "r_arb_half_float_vertex",
"Use GL_ARB_half_float_vertex if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_indirect_parameters( "r_arb_indirect_parameters",
"Use GL_ARB_indirect_parameters if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_internalformat_query2( "r_arb_internalformat_query2",
"Use GL_ARB_internalformat_query2 if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_map_buffer_range( "r_arb_map_buffer_range",
"Use GL_ARB_map_buffer_range if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_multi_draw_indirect( "r_arb_multi_draw_indirect",
"Use GL_ARB_multi_draw_indirect if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shader_draw_parameters( "r_arb_shader_draw_parameters",
"Use GL_ARB_shader_draw_parameters if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shader_atomic_counters( "r_arb_shader_atomic_counters",
"Use GL_ARB_shader_atomic_counters if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shader_atomic_counter_ops( "r_arb_shader_atomic_counter_ops",
"Use GL_ARB_shader_atomic_counter_ops if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shader_image_load_store( "r_arb_shader_image_load_store",
"Use GL_ARB_shader_image_load_store if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shader_storage_buffer_object( "r_arb_shader_storage_buffer_object",
"Use GL_ARB_shader_storage_buffer_object if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_shading_language_420pack( "r_arb_shading_language_420pack",
"Use GL_ARB_shading_language_420pack if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_sync( "r_arb_sync",
"Use GL_ARB_sync if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_texture_gather( "r_arb_texture_gather",
"Use GL_ARB_texture_gather if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_uniform_buffer_object( "r_arb_uniform_buffer_object",
"Use GL_ARB_uniform_buffer_object if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_arb_vertex_attrib_binding( "r_arb_vertex_attrib_binding",
"Use GL_ARB_vertex_attrib_binding if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_ext_draw_buffers( "r_ext_draw_buffers",
"Use GL_EXT_draw_buffers if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_ext_gpu_shader4( "r_ext_gpu_shader4",
"Use GL_EXT_gpu_shader4 if available", Cvar::NONE, true );
static Cvar::Range<Cvar::Cvar<float>> r_ext_texture_filter_anisotropic( "r_ext_texture_filter_anisotropic",
"Use GL_EXT_texture_filter_anisotropic if available: anisotropy value", Cvar::NONE, 4.0f, 0.0f, 16.0f );
static Cvar::Cvar<bool> r_ext_texture_float( "r_ext_texture_float",
"Use GL_EXT_texture_float if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_ext_texture_integer( "r_ext_texture_integer",
"Use GL_EXT_texture_integer if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_ext_texture_rg( "r_ext_texture_rg",
"Use GL_EXT_texture_rg if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_khr_debug( "r_khr_debug",
"Use GL_KHR_debug if available", Cvar::NONE, true );
static Cvar::Cvar<bool> r_khr_shader_subgroup( "r_khr_shader_subgroup",
"Use GL_KHR_shader_subgroup if available", Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_amd_adrenalin_disableBindlessTexture(
"workaround.glDriver.amd.adrenalin.disableBindlessTexture",
"Disable ARB_bindless_texture on AMD Adrenalin driver",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_amd_oglp_disableBindlessTexture(
"workaround.glDriver.amd.oglp.disableBindlessTexture",
"Disable ARB_bindless_texture on AMD OGLP driver",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_ati_rv300_disableRgba16Blend(
"workaround.glDriver.mesa.ati.rv300.disableRgba16Blend",
"Disable misdetected RGBA16 on Mesa driver on RV300 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_ati_rv300_useFloatVertex(
"workaround.glDriver.mesa.ati.rv300.useFloatVertex",
"Use float vertex instead of supported-but-slower half-float vertex on Mesa driver on ATI RV300 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_ati_rv600_disableHyperZ(
"workaround.glDriver.mesa.ati.rv600.disableHyperZ",
"Disable Hyper-Z on Mesa driver on RV600 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_broadcom_vc4_useFloatVertex(
"workaround.glDriver.mesa.broadcom.vc4.useFloatVertex",
"Use float vertex instead of supported-but-slower half-float vertex on Mesa driver on Broadcom VC4 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_forceS3tc(
"workaround.glDriver.mesa.forceS3tc",
"Enable S3TC on Mesa even when libtxc-dxtn is not available",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_intel_gma3_forceFragmentShader(
"workaround.glDriver.mesa.intel.gma3.forceFragmentShader",
"Force fragment shader on Intel GMA Gen 3 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_intel_gma3_stubOcclusionQuery(
"workaround.glDriver.mesa.intel.gma3.stubOcclusionQuery",
"Stub out occlusion query on Intel GMA Gen 3 hardware",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_mesa_v241_disableBindlessTexture(
"workaround.glDriver.mesa.v241.disableBindlessTexture",
"Disable ARB_bindless_texture on Mesa 24.1 driver",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glDriver_nvidia_v340_disableTextureGather(
"workaround.glDriver.nvidia.v340.disableTextureGather",
"Disable ARB_texture_gather on Nvidia 340 driver",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glExtension_missingArbFbo_useExtFbo(
"workaround.glExtension.missingArbFbo.useExtFbo",
"Use EXT_framebuffer_object and EXT_framebuffer_blit when ARB_framebuffer_object is not available",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glExtension_glsl120_disableShaderDrawParameters(
"workaround.glExtension.glsl120.disableShaderDrawParameters",
"Disable ARB_shader_draw_parameters on GLSL 1.20",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glExtension_glsl120_disableGpuShader4(
"workaround.glExtension.glsl120.disableGpuShader4",
"Disable EXT_gpu_shader4 on GLSL 1.20",
Cvar::NONE, true );
static Cvar::Cvar<bool> workaround_glHardware_intel_useFirstProvokinVertex(
"workaround.glHardware.intel.useFirstProvokinVertex",
"Use first provoking vertex on Intel hardware supporting ARB_provoking_vertex",
Cvar::NONE, true );
SDL_Window *window = nullptr;
static SDL_GLContext glContext = nullptr;
#ifdef USE_SMP
static void GLimp_SetCurrentContext( bool enable )
{
if ( enable )
{
SDL_GL_MakeCurrent( window, glContext );
}
else
{
SDL_GL_MakeCurrent( window, nullptr );
}
}
/*
===========================================================
SMP acceleration
===========================================================
*/
/*
* I have no idea if this will even work...most platforms don't offer
* thread-safe OpenGL libraries.
*/
static SDL_mutex *smpMutex = nullptr;
static SDL_cond *renderCommandsEvent = nullptr;
static SDL_cond *renderCompletedEvent = nullptr;
static void ( *renderThreadFunction )() = nullptr;
static SDL_Thread *renderThread = nullptr;
/*
===============
GLimp_RenderThreadWrapper
===============
*/
ALIGN_STACK_FOR_MINGW static int GLimp_RenderThreadWrapper( void* )
{
// These printfs cause race conditions which mess up the console output
logger.Notice( "Render thread starting" );
renderThreadFunction();
GLimp_SetCurrentContext( false );
logger.Notice( "Render thread terminating" );
return 0;
}
/*
===============
GLimp_SpawnRenderThread
===============
*/
bool GLimp_SpawnRenderThread( void ( *function )() )
{
static bool warned = false;
if ( !warned )
{
logger.Warn( "You enable r_smp at your own risk!" );
warned = true;
}
if ( renderThread != nullptr ) /* hopefully just a zombie at this point... */
{
logger.Notice( "Already a render thread? Trying to clean it up..." );
GLimp_ShutdownRenderThread();
}
smpMutex = SDL_CreateMutex();
if ( smpMutex == nullptr )
{
logger.Notice( "smpMutex creation failed: %s", SDL_GetError() );
GLimp_ShutdownRenderThread();
return false;
}
renderCommandsEvent = SDL_CreateCond();
if ( renderCommandsEvent == nullptr )
{
logger.Notice( "renderCommandsEvent creation failed: %s", SDL_GetError() );
GLimp_ShutdownRenderThread();
return false;
}
renderCompletedEvent = SDL_CreateCond();
if ( renderCompletedEvent == nullptr )
{
logger.Notice( "renderCompletedEvent creation failed: %s", SDL_GetError() );
GLimp_ShutdownRenderThread();
return false;
}
renderThreadFunction = function;
renderThread = SDL_CreateThread( GLimp_RenderThreadWrapper, "render thread", nullptr );
if ( renderThread == nullptr )
{
logger.Notice("SDL_CreateThread() returned %s", SDL_GetError() );
GLimp_ShutdownRenderThread();
return false;
}
return true;
}
/*
===============
GLimp_ShutdownRenderThread
===============
*/
void GLimp_ShutdownRenderThread()
{
if ( renderThread != nullptr )
{
GLimp_WakeRenderer( nullptr );
SDL_WaitThread( renderThread, nullptr );
renderThread = nullptr;
glConfig.smpActive = false;
}
if ( smpMutex != nullptr )
{
SDL_DestroyMutex( smpMutex );
smpMutex = nullptr;
}
if ( renderCommandsEvent != nullptr )
{
SDL_DestroyCond( renderCommandsEvent );
renderCommandsEvent = nullptr;
}
if ( renderCompletedEvent != nullptr )
{
SDL_DestroyCond( renderCompletedEvent );
renderCompletedEvent = nullptr;
}
renderThreadFunction = nullptr;
}
static volatile void *smpData = nullptr;
static volatile bool smpDataReady;
/*
===============
GLimp_RendererSleep
===============
*/
void *GLimp_RendererSleep()
{
void *data = nullptr;
GLimp_SetCurrentContext( false );
SDL_LockMutex( smpMutex );
{
smpData = nullptr;
smpDataReady = false;
// after this, the front end can exit GLimp_FrontEndSleep
SDL_CondSignal( renderCompletedEvent );
while ( !smpDataReady )
{
SDL_CondWait( renderCommandsEvent, smpMutex );
}
data = ( void * ) smpData;
}
SDL_UnlockMutex( smpMutex );
GLimp_SetCurrentContext( true );
return data;
}
/*
===============
GLimp_FrontEndSleep
===============
*/
void GLimp_FrontEndSleep()
{
SDL_LockMutex( smpMutex );
{
while ( smpData )
{
SDL_CondWait( renderCompletedEvent, smpMutex );
}
}
SDL_UnlockMutex( smpMutex );
}
/*
===============
GLimp_SyncRenderThread
===============
*/
void GLimp_SyncRenderThread()
{
GLimp_FrontEndSleep();
GLimp_SetCurrentContext( true );
}
/*
===============
GLimp_WakeRenderer
===============
*/
void GLimp_WakeRenderer( void *data )
{
GLimp_SetCurrentContext( false );
SDL_LockMutex( smpMutex );
{
ASSERT(smpData == nullptr);
smpData = data;
smpDataReady = true;
// after this, the renderer can continue through GLimp_RendererSleep
SDL_CondSignal( renderCommandsEvent );
}
SDL_UnlockMutex( smpMutex );
}
#else
// No SMP - stubs
void GLimp_RenderThreadWrapper( void* )
{
}
bool GLimp_SpawnRenderThread( void ( * )() )
{
logger.Warn("SMP support was disabled at compile time" );
return false;
}
void GLimp_ShutdownRenderThread()
{
}
void *GLimp_RendererSleep()
{
return nullptr;
}
void GLimp_FrontEndSleep()
{
}
void GLimp_SyncRenderThread()
{
}
void GLimp_WakeRenderer( void* )
{
}
#endif
enum class rserr_t
{
RSERR_OK,
RSERR_RESTART,
RSERR_INVALID_FULLSCREEN,
RSERR_INVALID_MODE,
RSERR_MISSING_GL,
RSERR_OLD_GL,
RSERR_UNKNOWN
};
cvar_t *r_allowResize; // make window resizable
cvar_t *r_centerWindow;
cvar_t *r_displayIndex;
cvar_t *r_sdlDriver;
static void GLimp_DestroyContextIfExists();
static void GLimp_DestroyWindowIfExists();
/*
===============
GLimp_Shutdown
===============
*/
void GLimp_Shutdown()
{
logger.Debug("Shutting down OpenGL subsystem" );
ri.IN_Shutdown();
#if defined( USE_SMP )
if ( renderThread != nullptr )
{
logger.Notice( "Destroying renderer thread..." );
GLimp_ShutdownRenderThread();
}
#endif
GLimp_DestroyContextIfExists();
GLimp_DestroyWindowIfExists();
SDL_QuitSubSystem( SDL_INIT_VIDEO );
ResetStruct( glConfig );
ResetStruct( glState );
}
static Cmd::LambdaCmd minimizeCmd(
"minimize", Cmd::CLIENT, "minimize the window",
[]( const Cmd::Args & ) { SDL_MinimizeWindow( window ); });
static void SetSwapInterval( int swapInterval )
{
/* Set the swap interval for the OpenGL context.
* -1 : adaptive sync
* 0 : immediate update
* 1 : generic sync, updates synchronized with the vertical refresh
* N : generic sync occurring on Nth vertical refresh
* -N : adaptive sync occurring on Nth vertical refresh
For example if screen has 60 Hz refresh rate:
* -1 will update the screen 60 times per second,
using adaptive sync if supported,
* 0 will update the screen as soon as it can,
* 1 will update the screen 60 times per second,
* 2 will update the screen 30 times per second.
* 3 will update the screen 20 times per second,
* 4 will update the screen 15 times per second,
* -4 will update the screen 15 times per second,
using adaptive sync if supported,
About adaptive sync:
> Some systems allow specifying -1 for the interval,
> to enable adaptive vsync.
> Adaptive vsync works the same as vsync, but if you've
> already missed the vertical retrace for a given frame,
> it swaps buffers immediately, which might be less
> jarring for the user during occasional framerate drops.
> -- https://wiki.libsdl.org/SDL_GL_SetSwapInterval
About the accepted values:
> A swap interval greater than 0 means that the GPU may force
> the CPU to wait due to previously issued buffer swaps.
> -- https://www.khronos.org/opengl/wiki/Swap_Interval
> If <interval> is negative, the minimum number of video frames
> between buffer swaps is the absolute value of <interval>.
> -- https://www.khronos.org/registry/OpenGL/extensions/EXT/GLX_EXT_swap_control_tear.txt
The max value is said to be implementation-dependent:
> The current swap interval and implementation-dependent max
> swap interval for a particular drawable can be obtained by
> calling glXQueryDrawable with the attribute […]
> -- https://www.khronos.org/registry/OpenGL/extensions/EXT/GLX_EXT_swap_control_tear.txt
About how to deal with errors:
> If an application requests adaptive vsync and the system
> does not support it, this function will fail and return -1.
> In such a case, you should probably retry the call with 1
> for the interval.
> -- https://wiki.libsdl.org/SDL_GL_SetSwapInterval
Given what's written in Swap Interval Khronos page, setting r_finish
to 1 or 0 to call or not call glFinish may impact the behaviour.
See https://www.khronos.org/opengl/wiki/Swap_Interval#GPU_vs_CPU_synchronization
According to the SDL documentation, only arguments from -1 to 1
are allowed to SDL_GL_SetSwapInterval. But investigation of SDL
internals shows that larger intervals should work on Linux and
Windows. See https://github.com/DaemonEngine/Daemon/pull/497
Only 0 and 1 work on Mac.
5 and -5 are arbitrarily set as ceiling and floor value
to prevent mistakes making the game unresponsive. */
R_SyncRenderThread();
int sign = swapInterval < 0 ? -1 : 1;
int interval = std::abs( swapInterval );
while ( SDL_GL_SetSwapInterval( sign * interval ) == -1 )
{
if ( sign == -1 )
{
logger.Warn("Adaptive sync is unsupported, fallback to generic sync: %s", SDL_GetError() );
sign = 1;
}
else
{
if ( interval > 1 )
{
logger.Warn("Sync interval %d is unsupported, fallback to 1: %s", interval, SDL_GetError() );
interval = 1;
}
else if ( interval == 1 )
{
logger.Warn("Sync is unsupported, disabling sync: %s", SDL_GetError() );
interval = 0;
}
else if ( interval == 0 )
{
logger.Warn("Can't disable sync, something is wrong: %s", SDL_GetError() );
break;
}
}
}
}
/*
===============
GLimp_CompareModes
===============
*/
static int GLimp_CompareModes( const void *a, const void *b )
{
const float ASPECT_EPSILON = 0.001f;
SDL_Rect *modeA = ( SDL_Rect * ) a;
SDL_Rect *modeB = ( SDL_Rect * ) b;
float aspectA = ( float ) modeA->w / ( float ) modeA->h;
float aspectB = ( float ) modeB->w / ( float ) modeB->h;
int areaA = modeA->w * modeA->h;
int areaB = modeB->w * modeB->h;
float aspectDiffA = fabsf( aspectA - glConfig.displayAspect );
float aspectDiffB = fabsf( aspectB - glConfig.displayAspect );
float aspectDiffsDiff = aspectDiffA - aspectDiffB;
if ( aspectDiffsDiff > ASPECT_EPSILON )
{
return 1;
}
else if ( aspectDiffsDiff < -ASPECT_EPSILON )
{
return -1;
}
else
{
return areaA - areaB;
}
}
/*
===============
GLimp_DetectAvailableModes
===============
*/
static bool GLimp_DetectAvailableModes()
{
char buf[ MAX_STRING_CHARS ] = { 0 };
SDL_Rect modes[ 128 ];
int numModes = 0;
int i;
SDL_DisplayMode windowMode;
int display;
display = SDL_GetWindowDisplayIndex( window );
if ( SDL_GetWindowDisplayMode( window, &windowMode ) < 0 )
{
logger.Warn("Couldn't get window display mode: %s", SDL_GetError() );
/* FIXME: returning true means the engine will crash if the window size is
larger than what the GPU can support, but we need to not fail to open a window
with a size the GPU can handle even if not using native screen resolutions. */
return true;
}
for ( i = 0; i < SDL_GetNumDisplayModes( display ); i++ )
{
SDL_DisplayMode mode;
if ( SDL_GetDisplayMode( display, i, &mode ) < 0 )
{
continue;
}
if ( !mode.w || !mode.h )
{
logger.Notice("Display supports any resolution" );
return true;
}
if ( windowMode.format != mode.format || windowMode.refresh_rate != mode.refresh_rate )
{
continue;
}
modes[ numModes ].w = mode.w;
modes[ numModes ].h = mode.h;
numModes++;
}
if ( numModes > 1 )
{
qsort( modes, numModes, sizeof( SDL_Rect ), GLimp_CompareModes );
}
for ( i = 0; i < numModes; i++ )
{
const char *newModeString = va( "%ux%u ", modes[ i ].w, modes[ i ].h );
if ( strlen( newModeString ) < sizeof( buf ) - strlen( buf ) )
{
Q_strcat( buf, sizeof( buf ), newModeString );
}
else
{
logger.Warn("Skipping mode %ux%x, buffer too small", modes[ i ].w, modes[ i ].h );
}
}
if ( *buf )
{
logger.Notice("Available modes: '%s'", buf );
Cvar::SetValueForce( r_availableModes.Name(), buf );
}
return true;
}
enum class glProfile {
UNDEFINED = 0,
COMPATIBILITY = 1,
CORE = 2,
};
struct glConfiguration {
int major;
int minor;
glProfile profile;
int colorBits;
};
static bool operator!=(const glConfiguration& c1, const glConfiguration& c2) {
return c1.major != c2.major
|| c1.minor != c2.minor
|| c1.profile != c2.profile
|| c1.colorBits != c2.colorBits;
}
static const char* GLimp_getProfileName( glProfile profile )
{
ASSERT(profile != glProfile::UNDEFINED);
return profile == glProfile::CORE ? "core" : "compatibility";
}
static std::string ContextDescription( const glConfiguration& configuration )
{
return Str::Format( "%d-bit OpenGL %d.%d %s",
configuration.colorBits,
configuration.major,
configuration.minor,
GLimp_getProfileName( configuration.profile ) );
}
static void GLimp_SetAttributes( const glConfiguration &configuration )
{
// FIXME: 3 * 4 = 12 which is more than 8
int perChannelColorBits = configuration.colorBits == 24 ? 8 : 4;
SDL_GL_SetAttribute( SDL_GL_RED_SIZE, perChannelColorBits );
SDL_GL_SetAttribute( SDL_GL_GREEN_SIZE, perChannelColorBits );
SDL_GL_SetAttribute( SDL_GL_BLUE_SIZE, perChannelColorBits );
// Depth/stencil channels are not needed since all 3D rendering is done in FBOs
SDL_GL_SetAttribute( SDL_GL_DEPTH_SIZE, 0 );
SDL_GL_SetAttribute( SDL_GL_STENCIL_SIZE, 0 );
SDL_GL_SetAttribute( SDL_GL_DOUBLEBUFFER, 1 );
if ( !r_glAllowSoftware->integer )
{
SDL_GL_SetAttribute( SDL_GL_ACCELERATED_VISUAL, 1 );
}
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, configuration.major );
SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, configuration.minor );
if ( configuration.profile == glProfile::CORE )
{
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
}
else
{
SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY );
}
if ( r_glDebugProfile.Get() )
{
SDL_GL_SetAttribute( SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG );
}
}
static bool GLimp_CreateWindow( bool fullscreen, bool bordered, const glConfiguration &configuration )
{
/* The requested attributes should be set before creating
an OpenGL window.
-- http://wiki.libsdl.org/SDL_GL_SetAttribute */
GLimp_SetAttributes( configuration );
Uint32 flags = SDL_WINDOW_HIDDEN | SDL_WINDOW_OPENGL;
if ( r_allowResize->integer )
{
flags |= SDL_WINDOW_RESIZABLE;
}
SDL_Surface *icon = nullptr;
icon = SDL_CreateRGBSurfaceFrom( ( void * ) CLIENT_WINDOW_ICON.pixel_data,
CLIENT_WINDOW_ICON.width,
CLIENT_WINDOW_ICON.height,
CLIENT_WINDOW_ICON.bytes_per_pixel * 8,
CLIENT_WINDOW_ICON.bytes_per_pixel * CLIENT_WINDOW_ICON.width,
#ifdef Q3_LITTLE_ENDIAN
0x000000FF, 0x0000FF00, 0x00FF0000, 0xFF000000
#else
0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF
#endif
);
const char *windowType = nullptr;
if ( fullscreen )
{
flags |= SDL_WINDOW_FULLSCREEN;
windowType = "fullscreen";
}
/* We need to set borderless flag even when fullscreen
because otherwise when disabling fullscreen the window
will be bordered while the borderless option is enabled. */
if ( !bordered )
{
flags |= SDL_WINDOW_BORDERLESS;
/* Don't tell fullscreen window is borderless,
it's meaningless. */
if ( ! fullscreen )
{
windowType = "borderless";
}
}
int x, y;
if ( r_centerWindow->integer )
{
// center window on specified display
x = SDL_WINDOWPOS_CENTERED_DISPLAY( r_displayIndex->integer );
y = SDL_WINDOWPOS_CENTERED_DISPLAY( r_displayIndex->integer );
}
else
{
x = SDL_WINDOWPOS_UNDEFINED_DISPLAY( r_displayIndex->integer );
y = SDL_WINDOWPOS_UNDEFINED_DISPLAY( r_displayIndex->integer );
}
window = SDL_CreateWindow( CLIENT_WINDOW_TITLE, x, y, glConfig.vidWidth, glConfig.vidHeight, flags );
if ( window )
{
int w, h;
SDL_GetWindowPosition( window, &x, &y );
SDL_GetWindowSize( window, &w, &h );
logger.Debug( "SDL %s%swindow created at %d,%d with %d×%d size",
windowType ? windowType : "",
windowType ? " ": "",
x, y, w, h );
}
else
{
logger.Warn( "SDL %d×%d %s%swindow not created",
glConfig.vidWidth, glConfig.vidHeight,
windowType ? windowType : "",
windowType ? " ": "" );
logger.Warn("SDL_CreateWindow failed: %s", SDL_GetError() );
return false;
}
SDL_SetWindowIcon( window, icon );
SDL_FreeSurface( icon );
return true;
}
static void GLimp_DestroyContextIfExists()
{
if ( glContext != nullptr )
{
SDL_GL_DeleteContext( glContext );
glContext = nullptr;
}
}
static void GLimp_DestroyWindowIfExists()
{
// Do not let orphaned context alive.
GLimp_DestroyContextIfExists();
if ( window != nullptr )
{
int x, y, w, h;
SDL_GetWindowPosition( window, &x, &y );
SDL_GetWindowSize( window, &w, &h );
logger.Debug("Destroying %d×%d SDL window at %d,%d", w, h, x, y );
SDL_DestroyWindow( window );
window = nullptr;
}
}
static bool GLimp_CreateContext( const glConfiguration &configuration )
{
GLimp_DestroyContextIfExists();
glContext = SDL_GL_CreateContext( window );
if ( glContext == nullptr )
{
logger.Debug( "Invalid context: %s", ContextDescription( configuration ) );
return false;
}
if ( glGetString( GL_VERSION ) == nullptr )
{
Sys::Error(
"SDL returned a broken OpenGL context.\n\n"
"Please report the bug and tell us what is your operating system,\n"
"OpenGL driver, graphic card, and if you built the game yourself.\n\n"
#if defined(DAEMON_OPENGL_ABI_GLVND)
"This engine was built with the \"GLVND\" OpenGL ABI,\n"
"try to reconfigure the build with the \"LEGACY\" one:\n\n"
" cmake -DOpenGL_GL_PREFERENCE=LEGACY\n\n"
#endif
"See: https://github.com/DaemonEngine/Daemon/issues/945"
);
}
return true;
}
/* GLimp_DestroyWindowIfExists checks if window exists before
destroying it so we can call GLimp_RecreateWindowWhenChange even
if no window is created yet. */
static bool GLimp_RecreateWindowWhenChange( const bool fullscreen, const bool bordered, const glConfiguration &configuration )
{
/* Those values doen't contribute to anything
when the window isn't created yet. */
static bool currentFullscreen = false;
static bool currentBordered = false;
static int currentWidth = 0;
static int currentHeight = 0;
static glConfiguration currentConfiguration = {};
if ( window == nullptr
/* We don't care if comparing default values
is wrong when the window isn't created yet as
the first thing we do is to overwrite them. */
|| glConfig.vidWidth != currentWidth
|| glConfig.vidHeight != currentHeight
|| configuration != currentConfiguration )
{
currentWidth = glConfig.vidWidth;
currentHeight = glConfig.vidHeight;
currentConfiguration = configuration;
GLimp_DestroyWindowIfExists();
if ( !GLimp_CreateWindow( fullscreen, bordered, configuration ) )
{
return false;
}
}
if ( fullscreen != currentFullscreen )
{
Uint32 flags = fullscreen ? SDL_WINDOW_FULLSCREEN : 0;
int sdlToggled = SDL_SetWindowFullscreen( window, flags );
if ( sdlToggled < 0 )
{
GLimp_DestroyWindowIfExists();
if ( !GLimp_CreateWindow( fullscreen, bordered, configuration ) )
{
return false;
}