This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit b578433e37
8 changed files with 784842 additions and 0 deletions

View file

@ -0,0 +1,108 @@
namespace Brutal.SdlApi;
public delegate bool SdlEventWatch(ref SdlEvent ev);
public static unsafe partial class Sdl
{
public static unsafe partial class Events
{
// Registered event watches, keyed by the managed delegate the caller passed. The GCHandle
// roots the delegate for as long as SDL holds the native function pointer, and its IntPtr is
// the userdata SDL threads back to the trampoline so it can dispatch to the right delegate.
// SDL_RemoveEventWatch matches on (function pointer, userdata), so the same handle value must
// be handed back on removal, hence the map. Guarded by a lock because SDL permits adding and
// removing watches from any thread.
private static readonly Dictionary<SdlEventWatch, GCHandle> Watches = new();
private static readonly Lock WatchLock = new();
public static bool PollEvent(out SdlEvent ev)
{
ev = default;
bool dequeued;
fixed (SdlEvent* p = &ev)
dequeued = PInvoke.PollEvent(p) != 0;
Sdl.ExceptionAggregator.CheckExceptions();
return dequeued;
}
public static void AddEventWatch(SdlEventWatch callback)
{
ArgumentNullException.ThrowIfNull(callback);
lock (WatchLock)
{
if (Watches.ContainsKey(callback))
return;
var handle = GCHandle.Alloc(callback);
if (PInvoke.AddEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle)) == 0)
{
handle.Free();
throw SdlException.FromError("SDL_AddEventWatch failed");
}
Watches[callback] = handle;
}
}
public static void RemoveEventWatch(SdlEventWatch callback)
{
ArgumentNullException.ThrowIfNull(callback);
lock (WatchLock)
{
if (!Watches.Remove(callback, out var handle))
return;
PInvoke.RemoveEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle));
handle.Free();
}
}
// Called from Sdl.Init.Quit so the managed map does not outlive SDL's own watch list.
internal static void ClearWatches()
{
lock (WatchLock)
{
foreach (var (_, handle) in Watches)
{
// Remove the native registration first (still valid pre-SDL_Quit), then release
// the managed root. Both are matched on (function pointer, userdata).
PInvoke.RemoveEventWatch(&EventWatchTrampoline, (void*)GCHandle.ToIntPtr(handle));
handle.Free();
}
Watches.Clear();
}
}
// The single native entry point for every registered watch. SDL passes the GCHandle IntPtr
// back as userdata; we resolve it to the managed delegate and invoke it inside a try/catch so
// no exception ever escapes into native code. Failures are parked in the aggregator and
// rethrown from the next PollEvent.
[UnmanagedCallersOnly(CallConvs = new[] { typeof(CallConvCdecl) })]
private static byte EventWatchTrampoline(void* userdata, SdlEvent* ev)
{
try
{
var handle = GCHandle.FromIntPtr((nint)userdata);
if (handle.Target is SdlEventWatch filter)
return filter(ref *ev) ? (byte)1 : (byte)0;
Sdl.ExceptionAggregator.Push(
"An SDL event watch fired with a dead or foreign GCHandle (its target was not an "
+ "SdlEventWatch); the callback was skipped."
);
}
catch (Exception ex)
{
Sdl.ExceptionAggregator.Push("An exception occurred in an SDL event watch callback.", ex);
}
// Event watches ignore the return value; permit by default.
return 1;
}
}
}

View file

@ -0,0 +1,35 @@
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static unsafe partial class Gamepad
{
public static bool GetGamepadTouchpadFinger(
SdlGamepad gamepad,
int touchpad,
int finger,
out bool down,
out float x,
out float y,
out float pressure
)
{
// SDL leaves the out-pointers untouched on failure, so pre-zero them.
byte downByte = 0;
bool result;
x = default;
y = default;
pressure = default;
fixed (float* xPtr = &x)
fixed (float* yPtr = &y)
fixed (float* pressurePtr = &pressure)
{
result =
PInvoke.GetGamepadTouchpadFinger(gamepad, touchpad, finger, &downByte, xPtr, yPtr, pressurePtr)
!= 0;
}
down = downByte != 0;
return result;
}
}
}

View file

@ -0,0 +1,21 @@
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static unsafe partial class Init
{
public static void Initialize(SdlInitFlags flags)
{
// SDL_Init returns SDL bool (false = failure), rendered as a byte by the raw layer.
if (PInvoke.Init(flags) == 0)
throw SdlException.FromError("SDL_Init failed");
}
public static void Quit()
{
Events.ClearWatches();
Sdl.ExceptionAggregator.Clear();
PInvoke.Quit();
}
}
}

