Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 060f117a01 |
+12
-271
@@ -1,323 +1,64 @@
|
||||
using System.Numerics;
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using Hexa.NET.ImGui;
|
||||
using Hexa.NET.ImPlot;
|
||||
using HexaGen.Runtime;
|
||||
using ImGuiNET;
|
||||
using SDL3_TestingSuite.SDL3;
|
||||
using SDL3;
|
||||
|
||||
namespace SDL3_TestingSuite;
|
||||
|
||||
public class Program
|
||||
{
|
||||
private static bool _demoWindowVisible = true;
|
||||
private static bool _imPlotDemoVisible;
|
||||
private static bool _fontStuff;
|
||||
private static readonly Dictionary<string, List<uint>?> GlyphsByName = new Dictionary<string, List<uint>?>();
|
||||
private static bool _fontStuffInitialized;
|
||||
private static bool _init;
|
||||
private static ImFontPtr _font;
|
||||
private static float size = 1f;
|
||||
private static SDL3Window _window = null!;
|
||||
private static OpenGLTexture? _imageTexture;
|
||||
private static string? _imageLoadError;
|
||||
|
||||
public static void Main()
|
||||
{
|
||||
string baseDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)!;
|
||||
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[]
|
||||
const SDL.WindowFlags flags = SDL.WindowFlags.Resizable | SDL.WindowFlags.HighPixelDensity | SDL.WindowFlags.Transparent;
|
||||
SDL3Window window = new SDL3Window("SDL3 Testing Suite", 100, 100, 1280, 720, flags);
|
||||
window.RenderCallback = () =>
|
||||
{
|
||||
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();
|
||||
ImGui.SetNextWindowPos(viewport.WorkPos);
|
||||
ImGui.SetNextWindowSize(viewport.WorkSize);
|
||||
ImGui.SetNextWindowViewport(viewport.ID);
|
||||
|
||||
ImGui.Begin("MainWindow", ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.MenuBar | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar | ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoMove | ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoBringToFrontOnFocus);
|
||||
|
||||
if (ImGui.BeginMenuBar())
|
||||
{
|
||||
if (ImGui.BeginMenu("Stuff"))
|
||||
{
|
||||
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();
|
||||
}
|
||||
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)
|
||||
{
|
||||
ImGui.SetNextWindowSize(new Vector2(250, 500), ImGuiCond.FirstUseEver);
|
||||
ImGui.Begin("FontStuff", ref _fontStuff);
|
||||
|
||||
ImGui.ShowFontSelector("Font");
|
||||
|
||||
bool change = false;
|
||||
if (ImGui.GetFont() != _font)
|
||||
{
|
||||
_font = ImGui.GetFont();
|
||||
change = true;
|
||||
}
|
||||
|
||||
string fontName = _font.GetDebugNameS();
|
||||
fontName = string.IsNullOrEmpty(fontName) ? _font.FontId.ToString() : fontName;
|
||||
if (!_fontStuffInitialized || change)
|
||||
{
|
||||
if (!GlyphsByName.TryGetValue(fontName, out List<uint>? glyphs))
|
||||
{
|
||||
glyphs = new List<uint>();
|
||||
|
||||
ImFontPtr font = _font;
|
||||
|
||||
for (uint codepoint = 0; codepoint <= 0x10FFFF; codepoint++)
|
||||
{
|
||||
if (codepoint >= 0xD800 && codepoint <= 0xDFFF)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!font.IsGlyphInFont(codepoint)) continue;
|
||||
|
||||
glyphs.Add(codepoint);
|
||||
}
|
||||
|
||||
GlyphsByName[fontName] = glyphs;
|
||||
Logger.Log($"Initialized font {fontName} with {glyphs.Count} glyphs");
|
||||
}
|
||||
|
||||
_fontStuffInitialized = true;
|
||||
}
|
||||
|
||||
ImGui.PushFont(null, 24);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
ImGui.Begin("Thing");
|
||||
float time = (float)ImGui.GetTime() * 5;
|
||||
if (ImPlot.BeginPlot("Moving Rainbow Sine Wave"))
|
||||
{
|
||||
int count = 200;
|
||||
|
||||
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)
|
||||
{
|
||||
ImGui.ShowDemoWindow(ref _demoWindowVisible);
|
||||
}
|
||||
if (_imPlotDemoVisible)
|
||||
{
|
||||
ImPlot.ShowDemoWindow(ref _imPlotDemoVisible);
|
||||
}
|
||||
};
|
||||
|
||||
_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;
|
||||
window.Run();
|
||||
}
|
||||
|
||||
public static class Logger
|
||||
{
|
||||
private const int MessageWidth = 80;
|
||||
private const int CallerWidth = 35;
|
||||
|
||||
public static void Log(object? value, [CallerFilePath] string path = "", [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
|
||||
public static void Log(string? str, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
|
||||
{
|
||||
if (value == null)
|
||||
{
|
||||
Write("null", path, caller, line);
|
||||
return;
|
||||
Console.WriteLine($"{caller}({line}): {str}");
|
||||
}
|
||||
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? str, [CallerMemberName] string caller = "", [CallerLineNumber] int line = 0)
|
||||
{
|
||||
if (values == null)
|
||||
{
|
||||
Write("null", path, caller, line);
|
||||
return;
|
||||
}
|
||||
Write(string.Join(" ", values), path, caller, line);
|
||||
}
|
||||
|
||||
private static void Write(string? str, string path, string caller, int line)
|
||||
{
|
||||
string message = (str ?? string.Empty).PadRight(MessageWidth);
|
||||
string method = caller.PadRight(CallerWidth);
|
||||
|
||||
Console.WriteLine($"{message} | {method} | {path}:{line}");
|
||||
Log(str?.ToString(), caller, line);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,18 +11,14 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<!--<PackageReference Include="ImGui.NET" Version="*" />-->
|
||||
<PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" />
|
||||
<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.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="ImGui.NET" Version="*" />
|
||||
<!-- <PackageReference Include="Hexa.NET.ImGui" Version="2.2.9" />-->
|
||||
<!-- <PackageReference Include="Hexa.NET.ImGui.Widgets" Version="1.2.18" />-->
|
||||
<!-- <PackageReference Include="Hexa.NET.ImPlot" Version="2.2.9" />-->
|
||||
<!-- <PackageReference Include="Hexa.NET.ImPlot3D" Version="2.2.9" />-->
|
||||
<!-- <PackageReference Include="Hexa.NET.Utilities" Version="2.2.12" />-->
|
||||
<PackageReference Include="SDL3-CS" Version="3.2.18" />
|
||||
<PackageReference Include="SDL3-CS.Native" Version="3.2.18" />
|
||||
<PackageReference Include="SDL3-CS.Native.Image" Version="3.3.0" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImFontConfig_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fc97073b326e54291bbfaa37650bd4af34d6200_003F7f_003F46ea95ef_003FImFontConfig_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImFontConfig_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003Fc97073b326e54291bbfaa37650bd4af34d6200_003F7f_003F46ea95ef_003FImFontConfig_002Ecs/@EntryIndexedValue">ForceIncluded</s:String>
|
||||
<s:String x:Key="/Default/CodeInspection/ExcludedFiles/FilesAndFoldersToSkip2/=7020124F_002D9FFC_002D4AC3_002D8F3D_002DAAB8E0240759_002Ff_003AImPtrVector_00601_002Ecs_002Fl_003A_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003F_002E_002E_003Fhome_003Fnepushiro_003F_002Econfig_003FJetBrains_003FRider2026_002E1_003Fresharper_002Dhost_003FDecompilerCache_003Fdecompiler_003F8243060d9bfb43bd93c81caad5fecadf4d800_003Ffa_003Ff2bd8dce_003FImPtrVector_00601_002Ecs/@EntryIndexedValue">ForceIncluded</s:String></wpf:ResourceDictionary>
|
||||
@@ -1,8 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SDL3_TestingSuite.SDL3;
|
||||
|
||||
public unsafe static class DelegateHelpers
|
||||
{
|
||||
public static void* GetPtrForDelegate<TDelegate>(this TDelegate _delegate) where TDelegate : notnull => (void*)Marshal.GetFunctionPointerForDelegate(_delegate);
|
||||
}
|
||||
@@ -1,176 +0,0 @@
|
||||
using Hexa.NET.ImGui;
|
||||
|
||||
namespace SDL3_TestingSuite.SDL3;
|
||||
|
||||
public struct FontMetrics
|
||||
{
|
||||
public ushort UnitsPerEm;
|
||||
|
||||
public short TypoAscender;
|
||||
public short TypoDescender;
|
||||
public short TypoLineGap;
|
||||
|
||||
public short WinAscent;
|
||||
public short WinDescent;
|
||||
|
||||
public int TypoLineHeight;
|
||||
public int WinLineHeight;
|
||||
}
|
||||
|
||||
public static class FontFind
|
||||
{
|
||||
extension(ImGuiIOPtr io)
|
||||
{
|
||||
public unsafe ImFontPtr AddFont(string fontPath, bool merge = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (fontPath == null || io.Handle == null) return null;
|
||||
FileInfo info = new FileInfo(fontPath);
|
||||
if (!info.Exists || info.Length <= 0) return null;
|
||||
|
||||
FontMetrics metrics = ReadFontMetricsSafe(fontPath);
|
||||
float size = GetRecommendedPixelSize(metrics);
|
||||
|
||||
ImFontConfigPtr config = ImGui.ImFontConfig();
|
||||
config.FontLoaderFlags |= (uint)ImGuiFreeTypeLoaderFlags.LoadColor | (uint)ImGuiFreeTypeLoaderFlags.Bitmap;
|
||||
config.MergeMode = merge;
|
||||
ImFontPtr font = io.Fonts.AddFontFromFileTTF(fontPath, size, config);
|
||||
Program.Logger.Log($"{(merge ? "Merged" : "Added")} font: " + Path.GetFileName(fontPath));
|
||||
return font;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
public unsafe bool RemoveFont(string? fontName)
|
||||
{
|
||||
if (fontName == null || io.Handle == null) return false;
|
||||
|
||||
bool flag = false;
|
||||
ImVector<ImFontPtr> fonts = io.Fonts.Fonts;
|
||||
List<ImFontPtr> toRemove = new List<ImFontPtr>();
|
||||
|
||||
for (int i = 0; i < fonts.Size; i++)
|
||||
{
|
||||
ImFontPtr font = fonts[i];
|
||||
if (font.GetDebugNameS() == fontName)
|
||||
{
|
||||
toRemove.Add(font);
|
||||
flag = true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (ImFontPtr font in toRemove)
|
||||
{
|
||||
io.Fonts.RemoveFont(font);
|
||||
Program.Logger.Log("Removed font: " + fontName);
|
||||
}
|
||||
|
||||
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)
|
||||
{
|
||||
byte[] data = File.ReadAllBytes(fontPath);
|
||||
|
||||
ushort numTables = ReadU16Be(4);
|
||||
const int tableDir = 12;
|
||||
|
||||
int headOffset = 0;
|
||||
int os2Offset = 0;
|
||||
|
||||
for (int i = 0; i < numTables; i++)
|
||||
{
|
||||
int entry = tableDir + i * 16;
|
||||
string tag = ReadTag(entry);
|
||||
|
||||
uint offset = ReadU32Be(entry + 8);
|
||||
|
||||
if (tag == "head")
|
||||
headOffset = (int)offset;
|
||||
|
||||
if (tag == "OS/2")
|
||||
os2Offset = (int)offset;
|
||||
}
|
||||
|
||||
FontMetrics metrics = new FontMetrics();
|
||||
|
||||
metrics.UnitsPerEm = ReadU16Be(headOffset + 18);
|
||||
|
||||
if (os2Offset != 0)
|
||||
{
|
||||
metrics.TypoAscender = ReadS16Be(os2Offset + 68);
|
||||
metrics.TypoDescender = ReadS16Be(os2Offset + 70);
|
||||
metrics.TypoLineGap = ReadS16Be(os2Offset + 72);
|
||||
|
||||
metrics.WinAscent = ReadS16Be(os2Offset + 74);
|
||||
metrics.WinDescent = ReadS16Be(os2Offset + 76);
|
||||
}
|
||||
|
||||
metrics.TypoLineHeight = metrics.TypoAscender - metrics.TypoDescender + metrics.TypoLineGap;
|
||||
|
||||
metrics.WinLineHeight = metrics.WinAscent + metrics.WinDescent;
|
||||
|
||||
return metrics;
|
||||
|
||||
ushort ReadU16Be(int o)
|
||||
{
|
||||
return (ushort)((data[o] << 8) | data[o + 1]);
|
||||
}
|
||||
|
||||
short ReadS16Be(int o)
|
||||
{
|
||||
return (short)ReadU16Be(o);
|
||||
}
|
||||
|
||||
uint ReadU32Be(int o)
|
||||
{
|
||||
return (uint)((data[o] << 24) | (data[o + 1] << 16) | (data[o + 2] << 8) | data[o + 3]);
|
||||
}
|
||||
|
||||
string ReadTag(int o)
|
||||
{
|
||||
char c1 = (char)data[o];
|
||||
char c2 = (char)data[o + 1];
|
||||
char c3 = (char)data[o + 2];
|
||||
char c4 = (char)data[o + 3];
|
||||
return new string(new char[] { c1, c2, c3, c4 });
|
||||
}
|
||||
}
|
||||
|
||||
public static int GetRecommendedPixelSize(FontMetrics metrics)
|
||||
{
|
||||
if (metrics.UnitsPerEm == 0 || metrics.TypoLineHeight == 0)
|
||||
return 16;
|
||||
|
||||
const float targetLineHeightPx = 18.0f;
|
||||
|
||||
float scale = targetLineHeightPx * metrics.UnitsPerEm / metrics.TypoLineHeight;
|
||||
|
||||
int size = (int)MathF.Round(scale);
|
||||
|
||||
if (size < 10) size = 10;
|
||||
if (size > 72) size = 72;
|
||||
|
||||
return size;
|
||||
}
|
||||
}
|
||||
+799
-838
File diff suppressed because it is too large
Load Diff
+282
-594
@@ -1,682 +1,370 @@
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using Hexa.NET.ImGui;
|
||||
using Hexa.NET.OpenGL;
|
||||
using ImGuiNET;
|
||||
using SDL3;
|
||||
|
||||
namespace SDL3_TestingSuite.SDL3;
|
||||
|
||||
/// <summary>
|
||||
/// Implementation of ImGui for SDL3 Renderer backend.
|
||||
/// https://github.com/ocornut/imgui/blob/master/backends/imgui_impl_sdlrenderer3.h
|
||||
/// </summary>
|
||||
public unsafe static class ImGuiSDL3Renderer
|
||||
{
|
||||
public class RendererData
|
||||
{
|
||||
public GL Gl = null!;
|
||||
public nint Renderer; // Main viewport's renderer
|
||||
public ImVector<SDL.FColor> ColorBuffer;
|
||||
|
||||
public uint GlVersion; // e.g. 320 for GL 3.2
|
||||
public string GlslVersionString = ""; // e.g. "#version 330 core\n"
|
||||
public bool GlProfileIsES2;
|
||||
public bool GlProfileIsES3;
|
||||
public bool GlProfileIsCompat;
|
||||
public int GlProfileMask;
|
||||
public int MaxTextureSize;
|
||||
|
||||
public uint ShaderHandle;
|
||||
public int AttribLocationTex;
|
||||
public int AttribLocationProjMtx;
|
||||
public uint AttribLocationVtxPos;
|
||||
public uint AttribLocationVtxUV;
|
||||
public uint AttribLocationVtxColor;
|
||||
public uint VboHandle;
|
||||
public uint ElementsHandle;
|
||||
|
||||
public bool HasPolygonMode;
|
||||
public bool HasBindSampler;
|
||||
public bool HasClipOrigin;
|
||||
|
||||
public uint[] TexSamplers = new uint[2]; // [0]=linear, [1]=nearest
|
||||
|
||||
public bool UseTexParameterToSetSampler;
|
||||
public int NextSampler; // GL_LINEAR or GL_NEAREST
|
||||
// Render State
|
||||
public SDL.ScaleMode CurrentScaleMode;
|
||||
}
|
||||
|
||||
public static RendererData? GetRendererData() => ImGui.GetCurrentContext().Handle != null ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData) : null;
|
||||
private struct BackupSDLRendererState
|
||||
{
|
||||
public SDL.Rect Viewport;
|
||||
public bool ViewportEnabled;
|
||||
public bool ClipEnabled;
|
||||
public SDL.Rect ClipRect;
|
||||
}
|
||||
|
||||
public static bool Init(GL gl, string? glslVersion = null)
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void RendererCreateWindowFn(ImGuiViewportPtr viewport);
|
||||
|
||||
private static readonly RendererCreateWindowFn RendererCreateWindowDelegate = RendererCreateWindow;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void RendererDestroyWindowFn(ImGuiViewportPtr viewport);
|
||||
|
||||
private static readonly RendererDestroyWindowFn RendererDestroyWindowDelegate = RendererDestroyWindow;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void RendererSetWindowSizeFn(ImGuiViewportPtr viewport, Vector2 size);
|
||||
|
||||
private static readonly RendererSetWindowSizeFn RendererSetWindowSizeDelegate = RendererSetWindowSize;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void RendererRenderWindowFn(ImGuiViewportPtr viewport);
|
||||
|
||||
private static readonly RendererRenderWindowFn RendererRenderWindowDelegate = RendererRenderWindow;
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
private delegate void RendererSwapBuffersFn(ImGuiViewportPtr viewport);
|
||||
|
||||
private static readonly RendererSwapBuffersFn RendererSwapBuffersDelegate = RendererSwapBuffers;
|
||||
|
||||
public static RendererData Data => ImGui.GetCurrentContext() != nint.Zero ? ImGuiUserData<RendererData>.Get(ImGui.GetIO().BackendRendererUserData)! : null!;
|
||||
|
||||
private static nint _fontTexture = nint.Zero;
|
||||
|
||||
public static bool Init(nint renderer)
|
||||
{
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
Debug.Assert(io.BackendRendererUserData == null, "Already initialised a renderer backend!");
|
||||
|
||||
RendererData bd = new RendererData { Gl = gl };
|
||||
RendererData bd = new RendererData();
|
||||
io.BackendRendererUserData = ImGuiUserData<RendererData>.Store(bd);
|
||||
io.BackendRendererName = (byte*)Marshal.StringToHGlobalAnsi("imgui_impl_opengl3_cs");
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; // We can honor the ImDrawCmd.VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports;
|
||||
|
||||
string? glVersionStr = Marshal.PtrToStringAnsi((nint)gl.GetString(GLStringName.Version));
|
||||
|
||||
if (glVersionStr != null && glVersionStr.StartsWith("OpenGL ES 2", StringComparison.Ordinal))
|
||||
{
|
||||
bd.GlVersion = 200;
|
||||
bd.GlProfileIsES2 = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
gl.GetIntegerv(GLGetPName.MajorVersion, out int major);
|
||||
gl.GetIntegerv(GLGetPName.MinorVersion, out int minor);
|
||||
if (major == 0 && minor == 0 && glVersionStr != null)
|
||||
{
|
||||
string[] parts = glVersionStr.Split('.');
|
||||
if (parts.Length >= 2)
|
||||
{
|
||||
int.TryParse(parts[0], out major);
|
||||
int.TryParse(new string(parts[1].TakeWhile(char.IsDigit).ToArray()), out minor);
|
||||
}
|
||||
}
|
||||
|
||||
bd.GlVersion = (uint)(major * 100 + minor * 10);
|
||||
|
||||
if (glVersionStr != null && glVersionStr.StartsWith("OpenGL ES 3", StringComparison.Ordinal))
|
||||
bd.GlProfileIsES3 = true;
|
||||
|
||||
gl.GetIntegerv(GLGetPName.MaxTextureSize, out bd.MaxTextureSize);
|
||||
|
||||
if (!bd.GlProfileIsES3 && bd.GlVersion >= 320)
|
||||
{
|
||||
gl.GetIntegerv(GLGetPName.ContextProfileMask, out bd.GlProfileMask);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
if (bd.GlVersion >= 320)
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; // large meshes
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures; // dynamic font atlas
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports; // multi-viewport
|
||||
bd.Renderer = renderer;
|
||||
|
||||
ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO();
|
||||
platformIO.RendererTextureMaxWidth = bd.MaxTextureSize;
|
||||
platformIO.RendererTextureMaxHeight = bd.MaxTextureSize;
|
||||
|
||||
if (glslVersion == null)
|
||||
{
|
||||
if (bd.GlProfileIsES2) glslVersion = "#version 100";
|
||||
else if (bd.GlProfileIsES3) glslVersion = "#version 300 es";
|
||||
else if (OperatingSystem.IsMacOS()) glslVersion = "#version 150";
|
||||
else glslVersion = "#version 130";
|
||||
}
|
||||
bd.GlslVersionString = glslVersion + "\n";
|
||||
|
||||
bd.HasPolygonMode = !bd.GlProfileIsES2 && !bd.GlProfileIsES3;
|
||||
bd.HasBindSampler = bd.GlVersion >= 330 || bd.GlProfileIsES3;
|
||||
bd.HasClipOrigin = bd.GlVersion >= 450;
|
||||
|
||||
if (!bd.HasClipOrigin && !bd.GlProfileIsES2 && !bd.GlProfileIsES3)
|
||||
{
|
||||
gl.GetIntegerv(GLGetPName.NumExtensions, out int numExt);
|
||||
for (uint i = 0; i < numExt; i++)
|
||||
{
|
||||
string? ext = Marshal.PtrToStringAnsi((nint)gl.GetStringi(GLStringName.Extensions, i));
|
||||
if (ext == "GL_ARB_clip_control")
|
||||
{
|
||||
bd.HasClipOrigin = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InitMultiViewportSupport();
|
||||
platformIO.Renderer_CreateWindow = Marshal.GetFunctionPointerForDelegate(RendererCreateWindowDelegate);
|
||||
platformIO.Renderer_DestroyWindow = Marshal.GetFunctionPointerForDelegate(RendererDestroyWindowDelegate);
|
||||
platformIO.Renderer_SetWindowSize = Marshal.GetFunctionPointerForDelegate(RendererSetWindowSizeDelegate);
|
||||
platformIO.Renderer_RenderWindow = Marshal.GetFunctionPointerForDelegate(RendererRenderWindowDelegate);
|
||||
platformIO.Renderer_SwapBuffers = Marshal.GetFunctionPointerForDelegate(RendererSwapBuffersDelegate);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void Dispose()
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
Debug.Assert(bd != null, "No renderer backend to shut down, or already shut down?");
|
||||
var io = ImGui.GetIO();
|
||||
var platformIO = ImGui.GetPlatformIO();
|
||||
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
|
||||
ShutdownMultiViewportSupport();
|
||||
DestroyDeviceObjects();
|
||||
|
||||
if (io.BackendRendererName != null)
|
||||
Marshal.FreeHGlobal((nint)io.BackendRendererName);
|
||||
|
||||
ImGuiUserData<RendererData>.Free(io.BackendRendererUserData);
|
||||
io.BackendRendererName = null;
|
||||
io.BackendRendererUserData = null;
|
||||
io.BackendFlags &= ~(ImGuiBackendFlags.RendererHasVtxOffset | ImGuiBackendFlags.RendererHasTextures | ImGuiBackendFlags.RendererHasViewports);
|
||||
io.BackendRendererUserData = nint.Zero;
|
||||
io.BackendFlags &= ~ImGuiBackendFlags.RendererHasVtxOffset;
|
||||
platformIO.Renderer_RenderState = nint.Zero;
|
||||
platformIO.Renderer_CreateWindow = nint.Zero;
|
||||
platformIO.Renderer_DestroyWindow = nint.Zero;
|
||||
platformIO.Renderer_SetWindowSize = nint.Zero;
|
||||
platformIO.Renderer_RenderWindow = nint.Zero;
|
||||
platformIO.Renderer_SwapBuffers = nint.Zero;
|
||||
}
|
||||
|
||||
public static void NewFrame()
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
Debug.Assert(bd != null, "Context or backend not initialised! Did you call ImGuiOpenGL3Renderer.Init()?");
|
||||
|
||||
if (bd.ShaderHandle == 0)
|
||||
if (_fontTexture == nint.Zero)
|
||||
{
|
||||
bool ok = CreateDeviceObjects();
|
||||
Debug.Assert(ok, "ImGuiOpenGL3Renderer.CreateDeviceObjects() failed!");
|
||||
CreateDeviceObjects();
|
||||
}
|
||||
}
|
||||
|
||||
public static void RenderDrawData(ImDrawDataPtr drawData)
|
||||
private static void RendererCreateWindow(ImGuiViewportPtr viewport)
|
||||
{
|
||||
if (drawData.Handle == null) return;
|
||||
Program.Logger.Log(null);
|
||||
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
|
||||
if (vd == null || vd.Window == nint.Zero)
|
||||
return;
|
||||
|
||||
int fbWidth = (int)(drawData.DisplaySize.X * drawData.FramebufferScale.X);
|
||||
int fbHeight = (int)(drawData.DisplaySize.Y * drawData.FramebufferScale.Y);
|
||||
if (fbWidth <= 0 || fbHeight <= 0) return;
|
||||
|
||||
RendererData bd = GetRendererData()!;
|
||||
GL gl = bd.Gl;
|
||||
|
||||
if (drawData.Textures.Size > 0)
|
||||
if (vd.Renderer == nint.Zero)
|
||||
{
|
||||
for (int i = 0; i < drawData.Textures.Size; i++)
|
||||
{
|
||||
ImTextureDataPtr tex = drawData.Textures[i];
|
||||
if (tex.Status != ImTextureStatus.Ok)
|
||||
UpdateTexture(tex);
|
||||
vd.Renderer = SDL.CreateRenderer(vd.Window, (string?)null);
|
||||
vd.RendererOwned = true;
|
||||
}
|
||||
Program.Logger.Log(null);
|
||||
}
|
||||
|
||||
gl.GetIntegerv(GLGetPName.ActiveTexture, out int lastActiveTexture);
|
||||
gl.ActiveTexture(GLTextureUnit.Texture0);
|
||||
gl.GetIntegerv(GLGetPName.CurrentProgram, out int lastProgram);
|
||||
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int lastTexture);
|
||||
gl.GetIntegerv(GLGetPName.SamplerBinding, out int lastSampler);
|
||||
gl.GetIntegerv(GLGetPName.ArrayBufferBinding, out int lastArrayBuffer);
|
||||
gl.GetIntegerv(GLGetPName.VertexArrayBinding, out int lastVertexArray);
|
||||
int[] lastPolygonMode = new int[2];
|
||||
if (bd.HasPolygonMode) gl.GetIntegerv(GLGetPName.PolygonMode, lastPolygonMode);
|
||||
int[] lastViewport = new int[4];
|
||||
gl.GetIntegerv(GLGetPName.Viewport, lastViewport);
|
||||
int[] lastScissorBox = new int[4];
|
||||
gl.GetIntegerv(GLGetPName.ScissorBox, lastScissorBox);
|
||||
|
||||
gl.GetIntegerv(GLGetPName.BlendSrcRgb, out int lastBlendSrcRgb);
|
||||
gl.GetIntegerv(GLGetPName.BlendDstRgb, out int lastBlendDstRgb);
|
||||
gl.GetIntegerv(GLGetPName.BlendSrcAlpha, out int lastBlendSrcAlpha);
|
||||
gl.GetIntegerv(GLGetPName.BlendDstAlpha, out int lastBlendDstAlpha);
|
||||
gl.GetIntegerv(GLGetPName.BlendEquationRgb, out int lastBlendEqRgb);
|
||||
gl.GetIntegerv(GLGetPName.BlendEquationAlpha, out int lastBlendEqAlpha);
|
||||
|
||||
bool lastBlend = gl.IsEnabled(GLEnableCap.Blend);
|
||||
bool lastCullFace = gl.IsEnabled(GLEnableCap.CullFace);
|
||||
bool lastDepthTest = gl.IsEnabled(GLEnableCap.DepthTest);
|
||||
bool lastStencilTest = gl.IsEnabled(GLEnableCap.StencilTest);
|
||||
bool lastScissorTest = gl.IsEnabled(GLEnableCap.ScissorTest);
|
||||
bool lastPrimRestart = bd.GlVersion >= 310 && !bd.GlProfileIsES3 && gl.IsEnabled(GLEnableCap.PrimitiveRestart);
|
||||
|
||||
uint vao = 0;
|
||||
gl.GenVertexArrays(1, ref vao);
|
||||
SetupRenderState(drawData, fbWidth, fbHeight, vao);
|
||||
|
||||
Vector2 clipOff = drawData.DisplayPos;
|
||||
Vector2 clipScale = drawData.FramebufferScale;
|
||||
|
||||
for (int listIdx = 0; listIdx < drawData.CmdListsCount; listIdx++)
|
||||
private static void RendererDestroyWindow(ImGuiViewportPtr viewport)
|
||||
{
|
||||
ImDrawListPtr drawList = drawData.CmdLists[listIdx];
|
||||
Program.Logger.Log(null);
|
||||
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
|
||||
if (vd == null)
|
||||
return;
|
||||
|
||||
int vtxSize = drawList.VtxBuffer.Size * sizeof(ImDrawVert);
|
||||
int idxSize = drawList.IdxBuffer.Size * sizeof(ushort);
|
||||
|
||||
gl.BufferData(GLBufferTargetARB.ArrayBuffer, vtxSize, drawList.VtxBuffer.Data, GLBufferUsageARB.StreamDraw);
|
||||
gl.BufferData(GLBufferTargetARB.ElementArrayBuffer, idxSize, drawList.IdxBuffer.Data, GLBufferUsageARB.StreamDraw);
|
||||
|
||||
for (int cmdIdx = 0; cmdIdx < drawList.CmdBuffer.Size; cmdIdx++)
|
||||
if (vd.RendererOwned && vd.Renderer != nint.Zero)
|
||||
{
|
||||
ImDrawCmd cmd = drawList.CmdBuffer[cmdIdx];
|
||||
|
||||
if (cmd.UserCallback != null)
|
||||
{
|
||||
|
||||
nint cbPtr = (nint)cmd.UserCallback;
|
||||
if (cbPtr == (nint)DelegateStorage.DrawCallbackResetRenderStateDelegate.GetPtrForDelegate())
|
||||
{
|
||||
SetupRenderState(drawData, fbWidth, fbHeight, vao);
|
||||
SDL.DestroyRenderer(vd.Renderer);
|
||||
}
|
||||
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerLinearDelegate.GetPtrForDelegate())
|
||||
{
|
||||
ApplySamplerLinear(bd);
|
||||
|
||||
vd.Renderer = nint.Zero;
|
||||
vd.RendererOwned = false;
|
||||
Program.Logger.Log(null);
|
||||
}
|
||||
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerNearestDelegate.GetPtrForDelegate())
|
||||
|
||||
private static void RendererSetWindowSize(ImGuiViewportPtr viewport, Vector2 size)
|
||||
{
|
||||
ApplySamplerNearest(bd);
|
||||
// SDL renderer windows track size through the platform window callback.
|
||||
Program.Logger.Log(null);
|
||||
}
|
||||
else
|
||||
|
||||
private static void RendererRenderWindow(ImGuiViewportPtr viewport)
|
||||
{
|
||||
ImDrawCmdPtr cmdPtr = new ImDrawCmdPtr { Handle = &cmd };
|
||||
((delegate* unmanaged[Cdecl]<ImDrawListPtr, ImDrawCmdPtr, void>)cmd.UserCallback)(drawList, cmdPtr);
|
||||
Program.Logger.Log(null);
|
||||
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
|
||||
if (vd == null || vd.Renderer == nint.Zero)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
RenderDrawData(viewport.DrawData, vd.Renderer);
|
||||
Program.Logger.Log(null);
|
||||
}
|
||||
|
||||
private static void RendererSwapBuffers(ImGuiViewportPtr viewport)
|
||||
{
|
||||
Program.Logger.Log(null);
|
||||
ImGuiSDL3Platform.ViewPortData? vd = ImGuiUserData<ImGuiSDL3Platform.ViewPortData>.Get(viewport.PlatformUserData);
|
||||
if (vd == null || vd.Renderer == nint.Zero)
|
||||
return;
|
||||
|
||||
SDL.RenderPresent(vd.Renderer);
|
||||
Program.Logger.Log(null);
|
||||
}
|
||||
|
||||
public static void RenderDrawData(ImDrawDataPtr drawData, nint renderer)
|
||||
{
|
||||
// Skip if no data to render
|
||||
if (drawData.NativePtr == null || drawData.CmdListsCount == 0)
|
||||
return;
|
||||
|
||||
SDL.GetRenderScale(renderer, out float renderScaleX, out float renderScaleY);
|
||||
Vector2 renderScale = new Vector2(
|
||||
renderScaleX == 1.0f ? drawData.FramebufferScale.X : 1.0f,
|
||||
renderScaleY == 1.0f ? drawData.FramebufferScale.Y : 1.0f);
|
||||
|
||||
int fbWidth = (int)(drawData.DisplaySize.X * renderScale.X);
|
||||
int fbHeight = (int)(drawData.DisplaySize.Y * renderScale.Y);
|
||||
if (fbWidth <= 0 || fbHeight <= 0)
|
||||
return;
|
||||
|
||||
// Backup SDL renderer state
|
||||
BackupSDLRendererState old = new BackupSDLRendererState
|
||||
{
|
||||
ViewportEnabled = SDL.RenderViewportSet(renderer),
|
||||
ClipEnabled = SDL.RenderClipEnabled(renderer)
|
||||
};
|
||||
SDL.GetRenderViewport(renderer, out var oldViewport);
|
||||
old.Viewport = oldViewport;
|
||||
SDL.GetRenderClipRect(renderer, out var oldClipRect);
|
||||
old.ClipRect = oldClipRect;
|
||||
|
||||
// Set up render state
|
||||
SDL.SetRenderViewport(renderer, 0);
|
||||
SDL.SetRenderClipRect(renderer, nint.Zero);
|
||||
|
||||
// Set render state in platform IO
|
||||
ImGuiPlatformIOPtr platformIo = ImGui.GetPlatformIO();
|
||||
platformIo.Renderer_RenderState = renderer;
|
||||
|
||||
Vector2 clipOffset = drawData.DisplayPos;
|
||||
|
||||
// Render command lists
|
||||
for (int n = 0; n < drawData.CmdListsCount; n++)
|
||||
{
|
||||
ImDrawListPtr cmdList = drawData.CmdLists[n];
|
||||
|
||||
for (int cmdIndex = 0; cmdIndex < cmdList.CmdBuffer.Size; cmdIndex++)
|
||||
{
|
||||
ImDrawCmdPtr cmd = cmdList.CmdBuffer[cmdIndex];
|
||||
|
||||
if (cmd.UserCallback != nint.Zero)
|
||||
{
|
||||
continue; // User callback not implemented
|
||||
}
|
||||
|
||||
// Apply clipping rectangle
|
||||
Vector4 clipRect = cmd.ClipRect;
|
||||
Vector2 clipMin = new Vector2((clipRect.X - clipOffset.X) * renderScale.X, (clipRect.Y - clipOffset.Y) * renderScale.Y);
|
||||
Vector2 clipMax = new Vector2((clipRect.Z - clipOffset.X) * renderScale.X, (clipRect.W - clipOffset.Y) * renderScale.Y);
|
||||
|
||||
clipMin.X = Math.Max(0, clipMin.X);
|
||||
clipMin.Y = Math.Max(0, clipMin.Y);
|
||||
clipMax.X = Math.Min(fbWidth, clipMax.X);
|
||||
clipMax.Y = Math.Min(fbHeight, clipMax.Y);
|
||||
if (clipMax.X <= clipMin.X || clipMax.Y <= clipMin.Y)
|
||||
continue;
|
||||
}
|
||||
|
||||
float clipMinX = (cmd.ClipRect.X - clipOff.X) * clipScale.X;
|
||||
float clipMinY = (cmd.ClipRect.Y - clipOff.Y) * clipScale.Y;
|
||||
float clipMaxX = (cmd.ClipRect.Z - clipOff.X) * clipScale.X;
|
||||
float clipMaxY = (cmd.ClipRect.W - clipOff.Y) * clipScale.Y;
|
||||
if (clipMaxX <= clipMinX || clipMaxY <= clipMinY) continue;
|
||||
|
||||
gl.Scissor((int)clipMinX, fbHeight - (int)clipMaxY, (int)(clipMaxX - clipMinX), (int)(clipMaxY - clipMinY));
|
||||
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, (uint)(nint)cmd.GetTexID());
|
||||
|
||||
if (!bd.HasBindSampler && bd.UseTexParameterToSetSampler)
|
||||
SDL.Rect r = new SDL.Rect
|
||||
{
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, bd.NextSampler);
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, bd.NextSampler);
|
||||
}
|
||||
X = (int)clipMin.X,
|
||||
Y = (int)clipMin.Y,
|
||||
W = (int)(clipMax.X - clipMin.X),
|
||||
H = (int)(clipMax.Y - clipMin.Y)
|
||||
};
|
||||
SDL.SetRenderClipRect(renderer, r);
|
||||
|
||||
if (bd.GlVersion >= 320)
|
||||
// Get texture
|
||||
nint texId = cmd.GetTexID();
|
||||
|
||||
// Convert ImGui vertices to SDL vertices
|
||||
if (!RenderDrawCommand(cmdList, cmd, renderer, texId, renderScale))
|
||||
{
|
||||
gl.DrawElementsBaseVertex(GLPrimitiveType.Triangles, (int)cmd.ElemCount, GLDrawElementsType.UnsignedShort, (void*)(cmd.IdxOffset * sizeof(ushort)), (int)cmd.VtxOffset);
|
||||
Console.WriteLine($"Failed to render ImGui draw command: {SDL.GetError()}");
|
||||
}
|
||||
else
|
||||
}
|
||||
}
|
||||
|
||||
// Reset render state
|
||||
platformIo.Renderer_RenderState = nint.Zero;
|
||||
|
||||
// Restore renderer state
|
||||
SDL.SetRenderViewport(renderer, old.ViewportEnabled ? old.Viewport : new SDL.Rect());
|
||||
SDL.SetRenderClipRect(renderer, old.ClipEnabled ? old.ClipRect : new SDL.Rect());
|
||||
}
|
||||
|
||||
private static bool RenderDrawCommand(ImDrawListPtr drawList, ImDrawCmdPtr cmd, nint renderer, nint texId, Vector2 scale)
|
||||
{
|
||||
gl.DrawElements(GLPrimitiveType.Triangles, (int)cmd.ElemCount, GLDrawElementsType.UnsignedShort, (void*)(cmd.IdxOffset * sizeof(ushort)));
|
||||
}
|
||||
}
|
||||
}
|
||||
uint indexOffset = cmd.IdxOffset;
|
||||
uint vertexOffset = cmd.VtxOffset;
|
||||
uint elemCount = cmd.ElemCount;
|
||||
|
||||
gl.DeleteVertexArray(vao);
|
||||
SDL.Vertex[] vertices = new SDL.Vertex[elemCount];
|
||||
int[] indices = new int[elemCount];
|
||||
|
||||
if (lastProgram == 0 || gl.IsProgram((uint)lastProgram))
|
||||
gl.UseProgram((uint)lastProgram);
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, (uint)lastTexture);
|
||||
if (bd.HasBindSampler) gl.BindSampler(0, (uint)lastSampler);
|
||||
gl.ActiveTexture((GLTextureUnit)lastActiveTexture);
|
||||
gl.BindVertexArray((uint)lastVertexArray);
|
||||
gl.BindBuffer(GLBufferTargetARB.ArrayBuffer, (uint)lastArrayBuffer);
|
||||
gl.BlendEquationSeparate((GLBlendEquationModeEXT)lastBlendEqRgb, (GLBlendEquationModeEXT)lastBlendEqAlpha);
|
||||
gl.BlendFuncSeparate((GLBlendingFactor)lastBlendSrcRgb, (GLBlendingFactor)lastBlendDstRgb, (GLBlendingFactor)lastBlendSrcAlpha, (GLBlendingFactor)lastBlendDstAlpha);
|
||||
|
||||
SetCap(gl, GLEnableCap.Blend, lastBlend);
|
||||
SetCap(gl, GLEnableCap.CullFace, lastCullFace);
|
||||
SetCap(gl, GLEnableCap.DepthTest, lastDepthTest);
|
||||
SetCap(gl, GLEnableCap.StencilTest, lastStencilTest);
|
||||
SetCap(gl, GLEnableCap.ScissorTest, lastScissorTest);
|
||||
if (bd.GlVersion >= 310 && !bd.GlProfileIsES3)
|
||||
SetCap(gl, GLEnableCap.PrimitiveRestart, lastPrimRestart);
|
||||
|
||||
if (bd.HasPolygonMode)
|
||||
for (int i = 0; i < elemCount; i++)
|
||||
{
|
||||
if (bd.GlVersion <= 310 || bd.GlProfileIsCompat)
|
||||
ushort idx = drawList.IdxBuffer[(int)indexOffset + i];
|
||||
int vertIdx = (int)(vertexOffset + idx);
|
||||
|
||||
ImDrawVertPtr srcVert = drawList.VtxBuffer[vertIdx];
|
||||
|
||||
uint col = srcVert.col;
|
||||
|
||||
byte r = (byte)((col >> 0) & 0xFF);
|
||||
byte g = (byte)((col >> 8) & 0xFF);
|
||||
byte b = (byte)((col >> 16) & 0xFF);
|
||||
byte a = (byte)((col >> 24) & 0xFF);
|
||||
|
||||
vertices[i] = new SDL.Vertex()
|
||||
{
|
||||
gl.PolygonMode(GLTriangleFace.Front, (GLPolygonMode)lastPolygonMode[0]);
|
||||
gl.PolygonMode(GLTriangleFace.Back, (GLPolygonMode)lastPolygonMode[1]);
|
||||
}
|
||||
else
|
||||
Position = new SDL.FPoint()
|
||||
{
|
||||
gl.PolygonMode(GLTriangleFace.FrontAndBack, (GLPolygonMode)lastPolygonMode[0]);
|
||||
}
|
||||
}
|
||||
|
||||
gl.Viewport(lastViewport[0], lastViewport[1], lastViewport[2], lastViewport[3]);
|
||||
gl.Scissor(lastScissorBox[0], lastScissorBox[1], lastScissorBox[2], lastScissorBox[3]);
|
||||
}
|
||||
|
||||
|
||||
private static void SetupRenderState(ImDrawDataPtr drawData, int fbWidth, int fbHeight, uint vao)
|
||||
X = srcVert.pos.X * scale.X,
|
||||
Y = srcVert.pos.Y * scale.Y
|
||||
},
|
||||
Color = new SDL.FColor()
|
||||
{
|
||||
RendererData bd = GetRendererData()!;
|
||||
GL gl = bd.Gl;
|
||||
|
||||
gl.Enable(GLEnableCap.Blend);
|
||||
gl.BlendEquation(GLBlendEquationModeEXT.FuncAdd);
|
||||
gl.BlendFuncSeparate(GLBlendingFactor.SrcAlpha, GLBlendingFactor.OneMinusSrcAlpha, GLBlendingFactor.One, GLBlendingFactor.OneMinusSrcAlpha);
|
||||
gl.Disable(GLEnableCap.CullFace);
|
||||
gl.Disable(GLEnableCap.DepthTest);
|
||||
gl.Disable(GLEnableCap.StencilTest);
|
||||
gl.Enable(GLEnableCap.ScissorTest);
|
||||
|
||||
if (bd.GlVersion >= 310 && !bd.GlProfileIsES3)
|
||||
gl.Disable(GLEnableCap.PrimitiveRestart);
|
||||
|
||||
if (bd.HasPolygonMode)
|
||||
gl.PolygonMode(GLTriangleFace.FrontAndBack, GLPolygonMode.Fill);
|
||||
|
||||
gl.Viewport(0, 0, fbWidth, fbHeight);
|
||||
|
||||
float L = drawData.DisplayPos.X;
|
||||
float R = drawData.DisplayPos.X + drawData.DisplaySize.X;
|
||||
float T = drawData.DisplayPos.Y;
|
||||
float B = drawData.DisplayPos.Y + drawData.DisplaySize.Y;
|
||||
|
||||
if (bd.HasClipOrigin)
|
||||
R = r / 255f,
|
||||
G = g / 255f,
|
||||
B = b / 255f,
|
||||
A = a / 255f
|
||||
},
|
||||
TexCoord = new SDL.FPoint()
|
||||
{
|
||||
gl.GetIntegerv(GLGetPName.ClipPlane0, out int clipOrigin);
|
||||
if (clipOrigin == (int)GLEnum.UpperLeft)
|
||||
{
|
||||
(T, B) = (B, T);
|
||||
X = srcVert.uv.X,
|
||||
Y = srcVert.uv.Y
|
||||
}
|
||||
}
|
||||
|
||||
float[] ortho =
|
||||
{
|
||||
2.0f / (R - L), 0.0f, 0.0f, 0.0f,
|
||||
0.0f, 2.0f / (T - B), 0.0f, 0.0f,
|
||||
0.0f, 0.0f, -1.0f, 0.0f,
|
||||
(R + L) / (L - R), (T + B) / (B - T), 0.0f, 1.0f
|
||||
};
|
||||
|
||||
gl.UseProgram(bd.ShaderHandle);
|
||||
gl.Uniform1f(bd.AttribLocationTex, 0);
|
||||
gl.UniformMatrix4fv(bd.AttribLocationProjMtx, 1, false, ortho);
|
||||
|
||||
if (bd.HasBindSampler)
|
||||
gl.BindSampler(0, bd.TexSamplers[0]); // linear
|
||||
|
||||
gl.BindVertexArray(vao);
|
||||
gl.BindBuffer(GLBufferTargetARB.ArrayBuffer, bd.VboHandle);
|
||||
gl.BindBuffer(GLBufferTargetARB.ElementArrayBuffer, bd.ElementsHandle);
|
||||
|
||||
gl.EnableVertexAttribArray(bd.AttribLocationVtxPos);
|
||||
gl.VertexAttribPointer(bd.AttribLocationVtxPos, 2, GLVertexAttribPointerType.Float, false, sizeof(ImDrawVert), (void*)0);
|
||||
|
||||
gl.EnableVertexAttribArray(bd.AttribLocationVtxUV);
|
||||
gl.VertexAttribPointer(bd.AttribLocationVtxUV, 2, GLVertexAttribPointerType.Float, false, sizeof(ImDrawVert), (void*)8);
|
||||
|
||||
gl.EnableVertexAttribArray(bd.AttribLocationVtxColor);
|
||||
gl.VertexAttribPointer(bd.AttribLocationVtxColor, 4, GLVertexAttribPointerType.UnsignedByte, true, sizeof(ImDrawVert), (void*)16);
|
||||
indices[i] = i;
|
||||
}
|
||||
|
||||
|
||||
public static void UpdateTexture(ImTextureDataPtr tex)
|
||||
{
|
||||
RendererData bd = GetRendererData()!;
|
||||
GL gl = bd.Gl;
|
||||
|
||||
if (tex.Status == ImTextureStatus.WantDestroy)
|
||||
{
|
||||
if (tex.TexID != ImTextureID.Null)
|
||||
{
|
||||
uint glId = (uint)(nint)tex.TexID;
|
||||
gl.DeleteTexture(glId);
|
||||
return SDL.RenderGeometry(renderer, texId, vertices, vertices.Length, indices, indices.Length);
|
||||
}
|
||||
tex.SetTexID(ImTextureID.Null);
|
||||
tex.SetStatus(ImTextureStatus.Destroyed);
|
||||
|
||||
public static void CreateDeviceObjects()
|
||||
{
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
var data = Data;
|
||||
|
||||
io.Fonts.AddFontDefault();
|
||||
|
||||
// TODO: Load custom fonts from "Fonts" directory
|
||||
//string fontsPath = Path.Combine(Plugin.AssemblyDirectory, "Fonts");
|
||||
//if (Path.Exists(fontsPath))
|
||||
//{
|
||||
// string[] fonts = Directory.GetFiles(fontsPath, "*.ttf");
|
||||
// if (fonts.Length > 0)
|
||||
// {
|
||||
// foreach (string font in fonts)
|
||||
// {
|
||||
// io.Fonts.AddFontFromFileTTF(font, 20f);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
|
||||
// Build texture atlas
|
||||
io.Fonts.GetTexDataAsRGBA32(out byte* pixels, out int width, out int height);
|
||||
|
||||
// Create surface from pixel data
|
||||
nint surface = SDL.CreateSurfaceFrom(width, height, SDL.PixelFormat.RGBA8888, (nint)pixels, width * 4);
|
||||
if (surface == nint.Zero)
|
||||
{
|
||||
SDL.LogError(SDL.LogCategory.Application, $"Failed to create font surface: {SDL.GetError()}");
|
||||
return;
|
||||
}
|
||||
|
||||
gl.PixelStoref(GLPixelStoreParameter.UnpackRowLength, 0);
|
||||
gl.PixelStoref(GLPixelStoreParameter.UnpackAlignment, 1);
|
||||
|
||||
if (tex.Status == ImTextureStatus.WantCreate)
|
||||
// Create texture
|
||||
_fontTexture = SDL.CreateTextureFromSurface(data.Renderer, surface);
|
||||
if (_fontTexture == nint.Zero)
|
||||
{
|
||||
Debug.Assert(tex.Format == ImTextureFormat.Rgba32);
|
||||
|
||||
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int lastTex);
|
||||
uint glTexId = 0;
|
||||
gl.GenTextures(1, ref glTexId);
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, glTexId);
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, (int)GLEnum.Linear);
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, (int)GLEnum.Linear);
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.WrapS, (int)GLEnum.ClampToEdge);
|
||||
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.WrapT, (int)GLEnum.ClampToEdge);
|
||||
gl.TexImage2D(GLTextureTarget.Texture2D, 0, GLInternalFormat.Rgba, tex.Width, tex.Height, 0, GLPixelFormat.Rgba, GLPixelType.UnsignedByte, tex.GetPixels());
|
||||
|
||||
tex.SetTexID((nint)glTexId);
|
||||
tex.SetStatus(ImTextureStatus.Ok);
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, (uint)lastTex);
|
||||
SDL.LogError(SDL.LogCategory.Application, $"Failed to create font texture: {SDL.GetError()}");
|
||||
return;
|
||||
}
|
||||
|
||||
if (tex.Status == ImTextureStatus.WantUpdates)
|
||||
// Update texture directly without converting pixel format
|
||||
if (!SDL.UpdateTexture(_fontTexture, nint.Zero, (nint)pixels, width * 4))
|
||||
{
|
||||
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int lastTex);
|
||||
uint glTexId = (uint)(nint)tex.TexID;
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, glTexId);
|
||||
|
||||
for (int i = 0; i < tex.Updates.Size; i++)
|
||||
{
|
||||
ImTextureRect r = tex.Updates[i];
|
||||
gl.PixelStoref(GLPixelStoreParameter.UnpackRowLength, tex.Width);
|
||||
gl.TexSubImage2D(GLTextureTarget.Texture2D, 0, r.X, r.Y, r.W, r.H, GLPixelFormat.Rgba, GLPixelType.UnsignedByte, tex.GetPixelsAt(r.X, r.Y));
|
||||
}
|
||||
gl.PixelStoref(GLPixelStoreParameter.UnpackRowLength, 0);
|
||||
|
||||
tex.SetStatus(ImTextureStatus.Ok);
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, (uint)lastTex);
|
||||
}
|
||||
SDL.LogError(SDL.LogCategory.Application, $"Failed to update font texture: {SDL.GetError()}");
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure proper blending for font rendering
|
||||
SDL.SetTextureBlendMode(_fontTexture, SDL.BlendMode.Blend);
|
||||
|
||||
public static bool CreateDeviceObjects()
|
||||
{
|
||||
RendererData bd = GetRendererData()!;
|
||||
GL gl = bd.Gl;
|
||||
// Use nearest neighbor filtering for crisp font rendering at small sizes
|
||||
SDL.SetTextureScaleMode(_fontTexture, SDL.ScaleMode.Linear);
|
||||
|
||||
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int lastTexture);
|
||||
gl.GetIntegerv(GLGetPName.ArrayBufferBinding, out int lastArrayBuffer);
|
||||
gl.GetIntegerv(GLGetPName.VertexArrayBinding, out int lastVertexArray);
|
||||
// Store our identifier
|
||||
io.Fonts.SetTexID(_fontTexture);
|
||||
|
||||
int glslVersion = 130;
|
||||
{
|
||||
string vstr = bd.GlslVersionString.TrimStart().TrimStart('#');
|
||||
if (vstr.StartsWith("version "))
|
||||
int.TryParse(vstr["version ".Length..].Split(' ')[0], out glslVersion);
|
||||
}
|
||||
|
||||
const string vertSrc120 = "uniform mat4 ProjMtx;\n" + "attribute vec2 Position;\n" + "attribute vec2 UV;\n" + "attribute vec4 Color;\n" + "varying vec2 Frag_UV;\n" + "varying vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n";
|
||||
const string fragSrc120 = "#ifdef GL_ES\n precision mediump float;\n#endif\n" + "uniform sampler2D Texture;\n" + "varying vec2 Frag_UV;\n" + "varying vec4 Frag_Color;\n" + "void main() {\n" + " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" + "}\n";
|
||||
const string vertSrc130 = "uniform mat4 ProjMtx;\n" + "in vec2 Position;\nin vec2 UV;\nin vec4 Color;\n" + "out vec2 Frag_UV;\nout vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n";
|
||||
const string fragSrc130 = "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\nin vec4 Frag_Color;\n" + "out vec4 Out_Color;\n" + "void main() {\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n";
|
||||
const string vertSrc300es = "precision highp float;\n" + "layout (location = 0) in vec2 Position;\n" + "layout (location = 1) in vec2 UV;\n" + "layout (location = 2) in vec4 Color;\n" + "uniform mat4 ProjMtx;\n" + "out vec2 Frag_UV;\nout vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n";
|
||||
const string fragSrc300es = "precision mediump float;\n" + "uniform sampler2D Texture;\n" + "in vec2 Frag_UV;\nin vec4 Frag_Color;\n" + "layout (location = 0) out vec4 Out_Color;\n" + "void main() {\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n";
|
||||
const string vertSrc410 = "layout (location = 0) in vec2 Position;\n" + "layout (location = 1) in vec2 UV;\n" + "layout (location = 2) in vec4 Color;\n" + "uniform mat4 ProjMtx;\n" + "out vec2 Frag_UV;\nout vec4 Frag_Color;\n" + "void main() {\n" + " Frag_UV = UV;\n" + " Frag_Color = Color;\n" + " gl_Position = ProjMtx * vec4(Position.xy, 0, 1);\n" + "}\n";
|
||||
const string fragSrc410 = "in vec2 Frag_UV;\nin vec4 Frag_Color;\n" + "uniform sampler2D Texture;\n" + "layout (location = 0) out vec4 Out_Color;\n" + "void main() {\n" + " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" + "}\n";
|
||||
|
||||
(string vertSrc, string fragSrc) = glslVersion switch
|
||||
{
|
||||
< 130 => (vertSrc120, fragSrc120),
|
||||
300 => (vertSrc300es, fragSrc300es),
|
||||
>= 410 => (vertSrc410, fragSrc410),
|
||||
_ => (vertSrc130, fragSrc130)
|
||||
};
|
||||
|
||||
string fullVert = bd.GlslVersionString + vertSrc;
|
||||
string fullFrag = bd.GlslVersionString + fragSrc;
|
||||
|
||||
uint vert = gl.CreateShader(GLShaderType.VertexShader);
|
||||
gl.ShaderSource(vert, fullVert);
|
||||
gl.CompileShader(vert);
|
||||
if (!CheckShader(gl, vert, "vertex shader")) return false;
|
||||
|
||||
uint frag = gl.CreateShader(GLShaderType.FragmentShader);
|
||||
gl.ShaderSource(frag, fullFrag);
|
||||
gl.CompileShader(frag);
|
||||
if (!CheckShader(gl, frag, "fragment shader")) return false;
|
||||
|
||||
bd.ShaderHandle = gl.CreateProgram();
|
||||
gl.AttachShader(bd.ShaderHandle, vert);
|
||||
gl.AttachShader(bd.ShaderHandle, frag);
|
||||
gl.LinkProgram(bd.ShaderHandle);
|
||||
if (!CheckProgram(gl, bd.ShaderHandle, "shader program")) return false;
|
||||
|
||||
gl.DetachShader(bd.ShaderHandle, vert);
|
||||
gl.DetachShader(bd.ShaderHandle, frag);
|
||||
gl.DeleteShader(vert);
|
||||
gl.DeleteShader(frag);
|
||||
|
||||
bd.AttribLocationTex = gl.GetUniformLocation(bd.ShaderHandle, "Texture");
|
||||
bd.AttribLocationProjMtx = gl.GetUniformLocation(bd.ShaderHandle, "ProjMtx");
|
||||
bd.AttribLocationVtxPos = (uint)gl.GetAttribLocation(bd.ShaderHandle, "Position");
|
||||
bd.AttribLocationVtxUV = (uint)gl.GetAttribLocation(bd.ShaderHandle, "UV");
|
||||
bd.AttribLocationVtxColor = (uint)gl.GetAttribLocation(bd.ShaderHandle, "Color");
|
||||
|
||||
gl.GenBuffers(1, ref bd.VboHandle);
|
||||
gl.GenBuffers(1, ref bd.ElementsHandle);
|
||||
|
||||
if (bd.HasBindSampler)
|
||||
{
|
||||
gl.GenSamplers(2, bd.TexSamplers);
|
||||
for (int i = 0; i < 2; i++)
|
||||
{
|
||||
int filter = i == 0 ? (int)GLEnum.Linear : (int)GLEnum.Nearest;
|
||||
gl.SamplerParameteri(bd.TexSamplers[i], GLSamplerParameterI.TextureMinFilter, filter);
|
||||
gl.SamplerParameteri(bd.TexSamplers[i], GLSamplerParameterI.TextureMagFilter, filter);
|
||||
gl.SamplerParameteri(bd.TexSamplers[i], GLSamplerParameterI.TextureWrapS, (int)GLEnum.ClampToEdge);
|
||||
gl.SamplerParameteri(bd.TexSamplers[i], GLSamplerParameterI.TextureWrapT, (int)GLEnum.ClampToEdge);
|
||||
}
|
||||
}
|
||||
|
||||
gl.BindTexture(GLTextureTarget.Texture2D, (uint)lastTexture);
|
||||
gl.BindBuffer(GLBufferTargetARB.ArrayBuffer, (uint)lastArrayBuffer);
|
||||
gl.BindVertexArray((uint)lastVertexArray);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void DestroyDeviceObjects()
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
if (bd == null) return;
|
||||
GL gl = bd.Gl;
|
||||
|
||||
if (bd.HasBindSampler && bd.TexSamplers[0] != 0)
|
||||
{
|
||||
gl.DeleteSamplers(2, bd.TexSamplers);
|
||||
bd.TexSamplers[0] = bd.TexSamplers[1] = 0;
|
||||
}
|
||||
|
||||
if (bd.VboHandle != 0)
|
||||
{
|
||||
gl.DeleteBuffer(bd.VboHandle);
|
||||
bd.VboHandle = 0;
|
||||
}
|
||||
if (bd.ElementsHandle != 0)
|
||||
{
|
||||
gl.DeleteBuffer(bd.ElementsHandle);
|
||||
bd.ElementsHandle = 0;
|
||||
}
|
||||
if (bd.ShaderHandle != 0)
|
||||
{
|
||||
gl.DeleteProgram(bd.ShaderHandle);
|
||||
bd.ShaderHandle = 0;
|
||||
}
|
||||
|
||||
ImVector<ImTextureDataPtr> textures = ImGui.GetPlatformIO().Textures;
|
||||
for (int i = 0; i < textures.Size; i++)
|
||||
{
|
||||
ImTextureDataPtr tex = textures[i];
|
||||
if (tex.RefCount == 1)
|
||||
{
|
||||
tex.SetStatus(ImTextureStatus.WantDestroy);
|
||||
UpdateTexture(tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static void InitMultiViewportSupport()
|
||||
{
|
||||
ImGuiPlatformIOPtr platformIO = ImGui.GetPlatformIO();
|
||||
platformIO.RendererRenderWindow = DelegateStorage.RendererRenderWindowDelegate.GetPtrForDelegate();
|
||||
}
|
||||
|
||||
private static void ShutdownMultiViewportSupport()
|
||||
{
|
||||
ImGui.DestroyPlatformWindows();
|
||||
}
|
||||
|
||||
private static void ApplySamplerLinear(RendererData bd)
|
||||
{
|
||||
if (bd.HasBindSampler)
|
||||
{
|
||||
bd.Gl.BindSampler(0, bd.TexSamplers[0]);
|
||||
}
|
||||
else
|
||||
{
|
||||
bd.UseTexParameterToSetSampler = true;
|
||||
bd.NextSampler = (int)GLEnum.Linear;
|
||||
}
|
||||
}
|
||||
|
||||
private static void ApplySamplerNearest(RendererData bd)
|
||||
{
|
||||
if (bd.HasBindSampler)
|
||||
{
|
||||
bd.Gl.BindSampler(0, bd.TexSamplers[1]);
|
||||
}
|
||||
else
|
||||
{
|
||||
bd.UseTexParameterToSetSampler = true;
|
||||
bd.NextSampler = (int)GLEnum.Nearest;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static bool CheckShader(GL gl, uint handle, string desc)
|
||||
{
|
||||
gl.GetShaderiv(handle, GLShaderParameterName.CompileStatus, out int status);
|
||||
gl.GetShaderiv(handle, GLShaderParameterName.InfoLogLength, out int logLen);
|
||||
if (status == 0)
|
||||
{
|
||||
string log = logLen > 1 ? gl.GetShaderInfoLog(handle) : "";
|
||||
Console.Error.WriteLine($"[ImGui OpenGL3] Failed to compile {desc}:\n{log}");
|
||||
}
|
||||
return status != 0;
|
||||
}
|
||||
|
||||
private static bool CheckProgram(GL gl, uint handle, string desc)
|
||||
{
|
||||
gl.GetProgramiv(handle, GLProgramPropertyARB.LinkStatus, out int status);
|
||||
gl.GetProgramiv(handle, GLProgramPropertyARB.InfoLogLength, out int logLen);
|
||||
if (status == 0)
|
||||
{
|
||||
string log = logLen > 1 ? gl.GetProgramInfoLog(handle) : "";
|
||||
Console.Error.WriteLine($"[ImGui OpenGL3] Failed to link {desc}:\n{log}");
|
||||
}
|
||||
return status != 0;
|
||||
}
|
||||
|
||||
|
||||
private static void SetCap(GL gl, GLEnableCap cap, bool enabled)
|
||||
{
|
||||
if (enabled) gl.Enable(cap);
|
||||
else gl.Disable(cap);
|
||||
}
|
||||
|
||||
|
||||
public static class DelegateStorage
|
||||
{
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void DrawCallbackFn(ImDrawListPtr drawList, ImDrawCmdPtr cmd);
|
||||
|
||||
internal static readonly DrawCallbackFn DrawCallbackResetRenderStateDelegate = DrawCallbackResetRenderState;
|
||||
private static void DrawCallbackResetRenderState(ImDrawListPtr _, ImDrawCmdPtr __) { } // Intentionally empty.
|
||||
|
||||
internal static readonly DrawCallbackFn DrawCallbackSetSamplerLinearDelegate = DrawCallbackSetSamplerLinear;
|
||||
private static void DrawCallbackSetSamplerLinear(ImDrawListPtr _, ImDrawCmdPtr __)
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
if (bd != null) ApplySamplerLinear(bd);
|
||||
}
|
||||
|
||||
internal static readonly DrawCallbackFn DrawCallbackSetSamplerNearestDelegate = DrawCallbackSetSamplerNearest;
|
||||
private static void DrawCallbackSetSamplerNearest(ImDrawListPtr _, ImDrawCmdPtr __)
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
if (bd != null) ApplySamplerNearest(bd);
|
||||
}
|
||||
|
||||
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
|
||||
internal delegate void RendererRenderWindowFn(ImGuiViewportPtr viewport, void* renderArg);
|
||||
|
||||
internal static readonly RendererRenderWindowFn RendererRenderWindowDelegate = RendererRenderWindow;
|
||||
private static void RendererRenderWindow(ImGuiViewportPtr viewport, void* renderArg)
|
||||
{
|
||||
if ((viewport.Flags & ImGuiViewportFlags.NoRendererClear) == 0)
|
||||
{
|
||||
RendererData? bd = GetRendererData();
|
||||
if (bd != null)
|
||||
{
|
||||
bd.Gl.ClearColor(0f, 0f, 0f, 1f);
|
||||
bd.Gl.Clear(GLClearBufferMask.ColorBufferBit);
|
||||
}
|
||||
}
|
||||
RenderDrawData(viewport.DrawData);
|
||||
}
|
||||
SDL.DestroySurface(surface);
|
||||
io.Fonts.ClearTexData();
|
||||
}
|
||||
|
||||
public static void DestroyDeviceObjects() { }
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace SDL3_TestingSuite.SDL3;
|
||||
|
||||
public unsafe static class ImGuiUserData<T> where T : class
|
||||
{
|
||||
public static void* Store(T value)
|
||||
{
|
||||
if (value == null)
|
||||
return null;
|
||||
|
||||
GCHandle handle = GCHandle.Alloc(value, GCHandleType.Normal);
|
||||
return (void*)GCHandle.ToIntPtr(handle);
|
||||
}
|
||||
|
||||
public static T? Get(void* ptr)
|
||||
{
|
||||
if (ptr == null)
|
||||
return null;
|
||||
|
||||
GCHandle handle = GCHandle.FromIntPtr((nint)ptr);
|
||||
return (T?)handle.Target;
|
||||
}
|
||||
|
||||
public static void Free(void* ptr)
|
||||
{
|
||||
if (ptr == null)
|
||||
return;
|
||||
|
||||
GCHandle handle = GCHandle.FromIntPtr((nint)ptr);
|
||||
|
||||
if (handle.IsAllocated)
|
||||
handle.Free();
|
||||
}
|
||||
}
|
||||
@@ -1,182 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
+67
-253
@@ -1,174 +1,92 @@
|
||||
using System.Numerics;
|
||||
using Hexa.NET.ImGui;
|
||||
using Hexa.NET.ImGuizmo;
|
||||
using Hexa.NET.ImPlot;
|
||||
using Hexa.NET.ImNodes;
|
||||
using Hexa.NET.OpenGL;
|
||||
using HexaGen.Runtime;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Runtime.InteropServices;
|
||||
using ImGuiNET;
|
||||
using SDL3;
|
||||
|
||||
namespace SDL3_TestingSuite.SDL3;
|
||||
|
||||
public sealed unsafe class SDL3Window : IDisposable
|
||||
public sealed class SDL3Window : IDisposable
|
||||
{
|
||||
public readonly nint Window;
|
||||
public readonly nint Renderer;
|
||||
|
||||
public readonly Vector4 DefaultClearColor = new Vector4(0.06f, 0.06f, 0.06f, 1f);
|
||||
internal Action? RenderCallback { get; set; }
|
||||
|
||||
private Vector4? _clearColor;
|
||||
public Vector4 ClearColor
|
||||
{
|
||||
get => _clearColor ?? DefaultClearColor;
|
||||
set => _clearColor = value;
|
||||
}
|
||||
public Vector4 ClearColor = new Vector4(0.06f, 0.05882353f, 0.05882353f, 1f);
|
||||
|
||||
public event Action? RenderCallback;
|
||||
public event Action? Disposing;
|
||||
public event Action<Vector4>? Resized;
|
||||
public event Action<SDL.Event>? EventCallback;
|
||||
private readonly Stopwatch _timer = Stopwatch.StartNew();
|
||||
private TimeSpan _time = TimeSpan.Zero;
|
||||
|
||||
private ImGuiContextPtr _imGuiContext;
|
||||
private ImPlotContextPtr _imPlotContext;
|
||||
private ImNodesContextPtr _imNodesContext;
|
||||
// private ImPLot3DContextPtr _imPlot3DContext;
|
||||
private SDL.Rect _screenClipRect;
|
||||
private nint _imGuiContext;
|
||||
|
||||
public bool Disposed => _disposed;
|
||||
private bool _disposed;
|
||||
|
||||
private readonly FileSystemWatcher? _watcher;
|
||||
|
||||
public readonly GL GL;
|
||||
private FileSystemWatcher? _watcher;
|
||||
|
||||
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))
|
||||
throw new Exception($"SDL_Init failed: {SDL.GetError()}");
|
||||
|
||||
SDL.GLSetAttribute(SDL.GLAttr.ContextFlags, (int)SDL.GLContextFlag.ForwardCompatible);
|
||||
SDL.GLSetAttribute(SDL.GLAttr.ContextProfileMask, (int)SDL.GLProfile.Core);
|
||||
SDL.GLSetAttribute(SDL.GLAttr.ContextMajorVersion, 4);
|
||||
SDL.GLSetAttribute(SDL.GLAttr.ContextMinorVersion, 6);
|
||||
|
||||
SDL.SetHint(SDL.Hints.IMEImplementedUI, "1");
|
||||
|
||||
// Create window & renderer
|
||||
SDL.GLSetAttribute(SDL.GLAttr.DoubleBuffer, 1);
|
||||
SDL.GLSetAttribute(SDL.GLAttr.DepthSize, 24);
|
||||
SDL.GLSetAttribute(SDL.GLAttr.StencilSize, 8);
|
||||
Window = SDL.CreateWindow(name, width, height, flags | SDL.WindowFlags.OpenGL);
|
||||
if (Window == nint.Zero)
|
||||
if (!SDL.CreateWindowAndRenderer(name, width, height, flags, out Window, out Renderer))
|
||||
throw new Exception($"SDL_CreateWindowAndRenderer failed: {SDL.GetError()}");
|
||||
|
||||
nint glContext = SDL.GLCreateContext(Window);
|
||||
if (glContext == nint.Zero)
|
||||
throw new Exception($"SDL_GL_CreateContext failed: {SDL.GetError()}");
|
||||
|
||||
SDL.GLMakeCurrent(Window, glContext);
|
||||
SDL.GLSetSwapInterval(1);
|
||||
|
||||
SDL.SetWindowPosition(Window, posX, posY);
|
||||
// SDL.SetRenderVSync(Renderer, 1);
|
||||
SDL.SetRenderVSync(Renderer, 1);
|
||||
SDL.ShowWindow(Window);
|
||||
|
||||
// Create ImGui context
|
||||
_imGuiContext = ImGui.CreateContext();
|
||||
_imPlotContext = ImPlot.CreateContext();
|
||||
_imNodesContext = ImNodes.CreateContext();
|
||||
// _imPlot3DContext = ImPlot3D.CreateContext();
|
||||
ImPlot.SetImGuiContext(_imGuiContext);
|
||||
ImGuizmo.SetImGuiContext(_imGuiContext);
|
||||
ImNodes.SetImGuiContext(_imGuiContext);
|
||||
// ImPlot3D.SetImGuiContext(_imGuiContext);
|
||||
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
io.ConfigFlags |= ImGuiConfigFlags.NavEnableKeyboard | ImGuiConfigFlags.NavEnableGamepad | ImGuiConfigFlags.DockingEnable;
|
||||
io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
|
||||
|
||||
// io.ConfigFlags |= ImGuiConfigFlags.ViewportsEnable;
|
||||
io.Fonts.Flags |= ImFontAtlasFlags.NoBakedLines;
|
||||
io.Fonts.AddFontDefault();
|
||||
|
||||
try
|
||||
{
|
||||
string fontsPath = Path.Combine(AppContext.BaseDirectory, "Fonts");
|
||||
if (!Path.Exists(fontsPath)) Directory.CreateDirectory(fontsPath);
|
||||
|
||||
_watcher = new FileSystemWatcher(fontsPath);
|
||||
_watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.CreationTime;
|
||||
_watcher.Created += (_, b) =>
|
||||
{
|
||||
if (!File.Exists(b.FullPath)) return;
|
||||
|
||||
if (Path.GetExtension(b.FullPath) != ".ttf") return;
|
||||
ImGui.GetIO().AddFont(b.FullPath);
|
||||
};
|
||||
_watcher.Deleted += (_, b) =>
|
||||
{
|
||||
if (Path.GetExtension(b.FullPath) != ".ttf") return;
|
||||
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.EnableRaisingEvents = true;
|
||||
|
||||
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)
|
||||
{
|
||||
io.AddFont(font);
|
||||
foreach (string merge in mergeFonts)
|
||||
{
|
||||
io.AddFont(merge, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(e);
|
||||
}
|
||||
|
||||
GL = new GL(new BindingsContext(Window, glContext));
|
||||
|
||||
// Init platform and renderer
|
||||
ImGuiSDL3Platform.Init(GL, Window, glContext);
|
||||
ImGuiSDL3Renderer.Init(GL, "#version 330");
|
||||
ImGuiSDL3Platform.Init(Window, Renderer);
|
||||
ImGuiSDL3Renderer.Init(Renderer);
|
||||
}
|
||||
|
||||
public bool ShouldClose;
|
||||
|
||||
public void Run()
|
||||
{
|
||||
while (!_disposed)
|
||||
{
|
||||
SDL.PumpEvents();
|
||||
ImGui.GetIO().DeltaTime = (float)(_timer.Elapsed - _time).TotalSeconds;
|
||||
_time = _timer.Elapsed;
|
||||
|
||||
PollEvents();
|
||||
|
||||
Update();
|
||||
|
||||
RenderCallback?.Invoke();
|
||||
|
||||
Render();
|
||||
|
||||
if (ShouldClose)
|
||||
{
|
||||
Dispose();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_disposed)
|
||||
Dispose();
|
||||
}
|
||||
|
||||
public bool ShouldClose;
|
||||
|
||||
private void PollEvents()
|
||||
{
|
||||
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))
|
||||
{
|
||||
@@ -181,40 +99,26 @@ public sealed unsafe class SDL3Window : IDisposable
|
||||
case SDL.EventType.Quit:
|
||||
ShouldClose = true;
|
||||
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))
|
||||
private void Update()
|
||||
{
|
||||
SDL.Delay(10);
|
||||
continue;
|
||||
}
|
||||
|
||||
GL.MakeCurrent();
|
||||
GL.ClearColor(ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
|
||||
GL.Clear(GLClearBufferMask.ColorBufferBit);
|
||||
|
||||
ImGuiSDL3Platform.NewFrame();
|
||||
ImGuiSDL3Renderer.NewFrame();
|
||||
ImGui.NewFrame();
|
||||
}
|
||||
|
||||
RenderCallback?.Invoke();
|
||||
|
||||
private void Render()
|
||||
{
|
||||
ImGuiIOPtr io = ImGui.GetIO();
|
||||
|
||||
ImGui.Render();
|
||||
|
||||
GL.MakeCurrent();
|
||||
|
||||
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData());
|
||||
SDL.SetRenderScale(Renderer, io.DisplayFramebufferScale.X, io.DisplayFramebufferScale.Y);
|
||||
SDL.SetRenderDrawColorFloat(Renderer, ClearColor.X, ClearColor.Y, ClearColor.Z, ClearColor.W);
|
||||
SDL.RenderClear(Renderer);
|
||||
ImGuiSDL3Renderer.RenderDrawData(ImGui.GetDrawData(), Renderer);
|
||||
|
||||
if ((io.ConfigFlags & ImGuiConfigFlags.ViewportsEnable) != 0)
|
||||
{
|
||||
@@ -222,18 +126,7 @@ public sealed unsafe class SDL3Window : IDisposable
|
||||
ImGui.RenderPlatformWindowsDefault();
|
||||
}
|
||||
|
||||
GL.MakeCurrent();
|
||||
GL.SwapBuffers();
|
||||
|
||||
if (ShouldClose)
|
||||
{
|
||||
Dispose();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_disposed)
|
||||
Dispose();
|
||||
SDL.RenderPresent(Renderer);
|
||||
}
|
||||
|
||||
~SDL3Window()
|
||||
@@ -254,53 +147,23 @@ public sealed unsafe class SDL3Window : IDisposable
|
||||
|
||||
if (disposing)
|
||||
{
|
||||
if (_imGuiContext.Handle != null)
|
||||
{
|
||||
ImGui.SetCurrentContext(_imGuiContext);
|
||||
}
|
||||
if (_imPlotContext.Handle != null)
|
||||
{
|
||||
ImPlot.SetCurrentContext(_imPlotContext);
|
||||
}
|
||||
|
||||
Disposing?.Invoke();
|
||||
|
||||
ImGuiSDL3Renderer.Dispose();
|
||||
ImGuiSDL3Platform.Dispose();
|
||||
|
||||
RenderCallback = null;
|
||||
Disposing = null;
|
||||
}
|
||||
|
||||
if (_imGuiContext.Handle != null)
|
||||
if (_imGuiContext != nint.Zero)
|
||||
{
|
||||
ImGui.SetCurrentContext(null);
|
||||
ImGui.SetCurrentContext(nint.Zero);
|
||||
ImGui.DestroyContext(_imGuiContext);
|
||||
_imGuiContext = null;
|
||||
_imGuiContext = nint.Zero;
|
||||
}
|
||||
if (_imPlotContext.Handle != null)
|
||||
{
|
||||
ImPlot.SetCurrentContext(null);
|
||||
ImPlot.DestroyContext(_imPlotContext);
|
||||
_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)
|
||||
// {
|
||||
// SDL.DestroyRenderer(Renderer);
|
||||
// }
|
||||
if (Renderer != nint.Zero)
|
||||
{
|
||||
SDL.DestroyRenderer(Renderer);
|
||||
}
|
||||
|
||||
if (Window != nint.Zero)
|
||||
{
|
||||
@@ -309,52 +172,3 @@ public sealed unsafe class SDL3Window : IDisposable
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public unsafe class BindingsContext : IGLContext
|
||||
{
|
||||
private readonly nint window;
|
||||
private readonly nint context;
|
||||
|
||||
public BindingsContext(nint window, nint context)
|
||||
{
|
||||
this.window = window;
|
||||
this.context = context;
|
||||
}
|
||||
|
||||
public nint Handle => window;
|
||||
|
||||
public bool IsCurrent => SDL.GLGetCurrentContext() == context;
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
public nint GetProcAddress(string procName)
|
||||
{
|
||||
return (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate();
|
||||
}
|
||||
|
||||
public bool IsExtensionSupported(string extensionName)
|
||||
{
|
||||
return SDL.GLExtensionSupported(extensionName);
|
||||
}
|
||||
|
||||
public void MakeCurrent()
|
||||
{
|
||||
SDL.GLMakeCurrent(window, context);
|
||||
}
|
||||
|
||||
public void SwapBuffers()
|
||||
{
|
||||
SDL.GLSwapWindow(window);
|
||||
}
|
||||
|
||||
public void SwapInterval(int interval)
|
||||
{
|
||||
SDL.GLSetSwapInterval(interval);
|
||||
}
|
||||
|
||||
public bool TryGetProcAddress(string procName, out nint procAddress)
|
||||
{
|
||||
procAddress = (nint)SDL.GLGetProcAddress(procName).GetPtrForDelegate();
|
||||
return procAddress != 0;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user