5 Commits

Author SHA1 Message Date
NepuShiro f932a7704b b 2026-05-21 23:33:23 -05:00
NepuShiro 85781f4510 a 2026-05-21 08:18:52 -05:00
NepuShiro 935edf0db8 Add easy textures 2026-05-21 05:01:06 -05:00
NepuShiro 5c17e233bc a 2026-05-20 11:29:55 -05:00
NepuShiro 7d5f242a43 opengl4 2026-05-20 04:23:47 -05:00
7 changed files with 925 additions and 503 deletions
+217 -113
View File
@@ -1,7 +1,9 @@
using System.Numerics; using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices; using System.Runtime.CompilerServices;
using Hexa.NET.ImGui; using Hexa.NET.ImGui;
using Hexa.NET.ImPlot; using Hexa.NET.ImPlot;
using HexaGen.Runtime;
using SDL3_TestingSuite.SDL3; using SDL3_TestingSuite.SDL3;
namespace SDL3_TestingSuite; namespace SDL3_TestingSuite;
@@ -12,169 +14,243 @@ public class Program
private static bool _imPlotDemoVisible; private static bool _imPlotDemoVisible;
private static bool _fontStuff; private static bool _fontStuff;
private static readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>(); private static readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>();
private static bool _initialized; private static bool _fontStuffInitialized;
private static bool _init;
private static ImFontPtr _font; private static ImFontPtr _font;
private static float size = 1f; private static float size = 1f;
private static SDL3Window _window = null!;
private static OpenGLTexture? _imageTexture;
private static string? _imageLoadError;
public static void Main() public static void Main()
{ {
SDL3Window window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720); string baseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
window.RenderCallback += () => string osPlatform = typeof(LibraryLoader).GetMethod("GetOSPlatform", BindingFlags.Static | BindingFlags.NonPublic)?.Invoke(null, null) as string ?? ""; // LibraryLoader.GetOSPlatform();
string architecture = typeof(LibraryLoader).GetMethod("GetArchitecture", BindingFlags.Static | BindingFlags.NonPublic)?.Invoke(null, null) as string ?? ""; // LibraryLoader.GetArchitecture());
LibraryLoader.CustomLoadFolders.AddRange(new string[]
{ {
Path.Combine(baseDirectory),
Path.Combine(baseDirectory, "runtimes", osPlatform, "native"),
Path.Combine(baseDirectory, "runtimes", $"{osPlatform}-{architecture}", "debug"), // allows debug builds sideload.
Path.Combine(baseDirectory, "runtimes", $"{osPlatform}-{architecture}", "native"),
});
_window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720);
_window.Disposing += DisposeImages;
_window.RenderCallback += () =>
{
if (!_init)
{
_init = true;
LoadImageTexture("");
}
ImGuiViewportPtr viewport = ImGui.GetMainViewport(); ImGuiViewportPtr viewport = ImGui.GetMainViewport();
ImGui.SetNextWindowPos(viewport.WorkPos); ImGui.SetNextWindowPos(viewport.WorkPos);
ImGui.SetNextWindowSize(viewport.WorkSize); ImGui.SetNextWindowSize(viewport.WorkSize);
ImGui.SetNextWindowViewport(viewport.ID); ImGui.SetNextWindowViewport(viewport.ID);
if (ImGui.Begin("MainWindow", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBringToFrontOnFocus)) ImGui.Begin("MainWindow", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBringToFrontOnFocus);
if (ImGui.BeginMenuBar())
{ {
if (ImGui.BeginMenuBar()) if (ImGui.BeginMenu("Stuff"))
{ {
if (ImGui.BeginMenu("Stuff")) if (ImGui.MenuItem("Quit"))
{ {
if (ImGui.MenuItem("Quit")) _window.ShouldClose = true;
{
window.ShouldClose = true;
}
ImGui.EndMenu();
} }
ImGui.Spacing();
ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible);
ImGui.Spacing();
ImGui.MenuItem("ImPlot Demo Window", "", ref _imPlotDemoVisible);
ImGui.Spacing();
ImGui.MenuItem("Font Stuff", "", ref _fontStuff);
ImGui.EndMenuBar(); ImGui.EndMenu();
} }
ImGui.Spacing();
ImGui.MenuItem("Demo Window", "", ref _demoWindowVisible);
ImGui.Spacing();
ImGui.MenuItem("ImPlot Demo Window", "", ref _imPlotDemoVisible);
ImGui.Spacing();
ImGui.MenuItem("Font Stuff", "", ref _fontStuff);
ImGui.End(); ImGui.EndMenuBar();
} }
string hash = "AAAA";
bool hasValue = true;
string text2 = "";
if (ImGui.InputTextWithHint($"##{hash}", hasValue ? "" : "Null", ref text2, 99999, ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.CtrlEnterForNewLine))
{
}
float buttonSize = ImGui.GetFrameHeight();
float avail = ImGui.GetContentRegionAvail().X;
float inputWidth = avail - buttonSize;
ImGui.PushItemWidth(inputWidth);
ImGui.SameLine(0f, 0f);
if (ImGui.Button($"X##{hash}_clear", new Vector2(buttonSize, buttonSize)))
{
}
ImGui.PopItemWidth();
ImGui.End();
if (_fontStuff) if (_fontStuff)
{ {
ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver); ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver);
if (ImGui.Begin("FontStuff", ref _fontStuff)) ImGui.Begin("FontStuff", ref _fontStuff);
ImGui.ShowFontSelector("Font");
bool change = false;
if (ImGui.GetFont() != _font)
{ {
ImGui.ShowFontSelector("Font"); _font = ImGui.GetFont();
change = true;
}
bool change = false; string fontName = _font.GetDebugNameS();
if (ImGui.GetFont() != _font) fontName = string.IsNullOrEmpty(fontName) ? _font.FontId.ToString() : fontName;
if (!_fontStuffInitialized || change)
{
if (!GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs))
{ {
_font = ImGui.GetFont(); glyphs = new List<uint>();
change = true;
}
string fontName = _font.GetDebugNameS(); ImFontPtr font = _font;
fontName = string.IsNullOrEmpty(fontName) ? _font.FontId.ToString() : fontName;
if (!_initialized || change) for (uint codepoint = 0; codepoint <= 0x10FFFF; codepoint++)
{
if (!GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs))
{ {
glyphs = new List<uint>(); if (codepoint >= 0xD800 && codepoint <= 0xDFFF)
ImFontPtr font = _font;
for (uint codepoint = 0; codepoint <= 0x10FFFF; codepoint++)
{ {
if (codepoint >= 0xD800 && codepoint <= 0xDFFF) continue;
{
continue;
}
if (!font.IsGlyphInFont(codepoint)) continue;
glyphs.Add(codepoint);
} }
GlyphsByName[fontName] = glyphs; if (!font.IsGlyphInFont(codepoint)) continue;
Logger.Log($"Initialized font {fontName} with {glyphs.Count} glyphs");
glyphs.Add(codepoint);
} }
_initialized = true; GlyphsByName[fontName] = glyphs;
Logger.Log($"Initialized font {fontName} with {glyphs.Count} glyphs");
} }
ImGui.PushFont(null, 24); _fontStuffInitialized = true;
if (GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs2))
{
float cursorXStart = ImGui.GetCursorPosX();
float maxWidth = ImGui.GetContentRegionAvail().X;
foreach (uint codepoint in glyphs2!)
{
string text = char.ConvertFromUtf32((int)codepoint);
float glyphWidth = ImGui.CalcTextSize(text).X;
float cursorX = ImGui.GetCursorPosX();
if (cursorX > cursorXStart && (cursorX + glyphWidth) > (cursorXStart + maxWidth))
{
ImGui.NewLine();
}
ImGui.TextUnformatted(text);
ImGui.SameLine();
}
}
ImGui.PopFont();
ImGui.End();
} }
}
if (ImGui.Begin("Thing")) ImGui.PushFont(null, 24);
{
float time = (float)ImGui.GetTime() * 5; if (GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs2))
if (ImPlot.BeginPlot("Moving Rainbow Sine Wave"))
{ {
int count = 200; float cursorXStart = ImGui.GetCursorPosX();
float maxWidth = ImGui.GetContentRegionAvail().X;
float[] xs = new float[2]; foreach (uint codepoint in glyphs2!)
float[] ys = new float[2];
for (int i = 0; i < count - 1; i++)
{ {
float x0 = i * 0.1f; string text = char.ConvertFromUtf32((int)codepoint);
float x1 = (i + 1) * 0.1f; float glyphWidth = ImGui.CalcTextSize(text).X;
float y0 = MathF.Sin(x0 * size + time); float cursorX = ImGui.GetCursorPosX();
float y1 = MathF.Sin(x1 * size + time); if (cursorX > cursorXStart && (cursorX + glyphWidth) > (cursorXStart + maxWidth))
{
ImGui.NewLine();
}
xs[0] = x0; ImGui.TextUnformatted(text);
xs[1] = x1;
ys[0] = y0;
ys[1] = y1;
float t = i / (float)count;
float r = 0.5f + 1f * MathF.Sin(6.2831f * (t));
float g = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.33f));
float b = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.66f));
ImPlot.PushStyleColor(ImPlotCol.Line, new Vector4(r, g, b, 1f));
ImPlot.PlotLine("##seg", ref xs[0], ref ys[0], 2);
ImPlot.PopStyleColor();
ImGui.SameLine();
} }
ImPlot.EndPlot();
} }
ImGui.SliderFloat("Sine", ref size, 1f, 120f);
ImGui.PopFont();
ImGui.End(); ImGui.End();
} }
if (ImGui.Begin("ImageThing")) ImGui.Begin("Thing");
float time = (float)ImGui.GetTime() * 5;
if (ImPlot.BeginPlot("Moving Rainbow Sine Wave"))
{ {
int count = 200;
ImGui.End(); float[] xs = new float[2];
float[] ys = new float[2];
for (int i = 0; i < count - 1; i++)
{
float x0 = i * 0.1f;
float x1 = (i + 1) * 0.1f;
float y0 = MathF.Sin(x0 * size + time);
float y1 = MathF.Sin(x1 * size + time);
xs[0] = x0;
xs[1] = x1;
ys[0] = y0;
ys[1] = y1;
float t = i / (float)count;
float r = 0.5f + 1f * MathF.Sin(6.2831f * (t));
float g = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.33f));
float b = 0.5f + 1f * MathF.Sin(6.2831f * (t + 0.66f));
ImPlot.PushStyleColor(ImPlotCol.Line, new Vector4(r, g, b, 1f));
ImPlot.PlotLine("##seg", ref xs[0], ref ys[0], 2);
ImPlot.PopStyleColor();
}
ImPlot.EndPlot();
} }
ImGui.SliderFloat("Sine", ref size, 1f, 120f);
ImGui.End();
bool regen1 = true;
if (_imageTexture != null)
{
Vector2 displaySize = ImGui.GetIO().DisplaySize;
Vector2 imageSize = new Vector2(_imageTexture.Width, _imageTexture.Height);
float maxWidth = displaySize.X * 0.5f;
float maxHeight = displaySize.Y * 0.5f;
float scale = MathF.Min(maxWidth / imageSize.X, maxHeight / imageSize.Y);
Vector2 scaledSize = imageSize * MathF.Min(scale, 1.0f);
Vector2 padding = ImGui.GetStyle().WindowPadding;
Vector2 windowSize = new Vector2(scaledSize.X + padding.X * 2, scaledSize.Y + padding.Y * 2 + (ImGui.GetFrameHeight() * 4));
ImGui.SetNextWindowSize(windowSize, ImGuiCond.Always);
ImGui.Begin(_imageTexture.FileName ?? "Image", ref regen1, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoSavedSettings);
regen1 = !ImGui.Button("Regen");
ImGui.Image(_imageTexture.ImGuiTexture, scaledSize);
string text1 = $"{_imageTexture.Width}x{_imageTexture.Height}";
ImGui.TextUnformatted(text1);
ImGui.SameLine(ImGui.CalcTextSize(text1).X + padding.X * 2);
ImGui.TextUnformatted($"EXT: {(_imageTexture.Extension ?? "Unknown Format")}");
ImGui.TextUnformatted($"{(_imageTexture.FilePath ?? "Unknown Path")}");
}
else
{
ImGui.Begin("Image", ref regen1, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoScrollbar | ImGuiWindowFlags.NoSavedSettings);
ImGui.TextUnformatted(_imageLoadError ?? "No image loaded.");
}
ImGui.End();
bool regen = !regen1;
if (regen)
{
DisposeImages();
LoadImageTexture("");
}
if (_demoWindowVisible) if (_demoWindowVisible)
{ {
ImGui.ShowDemoWindow(ref _demoWindowVisible); ImGui.ShowDemoWindow(ref _demoWindowVisible);
@@ -185,7 +261,30 @@ public class Program
} }
}; };
window.Run(); _window.Run();
}
private static void LoadImageTexture(string path)
{
if (string.IsNullOrEmpty(path)) return;
try
{
_imageTexture = OpenGLTexture.FromFile(_window.GL, path);
_imageLoadError = null;
}
catch (Exception e)
{
DisposeImages();
_imageLoadError = e.Message;
Logger.Log(e);
}
}
private static void DisposeImages()
{
_imageTexture?.Dispose();
_imageTexture = null;
} }
public static class Logger public static class Logger
@@ -195,7 +294,12 @@ public class Program
public static void Log(object? value, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0) public static void Log(object? value, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
{ {
Write(value?.ToString(), path, caller, line); if (value == null)
{
Write("null", path, caller, line);
return;
}
Write(value.ToString(), path, caller, line);
} }
public static void Log(object?[] values, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0) public static void Log(object?[] values, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
+5 -1
View File
@@ -14,11 +14,15 @@
<!--<PackageReference Include="ImGui.NET" Version="*" />--> <!--<PackageReference Include="ImGui.NET" Version="*" />-->
<PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" /> <PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" />
<PackageReference Include="Hexa.NET.ImGui.Widgets" Version="1.2.18" /> <PackageReference Include="Hexa.NET.ImGui.Widgets" Version="1.2.18" />
<PackageReference Include="Hexa.NET.ImNodes" Version="2.2.9" />
<PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" /> <PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" />
<PackageReference Include="Hexa.NET.OpenGL3" Version="1.1.0" /> <PackageReference Include="Hexa.NET.ImPlot3D" Version="2.2.9" />
<PackageReference Include="Hexa.NET.OpenGL4" Version="1.1.0" />
<PackageReference Include="Hexa.NET.SDL3.Image" Version="1.0.0" />
<PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" /> <PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" />
<PackageReference Include="SDL3-CS" Version="3.2.18" /> <PackageReference Include="SDL3-CS" Version="3.2.18" />
<PackageReference Include="SDL3-CS.Native" Version="3.2.18" /> <PackageReference Include="SDL3-CS.Native" Version="3.2.18" />
<PackageReference Include="SDL3-CS.Native.Image" Version="3.3.0" />
</ItemGroup> </ItemGroup>
</Project> </Project>
+20 -4
View File
@@ -21,7 +21,7 @@ public static class FontFind
{ {
extension(ImGuiIOPtr io) extension(ImGuiIOPtr io)
{ {
public unsafe ImFontPtr AddFont(string fontPath) public unsafe ImFontPtr AddFont(string fontPath, bool merge = false)
{ {
try try
{ {
@@ -29,13 +29,14 @@ public static class FontFind
FileInfo info = new FileInfo(fontPath); FileInfo info = new FileInfo(fontPath);
if (!info.Exists || info.Length <= 0) return null; if (!info.Exists || info.Length <= 0) return null;
FontMetrics metrics = ReadFontMetrics(fontPath); FontMetrics metrics = ReadFontMetricsSafe(fontPath);
float size = GetRecommendedPixelSize(metrics); float size = GetRecommendedPixelSize(metrics);
ImFontConfigPtr config = ImGui.ImFontConfig(); ImFontConfigPtr config = ImGui.ImFontConfig();
config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor; config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor | (uint)ImGuiFreeTypeLoaderFlags.Bitmap;
config.MergeMode = merge;
ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config); ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config);
Program.Logger.Log("Added font: " + Path.GetFileName(fontPath)); Program.Logger.Log($"{(merge ? "Merged" : "Added")} font: " + Path.GetFileName(fontPath));
return font; return font;
} }
catch (Exception e) catch (Exception e)
@@ -71,6 +72,21 @@ public static class FontFind
return flag; return flag;
} }
} }
public static FontMetrics ReadFontMetricsSafe(string fontPath)
{
try
{
return ReadFontMetrics(fontPath);
}
catch (Exception ex)
{
Console.WriteLine("Font parsing failed: " + fontPath);
Console.WriteLine(ex.ToString());
return new FontMetrics();
}
}
public static FontMetrics ReadFontMetrics(string fontPath) public static FontMetrics ReadFontMetrics(string fontPath)
{ {
+392 -350
View File
File diff suppressed because it is too large Load Diff
+20 -12
View File
@@ -10,6 +10,8 @@ public unsafe static class ImGuiSDL3Renderer
{ {
public class RendererData public class RendererData
{ {
public GL Gl = null!;
public uint GlVersion; // e.g. 320 for GL 3.2 public uint GlVersion; // e.g. 320 for GL 3.2
public string GlslVersionString = ""; // e.g. "#version 330 core\n" public string GlslVersionString = ""; // e.g. "#version 330 core\n"
public bool GlProfileIsES2; public bool GlProfileIsES2;
@@ -35,12 +37,10 @@ public unsafe static class ImGuiSDL3Renderer
public bool UseTexParameterToSetSampler; public bool UseTexParameterToSetSampler;
public int NextSampler; // GL_LINEAR or GL_NEAREST public int NextSampler; // GL_LINEAR or GL_NEAREST
public GL Gl = null!;
} }
public static RendererData? GetRendererData() => ImGui.GetCurrentContext().Handle != null ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData) : null; public static RendererData? GetRendererData() => ImGui.GetCurrentContext().Handle != null ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData) : null;
public static bool Init(GL gl, string? glslVersion = null) public static bool Init(GL gl, string? glslVersion = null)
{ {
ImGuiIOPtr io = ImGui.GetIO(); ImGuiIOPtr io = ImGui.GetIO();
@@ -143,7 +143,6 @@ public unsafe static class ImGuiSDL3Renderer
io.BackendRendererName = null; io.BackendRendererName = null;
io.BackendRendererUserData = null; io.BackendRendererUserData = null;
io.BackendFlags &= ~(ImGuiBackendFlags.RendererHasVtxOffset | ImGuiBackendFlags.RendererHasTextures | ImGuiBackendFlags.RendererHasViewports); io.BackendFlags &= ~(ImGuiBackendFlags.RendererHasVtxOffset | ImGuiBackendFlags.RendererHasTextures | ImGuiBackendFlags.RendererHasViewports);
} }
public static void NewFrame() public static void NewFrame()
@@ -222,7 +221,6 @@ public unsafe static class ImGuiSDL3Renderer
int idxSize = drawList.IdxBuffer.Size * sizeof(ushort); int idxSize = drawList.IdxBuffer.Size * sizeof(ushort);
gl.BufferData(GLBufferTargetARB.ArrayBuffer, vtxSize, drawList.VtxBuffer.Data, GLBufferUsageARB.StreamDraw); gl.BufferData(GLBufferTargetARB.ArrayBuffer, vtxSize, drawList.VtxBuffer.Data, GLBufferUsageARB.StreamDraw);
gl.BufferData(GLBufferTargetARB.ElementArrayBuffer, idxSize, drawList.IdxBuffer.Data, GLBufferUsageARB.StreamDraw); gl.BufferData(GLBufferTargetARB.ElementArrayBuffer, idxSize, drawList.IdxBuffer.Data, GLBufferUsageARB.StreamDraw);
for (int cmdIdx = 0; cmdIdx < drawList.CmdBuffer.Size; cmdIdx++) for (int cmdIdx = 0; cmdIdx < drawList.CmdBuffer.Size; cmdIdx++)
@@ -234,11 +232,17 @@ public unsafe static class ImGuiSDL3Renderer
nint cbPtr = (nint)cmd.UserCallback; nint cbPtr = (nint)cmd.UserCallback;
if (cbPtr == (nint)DelegateStorage.DrawCallbackResetRenderStateDelegate.GetPtrForDelegate()) if (cbPtr == (nint)DelegateStorage.DrawCallbackResetRenderStateDelegate.GetPtrForDelegate())
{
SetupRenderState(drawData, fbWidth, fbHeight, vao); SetupRenderState(drawData, fbWidth, fbHeight, vao);
}
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerLinearDelegate.GetPtrForDelegate()) else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerLinearDelegate.GetPtrForDelegate())
{
ApplySamplerLinear(bd); ApplySamplerLinear(bd);
}
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerNearestDelegate.GetPtrForDelegate()) else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerNearestDelegate.GetPtrForDelegate())
{
ApplySamplerNearest(bd); ApplySamplerNearest(bd);
}
else else
{ {
ImDrawCmdPtr cmdPtr = new ImDrawCmdPtr { Handle = &cmd }; ImDrawCmdPtr cmdPtr = new ImDrawCmdPtr { Handle = &cmd };
@@ -352,7 +356,7 @@ public unsafe static class ImGuiSDL3Renderer
2.0f / (R - L), 0.0f, 0.0f, 0.0f, 2.0f / (R - L), 0.0f, 0.0f, 0.0f,
0.0f, 2.0f / (T - B), 0.0f, 0.0f, 0.0f, 2.0f / (T - B), 0.0f, 0.0f,
0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f,
(R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f, (R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f
}; };
gl.UseProgram(bd.ShaderHandle); gl.UseProgram(bd.ShaderHandle);
@@ -467,7 +471,7 @@ public unsafe static class ImGuiSDL3Renderer
< 130 => (vertSrc120, fragSrc120), < 130 => (vertSrc120, fragSrc120),
300 => (vertSrc300es, fragSrc300es), 300 => (vertSrc300es, fragSrc300es),
>= 410 => (vertSrc410, fragSrc410), >= 410 => (vertSrc410, fragSrc410),
_ => (vertSrc130, fragSrc130), _ => (vertSrc130, fragSrc130)
}; };
string fullVert = bd.GlslVersionString + vertSrc; string fullVert = bd.GlslVersionString + vertSrc;
@@ -577,7 +581,10 @@ public unsafe static class ImGuiSDL3Renderer
private static void ApplySamplerLinear(RendererData bd) private static void ApplySamplerLinear(RendererData bd)
{ {
if (bd.HasBindSampler) bd.Gl.BindSampler(0, bd.TexSamplers[0]); if (bd.HasBindSampler)
{
bd.Gl.BindSampler(0, bd.TexSamplers[0]);
}
else else
{ {
bd.UseTexParameterToSetSampler = true; bd.UseTexParameterToSetSampler = true;
@@ -587,7 +594,10 @@ public unsafe static class ImGuiSDL3Renderer
private static void ApplySamplerNearest(RendererData bd) private static void ApplySamplerNearest(RendererData bd)
{ {
if (bd.HasBindSampler) bd.Gl.BindSampler(0, bd.TexSamplers[1]); if (bd.HasBindSampler)
{
bd.Gl.BindSampler(0, bd.TexSamplers[1]);
}
else else
{ {
bd.UseTexParameterToSetSampler = true; bd.UseTexParameterToSetSampler = true;
@@ -630,8 +640,6 @@ public unsafe static class ImGuiSDL3Renderer
public static class DelegateStorage public static class DelegateStorage
{ {
[UnmanagedFunctionPointer(CallingConvention.Cdecl)] [UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void DrawCallbackFn(ImDrawListPtr drawList, ImDrawCmdPtr cmd); internal delegate void DrawCallbackFn(ImDrawListPtr drawList, ImDrawCmdPtr cmd);
+182
View File
@@ -0,0 +1,182 @@
using System.Numerics;
using Hexa.NET.ImGui;
using Hexa.NET.OpenGL;
using SDL3;
namespace SDL3_TestingSuite.SDL3;
public sealed unsafe class OpenGLTexture : IDisposable
{
private readonly GL _gl;
public uint Handle { get; private set; }
public int Width { get; }
public int Height { get; }
public ImTextureRef ImGuiTexture => new ImTextureRef(null, (nint)Handle);
public Vector2 Size => new Vector2(Width, Height);
public string? FileName;
public string? FilePath;
public string? Extension;
private OpenGLTexture(GL gl, uint handle, int width, int height, string? path = null)
{
_gl = gl;
Handle = handle;
Width = width;
Height = height;
if (path == null) return;
FileName = Path.GetFileName(path);
FilePath = path;
Extension = Path.GetExtension(path);
}
public static OpenGLTexture FromFile(GL gl, string path)
{
nint surface = string.Equals(Path.GetExtension(path), ".bmp", StringComparison.OrdinalIgnoreCase)
? SDL.LoadBMP(path)
: Image.Load(path);
if (surface == nint.Zero)
{
throw new InvalidOperationException($"Failed to load image '{path}': {SDL.GetError()}");
}
try
{
return FromSurface(gl, surface, path);
}
finally
{
SDL.DestroySurface(surface);
}
}
public static OpenGLTexture FromSurface(GL gl, nint surface, string? path = null)
{
if (surface == nint.Zero)
{
throw new ArgumentException("Surface cannot be null.", nameof(surface));
}
SDL.PixelFormat uploadFormat = BitConverter.IsLittleEndian
? SDL.PixelFormat.ABGR8888
: SDL.PixelFormat.RGBA8888;
nint converted = SDL.ConvertSurface(surface, uploadFormat);
if (converted == nint.Zero)
{
throw new InvalidOperationException($"Failed to convert image surface to RGBA32: {SDL.GetError()}");
}
try
{
SDL.Surface* convertedSurface = (SDL.Surface*)converted;
bool locked = false;
if (SDL.MustLock(*convertedSurface))
{
if (!SDL.LockSurface(converted))
{
throw new InvalidOperationException($"Failed to lock image surface: {SDL.GetError()}");
}
locked = true;
}
try
{
uint texture = UploadRgba32(gl, convertedSurface);
return new OpenGLTexture(gl, texture, convertedSurface->Width, convertedSurface->Height, path);
}
finally
{
if (locked)
{
SDL.UnlockSurface(converted);
}
}
}
finally
{
SDL.DestroySurface(converted);
}
}
private static uint UploadRgba32(GL gl, SDL.Surface* surface)
{
uint texture = 0;
gl.GenTextures(1, ref texture);
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int previousTexture);
gl.BindTexture(GLTextureTarget.Texture2D, texture);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, (int)GLTextureMinFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, (int)GLTextureMagFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapS, (int)GLEnum.ClampToEdge);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapT, (int)GLEnum.ClampToEdge);
gl.PixelStorei(GLPixelStoreParameter.UnpackAlignment, 1);
gl.PixelStorei(GLPixelStoreParameter.UnpackRowLength, surface->Pitch / 4);
gl.TexImage2D(
GLTextureTarget.Texture2D,
0,
GLInternalFormat.Rgba,
surface->Width,
surface->Height,
0,
GLPixelFormat.Rgba,
GLPixelType.UnsignedByte,
surface->Pixels);
gl.PixelStorei(GLPixelStoreParameter.UnpackRowLength, 0);
gl.BindTexture(GLTextureTarget.Texture2D, (uint)previousTexture);
return texture;
}
private static uint UploadRgba32FromPixels(GL gl, byte[] pixels, int width, int height)
{
uint texture = 0;
gl.GenTextures(1, ref texture);
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int previousTexture);
gl.BindTexture(GLTextureTarget.Texture2D, texture);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, (int)GLTextureMinFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, (int)GLTextureMagFilter.Linear);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapS, (int)GLEnum.ClampToEdge);
gl.TexParameteri(GLTextureTarget.Texture2D, GLTextureParameterName.WrapT, (int)GLEnum.ClampToEdge);
gl.PixelStorei(GLPixelStoreParameter.UnpackAlignment, 1);
fixed (byte* ptr = &pixels[0])
{
gl.TexImage2D(
GLTextureTarget.Texture2D,
0,
GLInternalFormat.Rgba,
width,
height,
0,
GLPixelFormat.Rgba,
GLPixelType.UnsignedByte,
(nint)ptr);
}
gl.BindTexture(GLTextureTarget.Texture2D, (uint)previousTexture);
return texture;
}
public void Dispose()
{
if (Handle == 0)
{
return;
}
_gl.DeleteTexture(Handle);
Handle = 0;
}
}
+89 -23
View File
@@ -2,6 +2,7 @@
using Hexa.NET.ImGui; using Hexa.NET.ImGui;
using Hexa.NET.ImGuizmo; using Hexa.NET.ImGuizmo;
using Hexa.NET.ImPlot; using Hexa.NET.ImPlot;
using Hexa.NET.ImNodes;
using Hexa.NET.OpenGL; using Hexa.NET.OpenGL;
using HexaGen.Runtime; using HexaGen.Runtime;
using SDL3; using SDL3;
@@ -22,26 +23,34 @@ public sealed unsafe class SDL3Window : IDisposable
} }
public event Action? RenderCallback; public event Action? RenderCallback;
public event Action? Disposing;
public event Action<Vector4>? Resized;
public event Action<SDL.Event>? EventCallback;
private ImGuiContextPtr _imGuiContext; private ImGuiContextPtr _imGuiContext;
private ImPlotContextPtr _imPlotContext; private ImPlotContextPtr _imPlotContext;
private ImNodesContextPtr _imNodesContext;
// private ImPLot3DContextPtr _imPlot3DContext;
public bool Disposed => _disposed; public bool Disposed => _disposed;
private bool _disposed; private bool _disposed;
private readonly FileSystemWatcher? _watcher; private readonly FileSystemWatcher? _watcher;
private readonly GL _gl; public readonly GL GL;
public SDL3Window(string name, int posX, int posY, int width, int height, SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity) public SDL3Window(string name, int posX, int posY, int width, int height, SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity)
{ {
if (OperatingSystem.IsLinux())
SDL.SetHint(SDL.Hints.VideoDriver, "x11");
if (!SDL.Init(SDL.InitFlags.Events | SDL.InitFlags.Video | SDL.InitFlags.Gamepad)) if (!SDL.Init(SDL.InitFlags.Events | SDL.InitFlags.Video | SDL.InitFlags.Gamepad))
throw new Exception($"SDL_Init failed: {SDL.GetError()}"); throw new Exception($"SDL_Init failed: {SDL.GetError()}");
SDL.GLSetAttribute(SDL.GLAttr.ContextFlags, (int)SDL.GLContextFlag.ForwardCompatible); SDL.GLSetAttribute(SDL.GLAttr.ContextFlags, (int)SDL.GLContextFlag.ForwardCompatible);
SDL.GLSetAttribute(SDL.GLAttr.ContextProfileMask, (int)SDL.GLProfile.Core); SDL.GLSetAttribute(SDL.GLAttr.ContextProfileMask, (int)SDL.GLProfile.Core);
SDL.GLSetAttribute(SDL.GLAttr.ContextMajorVersion, 3); SDL.GLSetAttribute(SDL.GLAttr.ContextMajorVersion, 4);
SDL.GLSetAttribute(SDL.GLAttr.ContextMinorVersion, 3); SDL.GLSetAttribute(SDL.GLAttr.ContextMinorVersion, 6);
SDL.SetHint(SDL.Hints.IMEImplementedUI, "1"); SDL.SetHint(SDL.Hints.IMEImplementedUI, "1");
@@ -67,9 +76,13 @@ public sealed unsafe class SDL3Window : IDisposable
// Create ImGui context // Create ImGui context
_imGuiContext = ImGui.CreateContext(); _imGuiContext = ImGui.CreateContext();
_imPlotContext = ImPlot.CreateContext(); _imPlotContext = ImPlot.CreateContext();
_imNodesContext = ImNodes.CreateContext();
// _imPlot3DContext = ImPlot3D.CreateContext();
ImPlot.SetImGuiContext(_imGuiContext); ImPlot.SetImGuiContext(_imGuiContext);
ImGuizmo.SetImGuiContext(_imGuiContext); ImGuizmo.SetImGuiContext(_imGuiContext);
ImNodes.SetImGuiContext(_imGuiContext);
// ImPlot3D.SetImGuiContext(_imGuiContext);
ImGuiIOPtr io = ImGui.GetIO(); ImGuiIOPtr io = ImGui.GetIO();
io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.NavEnableGamepad | ImGuiConfigFlags.DockingEnable; io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.NavEnableGamepad | ImGuiConfigFlags.DockingEnable;
io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable; io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
@@ -89,23 +102,52 @@ public sealed unsafe class SDL3Window : IDisposable
if (!File.Exists(b.FullPath)) return; if (!File.Exists(b.FullPath)) return;
if (Path.GetExtension(b.FullPath) != ".ttf") return; if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().AddFont(b.FullPath); ImGui.GetIO().AddFont(b.FullPath);
}; };
_watcher.Deleted += (_, b) => _watcher.Deleted += (_, b) =>
{ {
if (Path.GetExtension(b.FullPath) != ".ttf") return; if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().RemoveFont(b.Name); ImGui.GetIO().RemoveFont(b.Name);
}; };
_watcher.Renamed += (_, b) =>
{
if (Path.GetExtension(b.OldFullPath) != ".ttf") return;
ImGui.GetIO().RemoveFont(b.OldName);
if (!File.Exists(b.FullPath)) return;
if (Path.GetExtension(b.FullPath) != ".ttf") return;
ImGui.GetIO().AddFont(b.FullPath);
};
_watcher.IncludeSubdirectories = false; _watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true; _watcher.EnableRaisingEvents = true;
string[] fonts = Directory.GetFiles(fontsPath, "*.ttf", SearchOption.AllDirectories); List<string> fonts = Directory.GetFiles(fontsPath, "*.ttf", SearchOption.AllDirectories).ToList();
fonts.Sort();
List<string> mergeFonts = new List<string>();
for (int i = fonts.Count - 1; i >= 0; i--)
{
if (Path.GetFileName(fonts[i]).StartsWith("merge_", StringComparison.OrdinalIgnoreCase))
{
mergeFonts.Add(fonts[i]);
fonts.RemoveAt(i);
}
}
mergeFonts.Reverse();
foreach (string merge in mergeFonts)
{
io.AddFont(merge, true);
}
foreach (string font in fonts) foreach (string font in fonts)
{ {
io.AddFont(font); io.AddFont(font);
foreach (string merge in mergeFonts)
{
io.AddFont(merge, true);
}
} }
} }
catch (Exception e) catch (Exception e)
@@ -113,11 +155,11 @@ public sealed unsafe class SDL3Window : IDisposable
Console.WriteLine(e); Console.WriteLine(e);
} }
_gl = new GL(new BindingsContext(Window, glContext)); GL = new GL(new BindingsContext(Window, glContext));
// Init platform and renderer // Init platform and renderer
ImGuiSDL3Platform.Init(_gl, glContext, Window, this); ImGuiSDL3Platform.Init(GL, Window, glContext);
ImGuiSDL3Renderer.Init(_gl, "#version 330"); ImGuiSDL3Renderer.Init(GL, "#version 330");
} }
public bool ShouldClose; public bool ShouldClose;
@@ -127,11 +169,6 @@ public sealed unsafe class SDL3Window : IDisposable
while (!_disposed) while (!_disposed)
{ {
SDL.PumpEvents(); SDL.PumpEvents();
if (ImGui.GetIO().WantTextInput && !SDL.TextInputActive(Window))
SDL.StartTextInput(Window);
else if (!ImGui.GetIO().WantTextInput && SDL.TextInputActive(Window))
SDL.StopTextInput(Window);
while (SDL.PollEvent(out SDL.Event ev)) while (SDL.PollEvent(out SDL.Event ev))
{ {
@@ -144,12 +181,26 @@ public sealed unsafe class SDL3Window : IDisposable
case SDL.EventType.Quit: case SDL.EventType.Quit:
ShouldClose = true; ShouldClose = true;
break; break;
case SDL.EventType.WindowResized:
case SDL.EventType.WindowMoved:
SDL.GetWindowSize(Window, out int w, out int h);
SDL.GetWindowPosition(Window, out int x, out int y);
Resized?.Invoke(new Vector4(x, y, w, h));
break;
} }
EventCallback?.Invoke(ev);
}
if (SDL.GetWindowFlags(Window).HasFlag(SDL.WindowFlags.Minimized))
{
SDL.Delay(10);
continue;
} }
_gl.MakeCurrent(); GL.MakeCurrent();
_gl.ClearColor(ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W); GL.ClearColor(ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
_gl.Clear(GLClearBufferMask.ColorBufferBit); GL.Clear(GLClearBufferMask.ColorBufferBit);
ImGuiSDL3Platform.NewFrame(); ImGuiSDL3Platform.NewFrame();
ImGuiSDL3Renderer.NewFrame(); ImGuiSDL3Renderer.NewFrame();
@@ -161,7 +212,7 @@ public sealed unsafe class SDL3Window : IDisposable
ImGui.Render(); ImGui.Render();
_gl.MakeCurrent(); GL.MakeCurrent();
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData()); ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData());
@@ -171,8 +222,8 @@ public sealed unsafe class SDL3Window : IDisposable
ImGui.RenderPlatformWindowsDefault(); ImGui.RenderPlatformWindowsDefault();
} }
_gl.MakeCurrent(); GL.MakeCurrent();
_gl.SwapBuffers(); GL.SwapBuffers();
if (ShouldClose) if (ShouldClose)
{ {
@@ -212,10 +263,13 @@ public sealed unsafe class SDL3Window : IDisposable
ImPlot.SetCurrentContext(_imPlotContext); ImPlot.SetCurrentContext(_imPlotContext);
} }
Disposing?.Invoke();
ImGuiSDL3Renderer.Dispose(); ImGuiSDL3Renderer.Dispose();
ImGuiSDL3Platform.Dispose(); ImGuiSDL3Platform.Dispose();
RenderCallback = null; RenderCallback = null;
Disposing = null;
} }
if (_imGuiContext.Handle != null) if (_imGuiContext.Handle != null)
@@ -230,6 +284,18 @@ public sealed unsafe class SDL3Window : IDisposable
ImPlot.DestroyContext(_imPlotContext); ImPlot.DestroyContext(_imPlotContext);
_imPlotContext = null; _imPlotContext = null;
} }
if (_imNodesContext.Handle != null)
{
ImNodes.SetCurrentContext(null);
ImNodes.DestroyContext(_imNodesContext);
_imNodesContext = null;
}
// if (_imPlot3DContext.Handle != null)
// {
// ImPlot3D.SetCurrentContext(null);
// ImPlot3D.DestroyContext(_imPlot3DContext);
// _imPlot3DContext = null;
// }
// if (Renderer != nint.Zero) // if (Renderer != nint.Zero)
// { // {
@@ -291,4 +357,4 @@ public unsafe class BindingsContext : IGLContext
procAddress = (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate(); procAddress = (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate();
return procAddress != 0; return procAddress != 0;
} }
} }