VeldridWindow.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Runtime.CompilerServices;
  5. using System.Runtime.InteropServices;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using Veldrid.OpenGL;
  9. using Veldrid.Sdl2;
  10. using Veldrid.Vk;
  11. using Vulkan.Xlib;
  12. namespace Veldrid.Common.StartupUtilities
  13. {
  14. public struct WindowCreateInfo
  15. {
  16. public int X;
  17. public int Y;
  18. public int WindowWidth;
  19. public int WindowHeight;
  20. public WindowState WindowInitialState;
  21. public string WindowTitle;
  22. public WindowCreateInfo(
  23. int x,
  24. int y,
  25. int windowWidth,
  26. int windowHeight,
  27. WindowState windowInitialState,
  28. string windowTitle)
  29. {
  30. X = x;
  31. Y = y;
  32. WindowWidth = windowWidth;
  33. WindowHeight = windowHeight;
  34. WindowInitialState = windowInitialState;
  35. WindowTitle = windowTitle;
  36. }
  37. }
  38. public static class VeldridWindow
  39. {
  40. public static void CreateWindowAndGraphicsDevice(
  41. WindowCreateInfo windowCI,
  42. out Sdl2Window window,
  43. out GraphicsDevice gd)
  44. => CreateWindowAndGraphicsDevice(
  45. windowCI,
  46. new GraphicsDeviceOptions(),
  47. GetPlatformDefaultBackend(),
  48. out window,
  49. out gd);
  50. public static void CreateWindowAndGraphicsDevice(
  51. WindowCreateInfo windowCI,
  52. GraphicsDeviceOptions deviceOptions,
  53. out Sdl2Window window,
  54. out GraphicsDevice gd)
  55. => CreateWindowAndGraphicsDevice(windowCI, deviceOptions, GetPlatformDefaultBackend(), out window, out gd);
  56. public static void CreateWindowAndGraphicsDevice(
  57. WindowCreateInfo windowCI,
  58. GraphicsDeviceOptions deviceOptions,
  59. GraphicsBackend preferredBackend,
  60. out Sdl2Window window,
  61. out GraphicsDevice gd)
  62. {
  63. Sdl2Native.SDL_Init(SDLInitFlags.Video);
  64. if (preferredBackend == GraphicsBackend.OpenGL || preferredBackend == GraphicsBackend.OpenGLES)
  65. {
  66. SetSDLGLContextAttributes(deviceOptions, preferredBackend);
  67. }
  68. window = CreateWindow(ref windowCI);
  69. gd = CreateGraphicsDevice(window, deviceOptions, preferredBackend);
  70. }
  71. public static Sdl2Window CreateWindow(WindowCreateInfo windowCI) => CreateWindow(ref windowCI);
  72. public static Sdl2Window CreateWindow(ref WindowCreateInfo windowCI)
  73. {
  74. SDL_WindowFlags flags = SDL_WindowFlags.OpenGL | SDL_WindowFlags.Resizable
  75. | GetWindowFlags(windowCI.WindowInitialState);
  76. if (windowCI.WindowInitialState != WindowState.Hidden)
  77. {
  78. flags |= SDL_WindowFlags.Shown;
  79. }
  80. Sdl2Window window = new Sdl2Window(
  81. windowCI.WindowTitle,
  82. windowCI.X,
  83. windowCI.Y,
  84. windowCI.WindowWidth,
  85. windowCI.WindowHeight,
  86. flags,
  87. false);
  88. return window;
  89. }
  90. private static SDL_WindowFlags GetWindowFlags(WindowState state)
  91. {
  92. switch (state)
  93. {
  94. case WindowState.Normal:
  95. return 0;
  96. case WindowState.FullScreen:
  97. return SDL_WindowFlags.Fullscreen;
  98. case WindowState.Maximized:
  99. return SDL_WindowFlags.Maximized;
  100. case WindowState.Minimized:
  101. return SDL_WindowFlags.Minimized;
  102. case WindowState.BorderlessFullScreen:
  103. return SDL_WindowFlags.FullScreenDesktop;
  104. case WindowState.Hidden:
  105. return SDL_WindowFlags.Hidden;
  106. default:
  107. throw new VeldridException("Invalid WindowState: " + state);
  108. }
  109. }
  110. public static GraphicsDevice CreateGraphicsDevice(Sdl2Window window)
  111. => CreateGraphicsDevice(window, new GraphicsDeviceOptions(), GetPlatformDefaultBackend());
  112. public static GraphicsDevice CreateGraphicsDevice(Sdl2Window window, GraphicsDeviceOptions options)
  113. => CreateGraphicsDevice(window, options, GetPlatformDefaultBackend());
  114. public static GraphicsDevice CreateGraphicsDevice(Sdl2Window window, GraphicsBackend preferredBackend)
  115. => CreateGraphicsDevice(window, new GraphicsDeviceOptions(), preferredBackend);
  116. public static GraphicsDevice CreateGraphicsDevice(
  117. Sdl2Window window,
  118. GraphicsDeviceOptions options,
  119. GraphicsBackend preferredBackend)
  120. {
  121. switch (preferredBackend)
  122. {
  123. case GraphicsBackend.Direct3D11:
  124. #if !EXCLUDE_D3D11_BACKEND
  125. return CreateDefaultD3D11GraphicsDevice(options, window);
  126. #else
  127. throw new VeldridException("D3D11 support has not been included in this configuration of Veldrid");
  128. #endif
  129. case GraphicsBackend.Vulkan:
  130. #if !EXCLUDE_VULKAN_BACKEND
  131. return CreateVulkanGraphicsDevice(options, window);
  132. #else
  133. throw new VeldridException("Vulkan support has not been included in this configuration of Veldrid");
  134. #endif
  135. case GraphicsBackend.OpenGL:
  136. #if !EXCLUDE_OPENGL_BACKEND
  137. return CreateDefaultOpenGLGraphicsDevice(options, window, preferredBackend);
  138. #else
  139. throw new VeldridException("OpenGL support has not been included in this configuration of Veldrid");
  140. #endif
  141. case GraphicsBackend.Metal:
  142. #if !EXCLUDE_METAL_BACKEND
  143. return CreateMetalGraphicsDevice(options, window);
  144. #else
  145. throw new VeldridException("Metal support has not been included in this configuration of Veldrid");
  146. #endif
  147. case GraphicsBackend.OpenGLES:
  148. #if !EXCLUDE_OPENGL_BACKEND
  149. return CreateDefaultOpenGLGraphicsDevice(options, window, preferredBackend);
  150. #else
  151. throw new VeldridException("OpenGL support has not been included in this configuration of Veldrid");
  152. #endif
  153. default:
  154. throw new VeldridException("Invalid GraphicsBackend: " + preferredBackend);
  155. }
  156. }
  157. public static unsafe SwapchainSource GetSwapchainSource(Sdl2Window window)
  158. {
  159. IntPtr sdlHandle = window.SdlWindowHandle;
  160. SDL_SysWMinfo sysWmInfo;
  161. Sdl2Native.SDL_GetVersion(&sysWmInfo.version);
  162. Sdl2Native.SDL_GetWMWindowInfo(sdlHandle, &sysWmInfo);
  163. switch (sysWmInfo.subsystem)
  164. {
  165. case SysWMType.Windows:
  166. Win32WindowInfo w32Info = Unsafe.Read<Win32WindowInfo>(&sysWmInfo.info);
  167. return SwapchainSource.CreateWin32(w32Info.Sdl2Window, w32Info.hinstance);
  168. case SysWMType.X11:
  169. X11WindowInfo x11Info = Unsafe.Read<X11WindowInfo>(&sysWmInfo.info);
  170. return SwapchainSource.CreateXlib(
  171. x11Info.display,
  172. x11Info.Sdl2Window);
  173. case SysWMType.Wayland:
  174. WaylandWindowInfo wlInfo = Unsafe.Read<WaylandWindowInfo>(&sysWmInfo.info);
  175. return SwapchainSource.CreateWayland(wlInfo.display, wlInfo.surface);
  176. case SysWMType.Cocoa:
  177. CocoaWindowInfo cocoaInfo = Unsafe.Read<CocoaWindowInfo>(&sysWmInfo.info);
  178. IntPtr nsWindow = cocoaInfo.Window;
  179. return SwapchainSource.CreateNSWindow(nsWindow);
  180. default:
  181. throw new PlatformNotSupportedException("Cannot create a SwapchainSource for " + sysWmInfo.subsystem + ".");
  182. }
  183. }
  184. #if !EXCLUDE_METAL_BACKEND
  185. private static unsafe GraphicsDevice CreateMetalGraphicsDevice(GraphicsDeviceOptions options, Sdl2Window window)
  186. => CreateMetalGraphicsDevice(options, window, options.SwapchainSrgbFormat);
  187. private static unsafe GraphicsDevice CreateMetalGraphicsDevice(
  188. GraphicsDeviceOptions options,
  189. Sdl2Window window,
  190. bool colorSrgb)
  191. {
  192. SwapchainSource source = GetSwapchainSource(window);
  193. SwapchainDescription swapchainDesc = new SwapchainDescription(
  194. source,
  195. (uint)window.Width, (uint)window.Height,
  196. options.SwapchainDepthFormat,
  197. options.SyncToVerticalBlank,
  198. colorSrgb);
  199. return GraphicsDevice.CreateMetal(options, swapchainDesc);
  200. }
  201. #endif
  202. public static GraphicsBackend GetPlatformDefaultBackend()
  203. {
  204. if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
  205. {
  206. return GraphicsBackend.Direct3D11;
  207. }
  208. else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
  209. {
  210. return GraphicsDevice.IsBackendSupported(GraphicsBackend.Metal)
  211. ? GraphicsBackend.Metal
  212. : GraphicsBackend.OpenGL;
  213. }
  214. else
  215. {
  216. return GraphicsDevice.IsBackendSupported(GraphicsBackend.Vulkan)
  217. ? GraphicsBackend.Vulkan
  218. : GraphicsBackend.OpenGL;
  219. }
  220. }
  221. #if !EXCLUDE_VULKAN_BACKEND
  222. public static unsafe GraphicsDevice CreateVulkanGraphicsDevice(GraphicsDeviceOptions options, Sdl2Window window)
  223. => CreateVulkanGraphicsDevice(options, window, false);
  224. public static unsafe GraphicsDevice CreateVulkanGraphicsDevice(
  225. GraphicsDeviceOptions options,
  226. Sdl2Window window,
  227. bool colorSrgb)
  228. {
  229. SwapchainDescription scDesc = new SwapchainDescription(
  230. GetSwapchainSource(window),
  231. (uint)window.Width,
  232. (uint)window.Height,
  233. options.SwapchainDepthFormat,
  234. options.SyncToVerticalBlank,
  235. colorSrgb);
  236. GraphicsDevice gd = GraphicsDevice.CreateVulkan(options, scDesc);
  237. return gd;
  238. }
  239. private static unsafe Veldrid.Vk.VkSurfaceSource GetSurfaceSource(SDL_SysWMinfo sysWmInfo)
  240. {
  241. switch (sysWmInfo.subsystem)
  242. {
  243. case SysWMType.Windows:
  244. Win32WindowInfo w32Info = Unsafe.Read<Win32WindowInfo>(&sysWmInfo.info);
  245. return Vk.VkSurfaceSource.CreateWin32(w32Info.hinstance, w32Info.Sdl2Window);
  246. case SysWMType.X11:
  247. X11WindowInfo x11Info = Unsafe.Read<X11WindowInfo>(&sysWmInfo.info);
  248. return Vk.VkSurfaceSource.CreateXlib(
  249. (Vulkan.Xlib.Display*)x11Info.display,
  250. new Vulkan.Xlib.Window() { Value = x11Info.Sdl2Window });
  251. default:
  252. throw new PlatformNotSupportedException("Cannot create a Vulkan surface for " + sysWmInfo.subsystem + ".");
  253. }
  254. }
  255. #endif
  256. #if !EXCLUDE_OPENGL_BACKEND
  257. public static unsafe GraphicsDevice CreateDefaultOpenGLGraphicsDevice(
  258. GraphicsDeviceOptions options,
  259. Sdl2Window window,
  260. GraphicsBackend backend)
  261. {
  262. Sdl2Native.SDL_ClearError();
  263. IntPtr sdlHandle = window.SdlWindowHandle;
  264. SDL_SysWMinfo sysWmInfo;
  265. Sdl2Native.SDL_GetVersion(&sysWmInfo.version);
  266. Sdl2Native.SDL_GetWMWindowInfo(sdlHandle, &sysWmInfo);
  267. SetSDLGLContextAttributes(options, backend);
  268. IntPtr contextHandle = Sdl2Native.SDL_GL_CreateContext(sdlHandle);
  269. byte* error = Sdl2Native.SDL_GetError();
  270. if (error != null)
  271. {
  272. string errorString = GetString(error);
  273. if (!string.IsNullOrEmpty(errorString))
  274. {
  275. throw new VeldridException(
  276. $"Unable to create OpenGL Context: \"{errorString}\". This may indicate that the system does not support the requested OpenGL profile, version, or Swapchain format.");
  277. }
  278. }
  279. int actualDepthSize;
  280. int result = Sdl2Native.SDL_GL_GetAttribute(SDL_GLAttribute.DepthSize, &actualDepthSize);
  281. int actualStencilSize;
  282. result = Sdl2Native.SDL_GL_GetAttribute(SDL_GLAttribute.StencilSize, &actualStencilSize);
  283. result = Sdl2Native.SDL_GL_SetSwapInterval(options.SyncToVerticalBlank ? 1 : 0);
  284. OpenGL.OpenGLPlatformInfo platformInfo = new OpenGL.OpenGLPlatformInfo(
  285. contextHandle,
  286. Sdl2Native.SDL_GL_GetProcAddress,
  287. context => Sdl2Native.SDL_GL_MakeCurrent(sdlHandle, context),
  288. () => Sdl2Native.SDL_GL_GetCurrentContext(),
  289. () => Sdl2Native.SDL_GL_MakeCurrent(new SDL_Window(IntPtr.Zero), IntPtr.Zero),
  290. Sdl2Native.SDL_GL_DeleteContext,
  291. () => Sdl2Native.SDL_GL_SwapWindow(sdlHandle),
  292. sync => Sdl2Native.SDL_GL_SetSwapInterval(sync ? 1 : 0));
  293. return GraphicsDevice.CreateOpenGL(
  294. options,
  295. platformInfo,
  296. (uint)window.Width,
  297. (uint)window.Height);
  298. }
  299. public static unsafe void SetSDLGLContextAttributes(GraphicsDeviceOptions options, GraphicsBackend backend)
  300. {
  301. if (backend != GraphicsBackend.OpenGL && backend != GraphicsBackend.OpenGLES)
  302. {
  303. throw new VeldridException(
  304. $"{nameof(backend)} must be {nameof(GraphicsBackend.OpenGL)} or {nameof(GraphicsBackend.OpenGLES)}.");
  305. }
  306. SDL_GLContextFlag contextFlags = options.Debug
  307. ? SDL_GLContextFlag.Debug | SDL_GLContextFlag.ForwardCompatible
  308. : SDL_GLContextFlag.ForwardCompatible;
  309. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextFlags, (int)contextFlags);
  310. (int major, int minor) = GetMaxGLVersion(backend == GraphicsBackend.OpenGLES);
  311. if (backend == GraphicsBackend.OpenGL)
  312. {
  313. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextProfileMask, (int)SDL_GLProfile.Core);
  314. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMajorVersion, major);
  315. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMinorVersion, minor);
  316. }
  317. else
  318. {
  319. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextProfileMask, (int)SDL_GLProfile.ES);
  320. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMajorVersion, major);
  321. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMinorVersion, minor);
  322. }
  323. int depthBits = 0;
  324. int stencilBits = 0;
  325. if (options.SwapchainDepthFormat.HasValue)
  326. {
  327. switch (options.SwapchainDepthFormat)
  328. {
  329. case PixelFormat.R16_UNorm:
  330. depthBits = 16;
  331. break;
  332. case PixelFormat.D24_UNorm_S8_UInt:
  333. depthBits = 24;
  334. stencilBits = 8;
  335. break;
  336. case PixelFormat.R32_Float:
  337. depthBits = 32;
  338. break;
  339. case PixelFormat.D32_Float_S8_UInt:
  340. depthBits = 32;
  341. stencilBits = 8;
  342. break;
  343. default:
  344. throw new VeldridException("Invalid depth format: " + options.SwapchainDepthFormat.Value);
  345. }
  346. }
  347. int result = Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.DepthSize, depthBits);
  348. result = Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.StencilSize, stencilBits);
  349. if (options.SwapchainSrgbFormat)
  350. {
  351. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.FramebufferSrgbCapable, 1);
  352. }
  353. else
  354. {
  355. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.FramebufferSrgbCapable, 0);
  356. }
  357. }
  358. #endif
  359. #if !EXCLUDE_D3D11_BACKEND
  360. public static GraphicsDevice CreateDefaultD3D11GraphicsDevice(
  361. GraphicsDeviceOptions options,
  362. Sdl2Window window)
  363. {
  364. SwapchainSource source = GetSwapchainSource(window);
  365. SwapchainDescription swapchainDesc = new SwapchainDescription(
  366. source,
  367. (uint)window.Width, (uint)window.Height,
  368. options.SwapchainDepthFormat,
  369. options.SyncToVerticalBlank,
  370. options.SwapchainSrgbFormat);
  371. return GraphicsDevice.CreateD3D11(options, swapchainDesc);
  372. }
  373. #endif
  374. private static unsafe string GetString(byte* stringStart)
  375. {
  376. int characters = 0;
  377. while (stringStart[characters] != 0)
  378. {
  379. characters++;
  380. }
  381. return Encoding.UTF8.GetString(stringStart, characters);
  382. }
  383. #if !EXCLUDE_OPENGL_BACKEND
  384. private static readonly object s_glVersionLock = new object();
  385. private static (int Major, int Minor)? s_maxSupportedGLVersion;
  386. private static (int Major, int Minor)? s_maxSupportedGLESVersion;
  387. private static (int Major, int Minor) GetMaxGLVersion(bool gles)
  388. {
  389. lock (s_glVersionLock)
  390. {
  391. (int Major, int Minor)? maxVer = gles ? s_maxSupportedGLESVersion : s_maxSupportedGLVersion;
  392. if (maxVer == null)
  393. {
  394. maxVer = TestMaxVersion(gles);
  395. if (gles) { s_maxSupportedGLESVersion = maxVer; }
  396. else { s_maxSupportedGLVersion = maxVer; }
  397. }
  398. return maxVer.Value;
  399. }
  400. }
  401. private static (int Major, int Minor) TestMaxVersion(bool gles)
  402. {
  403. (int, int)[] testVersions = gles
  404. ? new[] { (3, 2), (3, 0) }
  405. : new[] { (4, 6), (4, 3), (4, 0), (3, 3), (3, 0) };
  406. foreach ((int major, int minor) in testVersions)
  407. {
  408. if (TestIndividualGLVersion(gles, major, minor)) { return (major, minor); }
  409. }
  410. return (0, 0);
  411. }
  412. private static unsafe bool TestIndividualGLVersion(bool gles, int major, int minor)
  413. {
  414. SDL_GLProfile profileMask = gles ? SDL_GLProfile.ES : SDL_GLProfile.Core;
  415. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextProfileMask, (int)profileMask);
  416. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMajorVersion, major);
  417. Sdl2Native.SDL_GL_SetAttribute(SDL_GLAttribute.ContextMinorVersion, minor);
  418. SDL_Window window = Sdl2Native.SDL_CreateWindow(
  419. string.Empty,
  420. 0, 0,
  421. 1, 1,
  422. SDL_WindowFlags.Hidden | SDL_WindowFlags.OpenGL);
  423. byte* error = Sdl2Native.SDL_GetError();
  424. string errorString = GetString(error);
  425. if (window.NativePointer == IntPtr.Zero || !string.IsNullOrEmpty(errorString))
  426. {
  427. Sdl2Native.SDL_ClearError();
  428. return false;
  429. }
  430. IntPtr context = Sdl2Native.SDL_GL_CreateContext(window);
  431. error = Sdl2Native.SDL_GetError();
  432. if (error != null)
  433. {
  434. errorString = GetString(error);
  435. if (!string.IsNullOrEmpty(errorString))
  436. {
  437. Sdl2Native.SDL_ClearError();
  438. Sdl2Native.SDL_DestroyWindow(window);
  439. return false;
  440. }
  441. }
  442. Sdl2Native.SDL_GL_DeleteContext(context);
  443. Sdl2Native.SDL_DestroyWindow(window);
  444. return true;
  445. }
  446. #endif
  447. }
  448. }