View file

@ -0,0 +1,43 @@
using System.Text;
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static unsafe partial class Keyboard
{
// SDL keeps the name pointer without copying it, so each name lives in unmanaged memory until replaced.
private static readonly Dictionary<SdlScancode, nint> ScancodeNames = new();
private static readonly Lock ScancodeNameLock = new();
[LibraryImport(Dll, EntryPoint = "SDL_SetScancodeName")]
private static partial byte _SetScancodeName(SdlScancode scancode, byte* name);
public static void SetScancodeName(SdlScancode scancode, string name)
{
ArgumentNullException.ThrowIfNull(name);
// Copy `name` into unmanaged memory we own: a NUL-terminated UTF-8 buffer.
var byteCount = Encoding.UTF8.GetByteCount(name);
var buffer = (byte*)NativeMemory.Alloc((nuint)(byteCount + 1));
var span = new Span<byte>(buffer, byteCount + 1);
Encoding.UTF8.GetBytes(name, span);
span[byteCount] = 0;
lock (ScancodeNameLock)
{
if (_SetScancodeName(scancode, buffer) == 0)
{
// SDL did not take the pointer; free our copy and surface the error.
NativeMemory.Free(buffer);
throw SdlException.FromError("SDL_SetScancodeName failed");
}
// SDL no longer references the previous copy for this scancode.
if (ScancodeNames.TryGetValue(scancode, out var previous))
NativeMemory.Free((void*)previous);
ScancodeNames[scancode] = (nint)buffer;
}
}
}
}

View file

@ -0,0 +1,39 @@
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static class Log
{
public static void Message(SdlLogCategory category, SdlLogPriority priority, string message)
{
ArgumentNullException.ThrowIfNull(message);
PInvoke.LogMessage((int)category, priority, Escape(message));
}
public static void Message(string message) => Message(SdlLogCategory.Application, SdlLogPriority.Info, message);
public static void Trace(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Trace, message);
public static void Verbose(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Verbose, message);
public static void Debug(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Debug, message);
public static void Info(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Info, message);
public static void Warn(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Warn, message);
public static void Error(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Error, message);
public static void Critical(SdlLogCategory category, string message) =>
Message(category, SdlLogPriority.Critical, message);
// Escapes printf conversion specifiers so the caller's text is logged verbatim.
private static string Escape(string message) => message.Contains('%') ? message.Replace("%", "%%") : message;
}
}

View file

@ -0,0 +1,72 @@
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static unsafe partial class PInvoke
{
// Hand-bound: SDL_vulkan.h is outside the generator's input. Vulkan handles are passed as nint.
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_GetInstanceExtensions")]
private static partial byte** _Vulkan_GetInstanceExtensions(uint* count);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte** Vulkan_GetInstanceExtensions(uint* count)
{
Sdl.TraceLog.Trace();
return _Vulkan_GetInstanceExtensions(count);
}
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_CreateSurface")]
private static partial byte _Vulkan_CreateSurface(
SdlWindow window,
nint instance,
nint allocator,
nint* surface
);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static byte Vulkan_CreateSurface(SdlWindow window, nint instance, nint allocator, nint* surface)
{
Sdl.TraceLog.Trace();
return _Vulkan_CreateSurface(window, instance, allocator, surface);
}
[LibraryImport(Dll, EntryPoint = "SDL_Vulkan_DestroySurface")]
private static partial void _Vulkan_DestroySurface(nint instance, nint surface, nint allocator);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void Vulkan_DestroySurface(nint instance, nint surface, nint allocator)
{
Sdl.TraceLog.Trace();
_Vulkan_DestroySurface(instance, surface, allocator);
}
}
public static unsafe class Vulkan
{
public static string[] GetInstanceExtensions()
{
uint count;
var ptr = PInvoke.Vulkan_GetInstanceExtensions(&count);
if (ptr is null)
throw SdlException.FromError("SDL_Vulkan_GetInstanceExtensions failed");
// Owned by SDL - must not be freed here (see SDL_vulkan.h's doc comment).
var result = new string[count];
for (var i = 0; i < count; i++)
result[i] = Marshal.PtrToStringUTF8((nint)ptr[i])!;
return result;
}
public static nint CreateSurface(SdlWindow window, nint instance)
{
nint surface;
if (PInvoke.Vulkan_CreateSurface(window, instance, 0, &surface) == 0)
throw SdlException.FromError("SDL_Vulkan_CreateSurface failed");
return surface;
}
public static void DestroySurface(nint instance, nint surface) =>
PInvoke.Vulkan_DestroySurface(instance, surface, 0);
}
}

