From f347767480e356e80051ee97de03c74fc7edcf5d Mon Sep 17 00:00:00 2001 From: Earu <20880060+Earu@users.noreply.github.com> Date: Mon, 16 Nov 2026 14:57:35 +0400 Subject: [PATCH] Add macOS support Rendering: - Run the GL 4.6 renderer on macOS through Mesa (Zink over KosmicKrisp). SDL3_MesaEGL_Context renders into an EGL pbuffer at the engine's render size and presents each frame through SDL's Metal renderer. - Bundle libEGL, libgallium, KosmicKrisp and the Vulkan loader into Build//mesa/lib at build time. Requires `brew install mesa vulkan-loader`. - Scale mouse coordinates between window and render size so clicks land correctly when the two differ, as in fullscreen. - Implement HardwareConfig.CanDoSRGBReadFromRTs, which only the macOS shader path calls. Native libraries: - Move libsteam_api.dylib to runtimes/osx/native so arm64 finds it. - Use Homebrew's arm64 FreeImage on Apple Silicon, since the NuGet package only ships x86_64. - Implement GetSystemFontPath on macOS through CoreText. Cross-platform fixes: - Fix font fallback "NULL" entries being compared by reference, which looped forever when no fallback font could be loaded. - Use the invariant culture process-wide so data files parse correctly on locales with a comma decimal separator. - Resolve the mod directory, relative search paths and the platform directory against AppContext.BaseDirectory instead of the working directory, so launching from outside the build output works. - Find the Garry's Mod install through the macOS Steam library path. - Skip loading Chromium on macOS when the CEF framework is missing, instead of searching the working directory tree. --- Game.Assets/Assets.cs | 5 + .../native/libsteam_api.dylib | Bin Game.UI/GameUI.cs | 6 +- HTML.CEF/CefSystem.cs | 5 + Source.Common/Platform.cs | 5 + Source.Engine/Common.cs | 2 +- Source.Engine/Source.Engine.csproj | 3 +- Source.Filesystem/BaseFileSystem.cs | 4 +- Source.Launcher/Source.Launcher.csproj | 24 ++ Source.MaterialSystem/Surface/FontManager.cs | 2 +- Source.SDLInputSystem/SDL3_InputSystem.cs | 25 +- Source.SDLManager/SDL3_LauncherManager.cs | 28 ++ Source.SDLManager/SDL3_MesaEGL_Context.cs | 323 ++++++++++++++++++ Source.SDLManager/SDL3_Window.cs | 10 + Source.SDLSystem/SDL3_System.OSX.cs | 49 ++- Source.ShaderAPI.Gl46/HardwareConfig.cs | 4 +- 16 files changed, 478 insertions(+), 17 deletions(-) rename Game.Assets/runtimes/{osx-x64 => osx}/native/libsteam_api.dylib (100%) create mode 100644 Source.SDLManager/SDL3_MesaEGL_Context.cs diff --git a/Game.Assets/Assets.cs b/Game.Assets/Assets.cs index 4db9a793f..0cb3217da 100644 --- a/Game.Assets/Assets.cs +++ b/Game.Assets/Assets.cs @@ -80,6 +80,11 @@ public static List GetOptionalAssets() { } } } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { + string p = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Library", "Application Support", "Steam"); + if (Directory.Exists(p)) + steamPath = p; + } if (string.IsNullOrEmpty(steamPath)) return null; diff --git a/Game.Assets/runtimes/osx-x64/native/libsteam_api.dylib b/Game.Assets/runtimes/osx/native/libsteam_api.dylib similarity index 100% rename from Game.Assets/runtimes/osx-x64/native/libsteam_api.dylib rename to Game.Assets/runtimes/osx/native/libsteam_api.dylib diff --git a/Game.UI/GameUI.cs b/Game.UI/GameUI.cs index 7dea4a6b6..bfcf393af 100644 --- a/Game.UI/GameUI.cs +++ b/Game.UI/GameUI.cs @@ -157,11 +157,7 @@ public bool SetShowProgressText(bool show) { private bool FindPlatformDirectory(out ReadOnlySpan platformDir) { platformDir = string.Empty; -#if WIN32 - string? dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); -#else - string? dir = Directory.GetCurrentDirectory(); -#endif + string? dir = AppContext.BaseDirectory; if (string.IsNullOrEmpty(dir)) return false; diff --git a/HTML.CEF/CefSystem.cs b/HTML.CEF/CefSystem.cs index 6b66f2cbb..f7c51e04f 100644 --- a/HTML.CEF/CefSystem.cs +++ b/HTML.CEF/CefSystem.cs @@ -29,6 +29,11 @@ public bool Init(ReadOnlySpan pBaseDir, IHtmlResourceHandler resourceHandl if (OperatingSystem.IsWindows() && !LowIntegrityLabel.Apply(rootCachePath)) resourceHandler.Message($"Chromium: failed to set a low integrity label on {rootCachePath}, cookies and storage will not persist.\n"); + if (OperatingSystem.IsMacOS() && !Directory.Exists(Path.Combine(chromiumDir, "Chromium Embedded Framework.framework"))) { + resourceHandler.Message($"Chromium failed to load: Chromium Embedded Framework.framework is missing from {chromiumDir}\n"); + return false; + } + try { if (OperatingSystem.IsWindows()) CefRuntime.Load(chromiumDir); diff --git a/Source.Common/Platform.cs b/Source.Common/Platform.cs index dcf149b8a..ee06a8f78 100644 --- a/Source.Common/Platform.cs +++ b/Source.Common/Platform.cs @@ -1,6 +1,7 @@ using Source.Common; using System.Diagnostics; +using System.Globalization; using System.Runtime.InteropServices; namespace Source; @@ -56,6 +57,10 @@ public static unsafe void DebugString(ReadOnlySpan buf) { } public static void Initialize() { + CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; + CultureInfo.DefaultThreadCurrentUICulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; + CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; ThreadUtils.SetMainThread(); } } diff --git a/Source.Engine/Common.cs b/Source.Engine/Common.cs index 500997fc4..8a5f99878 100644 --- a/Source.Engine/Common.cs +++ b/Source.Engine/Common.cs @@ -103,7 +103,7 @@ public void InitFilesystem(ReadOnlySpan fullModPath) { FileSystem FileSystem = providers.GetRequiredService(); initInfo.FileSystem = engineAPI.GetRequiredService(); - initInfo.DirectoryName = new(fullModPath); + initInfo.DirectoryName = fullModPath.IsEmpty ? "" : Path.GetFullPath(new string(fullModPath), AppContext.BaseDirectory); if (initInfo.DirectoryName == null) initInfo.DirectoryName = Host.GetCurrentGame(); diff --git a/Source.Engine/Source.Engine.csproj b/Source.Engine/Source.Engine.csproj index 46c818649..6def64014 100644 --- a/Source.Engine/Source.Engine.csproj +++ b/Source.Engine/Source.Engine.csproj @@ -20,7 +20,8 @@ - + + diff --git a/Source.Filesystem/BaseFileSystem.cs b/Source.Filesystem/BaseFileSystem.cs index 91901b551..80dd595b9 100644 --- a/Source.Filesystem/BaseFileSystem.cs +++ b/Source.Filesystem/BaseFileSystem.cs @@ -101,7 +101,7 @@ private void AddMapPackFile(ReadOnlySpan path, ReadOnlySpan pathID, } private void AddVPKFile(ReadOnlySpan path, ReadOnlySpan pathID, SearchPathAdd addType, PathGroupName groupName) { - string newPath = Path.IsPathFullyQualified(path) ? new(path) : Path.GetFullPath(new(path)); + string newPath = Path.IsPathFullyQualified(path) ? new(path) : Path.GetFullPath(new(path), AppContext.BaseDirectory); if (!SearchPaths.OpenOrCreateCollection(pathID, out SearchPathCollection collection)) { for (int i = 0, c = collection.Count; i < c; i++) { @@ -136,7 +136,7 @@ private void AddSearchPathDiskInternal(ReadOnlySpan path, ReadOnlySpan + + + /opt/homebrew/opt/mesa + /opt/homebrew/opt/vulkan-loader + $(OutputPath)mesa/lib/ + + + + + + + + + + + + + + + + + + + diff --git a/Source.MaterialSystem/Surface/FontManager.cs b/Source.MaterialSystem/Surface/FontManager.cs index 8ab515c93..77df0fe41 100644 --- a/Source.MaterialSystem/Surface/FontManager.cs +++ b/Source.MaterialSystem/Surface/FontManager.cs @@ -622,7 +622,7 @@ internal void InitFontSettings() { for (KeyValues? kv = fallbackFonts.GetFirstSubKey(); kv != null; kv = kv.GetNextKey()) { string? key = kv.Name == "NULL" ? null : kv.Name; - string? value = kv.GetString() == "NULL" ? null : new(kv.GetString()); + string? value = kv.GetString().SequenceEqual("NULL") ? null : new(kv.GetString()); FallbackFonts[ffidx++] = new(key, value); } diff --git a/Source.SDLInputSystem/SDL3_InputSystem.cs b/Source.SDLInputSystem/SDL3_InputSystem.cs index 1fb498394..e9cfe6f10 100644 --- a/Source.SDLInputSystem/SDL3_InputSystem.cs +++ b/Source.SDLInputSystem/SDL3_InputSystem.cs @@ -634,11 +634,30 @@ public void SetConsoleTextMode(bool consoleTextMode) { public unsafe void GetCursorPosition(out int x, out int y) { float fx, fy; SDL3.SDL_GetMouseState(&fx, &fy); - x = (int)fx; - y = (int)fy; + GetCursorScale(out float sx, out float sy); + x = (int)(fx * sx); + y = (int)(fy * sy); } - public unsafe void SetCursorPosition(int x, int y) => SDL3.SDL_WarpMouseInWindow((SDL_Window*)Window!.GetHandle(), x, y); + public unsafe void SetCursorPosition(int x, int y) { + GetCursorScale(out float sx, out float sy); + SDL3.SDL_WarpMouseInWindow((SDL_Window*)Window!.GetHandle(), x / sx, y / sy); + } + + void GetCursorScale(out float sx, out float sy) { + sx = sy = 1.0f; +#if OSX + if (launcherMgr == null) + return; + int renderWidth = 0, renderHeight = 0; + launcherMgr.RenderedSize(false, ref renderWidth, ref renderHeight); + launcherMgr.DisplayedSize(out int displayWidth, out int displayHeight); + if (renderWidth > 0 && renderHeight > 0 && displayWidth > 0 && displayHeight > 0) { + sx = (float)renderWidth / displayWidth; + sy = (float)renderHeight / displayHeight; + } +#endif + } public ButtonCode VirtualKeyToButtonCode(int virtualKey) { return virtualKeyToButtonCode[virtualKey]; diff --git a/Source.SDLManager/SDL3_LauncherManager.cs b/Source.SDLManager/SDL3_LauncherManager.cs index d7fc38aed..5865e4045 100644 --- a/Source.SDLManager/SDL3_LauncherManager.cs +++ b/Source.SDLManager/SDL3_LauncherManager.cs @@ -109,7 +109,11 @@ public bool CreateGameWindow(string title, bool windowed, bool borderless, int w SDL_WindowFlags flags = default; GraphicsDriver driver = GraphicsDriver.OpenGL46; // todo, dont hardcode switch(driver.GetDriver()){ +#if OSX + case GraphicsDriver.OpenGL: flags |= SDL_WindowFlags.SDL_WINDOW_METAL; break; +#else case GraphicsDriver.OpenGL: flags |= SDL_WindowFlags.SDL_WINDOW_OPENGL; break; +#endif case GraphicsDriver.Metal: flags |= SDL_WindowFlags.SDL_WINDOW_METAL; break; case GraphicsDriver.Vulkan: flags |= SDL_WindowFlags.SDL_WINDOW_VULKAN; break; default: throw new Exception("Need graphics driver support"); @@ -226,6 +230,10 @@ public void RenderedSize(bool set, ref int width, ref int height) { if (set) { renderedWidth = width; renderedHeight = height; +#if OSX + window.RenderWidth = width; + window.RenderHeight = height; +#endif } else { width = renderedWidth; @@ -355,17 +363,37 @@ public bool PrepareContext(GraphicsDriver driver) { window = window == null ? this.window : window; if (0 != (deviceInfo.Driver & GraphicsDriver.OpenGL)) { nint handle = (nint)((SDL3_Window)window).HardwareHandle; +#if OSX + int modeWidth = deviceInfo.DisplayMode.Width, modeHeight = deviceInfo.DisplayMode.Height; + return SDL3_MesaEGL_Context.Create((SDL_Window*)handle, 4, 6, () => { + if (renderedWidth > 0 && renderedHeight > 0) + return (renderedWidth, renderedHeight); + if (modeWidth > 0 && modeHeight > 0) + return (modeWidth, modeHeight); + DisplayedSize(out int w, out int h); + return (w, h); + }); +#else nint ctx = (nint)SDL3.SDL_GL_CreateContext((SDL_Window*)handle); + if (ctx == 0) { + Warning($"Could not create GL context: {SDL3.SDL_GetError()}\n"); + return null; + } SDL3.SDL_GL_SetSwapInterval(0); gfx = new SDL3_OpenGL46_Context(handle, ctx); return gfx; +#endif } Warning("Cannot support this graphics API\n"); return null; } +#if OSX + public delegate* unmanaged[Cdecl] GL_LoadExtensionsPtr() => &SDL3_MesaEGL_Context.GetProcAddress; +#else public delegate* unmanaged[Cdecl] GL_LoadExtensionsPtr() => &GL_ProcAddress; +#endif ICursor[] DefaultCursors; diff --git a/Source.SDLManager/SDL3_MesaEGL_Context.cs b/Source.SDLManager/SDL3_MesaEGL_Context.cs new file mode 100644 index 000000000..0b715ee4c --- /dev/null +++ b/Source.SDLManager/SDL3_MesaEGL_Context.cs @@ -0,0 +1,323 @@ +using SDL; + +using Source.Common.Launcher; + +using System.Runtime.InteropServices; + +namespace Source.SDLManager; + +public unsafe class SDL3_MesaEGL_Context : IGraphicsContext +{ + const int EGL_NONE = 0x3038; + const int EGL_RED_SIZE = 0x3024, EGL_GREEN_SIZE = 0x3023, EGL_BLUE_SIZE = 0x3022, EGL_ALPHA_SIZE = 0x3021; + const int EGL_DEPTH_SIZE = 0x3025, EGL_STENCIL_SIZE = 0x3026; + const int EGL_SURFACE_TYPE = 0x3033, EGL_PBUFFER_BIT = 0x0001; + const int EGL_RENDERABLE_TYPE = 0x3040, EGL_OPENGL_BIT = 0x0008; + const int EGL_WIDTH = 0x3057, EGL_HEIGHT = 0x3056; + const int EGL_OPENGL_API = 0x30A2; + const int EGL_CONTEXT_MAJOR_VERSION = 0x3098, EGL_CONTEXT_MINOR_VERSION = 0x30FB; + const int EGL_CONTEXT_OPENGL_PROFILE_MASK = 0x30FD, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT = 0x1; + const int EGL_PLATFORM_SURFACELESS_MESA = 0x31DD; + + const int GL_PIXEL_PACK_BUFFER = 0x88EB, GL_PIXEL_PACK_BUFFER_BINDING = 0x88ED; + const int GL_READ_FRAMEBUFFER = 0x8CA8, GL_READ_FRAMEBUFFER_BINDING = 0x8CAA; + const int GL_READ_BUFFER = 0x0C02, GL_BACK = 0x0405; + const int GL_PACK_ALIGNMENT = 0x0D05, GL_PACK_ROW_LENGTH = 0x0D02; + const int GL_RGBA = 0x1908, GL_UNSIGNED_BYTE = 0x1401; + const int GL_STREAM_READ = 0x88E1, GL_MAP_READ_BIT = 0x0001; + const int GL_SYNC_GPU_COMMANDS_COMPLETE = 0x9117; + const ulong GL_TIMEOUT_IGNORED = ulong.MaxValue; + + static delegate* unmanaged[Cdecl] eglGetProcAddress; + static delegate* unmanaged[Cdecl] eglGetPlatformDisplayEXT; + static delegate* unmanaged[Cdecl] eglInitialize; + static delegate* unmanaged[Cdecl] eglBindAPI; + static delegate* unmanaged[Cdecl] eglChooseConfig; + static delegate* unmanaged[Cdecl] eglCreateContext; + static delegate* unmanaged[Cdecl] eglCreatePbufferSurface; + static delegate* unmanaged[Cdecl] eglDestroySurface; + static delegate* unmanaged[Cdecl] eglMakeCurrent; + static delegate* unmanaged[Cdecl] eglGetError; + + static delegate* unmanaged[Cdecl] glGetIntegerv; + static delegate* unmanaged[Cdecl] glBindFramebuffer; + static delegate* unmanaged[Cdecl] glReadBuffer; + static delegate* unmanaged[Cdecl] glPixelStorei; + static delegate* unmanaged[Cdecl] glGenBuffers; + static delegate* unmanaged[Cdecl] glBindBuffer; + static delegate* unmanaged[Cdecl] glBufferData; + static delegate* unmanaged[Cdecl] glReadPixels; + static delegate* unmanaged[Cdecl] glFenceSync; + static delegate* unmanaged[Cdecl] glDeleteSync; + static delegate* unmanaged[Cdecl] glClientWaitSync; + static delegate* unmanaged[Cdecl] glFlush; + static delegate* unmanaged[Cdecl] glMapBufferRange; + static delegate* unmanaged[Cdecl] glUnmapBuffer; + + [DllImport("libc", EntryPoint = "setenv")] + static extern int setenv([MarshalAs(UnmanagedType.LPUTF8Str)] string name, [MarshalAs(UnmanagedType.LPUTF8Str)] string value, int overwrite); + + public static string MesaLibDirectory => Path.Combine(AppContext.BaseDirectory, "mesa", "lib"); + + readonly SDL_Window* window; + readonly Func<(int Width, int Height)> targetSize; + nint display, config, context, surface; + int surfaceWidth, surfaceHeight; + + SDL_Renderer* renderer; + SDL_Texture* texture; + int textureWidth, textureHeight; + + readonly uint[] pbos = new uint[2]; + readonly nint[] fences = new nint[2]; + readonly (int Width, int Height)[] pboSizes = new (int, int)[2]; + uint frameIndex; + + SDL3_MesaEGL_Context(SDL_Window* window, Func<(int, int)> targetSize) { + this.window = window; + this.targetSize = targetSize; + } + + public nint HardwareHandle => context; + + public static SDL3_MesaEGL_Context? Create(SDL_Window* window, int major, int minor, Func<(int Width, int Height)> targetSize) { + if (!LoadEGL()) + return null; + + SDL3_MesaEGL_Context ctx = new(window, targetSize); + return ctx.Init(major, minor) ? ctx : null; + } + + static bool LoadEGL() { + if (eglGetProcAddress != null) + return true; + + string dir = MesaLibDirectory; + setenv("GALLIUM_DRIVER", "zink", 0); + setenv("VK_DRIVER_FILES", Path.Combine(dir, "kosmickrisp_icd.json"), 0); + setenv("MESA_GL_VERSION_OVERRIDE", "4.6", 0); + setenv("MESA_GLSL_VERSION_OVERRIDE", "460", 0); + + if (!NativeLibrary.TryLoad(Path.Combine(dir, "libEGL.1.dylib"), out nint lib)) { + Warning($"Could not load Mesa's libEGL from {dir}. Install it with 'brew install mesa vulkan-loader' and rebuild.\n"); + return false; + } + + eglGetProcAddress = (delegate* unmanaged[Cdecl])NativeLibrary.GetExport(lib, "eglGetProcAddress"); + eglGetPlatformDisplayEXT = (delegate* unmanaged[Cdecl])Proc("eglGetPlatformDisplayEXT"); + eglInitialize = (delegate* unmanaged[Cdecl])Proc("eglInitialize"); + eglBindAPI = (delegate* unmanaged[Cdecl])Proc("eglBindAPI"); + eglChooseConfig = (delegate* unmanaged[Cdecl])Proc("eglChooseConfig"); + eglCreateContext = (delegate* unmanaged[Cdecl])Proc("eglCreateContext"); + eglCreatePbufferSurface = (delegate* unmanaged[Cdecl])Proc("eglCreatePbufferSurface"); + eglDestroySurface = (delegate* unmanaged[Cdecl])Proc("eglDestroySurface"); + eglMakeCurrent = (delegate* unmanaged[Cdecl])Proc("eglMakeCurrent"); + eglGetError = (delegate* unmanaged[Cdecl])Proc("eglGetError"); + return true; + } + + static void* Proc(string name) { + byte* str = (byte*)Marshal.StringToCoTaskMemUTF8(name); + void* ptr = eglGetProcAddress(str); + Marshal.FreeCoTaskMem((nint)str); + if (ptr == null) + throw new EntryPointNotFoundException($"Mesa EGL is missing {name}"); + return ptr; + } + + [UnmanagedCallersOnly(CallConvs = [typeof(System.Runtime.CompilerServices.CallConvCdecl)])] + internal static void* GetProcAddress(byte* name) => eglGetProcAddress(name); + + bool Init(int major, int minor) { + display = eglGetPlatformDisplayEXT(EGL_PLATFORM_SURFACELESS_MESA, 0, null); + int vmaj, vmin; + if (display == 0 || eglInitialize(display, &vmaj, &vmin) == 0) { + Warning($"Mesa EGL: could not initialize the surfaceless display (0x{eglGetError():X})\n"); + return false; + } + eglBindAPI(EGL_OPENGL_API); + + int* cfgAttrs = stackalloc int[] { + EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, + EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_ALPHA_SIZE, 8, + EGL_DEPTH_SIZE, 24, EGL_STENCIL_SIZE, 8, + EGL_NONE + }; + nint cfg; + int numConfigs; + if (eglChooseConfig(display, cfgAttrs, &cfg, 1, &numConfigs) == 0 || numConfigs < 1) { + Warning($"Mesa EGL: no matching config (0x{eglGetError():X})\n"); + return false; + } + config = cfg; + + int* ctxAttrs = stackalloc int[] { + EGL_CONTEXT_MAJOR_VERSION, major, + EGL_CONTEXT_MINOR_VERSION, minor, + EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, + EGL_NONE + }; + context = eglCreateContext(display, config, 0, ctxAttrs); + if (context == 0) { + Warning($"Mesa EGL: could not create a GL {major}.{minor} core context (0x{eglGetError():X})\n"); + return false; + } + + (int w, int h) = targetSize(); + if (!CreateSurface(w, h)) + return false; + + renderer = SDL3.SDL_CreateRenderer(window, "metal"); + if (renderer == null) { + Warning($"Mesa EGL: could not create the SDL Metal renderer: {SDL3.SDL_GetError()}\n"); + return false; + } + + glGetIntegerv = (delegate* unmanaged[Cdecl])Proc("glGetIntegerv"); + glBindFramebuffer = (delegate* unmanaged[Cdecl])Proc("glBindFramebuffer"); + glReadBuffer = (delegate* unmanaged[Cdecl])Proc("glReadBuffer"); + glPixelStorei = (delegate* unmanaged[Cdecl])Proc("glPixelStorei"); + glGenBuffers = (delegate* unmanaged[Cdecl])Proc("glGenBuffers"); + glBindBuffer = (delegate* unmanaged[Cdecl])Proc("glBindBuffer"); + glBufferData = (delegate* unmanaged[Cdecl])Proc("glBufferData"); + glReadPixels = (delegate* unmanaged[Cdecl])Proc("glReadPixels"); + glFenceSync = (delegate* unmanaged[Cdecl])Proc("glFenceSync"); + glDeleteSync = (delegate* unmanaged[Cdecl])Proc("glDeleteSync"); + glClientWaitSync = (delegate* unmanaged[Cdecl])Proc("glClientWaitSync"); + glFlush = (delegate* unmanaged[Cdecl])Proc("glFlush"); + glMapBufferRange = (delegate* unmanaged[Cdecl])Proc("glMapBufferRange"); + glUnmapBuffer = (delegate* unmanaged[Cdecl])Proc("glUnmapBuffer"); + return true; + } + + bool CreateSurface(int width, int height) { + width = Math.Max(width, 1); + height = Math.Max(height, 1); + + int* attrs = stackalloc int[] { EGL_WIDTH, width, EGL_HEIGHT, height, EGL_NONE }; + nint newSurface = eglCreatePbufferSurface(display, config, attrs); + if (newSurface == 0) { + Warning($"Mesa EGL: could not create a {width}x{height} pbuffer (0x{eglGetError():X})\n"); + return false; + } + + DevMsg($"Mesa EGL: framebuffer {width}x{height}\n"); + nint oldSurface = surface; + surface = newSurface; + surfaceWidth = width; + surfaceHeight = height; + + eglMakeCurrent(display, surface, surface, context); + if (oldSurface != 0) + eglDestroySurface(display, oldSurface); + return true; + } + + public void MakeCurrent() { + if (eglMakeCurrent(display, surface, surface, context) == 0) + Warning($"Could not make GL context current (0x{eglGetError():X})\n"); + } + + public void ReleaseCurrent() { + if (eglMakeCurrent(display, 0, 0, 0) == 0) + Warning($"Could not release GL context (0x{eglGetError():X})\n"); + } + + public void SetSwapInterval(float swapInterval) { + if (!SDL3.SDL_SetRenderVSync(renderer, swapInterval != 0 ? 1 : 0)) + Warning($"Could not set vsync: {SDL3.SDL_GetError()}\n"); + } + + public void SwapBuffers() { + int prevPackBuffer, prevReadFramebuffer, prevReadBuffer, prevAlignment, prevRowLength; + glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &prevPackBuffer); + glGetIntegerv(GL_READ_FRAMEBUFFER_BINDING, &prevReadFramebuffer); + glGetIntegerv(GL_PACK_ALIGNMENT, &prevAlignment); + glGetIntegerv(GL_PACK_ROW_LENGTH, &prevRowLength); + + glBindFramebuffer(GL_READ_FRAMEBUFFER, 0); + glGetIntegerv(GL_READ_BUFFER, &prevReadBuffer); + glReadBuffer(GL_BACK); + glPixelStorei(GL_PACK_ALIGNMENT, 4); + glPixelStorei(GL_PACK_ROW_LENGTH, 0); + + if (pbos[0] == 0) + fixed (uint* p = pbos) + glGenBuffers(pbos.Length, p); + + int cur = (int)(frameIndex % 2); + int prev = (int)((frameIndex + 1) % 2); + + glBindBuffer(GL_PIXEL_PACK_BUFFER, pbos[cur]); + if (pboSizes[cur] != (surfaceWidth, surfaceHeight)) { + glBufferData(GL_PIXEL_PACK_BUFFER, (nint)surfaceWidth * surfaceHeight * 4, null, GL_STREAM_READ); + pboSizes[cur] = (surfaceWidth, surfaceHeight); + } + glReadPixels(0, 0, surfaceWidth, surfaceHeight, GL_RGBA, GL_UNSIGNED_BYTE, null); + + if (fences[cur] != 0) + glDeleteSync(fences[cur]); + fences[cur] = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); + glFlush(); + + (int w, int h) = pboSizes[prev]; + if (fences[prev] != 0 && w > 0 && h > 0) { + glClientWaitSync(fences[prev], 0, GL_TIMEOUT_IGNORED); + glDeleteSync(fences[prev]); + fences[prev] = 0; + + glBindBuffer(GL_PIXEL_PACK_BUFFER, pbos[prev]); + void* data = glMapBufferRange(GL_PIXEL_PACK_BUFFER, 0, (nint)w * h * 4, GL_MAP_READ_BIT); + if (data != null) { + UploadFrame(data, w, h); + glUnmapBuffer(GL_PIXEL_PACK_BUFFER); + } + } + + glBindBuffer(GL_PIXEL_PACK_BUFFER, (uint)prevPackBuffer); + glReadBuffer(prevReadBuffer); + glPixelStorei(GL_PACK_ALIGNMENT, prevAlignment); + glPixelStorei(GL_PACK_ROW_LENGTH, prevRowLength); + glBindFramebuffer(GL_READ_FRAMEBUFFER, (uint)prevReadFramebuffer); + + if (texture != null) { + SDL3.SDL_RenderTextureRotated(renderer, texture, null, null, 0, null, SDL_FlipMode.SDL_FLIP_VERTICAL); + SDL3.SDL_RenderPresent(renderer); + } + + frameIndex++; + + (int tw, int th) = targetSize(); + if (tw > 0 && th > 0 && (tw != surfaceWidth || th != surfaceHeight)) + CreateSurface(tw, th); + } + + void UploadFrame(void* data, int width, int height) { + + if (texture == null || textureWidth != width || textureHeight != height) { + if (texture != null) + SDL3.SDL_DestroyTexture(texture); + texture = SDL3.SDL_CreateTexture(renderer, SDL_PixelFormat.SDL_PIXELFORMAT_XBGR8888, SDL_TextureAccess.SDL_TEXTUREACCESS_STREAMING, width, height); + if (texture == null) + return; + SDL3.SDL_SetTextureBlendMode(texture, SDL3.SDL_BLENDMODE_NONE); + textureWidth = width; + textureHeight = height; + } + + nint pixels; + int pitch; + if (!SDL3.SDL_LockTexture(texture, null, &pixels, &pitch)) + return; + + int rowBytes = width * 4; + if (pitch == rowBytes) + Buffer.MemoryCopy(data, (void*)pixels, (long)rowBytes * height, (long)rowBytes * height); + else + for (int y = 0; y < height; y++) + Buffer.MemoryCopy((byte*)data + (long)y * rowBytes, (byte*)pixels + (long)y * pitch, pitch, rowBytes); + + SDL3.SDL_UnlockTexture(texture); + } +} diff --git a/Source.SDLManager/SDL3_Window.cs b/Source.SDLManager/SDL3_Window.cs index b2d3be4b1..3b03f0d48 100644 --- a/Source.SDLManager/SDL3_Window.cs +++ b/Source.SDLManager/SDL3_Window.cs @@ -43,6 +43,8 @@ public unsafe class SDL3_Window : IWindow public float MouseXScale = 1.0f; public float MouseYScale = 1.0f; + public int RenderWidth; + public int RenderHeight; public int GetEvents(WindowEvent[] buffer, int maxEvents) { if (maxEvents == 0) return 0; @@ -118,6 +120,14 @@ public bool Visible { public void PumpMessages() { SDL_Event ev; int eventsProcessed = 0; + + if (RenderWidth > 0 && RenderHeight > 0) { + int w, h; + if (SDL3.SDL_GetWindowSize(window, &w, &h) && w > 0 && h > 0) { + MouseXScale = (float)RenderWidth / w; + MouseYScale = (float)RenderHeight / h; + } + } while (SDL3.SDL_PollEvent(&ev) && eventsProcessed < 100) { eventsProcessed += 1; diff --git a/Source.SDLSystem/SDL3_System.OSX.cs b/Source.SDLSystem/SDL3_System.OSX.cs index 284de7ff3..782cba571 100644 --- a/Source.SDLSystem/SDL3_System.OSX.cs +++ b/Source.SDLSystem/SDL3_System.OSX.cs @@ -1,8 +1,55 @@ +using System.Runtime.InteropServices; + namespace Source.SDLManager; public unsafe partial class SDL3_System { + const string CoreFoundation = "/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation"; + const string CoreText = "/System/Library/Frameworks/CoreText.framework/CoreText"; + const uint kCTFontItalicTrait = 1 << 0; + const uint kCTFontBoldTrait = 1 << 1; + + [DllImport(CoreFoundation)] static extern nint CFStringCreateWithCharacters(nint alloc, char* chars, nint numChars); + [DllImport(CoreFoundation)] static extern void CFRelease(nint cf); + [DllImport(CoreFoundation)] static extern byte CFURLGetFileSystemRepresentation(nint url, byte resolveAgainstBase, byte* buffer, nint maxBufLen); + [DllImport(CoreText)] static extern nint CTFontCreateWithName(nint name, double size, nint matrix); + [DllImport(CoreText)] static extern nint CTFontCreateCopyWithSymbolicTraits(nint font, double size, nint matrix, uint symTraitValue, uint symTraitMask); + [DllImport(CoreText)] static extern nint CTFontCopyAttribute(nint font, nint attribute); + + static nint kCTFontURLAttribute; + public ReadOnlySpan GetSystemFontPath(ReadOnlySpan fontName, int weight = 0, bool italic = false) { - return null; + if (kCTFontURLAttribute == 0) + kCTFontURLAttribute = *(nint*)NativeLibrary.GetExport(NativeLibrary.Load(CoreText), "kCTFontURLAttribute"); + + nint name; + fixed (char* chars = fontName) + name = CFStringCreateWithCharacters(0, chars, fontName.Length); + if (name == 0) + return null; + + nint font = CTFontCreateWithName(name, 12, 0); + CFRelease(name); + if (font == 0) + return null; + + uint traits = (weight >= 600 ? kCTFontBoldTrait : 0) | (italic ? kCTFontItalicTrait : 0); + if (traits != 0) { + nint styled = CTFontCreateCopyWithSymbolicTraits(font, 0, 0, traits, traits); + if (styled != 0) { + CFRelease(font); + font = styled; + } + } + + nint url = CTFontCopyAttribute(font, kCTFontURLAttribute); + CFRelease(font); + if (url == 0) + return null; + + byte* path = stackalloc byte[1024]; + bool ok = CFURLGetFileSystemRepresentation(url, 1, path, 1024) != 0; + CFRelease(url); + return ok ? Marshal.PtrToStringUTF8((nint)path) : null; } } diff --git a/Source.ShaderAPI.Gl46/HardwareConfig.cs b/Source.ShaderAPI.Gl46/HardwareConfig.cs index d0599b525..fb812e247 100644 --- a/Source.ShaderAPI.Gl46/HardwareConfig.cs +++ b/Source.ShaderAPI.Gl46/HardwareConfig.cs @@ -14,9 +14,7 @@ public bool ActuallySupportsPixelShaders_2_b() { throw new NotImplementedException(); } - public bool CanDoSRGBReadFromRTs() { - throw new NotImplementedException(); - } + public bool CanDoSRGBReadFromRTs() => true; public bool FakeSRGBWrite() { throw new NotImplementedException();