674 lines
29 KiB
C#
674 lines
29 KiB
C#
using System.Diagnostics;
|
|
using System.Numerics;
|
|
using System.Runtime.InteropServices;
|
|
using Hexa.NET.ImGui;
|
|
using Hexa.NET.OpenGL;
|
|
|
|
namespace SDL3_TestingSuite.SDL3;
|
|
|
|
public unsafe static class ImGuiSDL3Renderer
|
|
{
|
|
public class RendererData
|
|
{
|
|
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
|
|
|
|
public GL Gl = 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)
|
|
{
|
|
ImGuiIOPtr io = ImGui.GetIO();
|
|
Debug.Assert(io.BackendRendererUserData == null, "Already initialised a renderer backend!");
|
|
|
|
RendererData bd = new RendererData { Gl = gl };
|
|
io.BackendRendererUserData = ImGuiUserData<RendererData>.Store(bd);
|
|
io.BackendRendererName = (byte*)Marshal.StringToHGlobalAnsi("imgui_impl_opengl3_cs");
|
|
|
|
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
|
|
|
|
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();
|
|
|
|
return true;
|
|
}
|
|
|
|
public static void Dispose()
|
|
{
|
|
RendererData? bd = GetRendererData();
|
|
Debug.Assert(bd != null, "No renderer backend to shut down, or already shut down?");
|
|
|
|
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);
|
|
|
|
}
|
|
|
|
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)
|
|
{
|
|
bool ok = CreateDeviceObjects();
|
|
Debug.Assert(ok, "ImGuiOpenGL3Renderer.CreateDeviceObjects() failed!");
|
|
}
|
|
}
|
|
|
|
public static void RenderDrawData(ImDrawDataPtr drawData)
|
|
{
|
|
if (drawData.Handle == null) 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)
|
|
{
|
|
for (int i = 0; i < drawData.Textures.Size; i++)
|
|
{
|
|
ImTextureDataPtr tex = drawData.Textures[i];
|
|
if (tex.Status != ImTextureStatus.Ok)
|
|
UpdateTexture(tex);
|
|
}
|
|
}
|
|
|
|
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++)
|
|
{
|
|
ImDrawListPtr drawList = drawData.CmdLists[listIdx];
|
|
|
|
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++)
|
|
{
|
|
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);
|
|
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerLinearDelegate.GetPtrForDelegate())
|
|
ApplySamplerLinear(bd);
|
|
else if (cbPtr == (nint)DelegateStorage.DrawCallbackSetSamplerNearestDelegate.GetPtrForDelegate())
|
|
ApplySamplerNearest(bd);
|
|
else
|
|
{
|
|
ImDrawCmdPtr cmdPtr = new ImDrawCmdPtr { Handle = &cmd };
|
|
((delegate* unmanaged[Cdecl]<ImDrawListPtr, ImDrawCmdPtr, void>)cmd.UserCallback)(drawList, cmdPtr);
|
|
}
|
|
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)
|
|
{
|
|
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MinFilter, bd.NextSampler);
|
|
gl.TexParameterf(GLTextureTarget.Texture2D, GLTextureParameterName.MagFilter, bd.NextSampler);
|
|
}
|
|
|
|
if (bd.GlVersion >= 320)
|
|
{
|
|
gl.DrawElementsBaseVertex(GLPrimitiveType.Triangles, (int)cmd.ElemCount, GLDrawElementsType.UnsignedShort, (void*)(cmd.IdxOffset * sizeof(ushort)), (int)cmd.VtxOffset);
|
|
}
|
|
else
|
|
{
|
|
gl.DrawElements(GLPrimitiveType.Triangles, (int)cmd.ElemCount, GLDrawElementsType.UnsignedShort, (void*)(cmd.IdxOffset * sizeof(ushort)));
|
|
}
|
|
}
|
|
}
|
|
|
|
gl.DeleteVertexArray(vao);
|
|
|
|
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)
|
|
{
|
|
if (bd.GlVersion <= 310 || bd.GlProfileIsCompat)
|
|
{
|
|
gl.PolygonMode(GLTriangleFace.Front, (GLPolygonMode)lastPolygonMode[0]);
|
|
gl.PolygonMode(GLTriangleFace.Back, (GLPolygonMode)lastPolygonMode[1]);
|
|
}
|
|
else
|
|
{
|
|
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)
|
|
{
|
|
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)
|
|
{
|
|
gl.GetIntegerv(GLGetPName.ClipPlane0, out int clipOrigin);
|
|
if (clipOrigin == (int)GLEnum.UpperLeft)
|
|
{
|
|
(T, B) = (B, T);
|
|
}
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
|
|
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);
|
|
}
|
|
tex.SetTexID(ImTextureID.Null);
|
|
tex.SetStatus(ImTextureStatus.Destroyed);
|
|
return;
|
|
}
|
|
|
|
gl.PixelStoref(GLPixelStoreParameter.UnpackRowLength, 0);
|
|
gl.PixelStoref(GLPixelStoreParameter.UnpackAlignment, 1);
|
|
|
|
if (tex.Status == ImTextureStatus.WantCreate)
|
|
{
|
|
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);
|
|
return;
|
|
}
|
|
|
|
if (tex.Status == ImTextureStatus.WantUpdates)
|
|
{
|
|
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);
|
|
}
|
|
}
|
|
|
|
|
|
public static bool CreateDeviceObjects()
|
|
{
|
|
RendererData bd = GetRendererData()!;
|
|
GL gl = bd.Gl;
|
|
|
|
gl.GetIntegerv(GLGetPName.TextureBinding2D, out int lastTexture);
|
|
gl.GetIntegerv(GLGetPName.ArrayBufferBinding, out int lastArrayBuffer);
|
|
gl.GetIntegerv(GLGetPName.VertexArrayBinding, out int lastVertexArray);
|
|
|
|
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);
|
|
}
|
|
}
|
|
|
|
} |