View file

@ -0,0 +1,92 @@
using System.Reflection;
namespace Brutal.SdlApi;
public static unsafe partial class Sdl
{
public static unsafe partial class PInvoke
{
// The native SDL3 handle, resolved lazily by the DllImportResolver below and cached so the
// library is loaded at most once regardless of how many entry points are resolved.
private static nint _nativeHandle;
// Serializes resolution. The .NET resolver can be invoked concurrently from multiple threads
// resolving different entry points; without this two threads could both observe a zero handle
// and race to load, leaking one of the two library handles.
private static readonly Lock ResolveLock = new();
// Registered here so the resolver is installed before any P/Invoke in this assembly resolves.
static PInvoke()
{
NativeLibrary.SetDllImportResolver(typeof(Sdl).Assembly, Resolve);
}
// Normalizes the "SDL3" import name to the platform-specific shared library filename
// (SDL3.dll on Windows, libSDL3.dylib on macOS, libSDL3.so.0 on Linux). SDL's Linux build
// installs a versioned soname (libSDL3.so.0) that the default probing conventions do not
// try, so the candidate list is spelled out explicitly, most-specific first, with the
// default convention name as a fallback.
private static nint Resolve(string libraryName, Assembly assembly, DllImportSearchPath? searchPath)
{
// Only ever asked to resolve SDL3; anything else is left to the default resolver.
if (libraryName != Dll)
return IntPtr.Zero;
lock (ResolveLock)
{
if (_nativeHandle != IntPtr.Zero)
return _nativeHandle;
var search = searchPath ?? DllImportSearchPath.AssemblyDirectory;
// Load (not TryLoad) so each candidate's OS error text reaches the final exception.
var failures = new List<string>();
foreach (var candidate in Candidates())
{
try
{
_nativeHandle = NativeLibrary.Load(candidate, assembly, search);
return _nativeHandle;
}
catch (Exception ex)
{
failures.Add($"'{candidate}': {ex.Message}");
}
}
throw new DllNotFoundException(
"Could not load the SDL3 native library. Attempts (most specific first): "
+ string.Join("; ", failures)
+ "."
);
}
}
private static string[] Candidates()
{
if (OperatingSystem.IsWindows())
return ["SDL3.dll", "SDL3"];
if (OperatingSystem.IsMacOS())
return ["libSDL3.dylib", "SDL3"];
// Linux and other Unix-likes.
return ["libSDL3.so.0", "libSDL3.so", "SDL3"];
}
// SDL_LogMessage is variadic; it is bound fixed-arity and never passed variadic arguments.
[LibraryImport(
Dll,
EntryPoint = "SDL_LogMessage",
StringMarshalling = StringMarshalling.Custom,
StringMarshallingCustomType = typeof(CustomStringMarshaller)
)]
private static partial void _LogMessage(int category, SdlLogPriority priority, string fmt);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void LogMessage(int category, SdlLogPriority priority, string preformatted)
{
ArgumentNullException.ThrowIfNull(preformatted);
Sdl.TraceLog.Trace();
_LogMessage(category, priority, preformatted);
}
}
}

View file

@ -0,0 +1,41 @@
namespace Brutal.SdlApi;
[StructLayout(LayoutKind.Explicit, Size = 32)]
public struct SdlGamepadBinding
{
[FieldOffset(0)]
public SdlGamepadBindingType InputType;
[FieldOffset(4)]
public int InputButton;
[FieldOffset(4)]
public int InputAxis;
[FieldOffset(8)]
public int InputAxisMin;
[FieldOffset(12)]
public int InputAxisMax;
[FieldOffset(4)]
public int InputHat;
[FieldOffset(8)]
public int InputHatMask;
[FieldOffset(16)]
public SdlGamepadBindingType OutputType;
[FieldOffset(20)]
public SdlGamepadButton OutputButton;
[FieldOffset(20)]
public SdlGamepadAxis OutputAxis;
[FieldOffset(24)]
public int OutputAxisMin;
[FieldOffset(28)]
public int OutputAxisMax;
}