1#include <base/detect.h>
2
3#ifndef CONF_BACKEND_OPENGL_ES
4#include <GL/glew.h>
5#endif
6
7#include <base/log.h>
8#include <base/math.h>
9#include <base/sphore.h>
10#include <base/str.h>
11#include <base/thread.h>
12
13#include <engine/shared/config.h>
14#include <engine/shared/localization.h>
15
16#include <SDL.h>
17#include <SDL_messagebox.h>
18#include <SDL_vulkan.h>
19
20#if defined(CONF_VIDEORECORDER)
21#include <engine/shared/video.h>
22#endif
23
24#include "backend_sdl.h"
25
26#if defined(CONF_HEADLESS_CLIENT)
27#include "backend/null/backend_null.h"
28#endif
29
30#if !defined(CONF_BACKEND_OPENGL_ES)
31#include "backend/opengl/backend_opengl3.h"
32#endif
33
34#if defined(CONF_BACKEND_OPENGL_ES3) || defined(CONF_BACKEND_OPENGL_ES)
35#include "backend/opengles/backend_opengles3.h"
36#endif
37
38#if defined(CONF_BACKEND_VULKAN)
39#include "backend/vulkan/backend_vulkan.h"
40#endif
41
42#include "graphics_threaded.h"
43
44#include <engine/graphics.h>
45
46#include <algorithm>
47#include <cstdlib>
48
49class IStorage;
50
51// ------------ CGraphicsBackend_Threaded
52
53// Run everything single threaded when compiling for Emscripten, as context binding does not work outside of the main thread with SDL2.
54// TODO SDL3: Check if SDL3 supports threaded graphics and PROXY_TO_PTHREAD, OFFSCREENCANVAS_SUPPORT and OFFSCREEN_FRAMEBUFFER correctly.
55#if !defined(CONF_PLATFORM_EMSCRIPTEN)
56void CGraphicsBackend_Threaded::ThreadFunc(void *pUser)
57{
58 auto *pSelf = (CGraphicsBackend_Threaded *)pUser;
59 std::unique_lock<std::mutex> Lock(pSelf->m_BufferSwapMutex);
60 // notify, that the thread started
61 pSelf->m_Started = true;
62 pSelf->m_BufferSwapCond.notify_all();
63 while(!pSelf->m_Shutdown)
64 {
65 pSelf->m_BufferSwapCond.wait(lock&: Lock, p: [&pSelf] { return pSelf->m_pBuffer != nullptr || pSelf->m_Shutdown; });
66 if(pSelf->m_pBuffer)
67 {
68#ifdef CONF_PLATFORM_MACOS
69 CAutoreleasePool AutoreleasePool;
70#endif
71 pSelf->m_pProcessor->RunBuffer(pBuffer: pSelf->m_pBuffer);
72
73 pSelf->m_pBuffer = nullptr;
74 pSelf->m_BufferInProcess.store(i: false, m: std::memory_order_relaxed);
75 pSelf->m_BufferSwapCond.notify_all();
76
77#if defined(CONF_VIDEORECORDER)
78 if(IVideo::Current())
79 IVideo::Current()->NextVideoFrameThread();
80#endif
81 }
82 }
83}
84#endif
85
86CGraphicsBackend_Threaded::CGraphicsBackend_Threaded(TTranslateFunc &&TranslateFunc) :
87 m_TranslateFunc(std::move(TranslateFunc))
88{
89 m_pProcessor = nullptr;
90 m_Shutdown = true;
91#if !defined(CONF_PLATFORM_EMSCRIPTEN)
92 m_pBuffer = nullptr;
93 m_BufferInProcess.store(i: false, m: std::memory_order_relaxed);
94#endif
95}
96
97void CGraphicsBackend_Threaded::StartProcessor(ICommandProcessor *pProcessor)
98{
99 dbg_assert(m_Shutdown, "Processor was already not shut down.");
100 m_Shutdown = false;
101 m_pProcessor = pProcessor;
102#if !defined(CONF_PLATFORM_EMSCRIPTEN)
103 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
104 m_pThread = thread_init(threadfunc: ThreadFunc, user: this, name: "Graphics thread");
105 // wait for the thread to start
106 m_BufferSwapCond.wait(lock&: Lock, p: [this]() -> bool { return m_Started; });
107#endif
108}
109
110void CGraphicsBackend_Threaded::StopProcessor()
111{
112 dbg_assert(!m_Shutdown, "Processor was already shut down.");
113 m_Shutdown = true;
114#if defined(CONF_PLATFORM_EMSCRIPTEN)
115 m_Warning = m_pProcessor->GetWarning();
116#else
117 {
118 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
119 m_Warning = m_pProcessor->GetWarning();
120 m_BufferSwapCond.notify_all();
121 }
122 thread_wait(thread: m_pThread);
123#endif
124}
125
126void CGraphicsBackend_Threaded::RunBuffer(CCommandBuffer *pBuffer)
127{
128 SGfxErrorContainer Error;
129#if defined(CONF_PLATFORM_EMSCRIPTEN)
130 Error = m_pProcessor->GetError();
131 if(Error.m_ErrorType == GFX_ERROR_TYPE_NONE)
132 {
133 RunBufferSingleThreadedUnsafe(pBuffer);
134#if defined(CONF_VIDEORECORDER)
135 if(IVideo::Current())
136 IVideo::Current()->NextVideoFrameThread();
137#endif
138 }
139#else
140 WaitForIdle();
141 {
142 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
143 Error = m_pProcessor->GetError();
144 if(Error.m_ErrorType == GFX_ERROR_TYPE_NONE)
145 {
146 m_pBuffer = pBuffer;
147 m_BufferInProcess.store(i: true, m: std::memory_order_relaxed);
148 m_BufferSwapCond.notify_all();
149 }
150 }
151#endif
152
153 // Process error after lock is released to prevent deadlock
154 if(Error.m_ErrorType != GFX_ERROR_TYPE_NONE)
155 {
156 ProcessError(Error);
157 }
158}
159
160void CGraphicsBackend_Threaded::RunBufferSingleThreadedUnsafe(CCommandBuffer *pBuffer)
161{
162 m_pProcessor->RunBuffer(pBuffer);
163}
164
165bool CGraphicsBackend_Threaded::IsIdle() const
166{
167#if defined(CONF_PLATFORM_EMSCRIPTEN)
168 return true;
169#else
170 return !m_BufferInProcess.load(m: std::memory_order_relaxed);
171#endif
172}
173
174void CGraphicsBackend_Threaded::WaitForIdle()
175{
176#if !defined(CONF_PLATFORM_EMSCRIPTEN)
177 std::unique_lock<std::mutex> Lock(m_BufferSwapMutex);
178 m_BufferSwapCond.wait(lock&: Lock, p: [this]() { return m_pBuffer == nullptr; });
179#endif
180}
181
182void CGraphicsBackend_Threaded::ProcessError(const SGfxErrorContainer &Error)
183{
184 m_FatalError = "";
185 for(const auto &ErrStr : Error.m_vErrors)
186 {
187 if(!m_FatalError.empty())
188 {
189 m_FatalError.append(s: "\n");
190 }
191 if(ErrStr.m_RequiresTranslation)
192 m_FatalError.append(s: m_TranslateFunc(ErrStr.m_Err.c_str(), ""));
193 else
194 m_FatalError.append(str: ErrStr.m_Err);
195 }
196 std::string LogMessage = "Graphics Error:\n" + m_FatalError;
197 dbg_assert_failed("%s", LogMessage.c_str());
198}
199
200const char *CGraphicsBackend_Threaded::GetFatalError() const
201{
202 return m_FatalError.c_str();
203}
204
205bool CGraphicsBackend_Threaded::GetWarning(std::vector<std::string> &WarningStrings)
206{
207 if(m_Warning.m_WarningType != GFX_WARNING_TYPE_NONE)
208 {
209 m_Warning.m_WarningType = GFX_WARNING_TYPE_NONE;
210 WarningStrings = m_Warning.m_vWarnings;
211 return true;
212 }
213 return false;
214}
215
216// ------------ CCommandProcessorFragment_General
217
218void CCommandProcessorFragment_General::Cmd_Signal(const CCommandBuffer::SCommand_Signal *pCommand)
219{
220 pCommand->m_pSemaphore->Signal();
221}
222
223bool CCommandProcessorFragment_General::RunCommand(const CCommandBuffer::SCommand *pBaseCommand)
224{
225 switch(pBaseCommand->m_Cmd)
226 {
227 case CCommandBuffer::CMD_SIGNAL: Cmd_Signal(pCommand: static_cast<const CCommandBuffer::SCommand_Signal *>(pBaseCommand)); break;
228 default: return false;
229 }
230
231 return true;
232}
233
234// ------------ CCommandProcessorFragment_SDL
235void CCommandProcessorFragment_SDL::Cmd_Init(const SCommand_Init *pCommand)
236{
237 m_GLContext = pCommand->m_GLContext;
238 m_pWindow = pCommand->m_pWindow;
239 if(m_GLContext)
240 SDL_GL_MakeCurrent(window: m_pWindow, context: m_GLContext);
241}
242
243void CCommandProcessorFragment_SDL::Cmd_Shutdown(const SCommand_Shutdown *pCommand)
244{
245 if(m_GLContext)
246 SDL_GL_MakeCurrent(window: nullptr, context: nullptr);
247}
248
249void CCommandProcessorFragment_SDL::Cmd_Swap(const CCommandBuffer::SCommand_Swap *pCommand)
250{
251 if(m_GLContext)
252 SDL_GL_SwapWindow(window: m_pWindow);
253}
254
255void CCommandProcessorFragment_SDL::Cmd_VSync(const CCommandBuffer::SCommand_VSync *pCommand)
256{
257 if(m_GLContext)
258 {
259#if defined(CONF_PLATFORM_EMSCRIPTEN)
260 // SDL_GL_SetSwapInterval is not supported with Emscripten as this is only a wrapper for the
261 // emscripten_set_main_loop_timing function which does not work because we do not use the
262 // emscripten_set_main_loop function before.
263 *pCommand->m_pRetOk = !pCommand->m_VSync;
264#else
265 *pCommand->m_pRetOk = SDL_GL_SetSwapInterval(interval: pCommand->m_VSync) == 0;
266#endif
267 }
268}
269
270void CCommandProcessorFragment_SDL::Cmd_WindowCreateNtf(const CCommandBuffer::SCommand_WindowCreateNtf *pCommand)
271{
272 m_pWindow = SDL_GetWindowFromID(id: pCommand->m_WindowId);
273 // Android destroys windows when they are not visible, so we get the new one and work with that
274 // The graphic context does not need to be recreated, just unbound see @see SCommand_WindowDestroyNtf
275#ifdef CONF_PLATFORM_ANDROID
276 if(m_GLContext)
277 SDL_GL_MakeCurrent(m_pWindow, m_GLContext);
278#endif
279}
280
281void CCommandProcessorFragment_SDL::Cmd_WindowDestroyNtf(const CCommandBuffer::SCommand_WindowDestroyNtf *pCommand)
282{
283 // Unbind the graphic context from the window, so it does not get destroyed
284#ifdef CONF_PLATFORM_ANDROID
285 if(m_GLContext)
286 SDL_GL_MakeCurrent(nullptr, nullptr);
287#endif
288}
289
290CCommandProcessorFragment_SDL::CCommandProcessorFragment_SDL() = default;
291
292bool CCommandProcessorFragment_SDL::RunCommand(const CCommandBuffer::SCommand *pBaseCommand)
293{
294 switch(pBaseCommand->m_Cmd)
295 {
296 case CCommandBuffer::CMD_WINDOW_CREATE_NTF: Cmd_WindowCreateNtf(pCommand: static_cast<const CCommandBuffer::SCommand_WindowCreateNtf *>(pBaseCommand)); break;
297 case CCommandBuffer::CMD_WINDOW_DESTROY_NTF: Cmd_WindowDestroyNtf(pCommand: static_cast<const CCommandBuffer::SCommand_WindowDestroyNtf *>(pBaseCommand)); break;
298 case CCommandBuffer::CMD_SWAP: Cmd_Swap(pCommand: static_cast<const CCommandBuffer::SCommand_Swap *>(pBaseCommand)); break;
299 case CCommandBuffer::CMD_VSYNC: Cmd_VSync(pCommand: static_cast<const CCommandBuffer::SCommand_VSync *>(pBaseCommand)); break;
300 case CCommandBuffer::CMD_MULTISAMPLING: break;
301 case CMD_INIT: Cmd_Init(pCommand: static_cast<const SCommand_Init *>(pBaseCommand)); break;
302 case CMD_SHUTDOWN: Cmd_Shutdown(pCommand: static_cast<const SCommand_Shutdown *>(pBaseCommand)); break;
303 case CCommandProcessorFragment_GLBase::CMD_PRE_INIT: break;
304 case CCommandProcessorFragment_GLBase::CMD_POST_SHUTDOWN: break;
305 default: return false;
306 }
307
308 return true;
309}
310
311// ------------ CCommandProcessor_SDL_GL
312
313void CCommandProcessor_SDL_GL::HandleError()
314{
315 switch(m_Error.m_ErrorType)
316 {
317 case GFX_ERROR_TYPE_INIT:
318 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "Failed during initialization. Try to change gfx_backend to OpenGL or Vulkan in settings_ddnet.cfg in the config directory and try again.", pContext: "Graphics error")});
319 break;
320 case GFX_ERROR_TYPE_OUT_OF_MEMORY_IMAGE:
321 [[fallthrough]];
322 case GFX_ERROR_TYPE_OUT_OF_MEMORY_BUFFER:
323 [[fallthrough]];
324 case GFX_ERROR_TYPE_OUT_OF_MEMORY_STAGING:
325 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "Out of VRAM. Try setting 'cl_skins_loaded_max' to a lower value or remove custom assets (skins, entities, etc.), especially those with high resolution.", pContext: "Graphics error")});
326 break;
327 case GFX_ERROR_TYPE_RENDER_RECORDING:
328 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "An error during command recording occurred. Try to update your GPU drivers.", pContext: "Graphics error")});
329 break;
330 case GFX_ERROR_TYPE_RENDER_CMD_FAILED:
331 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "A render command failed. Try to update your GPU drivers.", pContext: "Graphics error")});
332 break;
333 case GFX_ERROR_TYPE_RENDER_SUBMIT_FAILED:
334 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "Submitting the render commands failed. Try to update your GPU drivers.", pContext: "Graphics error")});
335 break;
336 case GFX_ERROR_TYPE_SWAP_FAILED:
337 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "Failed to swap framebuffers. Try to update your GPU drivers.", pContext: "Graphics error")});
338 break;
339 case GFX_ERROR_TYPE_UNKNOWN:
340 [[fallthrough]];
341 default:
342 m_Error.m_vErrors.emplace_back(args: SGfxErrorContainer::SError{.m_RequiresTranslation: true, .m_Err: Localizable(pStr: "Unknown error. Try to change gfx_backend to OpenGL or Vulkan in settings_ddnet.cfg in the config directory and try again.", pContext: "Graphics error")});
343 break;
344 }
345}
346
347void CCommandProcessor_SDL_GL::HandleWarning()
348{
349 switch(m_Warning.m_WarningType)
350 {
351 case GFX_WARNING_TYPE_INIT_FAILED:
352 m_Warning.m_vWarnings.emplace_back(args: Localizable(pStr: "Could not initialize the given graphics backend, reverting to the default backend now.", pContext: "Graphics error"));
353 break;
354 case GFX_WARNING_TYPE_INIT_FAILED_MISSING_INTEGRATED_GPU_DRIVER:
355 m_Warning.m_vWarnings.emplace_back(args: Localizable(pStr: "Could not initialize the given graphics backend, this is probably because you didn't install the driver of the integrated graphics card.", pContext: "Graphics error"));
356 break;
357 case GFX_WARNING_MISSING_EXTENSION:
358 // ignore this warning for now
359 return;
360 case GFX_WARNING_LOW_ON_MEMORY:
361 // ignore this warning for now
362 return;
363 case GFX_WARNING_TYPE_INIT_FAILED_NO_DEVICE_WITH_REQUIRED_VERSION:
364 {
365 // Ignore this warning for now completely.
366 // A console message was already printed by the backend
367 m_Warning.m_WarningType = GFX_WARNING_TYPE_NONE;
368 m_Warning.m_vWarnings.clear();
369 return;
370 }
371 default:
372 dbg_assert_failed("Unhandled graphics warning type %d", (int)m_Warning.m_WarningType);
373 }
374}
375
376void CCommandProcessor_SDL_GL::RunBuffer(CCommandBuffer *pBuffer)
377{
378 m_pGLBackend->StartCommands(CommandCount: pBuffer->m_CommandCount, EstimatedRenderCallCount: pBuffer->m_RenderCallCount);
379
380 for(const CCommandBuffer::SCommand *pCommand = pBuffer->Head(); pCommand; pCommand = pCommand->m_pNext)
381 {
382 auto Res = m_pGLBackend->RunCommand(pBaseCommand: pCommand);
383 if(Res == ERunCommandReturnTypes::RUN_COMMAND_COMMAND_HANDLED)
384 {
385 continue;
386 }
387 else if(Res == ERunCommandReturnTypes::RUN_COMMAND_COMMAND_ERROR)
388 {
389 m_Error = m_pGLBackend->GetError();
390 HandleError();
391 return;
392 }
393 else if(Res == ERunCommandReturnTypes::RUN_COMMAND_COMMAND_WARNING)
394 {
395 m_Warning = m_pGLBackend->GetWarning();
396 HandleWarning();
397 return;
398 }
399
400 if(m_SDL.RunCommand(pBaseCommand: pCommand))
401 continue;
402
403 if(m_General.RunCommand(pBaseCommand: pCommand))
404 continue;
405
406 dbg_assert_failed("Unknown graphics command %d", pCommand->m_Cmd);
407 }
408
409 m_pGLBackend->EndCommands();
410}
411
412CCommandProcessor_SDL_GL::CCommandProcessor_SDL_GL(EBackendType BackendType, int GLMajor, int GLMinor, int GLPatch)
413{
414 m_BackendType = BackendType;
415
416#if defined(CONF_HEADLESS_CLIENT)
417 m_pGLBackend = new CCommandProcessorFragment_Null();
418#else
419 if(BackendType == BACKEND_TYPE_OPENGL_ES)
420 {
421#if defined(CONF_BACKEND_OPENGL_ES) || defined(CONF_BACKEND_OPENGL_ES3)
422 if(GLMajor < 3)
423 {
424 m_pGLBackend = new CCommandProcessorFragment_OpenGLES();
425 }
426 else
427 {
428 m_pGLBackend = new CCommandProcessorFragment_OpenGLES3();
429 }
430#endif
431 }
432 else if(BackendType == BACKEND_TYPE_OPENGL)
433 {
434#if !defined(CONF_BACKEND_OPENGL_ES)
435 if(GLMajor < 2)
436 {
437 m_pGLBackend = new CCommandProcessorFragment_OpenGL();
438 }
439 if(GLMajor == 2)
440 {
441 m_pGLBackend = new CCommandProcessorFragment_OpenGL2();
442 }
443 if(GLMajor == 3 && GLMinor == 0)
444 {
445 m_pGLBackend = new CCommandProcessorFragment_OpenGL3();
446 }
447 else if((GLMajor == 3 && GLMinor == 3) || GLMajor >= 4)
448 {
449 m_pGLBackend = new CCommandProcessorFragment_OpenGL3_3();
450 }
451#endif
452 }
453 else if(BackendType == BACKEND_TYPE_VULKAN)
454 {
455#if defined(CONF_BACKEND_VULKAN)
456 m_pGLBackend = CreateVulkanCommandProcessorFragment();
457#endif
458 }
459#endif
460}
461
462CCommandProcessor_SDL_GL::~CCommandProcessor_SDL_GL()
463{
464 delete m_pGLBackend;
465}
466
467const SGfxErrorContainer &CCommandProcessor_SDL_GL::GetError() const
468{
469 return m_Error;
470}
471
472void CCommandProcessor_SDL_GL::ErroneousCleanup()
473{
474 m_pGLBackend->ErroneousCleanup();
475}
476
477const SGfxWarningContainer &CCommandProcessor_SDL_GL::GetWarning() const
478{
479 return m_Warning;
480}
481
482// ------------ CGraphicsBackend_SDL_GL
483
484#if !defined(CONF_HEADLESS_CLIENT)
485static bool BackendInitGlew(EBackendType BackendType, int &GlewMajor, int &GlewMinor, int &GlewPatch)
486{
487 if(BackendType == BACKEND_TYPE_OPENGL)
488 {
489#if !defined(CONF_BACKEND_OPENGL_ES)
490 // Support graphic cards that are pretty old (and Linux)
491 glewExperimental = GL_TRUE;
492#ifdef CONF_GLEW_HAS_CONTEXT_INIT
493 const GLenum InitResult = glewContextInit();
494 if(InitResult != GLEW_OK)
495 {
496 log_error("gfx", "Unable to init glew (glewContextInit): %s", glewGetErrorString(InitResult));
497 return false;
498 }
499#else
500 const GLenum InitResult = glewInit();
501 if(InitResult != GLEW_OK)
502 {
503 // With wayland the glewInit function is allowed to fail with GLEW_ERROR_NO_GLX_DISPLAY,
504 // as it will already have initialized the context with glewContextInit internally.
505 const char *pVideoDriver = SDL_GetCurrentVideoDriver();
506 if(pVideoDriver == nullptr || str_comp(a: pVideoDriver, b: "wayland") != 0 || InitResult != GLEW_ERROR_NO_GLX_DISPLAY)
507 {
508 log_error("gfx", "Unable to init glew (glewInit): %s", glewGetErrorString(InitResult));
509 return false;
510 }
511 }
512#endif
513
514#ifdef GLEW_VERSION_4_6
515 if(GLEW_VERSION_4_6)
516 {
517 GlewMajor = 4;
518 GlewMinor = 6;
519 GlewPatch = 0;
520 return true;
521 }
522#endif
523#ifdef GLEW_VERSION_4_5
524 if(GLEW_VERSION_4_5)
525 {
526 GlewMajor = 4;
527 GlewMinor = 5;
528 GlewPatch = 0;
529 return true;
530 }
531#endif
532// Don't allow GL 3.3, if the driver doesn't support at least OpenGL 4.5
533#ifndef CONF_FAMILY_WINDOWS
534 if(GLEW_VERSION_4_4)
535 {
536 GlewMajor = 4;
537 GlewMinor = 4;
538 GlewPatch = 0;
539 return true;
540 }
541 if(GLEW_VERSION_4_3)
542 {
543 GlewMajor = 4;
544 GlewMinor = 3;
545 GlewPatch = 0;
546 return true;
547 }
548 if(GLEW_VERSION_4_2)
549 {
550 GlewMajor = 4;
551 GlewMinor = 2;
552 GlewPatch = 0;
553 return true;
554 }
555 if(GLEW_VERSION_4_1)
556 {
557 GlewMajor = 4;
558 GlewMinor = 1;
559 GlewPatch = 0;
560 return true;
561 }
562 if(GLEW_VERSION_4_0)
563 {
564 GlewMajor = 4;
565 GlewMinor = 0;
566 GlewPatch = 0;
567 return true;
568 }
569 if(GLEW_VERSION_3_3)
570 {
571 GlewMajor = 3;
572 GlewMinor = 3;
573 GlewPatch = 0;
574 return true;
575 }
576#endif
577 if(GLEW_VERSION_3_0)
578 {
579 GlewMajor = 3;
580 GlewMinor = 0;
581 GlewPatch = 0;
582 return true;
583 }
584 if(GLEW_VERSION_2_1)
585 {
586 GlewMajor = 2;
587 GlewMinor = 1;
588 GlewPatch = 0;
589 return true;
590 }
591 if(GLEW_VERSION_2_0)
592 {
593 GlewMajor = 2;
594 GlewMinor = 0;
595 GlewPatch = 0;
596 return true;
597 }
598 if(GLEW_VERSION_1_5)
599 {
600 GlewMajor = 1;
601 GlewMinor = 5;
602 GlewPatch = 0;
603 return true;
604 }
605 if(GLEW_VERSION_1_4)
606 {
607 GlewMajor = 1;
608 GlewMinor = 4;
609 GlewPatch = 0;
610 return true;
611 }
612 if(GLEW_VERSION_1_3)
613 {
614 GlewMajor = 1;
615 GlewMinor = 3;
616 GlewPatch = 0;
617 return true;
618 }
619 if(GLEW_VERSION_1_2_1)
620 {
621 GlewMajor = 1;
622 GlewMinor = 2;
623 GlewPatch = 1;
624 return true;
625 }
626 if(GLEW_VERSION_1_2)
627 {
628 GlewMajor = 1;
629 GlewMinor = 2;
630 GlewPatch = 0;
631 return true;
632 }
633 if(GLEW_VERSION_1_1)
634 {
635 GlewMajor = 1;
636 GlewMinor = 1;
637 GlewPatch = 0;
638 return true;
639 }
640#endif
641 }
642 else if(BackendType == BACKEND_TYPE_OPENGL_ES)
643 {
644 // just assume the version we need
645 GlewMajor = 3;
646 GlewMinor = 0;
647 GlewPatch = 0;
648 return true;
649 }
650 else
651 {
652 dbg_assert_failed("Invalid backend type for glew: %d", (int)BackendType);
653 }
654
655 return false;
656}
657
658static int IsVersionSupportedGlew(EBackendType BackendType, int VersionMajor, int VersionMinor, int VersionPatch, int GlewMajor, int GlewMinor, int GlewPatch)
659{
660 if(BackendType == BACKEND_TYPE_OPENGL)
661 {
662 if(VersionMajor >= 4 && GlewMajor < 4)
663 {
664 return -1;
665 }
666 else if(VersionMajor >= 3 && GlewMajor < 3)
667 {
668 return -1;
669 }
670 else if(VersionMajor == 3 && GlewMajor == 3)
671 {
672 if(VersionMinor >= 3 && GlewMinor < 3)
673 {
674 return -1;
675 }
676 if(VersionMinor >= 2 && GlewMinor < 2)
677 {
678 return -1;
679 }
680 if(VersionMinor >= 1 && GlewMinor < 1)
681 {
682 return -1;
683 }
684 if(VersionMinor >= 0 && GlewMinor < 0)
685 {
686 return -1;
687 }
688 }
689 else if(VersionMajor >= 2 && GlewMajor < 2)
690 {
691 return -1;
692 }
693 else if(VersionMajor == 2 && GlewMajor == 2)
694 {
695 if(VersionMinor >= 1 && GlewMinor < 1)
696 {
697 return -1;
698 }
699 if(VersionMinor >= 0 && GlewMinor < 0)
700 {
701 return -1;
702 }
703 }
704 else if(VersionMajor >= 1 && GlewMajor < 1)
705 {
706 return -1;
707 }
708 else if(VersionMajor == 1 && GlewMajor == 1)
709 {
710 if(VersionMinor >= 5 && GlewMinor < 5)
711 {
712 return -1;
713 }
714 if(VersionMinor >= 4 && GlewMinor < 4)
715 {
716 return -1;
717 }
718 if(VersionMinor >= 3 && GlewMinor < 3)
719 {
720 return -1;
721 }
722 if(VersionMinor >= 2 && GlewMinor < 2)
723 {
724 return -1;
725 }
726 else if(VersionMinor == 2 && GlewMinor == 2)
727 {
728 if(VersionPatch >= 1 && GlewPatch < 1)
729 {
730 return -1;
731 }
732 if(VersionPatch >= 0 && GlewPatch < 0)
733 {
734 return -1;
735 }
736 }
737 if(VersionMinor >= 1 && GlewMinor < 1)
738 {
739 return -1;
740 }
741 if(VersionMinor >= 0 && GlewMinor < 0)
742 {
743 return -1;
744 }
745 }
746 }
747 return 0;
748}
749#endif // !CONF_HEADLESS_CLIENT
750
751EBackendType CGraphicsBackend_SDL_GL::DetectBackend()
752{
753 EBackendType RetBackendType = BACKEND_TYPE_OPENGL;
754#if defined(CONF_BACKEND_VULKAN)
755 const char *pEnvDriver = SDL_getenv(name: "DDNET_DRIVER");
756 if(pEnvDriver && str_comp_nocase(a: pEnvDriver, b: "GLES") == 0)
757 {
758 RetBackendType = BACKEND_TYPE_OPENGL_ES;
759 }
760 else if(pEnvDriver && str_comp_nocase(a: pEnvDriver, b: "Vulkan") == 0)
761 {
762 RetBackendType = BACKEND_TYPE_VULKAN;
763 }
764 else if(pEnvDriver && str_comp_nocase(a: pEnvDriver, b: "OpenGL") == 0)
765 {
766 RetBackendType = BACKEND_TYPE_OPENGL;
767 }
768 else if(pEnvDriver == nullptr)
769 {
770 // load the config backend
771 const char *pConfBackend = g_Config.m_GfxBackend;
772 if(str_comp_nocase(a: pConfBackend, b: "GLES") == 0)
773 RetBackendType = BACKEND_TYPE_OPENGL_ES;
774 else if(str_comp_nocase(a: pConfBackend, b: "Vulkan") == 0)
775 RetBackendType = BACKEND_TYPE_VULKAN;
776 else if(str_comp_nocase(a: pConfBackend, b: "OpenGL") == 0)
777 RetBackendType = BACKEND_TYPE_OPENGL;
778 }
779#else
780 RetBackendType = BACKEND_TYPE_OPENGL;
781#endif
782#if !defined(CONF_BACKEND_OPENGL_ES) && !defined(CONF_BACKEND_OPENGL_ES3)
783 if(RetBackendType == BACKEND_TYPE_OPENGL_ES)
784 RetBackendType = BACKEND_TYPE_OPENGL;
785#elif defined(CONF_BACKEND_OPENGL_ES)
786 if(RetBackendType == BACKEND_TYPE_OPENGL)
787 RetBackendType = BACKEND_TYPE_OPENGL_ES;
788#endif
789 return RetBackendType;
790}
791
792void CGraphicsBackend_SDL_GL::ClampDriverVersion(EBackendType BackendType)
793{
794 if(BackendType == BACKEND_TYPE_OPENGL)
795 {
796 // clamp the versions to existing versions(only for OpenGL major <= 3)
797 if(g_Config.m_GfxGLMajor == 1)
798 {
799 g_Config.m_GfxGLMinor = std::clamp(val: g_Config.m_GfxGLMinor, lo: 1, hi: 5);
800 if(g_Config.m_GfxGLMinor == 2)
801 g_Config.m_GfxGLPatch = std::clamp(val: g_Config.m_GfxGLPatch, lo: 0, hi: 1);
802 else
803 g_Config.m_GfxGLPatch = 0;
804 }
805 else if(g_Config.m_GfxGLMajor == 2)
806 {
807 g_Config.m_GfxGLMinor = std::clamp(val: g_Config.m_GfxGLMinor, lo: 0, hi: 1);
808 g_Config.m_GfxGLPatch = 0;
809 }
810 else if(g_Config.m_GfxGLMajor == 3)
811 {
812 g_Config.m_GfxGLMinor = std::clamp(val: g_Config.m_GfxGLMinor, lo: 0, hi: 3);
813 if(g_Config.m_GfxGLMinor < 3)
814 g_Config.m_GfxGLMinor = 0;
815 g_Config.m_GfxGLPatch = 0;
816 }
817 }
818 else if(BackendType == BACKEND_TYPE_OPENGL_ES)
819 {
820#if !defined(CONF_BACKEND_OPENGL_ES3)
821 // Make sure GLES is set to 1.0 (which is equivalent to OpenGL 1.3), if its not set to >= 3.0(which is equivalent to OpenGL 3.3)
822 if(g_Config.m_GfxGLMajor < 3)
823 {
824 g_Config.m_GfxGLMajor = 1;
825 g_Config.m_GfxGLMinor = 0;
826 g_Config.m_GfxGLPatch = 0;
827
828 // GLES also doesn't know GL_QUAD
829 g_Config.m_GfxQuadAsTriangle = 1;
830 }
831#else
832 g_Config.m_GfxGLMajor = 3;
833 g_Config.m_GfxGLMinor = 0;
834 g_Config.m_GfxGLPatch = 0;
835#endif
836 }
837 else if(BackendType == BACKEND_TYPE_VULKAN)
838 {
839#if defined(CONF_BACKEND_VULKAN)
840 g_Config.m_GfxGLMajor = BACKEND_VULKAN_VERSION_MAJOR;
841 g_Config.m_GfxGLMinor = BACKEND_VULKAN_VERSION_MINOR;
842 g_Config.m_GfxGLPatch = 0;
843#endif
844 }
845}
846
847static Uint32 MessageBoxTypeToSdlFlags(IGraphics::EMessageBoxType Type)
848{
849 switch(Type)
850 {
851 case IGraphics::EMessageBoxType::ERROR:
852 return SDL_MESSAGEBOX_ERROR;
853 case IGraphics::EMessageBoxType::WARNING:
854 return SDL_MESSAGEBOX_WARNING;
855 case IGraphics::EMessageBoxType::INFO:
856 return SDL_MESSAGEBOX_INFORMATION;
857 default:
858 dbg_assert_failed("Type invalid");
859 }
860}
861
862static std::optional<int> ShowMessageBoxImpl(const IGraphics::CMessageBox &MessageBox, SDL_Window *pWindow)
863{
864 dbg_assert(!MessageBox.m_vButtons.empty(), "At least one button is required");
865
866 std::vector<SDL_MessageBoxButtonData> vButtonData;
867 vButtonData.reserve(n: MessageBox.m_vButtons.size());
868 for(const auto &Button : MessageBox.m_vButtons)
869 {
870 SDL_MessageBoxButtonData ButtonData{};
871 ButtonData.buttonid = vButtonData.size();
872 ButtonData.flags = (Button.m_Confirm ? SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT : 0) | (Button.m_Cancel ? SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT : 0);
873 ButtonData.text = Button.m_pLabel;
874 vButtonData.emplace_back(args&: ButtonData);
875 }
876#if defined(CONF_FAMILY_WINDOWS)
877 // TODO SDL3: The order of buttons is not defined by default, but the flags returned by MessageBoxTypeToSdlFlags do not work together
878 // with SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT with SDL2 on various platforms. Windows appears to be the only platform that
879 // lays out buttons from right to left by default, so we reverse the order manually.
880 std::reverse(vButtonData.begin(), vButtonData.end());
881#endif
882 SDL_MessageBoxData MessageBoxData{};
883 MessageBoxData.title = MessageBox.m_pTitle;
884 MessageBoxData.message = MessageBox.m_pMessage;
885 MessageBoxData.flags = MessageBoxTypeToSdlFlags(Type: MessageBox.m_Type);
886 MessageBoxData.numbuttons = vButtonData.size();
887 MessageBoxData.buttons = vButtonData.data();
888 MessageBoxData.window = pWindow;
889 int ButtonId = -1;
890 if(SDL_ShowMessageBox(messageboxdata: &MessageBoxData, buttonid: &ButtonId) != 0)
891 {
892 return std::nullopt;
893 }
894 return ButtonId;
895}
896
897std::optional<int> ShowMessageBoxWithoutGraphics(const IGraphics::CMessageBox &MessageBox)
898{
899 return ShowMessageBoxImpl(MessageBox, pWindow: nullptr);
900}
901
902std::optional<int> CGraphicsBackend_SDL_GL::ShowMessageBox(const IGraphics::CMessageBox &MessageBox)
903{
904 if(m_pProcessor != nullptr)
905 {
906 m_pProcessor->ErroneousCleanup();
907 }
908 // TODO: Remove this workaround when https://github.com/libsdl-org/SDL/issues/3750 is
909 // fixed and pass the window to SDL_ShowSimpleMessageBox to make the popup modal instead
910 // of destroying the window before opening the popup.
911 if(m_pWindow != nullptr)
912 {
913 SDL_DestroyWindow(window: m_pWindow);
914 m_pWindow = nullptr;
915 }
916 return ShowMessageBoxImpl(MessageBox, pWindow: m_pWindow);
917}
918
919bool CGraphicsBackend_SDL_GL::IsModernAPI(EBackendType BackendType)
920{
921 if(BackendType == BACKEND_TYPE_OPENGL)
922 return (g_Config.m_GfxGLMajor == 3 && g_Config.m_GfxGLMinor == 3) || g_Config.m_GfxGLMajor >= 4;
923 else if(BackendType == BACKEND_TYPE_OPENGL_ES)
924 return g_Config.m_GfxGLMajor >= 3;
925 else if(BackendType == BACKEND_TYPE_VULKAN)
926 return true;
927
928 return false;
929}
930
931bool CGraphicsBackend_SDL_GL::GetDriverVersion(EGraphicsDriverAgeType DriverAgeType, int &Major, int &Minor, int &Patch, const char *&pName, EBackendType BackendType)
932{
933 if(BackendType == BACKEND_TYPE_AUTO)
934 BackendType = m_BackendType;
935 if(BackendType == BACKEND_TYPE_OPENGL)
936 {
937 pName = "OpenGL";
938#ifndef CONF_BACKEND_OPENGL_ES
939 if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_LEGACY)
940 {
941 Major = 1;
942 Minor = 4;
943 Patch = 0;
944 return true;
945 }
946 else if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_DEFAULT)
947 {
948 Major = 3;
949 Minor = 0;
950 Patch = 0;
951 return true;
952 }
953 else if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_MODERN)
954 {
955 Major = 3;
956 Minor = 3;
957 Patch = 0;
958 return true;
959 }
960#endif
961 }
962 else if(BackendType == BACKEND_TYPE_OPENGL_ES)
963 {
964 pName = "GLES";
965#ifdef CONF_BACKEND_OPENGL_ES
966 if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_LEGACY)
967 {
968 Major = 1;
969 Minor = 0;
970 Patch = 0;
971 return true;
972 }
973 else if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_DEFAULT)
974 {
975 Major = 3;
976 Minor = 0;
977 Patch = 0;
978 // there isn't really a default one
979 return false;
980 }
981#endif
982#ifdef CONF_BACKEND_OPENGL_ES3
983 if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_MODERN)
984 {
985 Major = 3;
986 Minor = 0;
987 Patch = 0;
988 return true;
989 }
990#endif
991 }
992 else if(BackendType == BACKEND_TYPE_VULKAN)
993 {
994 pName = "Vulkan";
995#ifdef CONF_BACKEND_VULKAN
996 if(DriverAgeType == GRAPHICS_DRIVER_AGE_TYPE_DEFAULT)
997 {
998 Major = BACKEND_VULKAN_VERSION_MAJOR;
999 Minor = BACKEND_VULKAN_VERSION_MINOR;
1000 Patch = 0;
1001 return true;
1002 }
1003#else
1004 return false;
1005#endif
1006 }
1007 return false;
1008}
1009
1010const char *CGraphicsBackend_SDL_GL::GetScreenName(int Screen) const
1011{
1012 const char *pName = SDL_GetDisplayName(displayIndex: Screen);
1013 return pName == nullptr ? "unknown/error" : pName;
1014}
1015
1016static void DisplayToVideoMode(CVideoMode *pVMode, SDL_DisplayMode *pMode, float HiDPIScale, int RefreshRate)
1017{
1018 pVMode->m_CanvasWidth = pMode->w * HiDPIScale;
1019 pVMode->m_CanvasHeight = pMode->h * HiDPIScale;
1020 pVMode->m_WindowWidth = pMode->w;
1021 pVMode->m_WindowHeight = pMode->h;
1022 pVMode->m_RefreshRate = RefreshRate;
1023}
1024
1025void CGraphicsBackend_SDL_GL::GetVideoModes(CVideoMode *pModes, int MaxModes, int *pNumModes, float HiDPIScale, int MaxWindowWidth, int MaxWindowHeight, int ScreenId)
1026{
1027 SDL_DisplayMode DesktopMode;
1028 int MaxModesAvailable = SDL_GetNumDisplayModes(displayIndex: ScreenId);
1029
1030 // Only collect fullscreen modes when requested, that makes sure in windowed mode no refresh rates are shown that aren't supported without
1031 // fullscreen anyway(except fullscreen desktop)
1032 bool IsFullscreenDesktop = m_pWindow != nullptr && (((SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP) || g_Config.m_GfxFullscreen == 3);
1033 bool CollectFullscreenModes = m_pWindow == nullptr || ((SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_FULLSCREEN) != 0 && !IsFullscreenDesktop);
1034
1035 if(SDL_GetDesktopDisplayMode(displayIndex: ScreenId, mode: &DesktopMode) < 0)
1036 {
1037 log_error("gfx", "Unable to get desktop display mode of screen %d: %s", ScreenId, SDL_GetError());
1038 }
1039
1040 constexpr int ModeCount = 256;
1041 SDL_DisplayMode aModes[ModeCount];
1042 int NumModes = 0;
1043 for(int i = 0; i < MaxModesAvailable && NumModes < ModeCount; i++)
1044 {
1045 SDL_DisplayMode Mode;
1046 if(SDL_GetDisplayMode(displayIndex: ScreenId, modeIndex: i, mode: &Mode) < 0)
1047 {
1048 log_error("gfx", "Unable to get display mode %d of screen %d: %s", i, ScreenId, SDL_GetError());
1049 continue;
1050 }
1051
1052 aModes[NumModes] = Mode;
1053 ++NumModes;
1054 }
1055
1056 int NumModesInserted = 0;
1057 auto &&ModeInsert = [&](SDL_DisplayMode &Mode) {
1058 if(NumModesInserted < MaxModes)
1059 {
1060 // if last mode was equal, ignore this one --- in fullscreen this can really only happen if the screen
1061 // supports different color modes
1062 // in non fullscreen these are the modes that show different refresh rate, but are basically the same
1063 if(NumModesInserted > 0 && pModes[NumModesInserted - 1].m_WindowWidth == Mode.w && pModes[NumModesInserted - 1].m_WindowHeight == Mode.h && (pModes[NumModesInserted - 1].m_RefreshRate == Mode.refresh_rate || (Mode.refresh_rate != DesktopMode.refresh_rate && !CollectFullscreenModes)))
1064 return;
1065
1066 DisplayToVideoMode(pVMode: &pModes[NumModesInserted], pMode: &Mode, HiDPIScale, RefreshRate: !CollectFullscreenModes ? DesktopMode.refresh_rate : Mode.refresh_rate);
1067 NumModesInserted++;
1068 }
1069 };
1070
1071 for(int i = 0; i < NumModes; i++)
1072 {
1073 SDL_DisplayMode &Mode = aModes[i];
1074
1075 if(Mode.w > MaxWindowWidth || Mode.h > MaxWindowHeight)
1076 continue;
1077
1078 ModeInsert(Mode);
1079
1080 if(IsFullscreenDesktop)
1081 break;
1082
1083 if(NumModesInserted >= MaxModes)
1084 break;
1085 }
1086 *pNumModes = NumModesInserted;
1087}
1088
1089void CGraphicsBackend_SDL_GL::GetCurrentVideoMode(CVideoMode &CurMode, float HiDPIScale, int MaxWindowWidth, int MaxWindowHeight, int ScreenId)
1090{
1091 SDL_DisplayMode DpMode;
1092 // if "real" fullscreen, obtain the video mode for that
1093 if((SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN)
1094 {
1095 if(SDL_GetCurrentDisplayMode(displayIndex: ScreenId, mode: &DpMode))
1096 {
1097 log_error("gfx", "Unable to get current display mode of screen %d: %s", ScreenId, SDL_GetError());
1098 }
1099 }
1100 else
1101 {
1102 if(SDL_GetDesktopDisplayMode(displayIndex: ScreenId, mode: &DpMode) < 0)
1103 {
1104 log_error("gfx", "Unable to get desktop display mode of screen %d: %s", ScreenId, SDL_GetError());
1105 }
1106 else
1107 {
1108 int Width = 0;
1109 int Height = 0;
1110 if(m_BackendType != EBackendType::BACKEND_TYPE_VULKAN)
1111 SDL_GL_GetDrawableSize(window: m_pWindow, w: &Width, h: &Height);
1112 else
1113 SDL_Vulkan_GetDrawableSize(window: m_pWindow, w: &Width, h: &Height);
1114 // SDL video modes are in screen space which are logical pixels
1115 DpMode.w = Width / HiDPIScale;
1116 DpMode.h = Height / HiDPIScale;
1117 }
1118 }
1119 DisplayToVideoMode(pVMode: &CurMode, pMode: &DpMode, HiDPIScale, RefreshRate: DpMode.refresh_rate);
1120}
1121
1122CGraphicsBackend_SDL_GL::CGraphicsBackend_SDL_GL(TTranslateFunc &&TranslateFunc) :
1123 CGraphicsBackend_Threaded(std::move(TranslateFunc))
1124{
1125 m_aErrorString[0] = '\0';
1126}
1127
1128int CGraphicsBackend_SDL_GL::Init(const char *pName, int *pScreen, int *pWidth, int *pHeight, int *pRefreshRate, int *pFsaaSamples, int Flags, int *pDesktopWidth, int *pDesktopHeight, int *pCurrentWidth, int *pCurrentHeight, IStorage *pStorage)
1129{
1130#if defined(CONF_HEADLESS_CLIENT)
1131 m_BackendType = BACKEND_TYPE_OPENGL;
1132 g_Config.m_GfxGLMajor = 0;
1133 g_Config.m_GfxGLMinor = 0;
1134 g_Config.m_GfxGLPatch = 0;
1135 int InitError = 0;
1136 int GlewMajor = 0;
1137 int GlewMinor = 0;
1138 int GlewPatch = 0;
1139 *pScreen = 0;
1140 *pWidth = *pDesktopWidth = *pCurrentWidth = 800;
1141 *pHeight = *pDesktopHeight = *pCurrentHeight = 600;
1142 *pRefreshRate = 60;
1143 *pFsaaSamples = 0;
1144 log_info("gfx", "Created headless context");
1145#else
1146 // print sdl version
1147 {
1148 SDL_version Compiled;
1149 SDL_version Linked;
1150
1151 SDL_VERSION(&Compiled);
1152 SDL_GetVersion(ver: &Linked);
1153 log_info("sdl", "SDL version %d.%d.%d (compiled = %d.%d.%d)",
1154 Linked.major, Linked.minor, Linked.patch,
1155 Compiled.major, Compiled.minor, Compiled.patch);
1156
1157#if CONF_PLATFORM_LINUX && SDL_VERSION_ATLEAST(2, 0, 22)
1158 // needed to workaround SDL from forcing exclusively X11 if linking against the GLX flavour of GLEW instead of the EGL one
1159 // w/o this on Wayland systems (no XWayland support) SDL's Video subsystem will fail to load (starting from SDL2.30+)
1160 if(Linked.major == 2 && Linked.minor >= 30)
1161 SDL_SetHint(SDL_HINT_VIDEODRIVER, value: "x11,wayland");
1162#endif
1163 }
1164
1165 if(!SDL_WasInit(SDL_INIT_VIDEO))
1166 {
1167 if(SDL_InitSubSystem(SDL_INIT_VIDEO) < 0)
1168 {
1169 log_error("gfx", "Unable to initialize SDL video: %s", SDL_GetError());
1170 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_INIT_FAILED;
1171 }
1172 }
1173
1174 EBackendType OldBackendType = m_BackendType;
1175 m_BackendType = DetectBackend();
1176 // little fallback for Vulkan
1177 if(OldBackendType != BACKEND_TYPE_AUTO &&
1178 m_BackendType == BACKEND_TYPE_VULKAN)
1179 {
1180 // try default opengl settings
1181 str_copy(dst&: g_Config.m_GfxBackend, src: "OpenGL");
1182 g_Config.m_GfxGLMajor = 3;
1183 g_Config.m_GfxGLMinor = 0;
1184 g_Config.m_GfxGLPatch = 0;
1185 // do another analysis round too, just in case
1186 g_Config.m_Gfx3DTextureAnalysisRan = 0;
1187 g_Config.m_GfxDriverIsBlocked = 0;
1188 m_BackendType = DetectBackend();
1189 }
1190
1191 ClampDriverVersion(BackendType: m_BackendType);
1192
1193 const bool UseModernGL = IsModernAPI(BackendType: m_BackendType);
1194 const bool IsOpenGLFamilyBackend = m_BackendType == BACKEND_TYPE_OPENGL || m_BackendType == BACKEND_TYPE_OPENGL_ES;
1195
1196 if(IsOpenGLFamilyBackend)
1197 {
1198 SDL_GL_SetAttribute(attr: SDL_GL_CONTEXT_MAJOR_VERSION, value: g_Config.m_GfxGLMajor);
1199 SDL_GL_SetAttribute(attr: SDL_GL_CONTEXT_MINOR_VERSION, value: g_Config.m_GfxGLMinor);
1200 }
1201
1202 const char *pBackendName;
1203 switch(m_BackendType)
1204 {
1205 case BACKEND_TYPE_OPENGL:
1206 pBackendName = "OpenGL";
1207 break;
1208 case BACKEND_TYPE_OPENGL_ES:
1209 pBackendName = "OpenGL ES";
1210 break;
1211 case BACKEND_TYPE_VULKAN:
1212 pBackendName = "Vulkan";
1213 break;
1214 default:
1215 dbg_assert_failed("Invalid m_BackendType: %d", m_BackendType);
1216 }
1217 log_info("gfx", "Created %s %d.%d context", pBackendName, g_Config.m_GfxGLMajor, g_Config.m_GfxGLMinor);
1218
1219 if(m_BackendType == BACKEND_TYPE_OPENGL)
1220 {
1221 if(g_Config.m_GfxGLMajor == 3 && g_Config.m_GfxGLMinor == 0)
1222 {
1223 SDL_GL_SetAttribute(attr: SDL_GL_CONTEXT_PROFILE_MASK, value: SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
1224 }
1225 else if(UseModernGL)
1226 {
1227 SDL_GL_SetAttribute(attr: SDL_GL_CONTEXT_PROFILE_MASK, value: SDL_GL_CONTEXT_PROFILE_CORE);
1228 }
1229 }
1230 else if(m_BackendType == BACKEND_TYPE_OPENGL_ES)
1231 {
1232 SDL_GL_SetAttribute(attr: SDL_GL_CONTEXT_PROFILE_MASK, value: SDL_GL_CONTEXT_PROFILE_ES);
1233 }
1234
1235 if(IsOpenGLFamilyBackend)
1236 {
1237 *pFsaaSamples = std::clamp(val: *pFsaaSamples, lo: 0, hi: 8);
1238 }
1239
1240 // set screen
1241 m_NumScreens = SDL_GetNumVideoDisplays();
1242 if(m_NumScreens > 0)
1243 {
1244 SDL_Rect ScreenPos;
1245 *pScreen = std::clamp(val: *pScreen, lo: 0, hi: m_NumScreens - 1);
1246 if(SDL_GetDisplayBounds(displayIndex: *pScreen, rect: &ScreenPos) != 0)
1247 {
1248 log_error("gfx", "Unable to get display bounds of screen %d: %s", *pScreen, SDL_GetError());
1249 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_SCREEN_INFO_REQUEST_FAILED;
1250 }
1251 }
1252 else
1253 {
1254 log_error("gfx", "Unable to get number of screens: %s", SDL_GetError());
1255 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_SCREEN_REQUEST_FAILED;
1256 }
1257
1258 // store desktop resolution for settings reset button
1259 SDL_DisplayMode DisplayMode;
1260 if(SDL_GetDesktopDisplayMode(displayIndex: *pScreen, mode: &DisplayMode))
1261 {
1262 log_error("gfx", "Unable to get desktop display mode of screen %d: %s", *pScreen, SDL_GetError());
1263 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_SCREEN_RESOLUTION_REQUEST_FAILED;
1264 }
1265
1266 bool IsDesktopChanged = *pDesktopWidth == 0 || *pDesktopHeight == 0 || *pDesktopWidth != DisplayMode.w || *pDesktopHeight != DisplayMode.h;
1267
1268 *pDesktopWidth = DisplayMode.w;
1269 *pDesktopHeight = DisplayMode.h;
1270
1271 // fetch supported video modes
1272 bool SupportedResolution = false;
1273
1274 CVideoMode aModes[256];
1275 int ModesCount = 0;
1276 int IndexOfResolution = -1;
1277 GetVideoModes(pModes: aModes, MaxModes: std::size(aModes), pNumModes: &ModesCount, HiDPIScale: 1, MaxWindowWidth: *pDesktopWidth, MaxWindowHeight: *pDesktopHeight, ScreenId: *pScreen);
1278
1279 for(int i = 0; i < ModesCount; i++)
1280 {
1281 if(*pWidth == aModes[i].m_WindowWidth && *pHeight == aModes[i].m_WindowHeight && (*pRefreshRate == aModes[i].m_RefreshRate || *pRefreshRate == 0))
1282 {
1283 SupportedResolution = true;
1284 IndexOfResolution = i;
1285 break;
1286 }
1287 }
1288
1289 // set flags
1290 int SdlFlags = SDL_WINDOW_INPUT_GRABBED | SDL_WINDOW_INPUT_FOCUS | SDL_WINDOW_MOUSE_FOCUS | SDL_WINDOW_ALLOW_HIGHDPI;
1291 SdlFlags |= (IsOpenGLFamilyBackend) ? SDL_WINDOW_OPENGL : SDL_WINDOW_VULKAN;
1292 if(Flags & IGraphicsBackend::INITFLAG_RESIZABLE)
1293 SdlFlags |= SDL_WINDOW_RESIZABLE;
1294 if(Flags & IGraphicsBackend::INITFLAG_BORDERLESS)
1295 SdlFlags |= SDL_WINDOW_BORDERLESS;
1296 if(Flags & IGraphicsBackend::INITFLAG_FULLSCREEN)
1297 SdlFlags |= SDL_WINDOW_FULLSCREEN;
1298 else if(Flags & (IGraphicsBackend::INITFLAG_DESKTOP_FULLSCREEN))
1299 SdlFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP;
1300
1301 bool IsFullscreen = (SdlFlags & SDL_WINDOW_FULLSCREEN) != 0 || g_Config.m_GfxFullscreen == 3;
1302 // use desktop resolution as default resolution, clamp resolution if users's display is smaller than we remembered
1303 // if the user starts in fullscreen, and the resolution was not found use the desktop one
1304 if((IsFullscreen && !SupportedResolution) || *pWidth == 0 || *pHeight == 0 || (IsDesktopChanged && (!SupportedResolution || !IsFullscreen) && (*pWidth > *pDesktopWidth || *pHeight > *pDesktopHeight)))
1305 {
1306 *pWidth = *pDesktopWidth;
1307 *pHeight = *pDesktopHeight;
1308 *pRefreshRate = DisplayMode.refresh_rate;
1309 }
1310
1311 // if in fullscreen and refresh rate wasn't set yet, just use the one from the found list
1312 if(*pRefreshRate == 0 && SupportedResolution)
1313 {
1314 *pRefreshRate = aModes[IndexOfResolution].m_RefreshRate;
1315 }
1316 else if(*pRefreshRate == 0)
1317 {
1318 *pRefreshRate = DisplayMode.refresh_rate;
1319 }
1320
1321 // set gl attributes
1322 if(IsOpenGLFamilyBackend)
1323 {
1324 SDL_GL_SetAttribute(attr: SDL_GL_DOUBLEBUFFER, value: 1);
1325 if(*pFsaaSamples)
1326 {
1327 SDL_GL_SetAttribute(attr: SDL_GL_MULTISAMPLEBUFFERS, value: 1);
1328 SDL_GL_SetAttribute(attr: SDL_GL_MULTISAMPLESAMPLES, value: *pFsaaSamples);
1329 }
1330 else
1331 {
1332 SDL_GL_SetAttribute(attr: SDL_GL_MULTISAMPLEBUFFERS, value: 0);
1333 SDL_GL_SetAttribute(attr: SDL_GL_MULTISAMPLESAMPLES, value: 0);
1334 }
1335 }
1336
1337 m_pWindow = SDL_CreateWindow(
1338 title: pName,
1339 SDL_WINDOWPOS_CENTERED_DISPLAY(*pScreen),
1340 SDL_WINDOWPOS_CENTERED_DISPLAY(*pScreen),
1341 w: *pWidth,
1342 h: *pHeight,
1343 flags: SdlFlags);
1344
1345 // set caption
1346 if(m_pWindow == nullptr)
1347 {
1348 log_error("gfx", "Unable to create window: %s", SDL_GetError());
1349 if(m_BackendType == BACKEND_TYPE_VULKAN)
1350 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_GL_CONTEXT_FAILED;
1351 else
1352 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_SDL_WINDOW_CREATE_FAILED;
1353 }
1354
1355 int GlewMajor = 0;
1356 int GlewMinor = 0;
1357 int GlewPatch = 0;
1358
1359 if(IsOpenGLFamilyBackend)
1360 {
1361 m_GLContext = SDL_GL_CreateContext(window: m_pWindow);
1362
1363 if(m_GLContext == nullptr)
1364 {
1365 log_error("gfx", "Unable to create graphics context: %s", SDL_GetError());
1366 SDL_DestroyWindow(window: m_pWindow);
1367 m_pWindow = nullptr;
1368 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_GL_CONTEXT_FAILED;
1369 }
1370
1371 if(!BackendInitGlew(BackendType: m_BackendType, GlewMajor, GlewMinor, GlewPatch))
1372 {
1373 SDL_GL_DeleteContext(context: m_GLContext);
1374 SDL_DestroyWindow(window: m_pWindow);
1375 m_pWindow = nullptr;
1376 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_GLEW_INIT_FAILED;
1377 }
1378 }
1379
1380 int InitError = IsVersionSupportedGlew(BackendType: m_BackendType, VersionMajor: g_Config.m_GfxGLMajor, VersionMinor: g_Config.m_GfxGLMinor, VersionPatch: g_Config.m_GfxGLPatch, GlewMajor, GlewMinor, GlewPatch);
1381
1382 // SDL_GL_GetDrawableSize reports HiDPI resolution even with SDL_WINDOW_ALLOW_HIGHDPI not set, which is wrong
1383 if(SdlFlags & SDL_WINDOW_ALLOW_HIGHDPI)
1384 {
1385 if(IsOpenGLFamilyBackend)
1386 SDL_GL_GetDrawableSize(window: m_pWindow, w: pCurrentWidth, h: pCurrentHeight);
1387 else
1388 SDL_Vulkan_GetDrawableSize(window: m_pWindow, w: pCurrentWidth, h: pCurrentHeight);
1389 }
1390 else
1391 {
1392 SDL_GetWindowSize(window: m_pWindow, w: pCurrentWidth, h: pCurrentHeight);
1393 }
1394 SDL_GetWindowSize(window: m_pWindow, w: pWidth, h: pHeight);
1395
1396 if(IsOpenGLFamilyBackend)
1397 {
1398#if !defined(CONF_PLATFORM_EMSCRIPTEN)
1399 // SDL_GL_SetSwapInterval is not supported with Emscripten as this is only a wrapper for the
1400 // emscripten_set_main_loop_timing function which does not work because we do not use the
1401 // emscripten_set_main_loop function before.
1402 SDL_GL_SetSwapInterval(interval: Flags & IGraphicsBackend::INITFLAG_VSYNC ? 1 : 0);
1403#endif
1404 SDL_GL_MakeCurrent(window: nullptr, context: nullptr);
1405 }
1406
1407 if(InitError != 0)
1408 {
1409 if(m_GLContext)
1410 SDL_GL_DeleteContext(context: m_GLContext);
1411 SDL_DestroyWindow(window: m_pWindow);
1412 m_pWindow = nullptr;
1413
1414 // try setting to glew supported version
1415 g_Config.m_GfxGLMajor = GlewMajor;
1416 g_Config.m_GfxGLMinor = GlewMinor;
1417 g_Config.m_GfxGLPatch = GlewPatch;
1418
1419 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_GL_VERSION_FAILED;
1420 }
1421#endif // !CONF_HEADLESS_CLIENT
1422
1423 // start the command processor
1424 dbg_assert(m_pProcessor == nullptr, "Processor was not cleaned up properly.");
1425 m_pProcessor = new CCommandProcessor_SDL_GL(m_BackendType, g_Config.m_GfxGLMajor, g_Config.m_GfxGLMinor, g_Config.m_GfxGLPatch);
1426 StartProcessor(pProcessor: m_pProcessor);
1427
1428 // issue init commands for OpenGL and SDL
1429 CCommandBuffer CmdBuffer(1024, 512);
1430 CCommandProcessorFragment_GLBase::SCommand_PreInit CmdPre;
1431 CmdPre.m_pWindow = m_pWindow;
1432 CmdPre.m_Width = *pCurrentWidth;
1433 CmdPre.m_Height = *pCurrentHeight;
1434 CmdPre.m_pVendorString = m_aVendorString;
1435 CmdPre.m_pVersionString = m_aVersionString;
1436 CmdPre.m_pRendererString = m_aRendererString;
1437 CmdPre.m_pGpuList = &m_GpuList;
1438 CmdBuffer.AddCommandUnsafe(Command: CmdPre);
1439 RunBufferSingleThreadedUnsafe(pBuffer: &CmdBuffer);
1440 CmdBuffer.Reset();
1441
1442 // run sdl first to have the context in the thread
1443 CCommandProcessorFragment_SDL::SCommand_Init CmdSDL;
1444 CmdSDL.m_pWindow = m_pWindow;
1445 CmdSDL.m_GLContext = m_GLContext;
1446 CmdBuffer.AddCommandUnsafe(Command: CmdSDL);
1447 RunBuffer(pBuffer: &CmdBuffer);
1448 WaitForIdle();
1449 CmdBuffer.Reset();
1450
1451 const char *pErrorStr = nullptr;
1452 if(InitError == 0)
1453 {
1454 CCommandProcessorFragment_GLBase::SCommand_Init CmdGL;
1455 CmdGL.m_pWindow = m_pWindow;
1456 CmdGL.m_Width = *pCurrentWidth;
1457 CmdGL.m_Height = *pCurrentHeight;
1458 CmdGL.m_pTextureMemoryUsage = &m_TextureMemoryUsage;
1459 CmdGL.m_pBufferMemoryUsage = &m_BufferMemoryUsage;
1460 CmdGL.m_pStreamMemoryUsage = &m_StreamMemoryUsage;
1461 CmdGL.m_pStagingMemoryUsage = &m_StagingMemoryUsage;
1462 CmdGL.m_pGpuList = &m_GpuList;
1463 CmdGL.m_pReadPresentedImageDataFunc = &m_ReadPresentedImageDataFunc;
1464 CmdGL.m_pStorage = pStorage;
1465 CmdGL.m_pCapabilities = &m_Capabilities;
1466 CmdGL.m_pInitError = &InitError;
1467 CmdGL.m_RequestedMajor = g_Config.m_GfxGLMajor;
1468 CmdGL.m_RequestedMinor = g_Config.m_GfxGLMinor;
1469 CmdGL.m_RequestedPatch = g_Config.m_GfxGLPatch;
1470 CmdGL.m_GlewMajor = GlewMajor;
1471 CmdGL.m_GlewMinor = GlewMinor;
1472 CmdGL.m_GlewPatch = GlewPatch;
1473 CmdGL.m_pErrStringPtr = &pErrorStr;
1474 CmdGL.m_pVendorString = m_aVendorString;
1475 CmdGL.m_pVersionString = m_aVersionString;
1476 CmdGL.m_pRendererString = m_aRendererString;
1477 CmdGL.m_RequestedBackend = m_BackendType;
1478 CmdBuffer.AddCommandUnsafe(Command: CmdGL);
1479
1480 RunBuffer(pBuffer: &CmdBuffer);
1481 WaitForIdle();
1482 CmdBuffer.Reset();
1483 }
1484
1485 if(InitError != 0)
1486 {
1487 if(InitError != -2)
1488 {
1489 // shutdown the context, as it might have been initialized
1490 CCommandProcessorFragment_GLBase::SCommand_Shutdown CmdGL;
1491 CmdBuffer.AddCommandUnsafe(Command: CmdGL);
1492 RunBuffer(pBuffer: &CmdBuffer);
1493 WaitForIdle();
1494 CmdBuffer.Reset();
1495 }
1496
1497 CCommandProcessorFragment_SDL::SCommand_Shutdown Cmd;
1498 CmdBuffer.AddCommandUnsafe(Command: Cmd);
1499 RunBuffer(pBuffer: &CmdBuffer);
1500 WaitForIdle();
1501 CmdBuffer.Reset();
1502
1503 CCommandProcessorFragment_GLBase::SCommand_PostShutdown CmdPost;
1504 CmdBuffer.AddCommandUnsafe(Command: CmdPost);
1505 RunBufferSingleThreadedUnsafe(pBuffer: &CmdBuffer);
1506 CmdBuffer.Reset();
1507
1508 // stop and delete the processor
1509 StopProcessor();
1510 delete m_pProcessor;
1511 m_pProcessor = nullptr;
1512
1513 if(m_GLContext)
1514 SDL_GL_DeleteContext(context: m_GLContext);
1515 SDL_DestroyWindow(window: m_pWindow);
1516 m_pWindow = nullptr;
1517
1518 // try setting to version string's supported version
1519 if(InitError == -2)
1520 {
1521 g_Config.m_GfxGLMajor = m_Capabilities.m_ContextMajor;
1522 g_Config.m_GfxGLMinor = m_Capabilities.m_ContextMinor;
1523 g_Config.m_GfxGLPatch = m_Capabilities.m_ContextPatch;
1524 }
1525
1526 if(pErrorStr != nullptr)
1527 {
1528 str_copy(dst&: m_aErrorString, src: pErrorStr);
1529 }
1530
1531 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_GL_VERSION_FAILED;
1532 }
1533
1534 {
1535 CCommandBuffer::SCommand_Update_Viewport CmdSDL2;
1536 CmdSDL2.m_X = 0;
1537 CmdSDL2.m_Y = 0;
1538 CmdSDL2.m_Width = *pCurrentWidth;
1539 CmdSDL2.m_Height = *pCurrentHeight;
1540 CmdSDL2.m_ByResize = true;
1541 CmdBuffer.AddCommandUnsafe(Command: CmdSDL2);
1542 RunBuffer(pBuffer: &CmdBuffer);
1543 WaitForIdle();
1544 CmdBuffer.Reset();
1545 }
1546
1547 return EGraphicsBackendErrorCodes::GRAPHICS_BACKEND_ERROR_CODE_NONE;
1548}
1549
1550int CGraphicsBackend_SDL_GL::Shutdown()
1551{
1552 if(m_pProcessor != nullptr)
1553 {
1554 // issue a shutdown command
1555 CCommandBuffer CmdBuffer(1024, 512);
1556 CCommandProcessorFragment_GLBase::SCommand_Shutdown CmdGL;
1557 CmdBuffer.AddCommandUnsafe(Command: CmdGL);
1558 RunBuffer(pBuffer: &CmdBuffer);
1559 WaitForIdle();
1560 CmdBuffer.Reset();
1561
1562 CCommandProcessorFragment_SDL::SCommand_Shutdown Cmd;
1563 CmdBuffer.AddCommandUnsafe(Command: Cmd);
1564 RunBuffer(pBuffer: &CmdBuffer);
1565 WaitForIdle();
1566 CmdBuffer.Reset();
1567
1568 CCommandProcessorFragment_GLBase::SCommand_PostShutdown CmdPost;
1569 CmdBuffer.AddCommandUnsafe(Command: CmdPost);
1570 RunBufferSingleThreadedUnsafe(pBuffer: &CmdBuffer);
1571 CmdBuffer.Reset();
1572
1573 // stop and delete the processor
1574 StopProcessor();
1575 delete m_pProcessor;
1576 m_pProcessor = nullptr;
1577 }
1578
1579 if(m_GLContext != nullptr)
1580 SDL_GL_DeleteContext(context: m_GLContext);
1581 SDL_DestroyWindow(window: m_pWindow);
1582 m_pWindow = nullptr;
1583
1584 SDL_QuitSubSystem(SDL_INIT_VIDEO);
1585 return 0;
1586}
1587
1588uint64_t CGraphicsBackend_SDL_GL::TextureMemoryUsage() const
1589{
1590 return m_TextureMemoryUsage;
1591}
1592
1593uint64_t CGraphicsBackend_SDL_GL::BufferMemoryUsage() const
1594{
1595 return m_BufferMemoryUsage;
1596}
1597
1598uint64_t CGraphicsBackend_SDL_GL::StreamedMemoryUsage() const
1599{
1600 return m_StreamMemoryUsage;
1601}
1602
1603uint64_t CGraphicsBackend_SDL_GL::StagingMemoryUsage() const
1604{
1605 return m_StagingMemoryUsage;
1606}
1607
1608const TTwGraphicsGpuList &CGraphicsBackend_SDL_GL::GetGpus() const
1609{
1610 return m_GpuList;
1611}
1612
1613void CGraphicsBackend_SDL_GL::Minimize()
1614{
1615 SDL_MinimizeWindow(window: m_pWindow);
1616}
1617
1618void CGraphicsBackend_SDL_GL::SetWindowParams(int FullscreenMode, bool IsBorderless)
1619{
1620 // The flags have to be kept consistent with flags set in the CGraphics_Threaded::IssueInit function!
1621
1622 if(FullscreenMode > 0)
1623 {
1624 bool IsDesktopFullscreen = FullscreenMode == 2;
1625#ifndef CONF_FAMILY_WINDOWS
1626 // Windowed fullscreen is only available on Windows, use desktop fullscreen on other platforms
1627 IsDesktopFullscreen |= FullscreenMode == 3;
1628#endif
1629 if(FullscreenMode == 1)
1630 {
1631#if defined(CONF_PLATFORM_MACOS) || defined(CONF_PLATFORM_HAIKU)
1632 // Todo SDL: remove this when fixed (game freezes when losing focus in fullscreen)
1633 SDL_SetWindowFullscreen(m_pWindow, SDL_WINDOW_FULLSCREEN_DESKTOP);
1634#else
1635 SDL_SetWindowFullscreen(window: m_pWindow, flags: SDL_WINDOW_FULLSCREEN);
1636#endif
1637 SDL_SetWindowResizable(window: m_pWindow, resizable: SDL_FALSE);
1638 }
1639 else if(IsDesktopFullscreen)
1640 {
1641 SDL_SetWindowFullscreen(window: m_pWindow, flags: SDL_WINDOW_FULLSCREEN_DESKTOP);
1642 SDL_SetWindowResizable(window: m_pWindow, resizable: SDL_FALSE);
1643 }
1644 else // Windowed fullscreen
1645 {
1646 SDL_SetWindowFullscreen(window: m_pWindow, flags: 0);
1647 SDL_SetWindowBordered(window: m_pWindow, bordered: SDL_TRUE);
1648 SDL_SetWindowResizable(window: m_pWindow, resizable: SDL_FALSE);
1649 SDL_DisplayMode DpMode;
1650 if(SDL_GetDesktopDisplayMode(displayIndex: g_Config.m_GfxScreen, mode: &DpMode) < 0)
1651 {
1652 log_error("gfx", "Unable to get desktop display mode of screen %d: %s", g_Config.m_GfxScreen, SDL_GetError());
1653 }
1654 else
1655 {
1656 ResizeWindow(w: DpMode.w, h: DpMode.h, RefreshRate: DpMode.refresh_rate);
1657 SDL_SetWindowPosition(window: m_pWindow, SDL_WINDOWPOS_CENTERED_DISPLAY(g_Config.m_GfxScreen), SDL_WINDOWPOS_CENTERED_DISPLAY(g_Config.m_GfxScreen));
1658 }
1659 }
1660 }
1661 else // Windowed
1662 {
1663 SDL_SetWindowFullscreen(window: m_pWindow, flags: 0);
1664 SDL_SetWindowBordered(window: m_pWindow, bordered: SDL_bool(!IsBorderless));
1665 SDL_SetWindowResizable(window: m_pWindow, resizable: SDL_TRUE);
1666 }
1667}
1668
1669bool CGraphicsBackend_SDL_GL::SetWindowScreen(int Index, bool MoveToCenter, ivec2 *pDesktopSize)
1670{
1671 if(Index < 0 || Index >= m_NumScreens)
1672 {
1673 log_error("gfx", "Invalid screen number: %d (min: 0, max: %d)", Index, m_NumScreens);
1674 return false;
1675 }
1676
1677 SDL_Rect ScreenPos;
1678 if(SDL_GetDisplayBounds(displayIndex: Index, rect: &ScreenPos) != 0)
1679 {
1680 log_error("gfx", "Unable to get bounds of screen %d: %s", Index, SDL_GetError());
1681 return false;
1682 }
1683
1684 if(MoveToCenter)
1685 {
1686 SDL_SetWindowPosition(window: m_pWindow,
1687 SDL_WINDOWPOS_CENTERED_DISPLAY(Index),
1688 SDL_WINDOWPOS_CENTERED_DISPLAY(Index));
1689 }
1690 else
1691 {
1692 SDL_SetWindowPosition(window: m_pWindow,
1693 SDL_WINDOWPOS_UNDEFINED_DISPLAY(Index),
1694 SDL_WINDOWPOS_UNDEFINED_DISPLAY(Index));
1695 }
1696
1697 return UpdateDisplayMode(Index, pDesktopSize);
1698}
1699
1700bool CGraphicsBackend_SDL_GL::UpdateDisplayMode(int Index, ivec2 *pDesktopSize)
1701{
1702 SDL_DisplayMode DisplayMode;
1703 if(SDL_GetDesktopDisplayMode(displayIndex: Index, mode: &DisplayMode) < 0)
1704 {
1705 log_error("gfx", "Unable to get desktop display mode of screen %d: %s", Index, SDL_GetError());
1706 return false;
1707 }
1708
1709 g_Config.m_GfxScreen = Index;
1710 pDesktopSize->x = DisplayMode.w;
1711 pDesktopSize->y = DisplayMode.h;
1712 return true;
1713}
1714
1715int CGraphicsBackend_SDL_GL::GetWindowScreen()
1716{
1717 return SDL_GetWindowDisplayIndex(window: m_pWindow);
1718}
1719
1720int CGraphicsBackend_SDL_GL::WindowActive()
1721{
1722 return m_pWindow && SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_INPUT_FOCUS;
1723}
1724
1725int CGraphicsBackend_SDL_GL::WindowOpen()
1726{
1727 return m_pWindow && SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_SHOWN;
1728}
1729
1730void CGraphicsBackend_SDL_GL::SetWindowGrab(bool Grab)
1731{
1732 // Works around https://github.com/libsdl-org/sdl2-compat/issues/578.
1733 if(!m_pWindow)
1734 return;
1735
1736 SDL_SetWindowGrab(window: m_pWindow, grabbed: Grab ? SDL_TRUE : SDL_FALSE);
1737}
1738
1739bool CGraphicsBackend_SDL_GL::ResizeWindow(int w, int h, int RefreshRate)
1740{
1741 // don't call resize events when the window is at fullscreen desktop
1742 if(!m_pWindow || (SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_FULLSCREEN_DESKTOP) == SDL_WINDOW_FULLSCREEN_DESKTOP)
1743 return false;
1744
1745 // if the window is at fullscreen use SDL_SetWindowDisplayMode instead, suggested by SDL
1746 if(SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_FULLSCREEN)
1747 {
1748#ifdef CONF_FAMILY_WINDOWS
1749 // in windows make the window windowed mode first, this prevents strange window glitches (other games probably do something similar)
1750 SetWindowParams(0, true);
1751#endif
1752 SDL_DisplayMode SetMode = {};
1753 SDL_DisplayMode ClosestMode = {};
1754 SetMode.format = 0;
1755 SetMode.w = w;
1756 SetMode.h = h;
1757 SetMode.refresh_rate = RefreshRate;
1758 SDL_SetWindowDisplayMode(window: m_pWindow, mode: SDL_GetClosestDisplayMode(displayIndex: g_Config.m_GfxScreen, mode: &SetMode, closest: &ClosestMode));
1759#ifdef CONF_FAMILY_WINDOWS
1760 // now change it back to fullscreen, this will restore the above set state, bcs SDL saves fullscreen modes apart from other video modes (as of SDL 2.0.16)
1761 // see implementation of SDL_SetWindowDisplayMode
1762 SetWindowParams(1, false);
1763#endif
1764 return true;
1765 }
1766 else
1767 {
1768 SDL_SetWindowSize(window: m_pWindow, w, h);
1769 if(SDL_GetWindowFlags(window: m_pWindow) & SDL_WINDOW_MAXIMIZED)
1770 // remove maximize flag
1771 SDL_RestoreWindow(window: m_pWindow);
1772 }
1773
1774 return false;
1775}
1776
1777void CGraphicsBackend_SDL_GL::GetViewportSize(int &w, int &h)
1778{
1779 if(m_BackendType != EBackendType::BACKEND_TYPE_VULKAN)
1780 SDL_GL_GetDrawableSize(window: m_pWindow, w: &w, h: &h);
1781 else
1782 SDL_Vulkan_GetDrawableSize(window: m_pWindow, w: &w, h: &h);
1783}
1784
1785void CGraphicsBackend_SDL_GL::NotifyWindow()
1786{
1787 // Minimum version 2.0.16, after version 2.0.22 the naming is changed to 2.24.0 etc.
1788#if SDL_MAJOR_VERSION > 2 || (SDL_MAJOR_VERSION == 2 && SDL_MINOR_VERSION == 0 && SDL_PATCHLEVEL >= 16) || (SDL_MAJOR_VERSION == 2 && SDL_MINOR_VERSION > 0)
1789 if(SDL_FlashWindow(window: m_pWindow, operation: SDL_FlashOperation::SDL_FLASH_UNTIL_FOCUSED) != 0)
1790 {
1791 // fails if SDL hasn't implemented it
1792 return;
1793 }
1794#endif
1795}
1796
1797bool CGraphicsBackend_SDL_GL::IsScreenKeyboardShown()
1798{
1799 return SDL_IsScreenKeyboardShown(window: m_pWindow);
1800}
1801
1802void CGraphicsBackend_SDL_GL::WindowDestroyNtf(uint32_t WindowId)
1803{
1804}
1805
1806void CGraphicsBackend_SDL_GL::WindowCreateNtf(uint32_t WindowId)
1807{
1808 m_pWindow = SDL_GetWindowFromID(id: WindowId);
1809}
1810
1811TGLBackendReadPresentedImageData &CGraphicsBackend_SDL_GL::GetReadPresentedImageDataFuncUnsafe()
1812{
1813 return m_ReadPresentedImageDataFunc;
1814}
1815
1816IGraphicsBackend *CreateGraphicsBackend(TTranslateFunc &&TranslateFunc) { return new CGraphicsBackend_SDL_GL(std::move(TranslateFunc)); }
1817