mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
1485 changed files with 768360 additions and 0 deletions
|
|
@ -0,0 +1,78 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
public static class ConsoleColor
|
||||
{
|
||||
public static class Float4
|
||||
{
|
||||
public static readonly float4 Grey = float4.Rgb(0.4f, 0.4f, 0.4f);
|
||||
public static readonly float4 DarkGrey = float4.Rgb(0.1f, 0.1f, 0.1f);
|
||||
public static readonly float4 Orange = float4.Rgb(1f, 0.4f, 0f);
|
||||
public static readonly float4 Red = float4.Rgb(1f, 0f, 0f);
|
||||
public static readonly float4 RedTransparent = float4.Rgba(1f, 0f, 0f, 0.4f);
|
||||
public static readonly float4 DarkRed = float4.Rgb(0.6f, 0f, 0f);
|
||||
public static readonly float4 Black = float4.Rgb(0f, 0f, 0f);
|
||||
public static readonly float4 Yellow = float4.Rgb(1f, 0.7f, 0f);
|
||||
public static readonly float4 YellowTransparent = float4.Rgba(1f, 0.5f, 0f, 0.4f);
|
||||
public static readonly float4 Blue = float4.Rgb(0f, 0.3f, 1f);
|
||||
public static readonly float4 BlueTransparent = float4.Rgba(0f, 0.3f, 1f, 0.4f);
|
||||
public static readonly float4 Green = float4.Rgb(0f, 1f, 0f);
|
||||
public static readonly float4 GreenTransparent = float4.Rgba(0f, 1f, 0f, 0.4f);
|
||||
public static readonly float4 GreenGrey = float4.Rgb(0.1f, 0.5f, 0.1f);
|
||||
public static readonly float4 HalfTransparent = float4.Rgba(1f, 1f, 1f, 0.5f);
|
||||
public static readonly float4 Transparent = float4.Rgba(0f, 0f, 0f, 0f);
|
||||
public static readonly float4 Cyan = float4.Rgb(0f, 1f, 1f);
|
||||
public static readonly float4 Magenta = float4.Rgb(1f, 0f, 1);
|
||||
public static readonly float4 White = float4.Rgb(1f, 1f, 1);
|
||||
public static readonly float4 WhiteTransparent = float4.Rgba(1f, 1f, 1, 0.4f);
|
||||
public static readonly float4 DarkGreyTransparent = float4.Rgba(0.1f, 0.1f, 0.1f, 0.4f);
|
||||
public static readonly float4 LightBlue = float4.Unpack(byte4.Rgb(66, 200, 245), Unpack.Float.Normalize);
|
||||
public static readonly float4 GreyTransparent = float4.Rgba(0.4f, 0.4f, 0.4f, 0.4f);
|
||||
//public static float4 Border => ImGui.GetStyle().Colors[(int)ImGuiCol.Border];
|
||||
//public static float4 TabHovered => ImGui.GetStyle().Colors[(int)ImGuiCol.TabHovered];
|
||||
//public static float4 PlotHistogramHovered => ImGui.GetStyle().Colors[(int)ImGuiCol.PlotHistogramHovered];
|
||||
}
|
||||
|
||||
public static uint ColorConvertFloat4ToU32(float4 inVector)
|
||||
{
|
||||
uint outColor = 0;
|
||||
|
||||
var r = inVector.X;
|
||||
var g = inVector.Y;
|
||||
var b = inVector.Z;
|
||||
var a = inVector.W;
|
||||
|
||||
outColor += (uint)(255 * r / 1.0f) << 0;
|
||||
outColor += (uint)(255 * g / 1.0f) << 8;
|
||||
outColor += (uint)(255 * b / 1.0f) << 16;
|
||||
outColor += (uint)(255 * a / 1.0f) << 24;
|
||||
|
||||
return outColor;
|
||||
}
|
||||
|
||||
public static class Integer
|
||||
{
|
||||
public static readonly uint White = ColorConvertFloat4ToU32(Float4.White);
|
||||
public static readonly uint WhiteTransparent = ColorConvertFloat4ToU32(Float4.WhiteTransparent);
|
||||
public static readonly uint Black = ColorConvertFloat4ToU32(Float4.Black);
|
||||
public static readonly uint Grey = ColorConvertFloat4ToU32(Float4.Grey);
|
||||
public static readonly uint DarkGrey = ColorConvertFloat4ToU32(Float4.DarkGrey);
|
||||
public static readonly uint Yellow = ColorConvertFloat4ToU32(Float4.Yellow);
|
||||
public static readonly uint YellowTransparent = ColorConvertFloat4ToU32(Float4.YellowTransparent);
|
||||
public static readonly uint GreenTransparent = ColorConvertFloat4ToU32(Float4.GreenTransparent);
|
||||
public static readonly uint Orange = ColorConvertFloat4ToU32(Float4.Orange);
|
||||
public static readonly uint Red = ColorConvertFloat4ToU32(Float4.Red);
|
||||
public static readonly uint RedTransparent = ColorConvertFloat4ToU32(Float4.RedTransparent);
|
||||
public static readonly uint Green = ColorConvertFloat4ToU32(Float4.Green);
|
||||
public static readonly uint GreenGrey = ColorConvertFloat4ToU32(Float4.GreenGrey);
|
||||
public static readonly uint Blue = ColorConvertFloat4ToU32(Float4.Blue);
|
||||
public static readonly uint LightBlue = ColorConvertFloat4ToU32(Float4.LightBlue);
|
||||
public static readonly uint BlueTransparent = ColorConvertFloat4ToU32(Float4.BlueTransparent);
|
||||
|
||||
//public static readonly uint TabHovered = ColorConvertFloat4ToU32(Float4.TabHovered);
|
||||
//public static readonly uint Border = ColorConvertFloat4ToU32(Float4.Border);
|
||||
public static readonly uint HalfTransparent = ColorConvertFloat4ToU32(Float4.HalfTransparent);
|
||||
public static readonly uint Transparent = ColorConvertFloat4ToU32(Float4.Transparent);
|
||||
public static readonly uint DarkGreyTransparent = ColorConvertFloat4ToU32(Float4.DarkGreyTransparent);
|
||||
public static readonly uint GreyTransparent = ColorConvertFloat4ToU32(Float4.GreyTransparent);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
public static class ConsoleLineColors
|
||||
{
|
||||
public static readonly ImColor8 Default = new(178, 178, 178, 255);
|
||||
}
|
||||
|
||||
public struct ConsoleLogEntry()
|
||||
{
|
||||
public ImColor8 Color = ConsoleLineColors.Default;
|
||||
|
||||
public bool IsEmpty => TextSpanHandle.Length == 0;
|
||||
public ConsoleWindow.RingBuffer.SpanHandle TextSpanHandle = new();
|
||||
public ConsoleWindow.RingBuffer.SpanHandle TimeSpanHandle = new();
|
||||
|
||||
public float ActiveTime;
|
||||
}
|
||||
|
|
@ -0,0 +1,889 @@
|
|||
using System.Buffers;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Runtime.InteropServices;
|
||||
using Brutal.ImGuiApi.Internal;
|
||||
using Brutal.Strings;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// This logger receives log messages, formats them and sends them to the ConsoleWindow
|
||||
/// </summary>
|
||||
public class ConsoleWindowLogger : ILogger, IDisposable
|
||||
{
|
||||
private readonly ConsoleWindow _consoleWindow;
|
||||
private readonly string _categoryName;
|
||||
|
||||
/// <summary>
|
||||
/// Log formatter function - users can override this, but we provide a default
|
||||
/// LogLevel: The log level
|
||||
/// string: The category name
|
||||
/// string: The log message
|
||||
/// Returns the formatted log string
|
||||
/// </summary>
|
||||
public static Func<LogLevel, string, string, string>? LogFormatter { get; set; }
|
||||
|
||||
public ConsoleWindowLogger(ConsoleWindow consoleWindow, string categoryName)
|
||||
{
|
||||
_categoryName = categoryName;
|
||||
_consoleWindow = consoleWindow;
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
/// <summary>
|
||||
/// Receive a log message, format it and send it to the ConsoleWindow
|
||||
/// </summary>
|
||||
public void Log<TState>(
|
||||
LogLevel logLevel,
|
||||
EventId eventId,
|
||||
TState state,
|
||||
Exception? exception,
|
||||
Func<TState, Exception?, string> formatter
|
||||
)
|
||||
{
|
||||
var formattedMessage = formatter(state, exception);
|
||||
var message = LogFormatter != null ? LogFormatter(logLevel, _categoryName, formattedMessage) : formattedMessage;
|
||||
|
||||
_consoleWindow.OnLog(_categoryName, logLevel, message);
|
||||
}
|
||||
|
||||
public bool IsEnabled(LogLevel logLevel)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public IDisposable? BeginScope<TState>(TState state)
|
||||
where TState : notnull
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public class ConsoleWindow : ILoggerProvider
|
||||
{
|
||||
public const int DEFAULT_LOG_TIME = 5;
|
||||
public const int INITIAL_BUFFER_CAPACITY = 128;
|
||||
|
||||
private readonly struct PendingMessage
|
||||
{
|
||||
public readonly int TextOffset;
|
||||
public readonly int TextLength; // -1 signals a Clear
|
||||
public readonly DateTime Timestamp;
|
||||
public readonly ImColor8 Color;
|
||||
public readonly int TimeToShow;
|
||||
|
||||
public PendingMessage(int textOffset, int textLength, ImColor8 color, int timeToShow)
|
||||
{
|
||||
TextOffset = textOffset;
|
||||
TextLength = textLength;
|
||||
Timestamp = DateTime.Now;
|
||||
Color = color;
|
||||
TimeToShow = timeToShow;
|
||||
}
|
||||
}
|
||||
|
||||
private readonly Lock _pendingLock = new();
|
||||
private bool _pendingClear;
|
||||
|
||||
private const int BUFFER_COUNT = 2;
|
||||
private const int PENDING_TEXT_BUFFER_SIZE = 1024 * 1024; // 1MB pre-allocated for the pending text per-buffer for now, should be enough
|
||||
private int _currentActiveBuffer = 0;
|
||||
private readonly List<PendingMessage>[] _pendingMessages = new List<PendingMessage>[BUFFER_COUNT] { new(), new() };
|
||||
private readonly byte[][] _pendingText = [new byte[PENDING_TEXT_BUFFER_SIZE], new byte[PENDING_TEXT_BUFFER_SIZE]];
|
||||
private readonly int[] _pendingTextPos = new int[BUFFER_COUNT];
|
||||
|
||||
private class GrowingRingBuffer<T>(int initialCapacity)
|
||||
{
|
||||
private T[] _backingArray = new T[initialCapacity];
|
||||
|
||||
public int Begin;
|
||||
public int End;
|
||||
public int Capacity => _backingArray.Length;
|
||||
public int Count => End >= Begin ? End - Begin : Capacity - Begin + End;
|
||||
|
||||
public ref T this[int index] => ref _backingArray[(Begin + index) % Capacity];
|
||||
|
||||
public static implicit operator Span<T>(GrowingRingBuffer<T> array) => array._backingArray;
|
||||
|
||||
public void Reset(int newCapacity)
|
||||
{
|
||||
if (newCapacity != Capacity)
|
||||
_backingArray = new T[newCapacity];
|
||||
Begin = 0;
|
||||
End = 0;
|
||||
}
|
||||
|
||||
public void Resize(int newCapacity)
|
||||
{
|
||||
var oldCount = Count;
|
||||
var newArray = new T[newCapacity];
|
||||
if (End > Begin)
|
||||
{
|
||||
// |--BbbeeE--| |BbbeeE--------------|
|
||||
Array.Copy(_backingArray, Begin, newArray, 0, End - Begin);
|
||||
}
|
||||
else
|
||||
{
|
||||
// |eeE----Bbb| |BbbeeE--------------|
|
||||
Array.Copy(_backingArray, Begin, newArray, 0, Capacity - Begin);
|
||||
Array.Copy(_backingArray, 0, newArray, Capacity - Begin, End);
|
||||
}
|
||||
|
||||
_backingArray = newArray;
|
||||
Begin = 0;
|
||||
End = oldCount;
|
||||
|
||||
Debug.Assert(End != Begin);
|
||||
Debug.Assert(End < Capacity);
|
||||
}
|
||||
|
||||
public void Push(T newItem)
|
||||
{
|
||||
if ((End + 1) % Capacity == Begin)
|
||||
Resize(Capacity * 2);
|
||||
|
||||
_backingArray[End] = newItem;
|
||||
End = (End + 1) % Capacity;
|
||||
|
||||
Debug.Assert(End != Begin);
|
||||
}
|
||||
}
|
||||
|
||||
private readonly GrowingRingBuffer<ConsoleLogEntry> _consoleBuffer = new(INITIAL_BUFFER_CAPACITY);
|
||||
|
||||
public void DrawStats()
|
||||
{
|
||||
ImGui.Text($"Capacity: {_consoleBuffer.Capacity}");
|
||||
ImGui.Text($"Count: {_consoleBuffer.Count}");
|
||||
ImGui.Text($"Begin: {_consoleBuffer.Begin}");
|
||||
ImGui.Text($"End: {_consoleBuffer.End}");
|
||||
|
||||
var units = Math.Min(20, _consoleBuffer.Capacity);
|
||||
|
||||
var region1Units = 0;
|
||||
var region2Units = 0;
|
||||
var region3Units = 0;
|
||||
var region1Char = '?';
|
||||
var region2Char = '?';
|
||||
var region3Char = '?';
|
||||
var region1Color = ConsoleColor.Float4.Magenta;
|
||||
var region2Color = ConsoleColor.Float4.Magenta;
|
||||
var region3Color = ConsoleColor.Float4.Magenta;
|
||||
|
||||
if (_consoleBuffer.Begin > _consoleBuffer.End)
|
||||
{
|
||||
region1Units = (int)((float)_consoleBuffer.End / _consoleBuffer.Capacity * units);
|
||||
region2Units = (int)((float)(_consoleBuffer.Begin - _consoleBuffer.End) / _consoleBuffer.Capacity * units);
|
||||
|
||||
region1Char = 'x';
|
||||
region2Char = '-';
|
||||
region3Char = 'x';
|
||||
region1Color = ConsoleColor.Float4.Green;
|
||||
region2Color = ConsoleColor.Float4.Grey;
|
||||
region3Color = ConsoleColor.Float4.Green;
|
||||
}
|
||||
else
|
||||
{
|
||||
region1Units = (int)(((float)_consoleBuffer.Begin / _consoleBuffer.Capacity) * units);
|
||||
|
||||
var num = _consoleBuffer.End - _consoleBuffer.Begin;
|
||||
region2Units = (int)((float)num / _consoleBuffer.Capacity * units);
|
||||
if (region2Units == 0 && num != 0)
|
||||
region2Units = 1;
|
||||
|
||||
region1Char = '-';
|
||||
region2Char = 'x';
|
||||
region3Char = '-';
|
||||
region1Color = ConsoleColor.Float4.Grey;
|
||||
region2Color = ConsoleColor.Float4.Green;
|
||||
region3Color = ConsoleColor.Float4.Grey;
|
||||
}
|
||||
|
||||
region3Units = units - region1Units - region2Units;
|
||||
|
||||
ImGui.Text("Buffer: |"u8);
|
||||
ImGui.SameLine();
|
||||
ImGui.TextColored(region1Color, new string(region1Char, region1Units));
|
||||
ImGui.SameLine();
|
||||
ImGui.TextColored(region2Color, new string(region2Char, region2Units));
|
||||
ImGui.SameLine();
|
||||
ImGui.TextColored(region3Color, new string(region3Char, region3Units));
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("|"u8);
|
||||
}
|
||||
|
||||
public TerminalInterface Terminal;
|
||||
|
||||
private bool _show;
|
||||
private bool _setFocus;
|
||||
private bool _overwrite;
|
||||
private bool _scrollToBottom;
|
||||
private bool _autoScroll = false;
|
||||
private bool _fadeMessages = true;
|
||||
|
||||
private readonly ImInputString _consoleInput = new(512, []);
|
||||
public readonly RingBuffer Storage;
|
||||
private bool _clearConsoleInput;
|
||||
|
||||
public bool IsOpen => _show;
|
||||
|
||||
// #TODO-batchmode: Implement BatchMode()
|
||||
|
||||
private float2 _inputSize;
|
||||
private bool _inputLastActive;
|
||||
|
||||
private readonly string[] _commandBuffer = new string[8];
|
||||
private int _commandBufferIndex;
|
||||
private int _headIndex;
|
||||
private int _tailIndex;
|
||||
|
||||
private static readonly ImColor8 DefaultColor = ConsoleColor.ColorConvertFloat4ToU32(
|
||||
new float4(0.7f, 0.7f, 0.7f, 1f)
|
||||
);
|
||||
public static ImColor8 InfoColor = DefaultColor;
|
||||
public static ImColor8 DebugColor = ConsoleColor.Integer.Yellow;
|
||||
public static ImColor8 WarningColor = ConsoleColor.Integer.Orange;
|
||||
public static ImColor8 ErrorColor = ConsoleColor.Integer.Red;
|
||||
public static ImColor8 CriticalColor = ConsoleColor.Integer.Red;
|
||||
public static ImColor8 TraceColor = ConsoleColor.Integer.GreenGrey;
|
||||
|
||||
/// <summary>
|
||||
/// Scale of the font in the console window.
|
||||
/// Use as a field so it can be referenced in an ImGui slider etc.
|
||||
/// </summary>
|
||||
public float FontScale = 1f;
|
||||
|
||||
/// <summary>
|
||||
/// Font Pointer for rendering texting to console window
|
||||
/// <para></para>
|
||||
/// This shouldn't really be changed. Only used for more easily testing fonts for ConsoleWindow.
|
||||
/// For the sake of consistency between games. Leave this value as is.
|
||||
/// </summary>
|
||||
public ImFontPtr FontPtr;
|
||||
|
||||
public ConsoleWindow()
|
||||
: this(ByteSize.FromMegabytes(2)) { }
|
||||
|
||||
public ConsoleWindow(ByteSize bufferSize)
|
||||
{
|
||||
Storage = new RingBuffer(bufferSize);
|
||||
Terminal = new(this);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Retrieves the default font for the console window.
|
||||
/// If no fonts are available in the font atlas, a default font is added and returned.
|
||||
/// Otherwise, the first font in the font atlas is returned.
|
||||
/// </summary>
|
||||
/// <returns>The pointer to the default font in the font atlas.</returns>
|
||||
public ImFontPtr GetDefaultFont()
|
||||
{
|
||||
var fontAtlas = ImGui.GetIO().Fonts;
|
||||
var fonts = fontAtlas.Fonts;
|
||||
return fonts.Count == 0 ? fontAtlas.AddFontDefault() : fonts[0];
|
||||
}
|
||||
|
||||
public ILogger CreateLogger(string categoryName)
|
||||
{
|
||||
return new ConsoleWindowLogger(this, categoryName);
|
||||
}
|
||||
|
||||
public void OnLog(string categoryName, LogLevel logLevel, string message)
|
||||
{
|
||||
// Otherwise just sort by log level
|
||||
switch (logLevel)
|
||||
{
|
||||
case LogLevel.None:
|
||||
case LogLevel.Information:
|
||||
Print(message, InfoColor);
|
||||
break;
|
||||
case LogLevel.Trace:
|
||||
Print(message, TraceColor);
|
||||
break;
|
||||
case LogLevel.Debug:
|
||||
Print(message, DebugColor);
|
||||
break;
|
||||
case LogLevel.Warning:
|
||||
Print(message, WarningColor);
|
||||
break;
|
||||
case LogLevel.Error:
|
||||
Print(message, ErrorColor);
|
||||
break;
|
||||
case LogLevel.Critical:
|
||||
Print(message, CriticalColor);
|
||||
break;
|
||||
default:
|
||||
throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null);
|
||||
}
|
||||
}
|
||||
|
||||
public void Show()
|
||||
{
|
||||
_show = true;
|
||||
_setFocus = true;
|
||||
_inputLastActive = true;
|
||||
}
|
||||
|
||||
public void Hide()
|
||||
{
|
||||
_show = false;
|
||||
_inputLastActive = false;
|
||||
}
|
||||
|
||||
public void EnableMessageFading()
|
||||
{
|
||||
_fadeMessages = true;
|
||||
}
|
||||
|
||||
public void DisableMessageFading()
|
||||
{
|
||||
_fadeMessages = false;
|
||||
}
|
||||
|
||||
private void DrawLog(float unscaledDeltaTime, bool noFade = false)
|
||||
{
|
||||
_inputSize = ImGui.GetStyle().WindowPadding;
|
||||
|
||||
for (var i = 0; i < _consoleBuffer.Count; ++i)
|
||||
Draw(ref _consoleBuffer[i], ref _inputSize, _show, unscaledDeltaTime, noFade);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Draws the ConsoleWindow to the screen using the position and size of the current viewport
|
||||
/// </summary>
|
||||
/// <param name="viewportPosition"></param>
|
||||
/// <param name="viewportSize"></param>
|
||||
/// <param name="unscaledDeltaTime"></param>
|
||||
/// <param name="noFade"></param>
|
||||
public void Draw(float2 viewportPosition, float2 viewportSize, float unscaledDeltaTime, bool noFade = false)
|
||||
{
|
||||
// Swap the buffers before to resolve all the "pending messages"
|
||||
SwapBuffers();
|
||||
|
||||
if (FontPtr.IsNull())
|
||||
FontPtr = GetDefaultFont();
|
||||
|
||||
ImGui.PushFont(FontPtr, ImGui.GetStyle().FontSizeBase * FontScale);
|
||||
|
||||
// PREPARE WINDOW FLAGS
|
||||
var flags =
|
||||
ImGuiWindowFlags.NoCollapse
|
||||
| ImGuiWindowFlags.NoSavedSettings
|
||||
| ImGuiWindowFlags.NoTitleBar
|
||||
| ImGuiWindowFlags.NoMove
|
||||
| ImGuiWindowFlags.NoResize
|
||||
| ImGuiWindowFlags.NoScrollbar
|
||||
| ImGuiWindowFlags.NoMouseInputs;
|
||||
if (!_show)
|
||||
flags |= ImGuiWindowFlags.NoBackground;
|
||||
|
||||
// CREATE WINDOW SIZE
|
||||
var scalingSize = _inputSize.Y + ImGui.GetItemRectSize().Y;
|
||||
var ySize = _show ? Math.Min(scalingSize, viewportSize.Y / 3) : _inputSize.Y;
|
||||
ImGui.SetNextWindowSize(viewportSize with { Y = ySize }, ImGuiCond.Always);
|
||||
ImGui.SetNextWindowPos(viewportPosition + new float2(0, viewportSize.Y - ySize), ImGuiCond.Always);
|
||||
|
||||
// SET STYLES FOR WINDOW
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.WindowRounding, 0f);
|
||||
ImGui.PushStyleColor(ImGuiCol.WindowBg, ConsoleColor.Integer.Black);
|
||||
ImGui.PushStyleColor(ImGuiCol.Border, ConsoleColor.Integer.DarkGrey);
|
||||
|
||||
// BEGIN THE DRAW PHASE
|
||||
if (ImGui.Begin("ConsoleWindow"u8, ref _show, flags))
|
||||
{
|
||||
//POP THE BORDER AND BG STYLES
|
||||
ImGui.PopStyleColor(2);
|
||||
ImGui.PopStyleVar();
|
||||
|
||||
// IF CONSOLE IS OPEN
|
||||
if (_show)
|
||||
{
|
||||
// DRAW A SCROLL AREA FOR HISTORY
|
||||
var footerSize = ImGui.GetFrameHeightWithSpacing();
|
||||
if (ImGui.BeginChild("ScrollingRegion"u8, new float2(0, -footerSize)))
|
||||
{
|
||||
DrawLog(unscaledDeltaTime, noFade);
|
||||
if (_scrollToBottom || (_autoScroll && ImGui.GetScrollY() >= ImGui.GetScrollMaxY()))
|
||||
ImGui.SetScrollHereY(1.0f);
|
||||
_scrollToBottom = false;
|
||||
ImGui.EndChild();
|
||||
}
|
||||
|
||||
//ImGui.Separator();
|
||||
|
||||
// PREPARE INPUT FIELD
|
||||
ImGui.Text(">"u8);
|
||||
ImGui.SameLine();
|
||||
ImGui.PushItemWidth(ImGui.GetContentRegionAvail().X);
|
||||
ImGui.PushStyleColor(ImGuiCol.Border, ConsoleColor.Integer.Transparent);
|
||||
ImGui.PushStyleColor(ImGuiCol.FrameBg, ConsoleColor.Integer.Transparent);
|
||||
|
||||
// DRAW INPUT FIELD
|
||||
var id = "###ConsoleInput"u8;
|
||||
if (_overwrite)
|
||||
{
|
||||
_overwrite = false;
|
||||
ImGui.Internal.GetInputTextState(ImGui.GetID(id)).ReloadUserBufAndMoveToEnd();
|
||||
}
|
||||
|
||||
ImGui.InputText(id, _consoleInput);
|
||||
_inputLastActive = ImGui.IsItemActive();
|
||||
|
||||
// SET FOCUS ON INPUT FIELD
|
||||
ImGuiUtils.SetLastFocusOnAppearing(true);
|
||||
_inputSize += ImGui.GetItemRectSize();
|
||||
ImGui.PopStyleColor(2);
|
||||
ImGui.PopItemWidth();
|
||||
|
||||
if (ImGui.IsItemVisible())
|
||||
{
|
||||
if (_setFocus)
|
||||
{
|
||||
ImGui.SetWindowFocus();
|
||||
ImGui.SetKeyboardFocusHere();
|
||||
_setFocus = false;
|
||||
_scrollToBottom = true;
|
||||
}
|
||||
else if (!ImGui.IsWindowFocused())
|
||||
{
|
||||
_show = false;
|
||||
_scrollToBottom = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
// IF CONSOLE IS CLOSED
|
||||
else
|
||||
{
|
||||
// DRAW FADING CRITICAL LOG HISTORY SUCH AS ACTIONS OR ERRORS
|
||||
DrawLog(unscaledDeltaTime, noFade);
|
||||
}
|
||||
|
||||
// CLEAR THE INPUT FIELD
|
||||
if (_clearConsoleInput)
|
||||
{
|
||||
_clearConsoleInput = false;
|
||||
_consoleInput.Clear();
|
||||
_scrollToBottom = true;
|
||||
}
|
||||
}
|
||||
|
||||
//END THE DRAW PHASE
|
||||
ImGui.End();
|
||||
ImGui.PopFont();
|
||||
}
|
||||
|
||||
public void Submit(string input)
|
||||
{
|
||||
_consoleInput.Value16 = input;
|
||||
Submit();
|
||||
}
|
||||
|
||||
private void Submit()
|
||||
{
|
||||
if (_consoleInput.IsEmpty)
|
||||
{
|
||||
Hide();
|
||||
return;
|
||||
}
|
||||
|
||||
Terminal.Execute(_consoleInput.ToString());
|
||||
|
||||
_clearConsoleInput = true;
|
||||
_setFocus = true;
|
||||
_scrollToBottom = true;
|
||||
}
|
||||
|
||||
public void ClearConsole()
|
||||
{
|
||||
// #TODO-batchmode Implement clear console for batch mode
|
||||
lock (_pendingLock)
|
||||
{
|
||||
var buf = _currentActiveBuffer;
|
||||
_pendingMessages[buf].Clear();
|
||||
_pendingTextPos[buf] = 0;
|
||||
_pendingClear = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void PrintMessage(string message) => Print(message, ConsoleColor.Integer.LightBlue);
|
||||
|
||||
// Default colour
|
||||
public void Print(string text, int timeToShow = DEFAULT_LOG_TIME) => Print(text, DefaultColor, timeToShow);
|
||||
|
||||
public void Print(ImString text, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
Print((ReadOnlySpan<byte>)text, DefaultColor, timeToShow);
|
||||
|
||||
public void Print(ReadOnlySpan<char> text, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
Print(text, DefaultColor, timeToShow);
|
||||
|
||||
public void Print(ReadOnlySpan<byte> text, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
Print(text, DefaultColor, timeToShow);
|
||||
|
||||
// With colour
|
||||
public void Print(ImString text, ImColor8 color, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
AddPendingMessage((ReadOnlySpan<byte>)text, color, timeToShow);
|
||||
|
||||
public void Print(ReadOnlySpan<byte> text, ImColor8 color, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
AddPendingMessage(text, color, timeToShow);
|
||||
|
||||
public void Print(ReadOnlySpan<char> text, ImColor8 color, int timeToShow = DEFAULT_LOG_TIME) =>
|
||||
AddPendingMessage(text, color, timeToShow);
|
||||
|
||||
private void AddPendingMessage(ReadOnlySpan<byte> text, ImColor8 color, int timeToShow)
|
||||
{
|
||||
// Don't show the message in the fading list if it's disabled
|
||||
if (!_fadeMessages)
|
||||
timeToShow = 0;
|
||||
lock (_pendingLock)
|
||||
{
|
||||
var bufIdx = _currentActiveBuffer;
|
||||
var offset = _pendingTextPos[bufIdx];
|
||||
Debug.Assert(
|
||||
offset + text.Length <= PENDING_TEXT_BUFFER_SIZE,
|
||||
"Pending text buffer overflow — increase PENDING_TEXT_BUFFER_SIZE"
|
||||
);
|
||||
if (offset + text.Length > PENDING_TEXT_BUFFER_SIZE)
|
||||
return;
|
||||
text.CopyTo(_pendingText[bufIdx].AsSpan(offset));
|
||||
_pendingTextPos[bufIdx] += text.Length;
|
||||
_pendingMessages[bufIdx].Add(new PendingMessage(offset, text.Length, color, timeToShow));
|
||||
}
|
||||
}
|
||||
|
||||
private void AddPendingMessage(ReadOnlySpan<char> text, ImColor8 color, int timeToShow)
|
||||
{
|
||||
// Don't show the message in the fading list if it's disabled
|
||||
if (!_fadeMessages)
|
||||
timeToShow = 0;
|
||||
var byteCount = Utf8.GetByteCount(text);
|
||||
lock (_pendingLock)
|
||||
{
|
||||
var bufIdx = _currentActiveBuffer;
|
||||
var offset = _pendingTextPos[bufIdx];
|
||||
Debug.Assert(
|
||||
offset + byteCount <= PENDING_TEXT_BUFFER_SIZE,
|
||||
"Pending text buffer overflow — increase PENDING_TEXT_BUFFER_SIZE"
|
||||
);
|
||||
if (offset + byteCount > PENDING_TEXT_BUFFER_SIZE)
|
||||
return;
|
||||
var status = Utf8.FromUtf16(text, _pendingText[bufIdx].AsSpan(offset), out _, out var bytesWritten);
|
||||
if (status != OperationStatus.Done)
|
||||
throw new InvalidOperationException($"Failed to convert UTF-16 to UTF-8: {status}");
|
||||
_pendingTextPos[bufIdx] += bytesWritten;
|
||||
_pendingMessages[bufIdx].Add(new PendingMessage(offset, bytesWritten, color, timeToShow));
|
||||
}
|
||||
}
|
||||
|
||||
public void SwapBuffers()
|
||||
{
|
||||
int active;
|
||||
bool clear;
|
||||
lock (_pendingLock)
|
||||
{
|
||||
active = _currentActiveBuffer;
|
||||
_currentActiveBuffer = (active + 1) % BUFFER_COUNT;
|
||||
clear = _pendingClear;
|
||||
_pendingClear = false;
|
||||
}
|
||||
|
||||
if (clear)
|
||||
{
|
||||
Storage.Reset();
|
||||
_consoleBuffer.Reset(INITIAL_BUFFER_CAPACITY);
|
||||
}
|
||||
|
||||
var messages = CollectionsMarshal.AsSpan(_pendingMessages[active]);
|
||||
var pendingText = _pendingText[active].AsSpan(0, _pendingTextPos[active]);
|
||||
for (var i = 0; i < messages.Length; ++i)
|
||||
{
|
||||
ref readonly var msg = ref messages[i];
|
||||
Apply(in msg, pendingText.Slice(msg.TextOffset, msg.TextLength));
|
||||
}
|
||||
|
||||
_pendingMessages[active].Clear();
|
||||
_pendingTextPos[active] = 0;
|
||||
}
|
||||
|
||||
private void Apply(in PendingMessage pending, ReadOnlySpan<byte> text)
|
||||
{
|
||||
var textHandle = Storage.Append(text);
|
||||
|
||||
Span<byte> timeBytes = stackalloc byte[8]; // "HH:mm:ss" is always 8 bytes
|
||||
pending.Timestamp.TryFormat(timeBytes, out var timeBytesWritten, "HH:mm:ss", CultureInfo.InvariantCulture);
|
||||
|
||||
_consoleBuffer.Push(
|
||||
new ConsoleLogEntry
|
||||
{
|
||||
TextSpanHandle = textHandle,
|
||||
Color = pending.Color,
|
||||
TimeSpanHandle = Storage.Append(timeBytes[..timeBytesWritten]),
|
||||
ActiveTime = pending.TimeToShow,
|
||||
}
|
||||
);
|
||||
|
||||
// push the begin pointer until we find the next valid message
|
||||
while (Storage.TokenIsStale(_consoleBuffer[0].TextSpanHandle))
|
||||
_consoleBuffer.Begin = (_consoleBuffer.Begin + 1) % _consoleBuffer.Capacity;
|
||||
}
|
||||
|
||||
public enum Actions
|
||||
{
|
||||
Up,
|
||||
Down,
|
||||
Submit,
|
||||
Toggle,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Callback for handling input actions.
|
||||
/// </summary>
|
||||
/// <param name="action">One of the supported actions.</param>
|
||||
/// <returns>True if the action was handled, false otherwise.</returns>
|
||||
public bool HandleInputAction(Actions action)
|
||||
{
|
||||
if (_inputLastActive)
|
||||
{
|
||||
if (action is Actions.Up or Actions.Down)
|
||||
{
|
||||
// save the current input if it is not already saved
|
||||
if (_commandBufferIndex == _headIndex)
|
||||
_commandBuffer[_headIndex] = _consoleInput.ToString();
|
||||
|
||||
if (action is Actions.Up)
|
||||
{
|
||||
var next = _commandBufferIndex == 0 ? _commandBuffer.Length - 1 : _commandBufferIndex - 1;
|
||||
if (_commandBufferIndex != _tailIndex)
|
||||
{
|
||||
_commandBufferIndex = next;
|
||||
_consoleInput.Value16 = _commandBuffer[_commandBufferIndex];
|
||||
_overwrite = true;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// key is down
|
||||
if (_commandBufferIndex != _headIndex)
|
||||
{
|
||||
_commandBufferIndex = (_commandBufferIndex + 1) % _commandBuffer.Length;
|
||||
_consoleInput.Value16 = _commandBuffer[_commandBufferIndex];
|
||||
_overwrite = true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!_show && action == Actions.Toggle)
|
||||
{
|
||||
Show();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!_show)
|
||||
return false;
|
||||
|
||||
if (action == Actions.Toggle)
|
||||
{
|
||||
Hide();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (action is Actions.Submit)
|
||||
{
|
||||
Submit();
|
||||
if (!_consoleInput.IsEmpty)
|
||||
{
|
||||
var inputString = _consoleInput.ToString();
|
||||
if (_commandBufferIndex == _headIndex)
|
||||
{
|
||||
// we wrote to the head, so we need to move the head
|
||||
_commandBuffer[_commandBufferIndex] = inputString;
|
||||
_headIndex = (_commandBufferIndex + 1) % _commandBuffer.Length;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (inputString != _commandBuffer[_commandBufferIndex])
|
||||
{
|
||||
// we have edited an old command, so we need to move the head and write to the head
|
||||
_commandBuffer[_headIndex] = inputString;
|
||||
_headIndex = (_headIndex + 1) % _commandBuffer.Length;
|
||||
}
|
||||
}
|
||||
|
||||
_commandBufferIndex = _headIndex;
|
||||
|
||||
// if the head is at the tail, we need to move the tail
|
||||
if (_headIndex == _tailIndex)
|
||||
_tailIndex = (_tailIndex + 1) % _commandBuffer.Length;
|
||||
|
||||
_consoleInput.Clear();
|
||||
_overwrite = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public void Draw(
|
||||
ref ConsoleLogEntry line,
|
||||
ref float2 inputSize,
|
||||
bool isShown,
|
||||
float unscaledDeltaTime,
|
||||
bool noFade = false
|
||||
)
|
||||
{
|
||||
Debug.Assert(!Storage.TokenIsStale(line.TimeSpanHandle));
|
||||
|
||||
if (line.IsEmpty || !isShown && line.ActiveTime <= 0f)
|
||||
return;
|
||||
|
||||
var isShowing = !isShown & line.ActiveTime <= 1f;
|
||||
|
||||
if (isShowing)
|
||||
{
|
||||
float alpha;
|
||||
if (noFade)
|
||||
alpha = line.ActiveTime > 0f ? 1f : 0f;
|
||||
else
|
||||
alpha = float.Lerp(0f, 1f, line.ActiveTime);
|
||||
|
||||
ImGui.PushStyleVar(ImGuiStyleVar.Alpha, alpha);
|
||||
}
|
||||
|
||||
DrawTime(line, isShown);
|
||||
ImGui.SameLine();
|
||||
|
||||
var textString = Storage.GetSpan(line.TextSpanHandle);
|
||||
|
||||
if (!isShown)
|
||||
{
|
||||
ImGuiUtils.TextShadow(textString, line.Color);
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, line.Color);
|
||||
ImGui.TextWrapped(textString);
|
||||
ImGui.PopStyleColor();
|
||||
}
|
||||
|
||||
inputSize += ImGui.GetItemRectSize() + ImGui.GetStyle().ItemSpacing;
|
||||
|
||||
if (isShowing)
|
||||
ImGui.PopStyleVar();
|
||||
if (line.ActiveTime > 0)
|
||||
line.ActiveTime -= unscaledDeltaTime;
|
||||
}
|
||||
|
||||
private void DrawTime(ConsoleLogEntry line, bool isShown)
|
||||
{
|
||||
var timeString = Storage.GetSpan(line.TimeSpanHandle);
|
||||
|
||||
if (!isShown)
|
||||
{
|
||||
ImGuiUtils.TextShadow(timeString, ConsoleColor.Integer.Grey);
|
||||
}
|
||||
else
|
||||
{
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, ConsoleColor.Integer.Grey);
|
||||
ImGui.Text(timeString);
|
||||
ImGui.PopStyleColor();
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose() { }
|
||||
|
||||
public class RingBuffer(ByteSize capacity)
|
||||
{
|
||||
public readonly record struct SpanHandle(int Offset, int Length, uint Generation);
|
||||
|
||||
private readonly byte[] _array = new byte[capacity.Bytes];
|
||||
internal int Position;
|
||||
private int Remaining => _array.Length - Position;
|
||||
public int CurrentPosition => Position;
|
||||
public uint Generation { get; private set; }
|
||||
|
||||
public Span<byte> Destination => _array.AsSpan(Position);
|
||||
|
||||
private SpanHandle Advance(int bytesWritten) => Advance(bytesWritten, true, Position);
|
||||
|
||||
public SpanHandle Advance(int bytesWritten, bool nullTerminate, int start)
|
||||
{
|
||||
Position += bytesWritten;
|
||||
var length = Position - start; // don't include the null terminator
|
||||
if (nullTerminate)
|
||||
_array[Position++] = 0;
|
||||
return new SpanHandle(start, length, Generation);
|
||||
}
|
||||
|
||||
public void EnsureCapacity(int requiredBytes)
|
||||
{
|
||||
if (requiredBytes > _array.Length)
|
||||
throw new OutOfMemoryException(
|
||||
$"Required bytes {requiredBytes} exceed buffer capacity {_array.Length}"
|
||||
);
|
||||
|
||||
if (Remaining < requiredBytes)
|
||||
{
|
||||
Position = 0; // reset position to the beginning of the buffer if we exceed capacity
|
||||
++Generation; // Increment the generation when we reset the position to track stale Tokens
|
||||
}
|
||||
}
|
||||
|
||||
public SpanHandle Append(ReadOnlySpan<byte> value)
|
||||
{
|
||||
EnsureCapacity(value.Length + 1); // +1 for null terminator added by Advance
|
||||
value.CopyTo(_array.AsSpan(Position));
|
||||
return Advance(value.Length);
|
||||
}
|
||||
|
||||
public ReadOnlySpan<byte> AppendToSpan(ReadOnlySpan<byte> value)
|
||||
{
|
||||
return GetSpan(Append(value));
|
||||
}
|
||||
|
||||
private SpanHandle Append(ReadOnlySpan<char> value, int requiredBytes)
|
||||
{
|
||||
EnsureCapacity(requiredBytes + 1); // +1 for null terminator added by Advance
|
||||
var status = Utf8.FromUtf16(value, _array.AsSpan(Position), out _, out var bytesWritten);
|
||||
if (status != OperationStatus.Done)
|
||||
throw new InvalidOperationException($"Failed to convert UTF-16 to UTF-8: {status}");
|
||||
return Advance(bytesWritten);
|
||||
}
|
||||
|
||||
public SpanHandle Append(ReadOnlySpan<char> value)
|
||||
{
|
||||
return Append(value, Utf8.GetByteCount(value));
|
||||
}
|
||||
|
||||
public ReadOnlySpan<byte> AppendToSpan(ReadOnlySpan<char> value)
|
||||
{
|
||||
return GetSpan(Append(value));
|
||||
}
|
||||
|
||||
public void Reset()
|
||||
{
|
||||
Position = 0;
|
||||
++Generation;
|
||||
}
|
||||
|
||||
public bool TokenIsStale(SpanHandle spanHandle)
|
||||
{
|
||||
if (spanHandle.Generation == Generation)
|
||||
return false; // we are the current generation
|
||||
if (spanHandle.Generation == Generation - 1)
|
||||
return Position > spanHandle.Offset;
|
||||
return true; // any older generations are always stale
|
||||
}
|
||||
|
||||
public ReadOnlySpan<byte> GetSpan(SpanHandle spanHandle)
|
||||
{
|
||||
return _array.AsSpan(spanHandle.Offset, spanHandle.Length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
using System.Text;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
public class TableString
|
||||
{
|
||||
private readonly List<Row> _rows = new();
|
||||
|
||||
private readonly List<int> _columnWidths = new();
|
||||
|
||||
public readonly struct Row
|
||||
{
|
||||
public readonly String[] Values;
|
||||
|
||||
public Row(string[] values)
|
||||
{
|
||||
Values = values;
|
||||
}
|
||||
|
||||
public static Row Create(params string[] values) => new(values);
|
||||
|
||||
public void ToConsole(ConsoleWindow console)
|
||||
{
|
||||
foreach (var value in Values)
|
||||
console.Print(value);
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRow(params string[] values) => _rows.Add(new Row(values));
|
||||
|
||||
public void ToConsole(ConsoleWindow console)
|
||||
{
|
||||
// populate column widths
|
||||
foreach (var row in _rows)
|
||||
{
|
||||
for (var i = 0; i < row.Values.Length; i++)
|
||||
{
|
||||
if (i >= _columnWidths.Count)
|
||||
_columnWidths.Add(0);
|
||||
var rowColumnValue = row.Values[i].Length + 1;
|
||||
if (rowColumnValue > _columnWidths[i])
|
||||
_columnWidths[i] = rowColumnValue;
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var row in _rows)
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
for (var i = 0; i < row.Values.Length; i++)
|
||||
{
|
||||
var value = row.Values[i];
|
||||
switch (i)
|
||||
{
|
||||
case > 0:
|
||||
sb.Append(' ');
|
||||
break;
|
||||
case 0:
|
||||
sb.Append("| ");
|
||||
break;
|
||||
}
|
||||
|
||||
sb.Append(value.PadRight(_columnWidths[i]));
|
||||
sb.Append(" |");
|
||||
}
|
||||
console.Print(sb.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
public void AddRow(Row toRow) => _rows.Add(toRow);
|
||||
|
||||
public void Sort()
|
||||
{
|
||||
// sort rows by first column
|
||||
_rows.Sort((a, b) => string.Compare(a.Values[0], b.Values[0], StringComparison.Ordinal));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,53 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Defines how a terminal action should be parsed
|
||||
/// </summary>
|
||||
public enum ArgParseMode
|
||||
{
|
||||
/// <summary>
|
||||
/// Parse the command string args into individual tokens, considering whitespace and quotes
|
||||
/// </summary>
|
||||
Default,
|
||||
|
||||
/// <summary>
|
||||
/// Output the raw unparsed command arg string
|
||||
/// </summary>
|
||||
Unparsed,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An attribute which is used to define methods that can be registered as callback through a TerminalInterface
|
||||
/// </summary>
|
||||
[AttributeUsage(AttributeTargets.Method)]
|
||||
public class TerminalActionAttribute : Attribute
|
||||
{
|
||||
/// <param name="commandName">The command name</param>
|
||||
/// <param name="description">A description of the command</param>
|
||||
/// <param name="parsingMode">The type of parsing which should be used on the command</param>
|
||||
public TerminalActionAttribute(
|
||||
string commandName,
|
||||
string description = "",
|
||||
ArgParseMode parsingMode = ArgParseMode.Default
|
||||
)
|
||||
{
|
||||
CommandName = commandName.ToLower();
|
||||
Description = description;
|
||||
ParsingMode = parsingMode;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The name of the command
|
||||
/// </summary>
|
||||
public string CommandName { get; }
|
||||
|
||||
/// <summary>
|
||||
/// A description of the command
|
||||
/// </summary>
|
||||
public string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The parsing mode of the command
|
||||
/// </summary>
|
||||
public ArgParseMode ParsingMode { get; }
|
||||
}
|
||||
|
|
@ -0,0 +1,197 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Defines the arguments which a command takes
|
||||
/// </summary>
|
||||
public struct ArgDefinition
|
||||
{
|
||||
/// <summary>
|
||||
/// The name of the arg
|
||||
/// </summary>
|
||||
public string Name;
|
||||
|
||||
/// <summary>
|
||||
/// The type of the arg
|
||||
/// </summary>
|
||||
public Type Type;
|
||||
|
||||
/// <summary>
|
||||
/// Whether or not this arg has a default value
|
||||
/// </summary>
|
||||
public bool HasDefault;
|
||||
|
||||
/// <summary>
|
||||
/// ToString() helper
|
||||
/// </summary>
|
||||
public override string ToString()
|
||||
{
|
||||
return Name;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A struct which represents a command which can be called through the terminal interface
|
||||
/// </summary>
|
||||
public readonly struct Command
|
||||
{
|
||||
private readonly List<ArgDefinition> _argDefinitions;
|
||||
private readonly Delegate _callback;
|
||||
|
||||
/// <summary>
|
||||
/// A description of the command
|
||||
/// </summary>
|
||||
public string Description { get; }
|
||||
|
||||
/// <summary>
|
||||
/// The parsing mode which should be used for this command
|
||||
/// </summary>
|
||||
public ArgParseMode ParsingMode { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Constructor, which takes a callback function and uses its parameters to define argument definitions
|
||||
/// </summary>
|
||||
/// <param name="callback"></param>
|
||||
/// <param name="description"></param>
|
||||
/// <param name="parsingMode"></param>
|
||||
public Command(Delegate callback, string description, ArgParseMode parsingMode)
|
||||
{
|
||||
_argDefinitions = new List<ArgDefinition>();
|
||||
_callback = callback;
|
||||
Description = description;
|
||||
ParsingMode = parsingMode;
|
||||
CreateArgDefinitions();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Call to issue this command
|
||||
/// </summary>
|
||||
/// <param name="args">The args to call the command with</param>
|
||||
public void Issue(string[]? args)
|
||||
{
|
||||
ParseArgs(args, out var parsedArgs);
|
||||
_callback.Method.Invoke(_callback.Target, parsedArgs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns a readonly list of the arg definitions for this command
|
||||
/// </summary>
|
||||
public IReadOnlyList<ArgDefinition> GetDefinitions => _argDefinitions;
|
||||
|
||||
private void ParseArgs(string[]? args, out object[]? outParsedArgs)
|
||||
{
|
||||
if (args?.Length > _argDefinitions.Count)
|
||||
throw new TerminalInterfaceException(
|
||||
"Command parsing failed,"
|
||||
+ $" too many arguments for command: {_callback.Method.Name}."
|
||||
+ $" Expected: {_argDefinitions.Count}, got: {args.Length}."
|
||||
);
|
||||
|
||||
if (_argDefinitions.Count == 0)
|
||||
{
|
||||
outParsedArgs = null;
|
||||
return;
|
||||
}
|
||||
|
||||
outParsedArgs = new object[_argDefinitions.Count];
|
||||
|
||||
// Iterate through our defined definitions and try to parse the args into the correct types
|
||||
for (var i = 0; i < _argDefinitions.Count; i++)
|
||||
{
|
||||
var definition = _argDefinitions[i];
|
||||
ref var outArg = ref outParsedArgs[i];
|
||||
|
||||
if (args is null || args.Length <= i)
|
||||
{
|
||||
// If an arg is optional pass Type.Missing to use the function's defined default
|
||||
if (definition.HasDefault)
|
||||
{
|
||||
outArg = Type.Missing;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new TerminalInterfaceException(
|
||||
"Command parsing failed,"
|
||||
+ $" missing required argument: {definition.Name}"
|
||||
+ $" of type: {definition.Type.Name}"
|
||||
);
|
||||
}
|
||||
|
||||
var arg = args[i];
|
||||
|
||||
TryParse(arg, definition.Type, out outArg);
|
||||
}
|
||||
}
|
||||
|
||||
private static void TryParse(string arg, Type type, out object value)
|
||||
{
|
||||
// TODO: Add specific cases that we want to handle with our own parsing logic - e.g. vectors
|
||||
|
||||
try
|
||||
{
|
||||
value = Convert.ChangeType(arg, type);
|
||||
}
|
||||
catch
|
||||
{
|
||||
throw new TerminalInterfaceException($"Failed to parse command argument: {arg} to type: {type.Name}.");
|
||||
}
|
||||
}
|
||||
|
||||
private void CreateArgDefinitions()
|
||||
{
|
||||
var parameters = _callback.Method.GetParameters();
|
||||
|
||||
// Validation of single string parsing mode
|
||||
if (ParsingMode == ArgParseMode.Unparsed)
|
||||
{
|
||||
if (parameters.Length != 1)
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ " single string parsing mode requires exactly one parameter"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
|
||||
if (parameters[0].ParameterType != typeof(string))
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ " single string parsing mode requires a string parameter"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
}
|
||||
|
||||
foreach (var parameter in parameters)
|
||||
{
|
||||
if (!TypeIsSupported(parameter.ParameterType))
|
||||
throw new TerminalInterfaceException(
|
||||
"Failed to parse delegate parameters into argument types,"
|
||||
+ $" unsupported argument type: {parameter.ParameterType.Name}"
|
||||
+ $" in callback: {_callback.Method.Name}"
|
||||
);
|
||||
|
||||
var definition = new ArgDefinition
|
||||
{
|
||||
Name = parameter.Name ?? $"param_{parameter.Position}",
|
||||
Type = parameter.ParameterType,
|
||||
HasDefault = parameter.HasDefaultValue,
|
||||
};
|
||||
|
||||
_argDefinitions.Add(definition);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool TypeIsSupported(Type type)
|
||||
{
|
||||
// Convert.ChangeType() supports primitives, strings, and DateTime
|
||||
if (type.IsPrimitive)
|
||||
return true;
|
||||
|
||||
if (type == typeof(string))
|
||||
return true;
|
||||
|
||||
if (type == typeof(DateTime))
|
||||
return true;
|
||||
|
||||
// TODO: add any types for which we offer custom parsing logic
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,272 @@
|
|||
using System.Linq.Expressions;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using Brutal.Logging;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// The type of message the terminal interface is outputting
|
||||
/// </summary>
|
||||
public enum TerminalInterfaceOutputType
|
||||
{
|
||||
/// <summary>
|
||||
/// An informative message
|
||||
/// </summary>
|
||||
Message,
|
||||
|
||||
/// <summary>
|
||||
/// An error with the processing of a command
|
||||
/// </summary>
|
||||
Error,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Provides an interface which can be used to register terminal commands and handle terminal input.
|
||||
/// </summary>
|
||||
public class TerminalInterface
|
||||
{
|
||||
public static LogCategory Log = LogCategory.Make("TerminalInterface");
|
||||
|
||||
private readonly Dictionary<object, Dictionary<string, Command>> CommandLibrary = new();
|
||||
private readonly Dictionary<string, Command> StaticCommandLibrary = new();
|
||||
private readonly ConsoleWindow _consoleWindow;
|
||||
|
||||
/// <summary>
|
||||
/// Invoked with a message when the terminal interface wants to output something
|
||||
/// </summary>
|
||||
public event Action<string, TerminalInterfaceOutputType>? OnOutput;
|
||||
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
public TerminalInterface(ConsoleWindow consoleWindow)
|
||||
{
|
||||
_consoleWindow = consoleWindow;
|
||||
RegisterCommand(ListCommands);
|
||||
RegisterCommand(ClearConsole);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Executes a batch of terminal input commands.
|
||||
/// </summary>
|
||||
/// <param name="inInput">A collection of terminal input strings.</param>
|
||||
public void Execute(params ReadOnlySpan<string> inInput)
|
||||
{
|
||||
foreach (var commandLine in inInput)
|
||||
Execute(commandLine);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Parses terminal input and processes it as commands.
|
||||
/// </summary>
|
||||
/// <param name="inInput">The input string from the terminal</param>
|
||||
public bool Execute(string inInput)
|
||||
{
|
||||
// Split full input into individual command statements
|
||||
foreach (var commandString in Parser.SplitToCommands(inInput))
|
||||
try
|
||||
{
|
||||
ProcessCommand(commandString);
|
||||
}
|
||||
catch (TerminalInterfaceException e)
|
||||
{
|
||||
OutputProcessCommandError(commandString, e.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static Type? GetDelegateTypeForMethod(MethodBase inMethodInfo)
|
||||
{
|
||||
var parameterTypes = Array.ConvertAll(inMethodInfo.GetParameters(), p => p.ParameterType);
|
||||
// Direct lookup of the right Action arity. Returns false when no Action can represent the
|
||||
// signature: more than 16 parameters, or ByRef/pointer parameter types.
|
||||
return Expression.TryGetActionType(parameterTypes, out var delegateType) ? delegateType : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Register an object with TerminalAction methods
|
||||
/// </summary>
|
||||
/// <param name="inObject">The object we want to register commands from</param>
|
||||
/// <exception cref="TerminalInterfaceException"></exception>
|
||||
public void RegisterObject(object inObject)
|
||||
{
|
||||
var methods = GetMethodInfos(inObject);
|
||||
|
||||
foreach (var method in methods)
|
||||
{
|
||||
var delegateType = GetDelegateTypeForMethod(method);
|
||||
|
||||
if (delegateType != null)
|
||||
{
|
||||
if (method.IsStatic)
|
||||
RegisterCommand(Delegate.CreateDelegate(delegateType, method), inObject);
|
||||
else
|
||||
RegisterCommand(Delegate.CreateDelegate(delegateType, inObject, method), inObject);
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new TerminalInterfaceException(
|
||||
$"Error registering command: callback {method.Name} has an unsupported signature"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private IEnumerable<MethodInfo> GetMethodInfos(object inObject)
|
||||
{
|
||||
const BindingFlags flags =
|
||||
BindingFlags.Instance
|
||||
| BindingFlags.Public
|
||||
| BindingFlags.NonPublic
|
||||
| BindingFlags.FlattenHierarchy
|
||||
| BindingFlags.Static;
|
||||
|
||||
var objectType = inObject.GetType();
|
||||
var allMethods = objectType.GetMethods(flags);
|
||||
return allMethods.Where(m => m.GetCustomAttribute<TerminalActionAttribute>() != null);
|
||||
}
|
||||
|
||||
public void UnregisterObject(object inObject)
|
||||
{
|
||||
if (CommandLibrary.ContainsKey(inObject))
|
||||
CommandLibrary.Remove(inObject);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers commands which can be called from the terminal.
|
||||
/// </summary>
|
||||
/// <param name="inCallback">The function which the command will call</param>
|
||||
/// <param name="inObject">Object to which the command delegate is bound to. Null for methods</param>
|
||||
public void RegisterCommand(Delegate inCallback, object? inObject = null)
|
||||
{
|
||||
var attribute = inCallback.Method.GetCustomAttribute<TerminalActionAttribute>();
|
||||
|
||||
if (attribute is null)
|
||||
throw new TerminalInterfaceException(
|
||||
$"Error registering command:" + $" callback {inCallback.Method.Name} has no TerminalActionAttribute"
|
||||
);
|
||||
|
||||
if (inObject is not null)
|
||||
{
|
||||
if (!CommandLibrary.ContainsKey(inObject))
|
||||
CommandLibrary[inObject] = new Dictionary<string, Command>();
|
||||
|
||||
CommandLibrary[inObject][attribute.CommandName] = new Command(
|
||||
inCallback,
|
||||
attribute.Description,
|
||||
attribute.ParsingMode
|
||||
);
|
||||
}
|
||||
else
|
||||
{
|
||||
StaticCommandLibrary[attribute.CommandName] = new Command(
|
||||
inCallback,
|
||||
attribute.Description,
|
||||
attribute.ParsingMode
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private void ProcessCommand(string inCommandString)
|
||||
{
|
||||
// Split command into command name and arguments
|
||||
Parser.SplitCommand(inCommandString, out var commandName, out var argsString);
|
||||
|
||||
if (StaticCommandLibrary.ContainsKey(commandName))
|
||||
{
|
||||
var args = Parser.SplitToArgs(argsString, StaticCommandLibrary[commandName].ParsingMode);
|
||||
|
||||
// Issue the command
|
||||
StaticCommandLibrary[commandName].Issue(args);
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var (_, commands) in CommandLibrary)
|
||||
{
|
||||
if (commands.ContainsKey(commandName))
|
||||
{
|
||||
var args = Parser.SplitToArgs(argsString, commands[commandName].ParsingMode);
|
||||
|
||||
// Issue the command
|
||||
commands[commandName].Issue(args);
|
||||
return;
|
||||
}
|
||||
}
|
||||
Log.Error($"unknown command {commandName}, use 'help' for a list of commands");
|
||||
}
|
||||
|
||||
[TerminalAction("clear", "Clears the console output")]
|
||||
private void ClearConsole() => _consoleWindow.ClearConsole();
|
||||
|
||||
[TerminalAction("help", "Lists all registered commands and their descriptions")]
|
||||
private void ListCommands()
|
||||
{
|
||||
var commandCount = 0;
|
||||
var tableString = new TableString();
|
||||
|
||||
var cmds = new Dictionary<string, Command>();
|
||||
|
||||
// commands
|
||||
foreach (var (command, args) in StaticCommandLibrary)
|
||||
cmds.Add(command, args);
|
||||
|
||||
// instanced commands
|
||||
foreach (var (_, commands) in CommandLibrary)
|
||||
foreach (var (command, args) in commands)
|
||||
cmds.Add(command, args);
|
||||
|
||||
foreach (var cmd in cmds)
|
||||
PrintHelpLine(cmd.Key, cmd.Value);
|
||||
|
||||
_consoleWindow.Print($"listing {commandCount} commands");
|
||||
_consoleWindow.Print(
|
||||
"Multiple commands can be called in a single statement by separating them with a ';' semicolon"
|
||||
);
|
||||
tableString.Sort();
|
||||
tableString.ToConsole(_consoleWindow);
|
||||
OnOutput?.Invoke(string.Empty, TerminalInterfaceOutputType.Message);
|
||||
return;
|
||||
|
||||
void PrintHelpLine(string command, Command args)
|
||||
{
|
||||
commandCount++;
|
||||
|
||||
var definitions = args.GetDefinitions;
|
||||
if (definitions.Count == 0)
|
||||
{
|
||||
tableString.AddRow(command, args.Description);
|
||||
return;
|
||||
}
|
||||
|
||||
var argSb = new StringBuilder();
|
||||
for (var i = 0; i < definitions.Count; i++)
|
||||
{
|
||||
if (i > 0)
|
||||
argSb.Append(", ");
|
||||
var definition = args.GetDefinitions[i];
|
||||
argSb.Append('<');
|
||||
var type = definition.Type.ToString();
|
||||
// remove "System." from the type name
|
||||
if (type.StartsWith("System."))
|
||||
type = type[7..];
|
||||
type = type.ToLowerInvariant();
|
||||
argSb.Append(type);
|
||||
argSb.Append('>');
|
||||
if (definition.HasDefault)
|
||||
argSb.Append('?');
|
||||
argSb.Append(' ');
|
||||
argSb.Append(definition.Name);
|
||||
}
|
||||
tableString.AddRow(command, args.Description, argSb.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
private void OutputProcessCommandError(string inCommand, string inErrorMessage)
|
||||
{
|
||||
var message = $"Terminal interface failed to process command: {inCommand}, error: {inErrorMessage}";
|
||||
OnOutput?.Invoke(message, TerminalInterfaceOutputType.Error);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// An exception which is thrown when a terminal command fails to issue
|
||||
/// </summary>
|
||||
public class TerminalInterfaceException : Exception
|
||||
{
|
||||
/// <summary>
|
||||
/// Constructor
|
||||
/// </summary>
|
||||
/// <param name="message"></param>
|
||||
public TerminalInterfaceException(string message)
|
||||
: base(message) { }
|
||||
}
|
||||
|
|
@ -0,0 +1,90 @@
|
|||
using System.CommandLine.Parsing;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// A parsing utility class for the terminal interface
|
||||
/// </summary>
|
||||
internal static class Parser
|
||||
{
|
||||
private const char CommandDelimiter = ';';
|
||||
|
||||
/// <summary>
|
||||
/// Splits an input string into individual command strings
|
||||
/// </summary>
|
||||
/// <param name="inInput">The raw string from terminal input</param>
|
||||
/// <returns>A list of individual command strings</returns>
|
||||
public static List<string> SplitToCommands(string inInput)
|
||||
{
|
||||
var commands = new List<string>();
|
||||
var withinQuotes = false;
|
||||
var startIndex = 0;
|
||||
|
||||
void TryAddCommand(string command)
|
||||
{
|
||||
var trimmedCommand = command.Trim();
|
||||
if (trimmedCommand.Length > 0)
|
||||
commands.Add(trimmedCommand);
|
||||
}
|
||||
|
||||
// Ignore our delimiter if it's part of a quoted string
|
||||
for (var i = 0; i < inInput.Length; i++)
|
||||
if (inInput[i] == '\"')
|
||||
{
|
||||
withinQuotes = !withinQuotes;
|
||||
}
|
||||
else if (inInput[i] == CommandDelimiter && !withinQuotes)
|
||||
{
|
||||
// Split input into individual commands by delimiter
|
||||
TryAddCommand(inInput.Substring(startIndex, i - startIndex));
|
||||
startIndex = i + 1;
|
||||
}
|
||||
|
||||
// Add the last command if there is one
|
||||
if (startIndex < inInput.Length)
|
||||
TryAddCommand(inInput.Substring(startIndex).Trim());
|
||||
|
||||
return commands;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits a command string into a command name and args string
|
||||
/// </summary>
|
||||
/// <param name="inCommandString">The command string to split</param>
|
||||
/// <param name="inCommandName">The command name part of the input string</param>
|
||||
/// <param name="inArgsString">The args part of the input string</param>
|
||||
public static void SplitCommand(string inCommandString, out string inCommandName, out string inArgsString)
|
||||
{
|
||||
const StringSplitOptions flags = StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries;
|
||||
|
||||
// Split at first whitespace
|
||||
var split = inCommandString.Split(Array.Empty<char>(), 2, flags);
|
||||
|
||||
if (split.Length == 0)
|
||||
throw new TerminalInterfaceException("Command parsing failed, command string was empty.");
|
||||
|
||||
inCommandName = split[0].ToLower();
|
||||
inArgsString = split.Length > 1 ? split[1] : "";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Splits an arg string into individual args according to the parsing mode
|
||||
/// </summary>
|
||||
/// <param name="inArgsString">The string to split</param>
|
||||
/// <param name="inArgParseMode">The parsing mode to use</param>
|
||||
/// <returns>An array of arg strings, or null if the args string was empty</returns>
|
||||
public static string[]? SplitToArgs(string inArgsString, ArgParseMode inArgParseMode)
|
||||
{
|
||||
// If we're using single string parsing mode, return the args as a single string
|
||||
if (inArgParseMode == ArgParseMode.Unparsed)
|
||||
// Remove outer whitespace and quotes if they exist
|
||||
return new[] { inArgsString };
|
||||
|
||||
// If there are no args, return null
|
||||
if (string.IsNullOrEmpty(inArgsString))
|
||||
return null;
|
||||
|
||||
// If we're using default parsing mode, split the args into individual strings
|
||||
return CommandLineParser.SplitCommandLine(inArgsString).ToArray();
|
||||
}
|
||||
}
|
||||
3
brutal.imgui/Brutal.ImGui.Abstractions/GlobalUsings.cs
Normal file
3
brutal.imgui/Brutal.ImGui.Abstractions/GlobalUsings.cs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
global using Brutal.ImGuiApi.Extensions;
|
||||
global using Brutal.Numerics;
|
||||
global using Brutal.Pointers;
|
||||
32
brutal.imgui/Brutal.ImGui.Abstractions/ImGuiUtils.cs
Normal file
32
brutal.imgui/Brutal.ImGui.Abstractions/ImGuiUtils.cs
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
using Brutal.ImGuiApi;
|
||||
|
||||
namespace Brutal.ImGuiApi.Abstractions;
|
||||
|
||||
public static class ImGuiUtils
|
||||
{
|
||||
public static void SetLastFocusOnAppearing(bool force = false)
|
||||
{
|
||||
if (
|
||||
force
|
||||
|| ImGui.IsItemHovered()
|
||||
|| (ImGui.IsAnyItemFocused() && !ImGui.IsAnyItemActive() && !ImGui.IsMouseClicked(0))
|
||||
)
|
||||
ImGui.SetKeyboardFocusHere(-1); // Auto focus
|
||||
}
|
||||
|
||||
public static void TextShadow(ImString text, ImColor8 color)
|
||||
{
|
||||
if (text.IsEmpty)
|
||||
return;
|
||||
|
||||
var cursorPos = ImGui.GetCursorPos();
|
||||
ImGui.SetCursorPos(cursorPos - new float2(-1, -1));
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, 0);
|
||||
ImGui.Text(text);
|
||||
ImGui.PopStyleColor();
|
||||
ImGui.SetCursorPos(cursorPos);
|
||||
ImGui.PushStyleColor(ImGuiCol.Text, color);
|
||||
ImGui.Text(text);
|
||||
ImGui.PopStyleColor();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
public interface IPlatformBackend : IDisposable
|
||||
{
|
||||
public void NewFrame();
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
public interface IRendererBackend : IDisposable
|
||||
{
|
||||
public void NewFrame();
|
||||
}
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
public partial class GlfwBackend
|
||||
{
|
||||
private static partial class GlfwInterop
|
||||
{
|
||||
private const string MacOSLibraryName = "glfw";
|
||||
private const string WindowsLibraryName = "glfw3";
|
||||
|
||||
[LibraryImport(MacOSLibraryName, EntryPoint = "glfwGetCocoaWindow")]
|
||||
public static partial nint GetCocoaWindow(nint glfwWindow);
|
||||
|
||||
[LibraryImport(WindowsLibraryName, EntryPoint = "glfwGetWin32Window")]
|
||||
public static partial nint GetWin32Window(nint glfwWindow);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,136 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
using BOOL = int;
|
||||
using LONG = int;
|
||||
using UINT = uint;
|
||||
using HANDLE = nint;
|
||||
using HWND = nint;
|
||||
using LONG_PTR = nint;
|
||||
using LPARAM = nint;
|
||||
using LPCSTR = ReadOnlySpan<byte>;
|
||||
using LRESULT = nint;
|
||||
using WNDPROC = nint;
|
||||
using WPARAM = nuint;
|
||||
|
||||
public partial class GlfwBackend
|
||||
{
|
||||
private static partial class WindowsNative
|
||||
{
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial LONG_PTR GetWindowLongPtrW(HWND hWnd, int nIndex);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial LONG_PTR SetWindowLongPtrW(HWND hWnd, int nIndex, LONG_PTR dwNewLong);
|
||||
|
||||
[LibraryImport("user32.dll", EntryPoint = "GetWindowLongW")]
|
||||
public static partial LONG GetWindowLong(HWND hWnd, int nIndex);
|
||||
|
||||
[LibraryImport("user32.dll", EntryPoint = "SetWindowLongW")]
|
||||
public static partial LONG SetWindowLong(HWND hWnd, int nIndex, LONG dwNewLong);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial BOOL SetPropA(HWND hWnd, LPCSTR lpString, LONG_PTR lParam);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial HANDLE GetPropA(HWND hWnd, LPCSTR lpString);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial LPARAM GetMessageExtraInfo();
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial LRESULT CallWindowProcW(
|
||||
WNDPROC lpPrevWndFunc,
|
||||
HWND hWnd,
|
||||
UINT msg,
|
||||
WPARAM wParam,
|
||||
LPARAM lParam
|
||||
);
|
||||
|
||||
[LibraryImport("user32.dll")]
|
||||
public static partial LRESULT DefWindowProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
|
||||
|
||||
public static class Constants
|
||||
{
|
||||
public const int GWL_EXSTYLE = -20;
|
||||
public const int GWLP_WNDPROC = -4;
|
||||
public const int WS_EX_APPWINDOW = 0x00040000;
|
||||
public const int WS_EX_TOOLWINDOW = 0x00000080;
|
||||
|
||||
public const int WM_MOUSEMOVE = 0x0200;
|
||||
public const int WM_NCMOUSEMOVE = 0x00A0;
|
||||
public const int WM_LBUTTONDOWN = 0x0201;
|
||||
public const int WM_LBUTTONDBLCLK = 0x0203;
|
||||
public const int WM_LBUTTONUP = 0x0202;
|
||||
public const int WM_RBUTTONDOWN = 0x0204;
|
||||
public const int WM_RBUTTONDBLCLK = 0x0206;
|
||||
public const int WM_RBUTTONUP = 0x0205;
|
||||
public const int WM_MBUTTONDOWN = 0x0207;
|
||||
public const int WM_MBUTTONDBLCLK = 0x0209;
|
||||
public const int WM_MBUTTONUP = 0x0208;
|
||||
public const int WM_XBUTTONDOWN = 0x020B;
|
||||
public const int WM_XBUTTONDBLCLK = 0x020D;
|
||||
public const int WM_XBUTTONUP = 0x020C;
|
||||
}
|
||||
|
||||
public static unsafe delegate* unmanaged[Cdecl]<HWND, UINT, WPARAM, LPARAM, LRESULT> WndProcDelegate = &WndProc;
|
||||
|
||||
// WndProc hook
|
||||
public static ImGuiMouseSource GetMouseSourceFromMessageExtraInfo()
|
||||
{
|
||||
LPARAM extra_info = GetMessageExtraInfo();
|
||||
if ((extra_info & 0xFFFFFF80) == 0xFF515700)
|
||||
return ImGuiMouseSource.Pen;
|
||||
if ((extra_info & 0xFFFFFF80) == 0xFF515780)
|
||||
return ImGuiMouseSource.TouchScreen;
|
||||
return ImGuiMouseSource.Mouse;
|
||||
}
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
public static unsafe LRESULT WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
var backendHandle = GetPropA(hWnd, "IMGUI_BACKEND_DATA"u8);
|
||||
if (GCHandle.FromIntPtr(backendHandle).Target is not GlfwBackend backend)
|
||||
throw new Exception("Failed to retrieve backend");
|
||||
|
||||
var io = GetIO(backend._context);
|
||||
|
||||
var prevWndProc = backend._prevWndProc;
|
||||
var viewport = (ImGuiViewport*)GetPropA(hWnd, "IMGUI_VIEWPORT"u8);
|
||||
if (viewport is not null)
|
||||
{
|
||||
var viewportData = (ViewportData*)viewport->PlatformUserData;
|
||||
if (viewportData is not null)
|
||||
prevWndProc = viewportData->PrevWndProc;
|
||||
}
|
||||
|
||||
switch (msg)
|
||||
{
|
||||
// GLFW doesn't allow to distinguish Mouse vs TouchScreen vs Pen.
|
||||
// Add support for Win32 (based on imgui_impl_win32), because we rely on _TouchScreen info to trickle inputs differently.
|
||||
case Constants.WM_MOUSEMOVE:
|
||||
case Constants.WM_NCMOUSEMOVE:
|
||||
case Constants.WM_LBUTTONDOWN:
|
||||
case Constants.WM_LBUTTONDBLCLK:
|
||||
case Constants.WM_LBUTTONUP:
|
||||
case Constants.WM_RBUTTONDOWN:
|
||||
case Constants.WM_RBUTTONDBLCLK:
|
||||
case Constants.WM_RBUTTONUP:
|
||||
case Constants.WM_MBUTTONDOWN:
|
||||
case Constants.WM_MBUTTONDBLCLK:
|
||||
case Constants.WM_MBUTTONUP:
|
||||
case Constants.WM_XBUTTONDOWN:
|
||||
case Constants.WM_XBUTTONDBLCLK:
|
||||
case Constants.WM_XBUTTONUP:
|
||||
io.AddMouseSourceEvent(GetMouseSourceFromMessageExtraInfo());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
|
||||
return CallWindowProcW(prevWndProc, hWnd, msg, wParam, lParam);
|
||||
}
|
||||
}
|
||||
}
|
||||
1227
brutal.imgui/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs
Normal file
1227
brutal.imgui/Brutal.ImGui.Backends/PlatformBackends/GlfwBackend.cs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,16 @@
|
|||
using Brutal.OpenGlApi;
|
||||
|
||||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
public partial class OpenGlBackend
|
||||
{
|
||||
internal static class Helpers
|
||||
{
|
||||
public static unsafe int GetIntegerv(GlEnum name)
|
||||
{
|
||||
var value = 0;
|
||||
OpenGl.GetIntegerv(name, new Span<int>(&value, 1));
|
||||
return value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,605 @@
|
|||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using Brutal.Numerics;
|
||||
using Brutal.OpenGlApi;
|
||||
using Brutal.Pointers;
|
||||
using Brutal.Strings;
|
||||
|
||||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
using static OpenGlBackend.Helpers;
|
||||
|
||||
/**
|
||||
* Brutal port based on the default imgui_impl_opengl3 C++ code
|
||||
* Key variations:
|
||||
* - Assumes version 4.1+
|
||||
* - Haven't added multi-context support, assumes we can just GetContext()
|
||||
* - Doesn't support forward compatibility using GL_CONTEXT_COMPATIBILITY_PROFILE_BIT
|
||||
*/
|
||||
|
||||
public partial class OpenGlBackend : IRendererBackend
|
||||
{
|
||||
private static readonly Ptr<byte> Name = "Brutal.ImGuiApi.OpenGlBackend"u8;
|
||||
|
||||
public unsafe OpenGlBackend()
|
||||
{
|
||||
var io = ImGui.GetIO();
|
||||
|
||||
io.BackendRendererUserData = (nint)GCHandle.Alloc(this);
|
||||
io.BackendRendererName = Name;
|
||||
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasVtxOffset; // We can honor the ImDrawCmd::VtxOffset field, allowing for large meshes.
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasTextures; // We can honor ImGuiPlatformIO::Textures[] requests during render.
|
||||
io.BackendFlags |= ImGuiBackendFlags.RendererHasViewports; // We can create multi-viewports on the Renderer side (optional)
|
||||
|
||||
var versionMaj = GetIntegerv(OpenGl.GL_MAJOR_VERSION);
|
||||
var versionMin = GetIntegerv(OpenGl.GL_MINOR_VERSION);
|
||||
_glVersion = versionMaj * 100 + versionMin;
|
||||
|
||||
_hasClipOrigin = _glVersion >= 450;
|
||||
|
||||
if (!_hasClipOrigin)
|
||||
{
|
||||
var numExtensions = GetIntegerv(OpenGl.GL_NUM_EXTENSIONS);
|
||||
|
||||
for (uint i = 0; i < numExtensions; i++)
|
||||
{
|
||||
var extension = OpenGl.GetStringi(OpenGl.GL_EXTENSIONS, i);
|
||||
|
||||
if (extension is not null)
|
||||
{
|
||||
var utf8String = Utf8.GetNullTerminatedSpan(extension);
|
||||
if (utf8String.SequenceEqual("GL_ARB_clip_control"u8))
|
||||
_hasClipOrigin = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
InitMultiViewportSupport();
|
||||
|
||||
// Note: original C++ code does this on NewFrame if not already loaded, couldn't see a good reason to wait though
|
||||
CreateDeviceObjects(out _shader, out _vertexBuffer, out _indexBuffer);
|
||||
}
|
||||
|
||||
public void NewFrame() { }
|
||||
|
||||
public unsafe void RenderDrawData(ImDrawDataPtr drawData)
|
||||
{
|
||||
var width = (int)(drawData.DisplaySize.X * drawData.FramebufferScale.X);
|
||||
var height = (int)(drawData.DisplaySize.Y * drawData.FramebufferScale.Y);
|
||||
if (width <= 0 || height <= 0)
|
||||
return;
|
||||
|
||||
if (drawData.Textures.IsNotNull())
|
||||
{
|
||||
for (var i = 0; i < drawData.Textures.Value.Count; i++)
|
||||
{
|
||||
var tex = drawData.Textures.Value[i];
|
||||
if (tex.Status != ImTextureStatus.OK)
|
||||
UpdateTexture(tex);
|
||||
}
|
||||
}
|
||||
|
||||
using var backupState = new GlStateBackup();
|
||||
|
||||
var vertexArrayObject = OpenGl.GenVertexArray();
|
||||
SetupRenderState(drawData, width, height, vertexArrayObject);
|
||||
|
||||
// Will project scissor/clipping rectangles into framebuffer space
|
||||
var clipOff = drawData.DisplayPos; // (0,0) unless using multi-viewports
|
||||
var clipScale = drawData.FramebufferScale; // (1,1) unless using retina display which are often (2,2)
|
||||
|
||||
// Render command lists
|
||||
for (var n = 0; n < drawData.CmdListsCount; n++)
|
||||
{
|
||||
var drawList = drawData.CmdLists[n];
|
||||
|
||||
OpenGl.BufferData(
|
||||
GlBindTarget.ArrayBuffer,
|
||||
new Span<ImDrawVert>(drawList.VtxBuffer.Data, drawList.VtxBuffer.Count),
|
||||
GlBufferUsage.StreamDraw
|
||||
);
|
||||
|
||||
OpenGl.BufferData(
|
||||
GlBindTarget.ElementArrayBuffer,
|
||||
new Span<ushort>(drawList.IdxBuffer.Data, drawList.IdxBuffer.Count),
|
||||
GlBufferUsage.StreamDraw
|
||||
);
|
||||
|
||||
for (var i = 0; i < drawList.CmdBuffer.Count; i++)
|
||||
{
|
||||
var command = drawList.CmdBuffer[i];
|
||||
|
||||
// Project scissor/clipping rectangles into framebuffer space
|
||||
var clipMin = new float2(
|
||||
(command.ClipRect.X - clipOff.X) * clipScale.X,
|
||||
(command.ClipRect.Y - clipOff.Y) * clipScale.Y
|
||||
);
|
||||
var clipMax = new float2(
|
||||
(command.ClipRect.Z - clipOff.X) * clipScale.X,
|
||||
(command.ClipRect.W - clipOff.Y) * clipScale.Y
|
||||
);
|
||||
if (clipMax.X <= clipMin.X || clipMax.Y <= clipMin.Y)
|
||||
continue;
|
||||
|
||||
// Apply scissor/clipping rectangle (Y is inverted in OpenGL)
|
||||
OpenGl.Scissor(
|
||||
(int)clipMin.X,
|
||||
(int)(height - clipMax.Y),
|
||||
(int)(clipMax.X - clipMin.X),
|
||||
(int)(clipMax.Y - clipMin.Y)
|
||||
);
|
||||
|
||||
// Bind texture, Draw
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, (uint)command.GetTexID().Value);
|
||||
OpenGl.DrawIndexed(
|
||||
GlTopology.Triangles,
|
||||
GlIndexType.UShort,
|
||||
indexCount: (int)command.ElemCount,
|
||||
instanceCount: 1,
|
||||
firstIndex: (int)command.IdxOffset * sizeof(ushort),
|
||||
vertexOffset: (int)command.VtxOffset,
|
||||
firstInstance: 0
|
||||
);
|
||||
|
||||
OpenGl.Scissor(0, 0, width, height); // Reset scissor to full viewport;
|
||||
}
|
||||
}
|
||||
|
||||
OpenGl.DeleteVertexArrays([vertexArrayObject]);
|
||||
}
|
||||
|
||||
private unsafe void SetupRenderState(ImDrawDataPtr drawData, int width, int height, GlVertexArray vertexArrayObject)
|
||||
{
|
||||
OpenGl.Enable(GlCapability.Blend);
|
||||
OpenGl.BlendEquation(OpenGl.GL_FUNC_ADD);
|
||||
OpenGl.BlendFuncSeparate(
|
||||
OpenGl.GL_SRC_ALPHA,
|
||||
OpenGl.GL_ONE_MINUS_SRC_ALPHA,
|
||||
OpenGl.GL_ONE,
|
||||
OpenGl.GL_ONE_MINUS_SRC_ALPHA
|
||||
);
|
||||
OpenGl.Disable(GlCapability.CullFace);
|
||||
OpenGl.Disable(GlCapability.DepthTest);
|
||||
OpenGl.Disable(GlCapability.StencilTest);
|
||||
OpenGl.Enable(GlCapability.ScissorTest);
|
||||
|
||||
OpenGl.Disable(GlCapability.PrimitiveRestart);
|
||||
OpenGl.PolygonMode(GlFace.FrontAndBack, OpenGl.GL_FILL);
|
||||
|
||||
var clipOriginLowerLeft = true;
|
||||
if (_hasClipOrigin)
|
||||
{
|
||||
if (GetIntegerv(OpenGl.GL_CLIP_ORIGIN) == OpenGl.GL_UPPER_LEFT)
|
||||
clipOriginLowerLeft = false;
|
||||
}
|
||||
|
||||
// Setup viewport, orthographic projection matrix
|
||||
// Our visible imgui space lies from draw_data->DisplayPos (top left) to draw_data->DisplayPos+data_data->DisplaySize (bottom right).
|
||||
// DisplayPos is (0,0) for single viewport apps.
|
||||
OpenGl.Viewport(0, 0, width, height);
|
||||
|
||||
var left = drawData.DisplayPos.X;
|
||||
var right = drawData.DisplayPos.X + drawData.DisplaySize.X;
|
||||
var top = drawData.DisplayPos.Y;
|
||||
var bottom = drawData.DisplayPos.Y + drawData.DisplaySize.Y;
|
||||
|
||||
// Swap top and bottom if origin is upper left
|
||||
if (!clipOriginLowerLeft)
|
||||
{
|
||||
(top, bottom) = (bottom, top);
|
||||
}
|
||||
|
||||
_shader.Use();
|
||||
OpenGl.Uniform(_shader.Locations.Tex, 0);
|
||||
OpenGl.Uniform(
|
||||
_shader.Locations.Projection,
|
||||
float4x4.CreateOrthographicOffCenter(left, right, bottom, top, 0.0f, 1.0f)
|
||||
);
|
||||
|
||||
// We use combined texture/sampler state. Applications using GL 3.3 and GL ES 3.0 may set that otherwise.
|
||||
OpenGl.BindSampler(0, default);
|
||||
|
||||
// Bind vertex/index buffers and setup attributes for ImDrawVert
|
||||
vertexArrayObject.Bind();
|
||||
_vertexBuffer.Bind(GlBindTarget.ArrayBuffer);
|
||||
_indexBuffer.Bind(GlBindTarget.ElementArrayBuffer);
|
||||
|
||||
OpenGl.EnableVertexAttribArray((uint)_shader.Locations.Position);
|
||||
OpenGl.EnableVertexAttribArray((uint)_shader.Locations.Uv);
|
||||
OpenGl.EnableVertexAttribArray((uint)_shader.Locations.Color);
|
||||
|
||||
OpenGl.VertexAttribute(
|
||||
new GlAttribute(
|
||||
(uint)_shader.Locations.Position,
|
||||
2,
|
||||
OpenGl.GL_FLOAT,
|
||||
OpenGl.GL_FALSE,
|
||||
sizeof(ImDrawVert),
|
||||
0 // Offset of pos
|
||||
)
|
||||
);
|
||||
OpenGl.VertexAttribute(
|
||||
new GlAttribute(
|
||||
(uint)_shader.Locations.Uv,
|
||||
2,
|
||||
OpenGl.GL_FLOAT,
|
||||
OpenGl.GL_FALSE,
|
||||
sizeof(ImDrawVert),
|
||||
8 // Offset of uv
|
||||
)
|
||||
);
|
||||
OpenGl.VertexAttribute(
|
||||
new GlAttribute(
|
||||
(uint)_shader.Locations.Color,
|
||||
4,
|
||||
OpenGl.GL_UNSIGNED_BYTE,
|
||||
GlScaling.Normalized, // TODO: This is supposed to be true but API seems wrong...
|
||||
sizeof(ImDrawVert),
|
||||
16 // Offset of color
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
public unsafe void Dispose()
|
||||
{
|
||||
var io = ImGui.GetIO();
|
||||
|
||||
GCHandle.FromIntPtr(io.BackendRendererUserData).Free();
|
||||
io.BackendRendererUserData = IntPtr.Zero;
|
||||
io.BackendRendererName = null;
|
||||
io.BackendFlags &= ~(
|
||||
ImGuiBackendFlags.RendererHasVtxOffset
|
||||
| ImGuiBackendFlags.RendererHasTextures
|
||||
| ImGuiBackendFlags.RendererHasViewports
|
||||
);
|
||||
|
||||
ShutdownMultiViewportSupport();
|
||||
DestroyDeviceObjects();
|
||||
}
|
||||
|
||||
private static unsafe void UpdateTexture(ImTextureDataPtr tex)
|
||||
{
|
||||
if (tex.Status is ImTextureStatus.WantCreate or ImTextureStatus.WantUpdates)
|
||||
{
|
||||
OpenGl.PixelStorei(OpenGl.GL_UNPACK_ROW_LENGTH, 0);
|
||||
OpenGl.PixelStorei(OpenGl.GL_UNPACK_ALIGNMENT, 1);
|
||||
}
|
||||
|
||||
if (tex.Status is ImTextureStatus.WantCreate)
|
||||
{
|
||||
// Create and upload new texture to graphics system
|
||||
ImGui.Assert(tex.TexID.Value == 0 && tex.BackendUserData is 0);
|
||||
ImGui.Assert(tex.Format is ImTextureFormat.RGBA32);
|
||||
var pixels = tex.GetPixels();
|
||||
|
||||
// Upload texture to graphics system
|
||||
// (Bilinear sampling is required by default. Set 'io.Fonts->Flags |= ImFontAtlasFlags_NoBakedLines' or 'style.AntiAliasedLinesUseTex = false' to allow point/nearest sampling)
|
||||
GlTexture glTextureId = default;
|
||||
var lastGlTextureId = GetIntegerv(OpenGl.GL_TEXTURE_BINDING_2D);
|
||||
OpenGl.GenTextures(new ReadOnlySpan<GlTexture>(&glTextureId, 1));
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, glTextureId.Id);
|
||||
OpenGl.TexParameterInt(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MIN_FILTER, [(int)OpenGl.GL_LINEAR]);
|
||||
OpenGl.TexParameterInt(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_MAG_FILTER, [(int)OpenGl.GL_LINEAR]);
|
||||
OpenGl.TexParameterInt(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_WRAP_S, [(int)OpenGl.GL_CLAMP_TO_EDGE]);
|
||||
OpenGl.TexParameterInt(OpenGl.GL_TEXTURE_2D, OpenGl.GL_TEXTURE_WRAP_T, [(int)OpenGl.GL_CLAMP_TO_EDGE]);
|
||||
OpenGl.TexImage2D(
|
||||
OpenGl.GL_TEXTURE_2D,
|
||||
0,
|
||||
(int)OpenGl.GL_RGBA,
|
||||
tex.Width,
|
||||
tex.Height,
|
||||
0,
|
||||
OpenGl.GL_RGBA,
|
||||
OpenGl.GL_UNSIGNED_BYTE,
|
||||
(void*)pixels
|
||||
);
|
||||
|
||||
// Store identifiers
|
||||
tex.SetTexID(new ImTextureID((nint)glTextureId.Id));
|
||||
tex.SetStatus(ImTextureStatus.OK);
|
||||
|
||||
// Restore state
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, (uint)lastGlTextureId);
|
||||
}
|
||||
else if (tex.Status == ImTextureStatus.WantUpdates)
|
||||
{
|
||||
// Update selected blocks. We only ever write to textures regions which have never been used before!
|
||||
// This backend choose to use tex.Updates[] but you can use tex.UpdateRect to upload a single region.
|
||||
var lastGlTextureId = GetIntegerv(OpenGl.GL_TEXTURE_BINDING_2D);
|
||||
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, (uint)tex.TexID.Value);
|
||||
OpenGl.PixelStorei(OpenGl.GL_UNPACK_ROW_LENGTH, tex.Width);
|
||||
for (var i = 0; i < tex.Updates.Count; i++)
|
||||
{
|
||||
var r = tex.Updates[i];
|
||||
OpenGl.TexSubImage2D(
|
||||
OpenGl.GL_TEXTURE_2D,
|
||||
0,
|
||||
r.x,
|
||||
r.y,
|
||||
r.w,
|
||||
r.h,
|
||||
(int)OpenGl.GL_RGBA,
|
||||
OpenGl.GL_UNSIGNED_BYTE,
|
||||
(void*)tex.GetPixelsAt(r.x, r.y)
|
||||
);
|
||||
}
|
||||
OpenGl.PixelStorei(OpenGl.GL_UNPACK_ROW_LENGTH, 0);
|
||||
tex.SetStatus(ImTextureStatus.OK);
|
||||
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, (uint)lastGlTextureId); // Restore state
|
||||
}
|
||||
else if (tex is { Status: ImTextureStatus.WantDestroy, UnusedFrames: > 0 })
|
||||
DestroyTexture(tex);
|
||||
}
|
||||
|
||||
private void CreateDeviceObjects(out Shader shader, out GlBuffer vertexBuffer, out GlBuffer indexBuffer)
|
||||
{
|
||||
// Note: at this point the C++ backend does some gl state backup/restore.
|
||||
// It didn't appear that any of it was actually required, so skipped here...
|
||||
|
||||
shader = new Shader();
|
||||
|
||||
ReadOnlySpan<GlBuffer> buffers = stackalloc GlBuffer[2];
|
||||
OpenGl.GenBuffers(buffers);
|
||||
|
||||
vertexBuffer = buffers[0];
|
||||
indexBuffer = buffers[1];
|
||||
}
|
||||
|
||||
private void DestroyDeviceObjects()
|
||||
{
|
||||
_shader.Dispose();
|
||||
OpenGl.DeleteBuffers([_vertexBuffer, _indexBuffer]);
|
||||
|
||||
// Destroy all textures
|
||||
var textures = ImGui.GetPlatformIO().Textures;
|
||||
foreach (var tex in textures)
|
||||
{
|
||||
if (tex.RefCount is 1)
|
||||
DestroyTexture(tex);
|
||||
}
|
||||
}
|
||||
|
||||
private static void DestroyTexture(ImTextureDataPtr tex)
|
||||
{
|
||||
var glTextureId = new GlTexture { Id = (uint)tex.TexID.Value };
|
||||
OpenGl.DeleteTextures([glTextureId]);
|
||||
|
||||
// Clear identifiers and mark as destroyed (in order to allow e.g. calling InvalidateDeviceObjects while running)
|
||||
tex.SetTexID(ImTextureID.Invalid);
|
||||
tex.SetStatus(ImTextureStatus.Destroyed);
|
||||
}
|
||||
|
||||
private Shader _shader;
|
||||
private readonly GlBuffer _vertexBuffer;
|
||||
private readonly GlBuffer _indexBuffer;
|
||||
|
||||
private int _glVersion;
|
||||
private bool _hasClipOrigin;
|
||||
|
||||
private unsafe struct GlStateBackup : IDisposable
|
||||
{
|
||||
private readonly int _lastActiveTexture;
|
||||
private readonly uint _lastProgram;
|
||||
private readonly uint _lastTexture;
|
||||
private readonly uint _lastSampler;
|
||||
private readonly uint _lastArrayBuffer;
|
||||
private readonly uint _lastVertexArrayObject;
|
||||
private fixed int _lastPolygonMode[2];
|
||||
private fixed int _lastViewport[4];
|
||||
private fixed int _lastScissorBox[4];
|
||||
private readonly int _lastBlendSrcRgb;
|
||||
private readonly int _lastBlendDstRgb;
|
||||
private readonly int _lastBlendSrcAlpha;
|
||||
private readonly int _lastBlendDstAlpha;
|
||||
private readonly int _lastBlendEquationRgb;
|
||||
private readonly int _lastBlendEquationAlpha;
|
||||
private readonly bool _lastEnableBlend;
|
||||
private readonly bool _lastEnableCullFace;
|
||||
private readonly bool _lastEnableDepthTest;
|
||||
private readonly bool _lastEnableStencilTest;
|
||||
private readonly bool _lastEnableScissorTest;
|
||||
private readonly bool _lastEnablePrimitiveRestart;
|
||||
|
||||
public GlStateBackup()
|
||||
{
|
||||
// Backup GL state
|
||||
_lastActiveTexture = GetIntegerv(OpenGl.GL_ACTIVE_TEXTURE);
|
||||
OpenGl.ActiveTexture(OpenGl.GL_TEXTURE0);
|
||||
_lastProgram = (uint)GetIntegerv(OpenGl.GL_CURRENT_PROGRAM);
|
||||
_lastTexture = (uint)GetIntegerv(OpenGl.GL_TEXTURE_BINDING_2D);
|
||||
_lastSampler = (uint)GetIntegerv(OpenGl.GL_SAMPLER_BINDING);
|
||||
_lastArrayBuffer = (uint)GetIntegerv(OpenGl.GL_ARRAY_BUFFER_BINDING);
|
||||
_lastVertexArrayObject = (uint)GetIntegerv(OpenGl.GL_VERTEX_ARRAY_BINDING);
|
||||
fixed (int* lastPolygonMode = _lastPolygonMode)
|
||||
OpenGl.GetIntegerv(OpenGl.GL_POLYGON_MODE, new ReadOnlySpan<int>(lastPolygonMode, 2));
|
||||
fixed (int* lastViewport = _lastViewport)
|
||||
OpenGl.GetIntegerv(OpenGl.GL_VIEWPORT, new ReadOnlySpan<int>(lastViewport, 4));
|
||||
fixed (int* lastScissorBox = _lastScissorBox)
|
||||
OpenGl.GetIntegerv(OpenGl.GL_SCISSOR_BOX, new ReadOnlySpan<int>(lastScissorBox, 4));
|
||||
_lastBlendSrcRgb = GetIntegerv(OpenGl.GL_BLEND_SRC_RGB);
|
||||
_lastBlendDstRgb = GetIntegerv(OpenGl.GL_BLEND_DST_RGB);
|
||||
_lastBlendSrcAlpha = GetIntegerv(OpenGl.GL_BLEND_SRC_ALPHA);
|
||||
_lastBlendDstAlpha = GetIntegerv(OpenGl.GL_BLEND_DST_ALPHA);
|
||||
_lastBlendEquationRgb = GetIntegerv(OpenGl.GL_BLEND_EQUATION_RGB);
|
||||
_lastBlendEquationAlpha = GetIntegerv(OpenGl.GL_BLEND_EQUATION_ALPHA);
|
||||
_lastEnableBlend = OpenGl.IsEnabled(OpenGl.GL_BLEND);
|
||||
_lastEnableCullFace = OpenGl.IsEnabled(OpenGl.GL_CULL_FACE);
|
||||
_lastEnableDepthTest = OpenGl.IsEnabled(OpenGl.GL_DEPTH_TEST);
|
||||
_lastEnableStencilTest = OpenGl.IsEnabled(OpenGl.GL_STENCIL_TEST);
|
||||
_lastEnableScissorTest = OpenGl.IsEnabled(OpenGl.GL_SCISSOR_TEST);
|
||||
_lastEnablePrimitiveRestart = OpenGl.IsEnabled(OpenGl.GL_PRIMITIVE_RESTART);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Restore modified GL state
|
||||
// This "glIsProgram()" check is required because if the program is "pending deletion" at the time of binding backup, it will have been deleted by now and will cause an OpenGL error. See #6220.
|
||||
if (_lastProgram is 0 || OpenGl.IsProgram(new GlProgram(_lastProgram)))
|
||||
new GlProgram(_lastProgram).Use();
|
||||
OpenGl.BindTexture(OpenGl.GL_TEXTURE_2D, _lastTexture);
|
||||
OpenGl.BindSampler(0, new GlSampler(_lastSampler));
|
||||
OpenGl.ActiveTexture((uint)_lastActiveTexture);
|
||||
new GlVertexArray(_lastVertexArrayObject).Bind();
|
||||
new GlBuffer(_lastArrayBuffer).Bind(GlBindTarget.ArrayBuffer);
|
||||
OpenGl.BlendEquationSeparate((uint)_lastBlendEquationRgb, (uint)_lastBlendEquationAlpha);
|
||||
OpenGl.BlendFuncSeparate(
|
||||
(uint)_lastBlendSrcRgb,
|
||||
(uint)_lastBlendDstRgb,
|
||||
(uint)_lastBlendSrcAlpha,
|
||||
(uint)_lastBlendDstAlpha
|
||||
);
|
||||
if (_lastEnableBlend)
|
||||
OpenGl.Enable(GlCapability.Blend);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.Blend);
|
||||
if (_lastEnableCullFace)
|
||||
OpenGl.Enable(GlCapability.CullFace);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.CullFace);
|
||||
if (_lastEnableDepthTest)
|
||||
OpenGl.Enable(GlCapability.DepthTest);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.DepthTest);
|
||||
if (_lastEnableStencilTest)
|
||||
OpenGl.Enable(GlCapability.StencilTest);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.StencilTest);
|
||||
if (_lastEnableScissorTest)
|
||||
OpenGl.Enable(GlCapability.ScissorTest);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.ScissorTest);
|
||||
if (_lastEnablePrimitiveRestart)
|
||||
OpenGl.Enable(GlCapability.PrimitiveRestart);
|
||||
else
|
||||
OpenGl.Disable(GlCapability.PrimitiveRestart);
|
||||
|
||||
OpenGl.PolygonMode(GlFace.FrontAndBack, (uint)_lastPolygonMode[0]);
|
||||
|
||||
OpenGl.Viewport(_lastViewport[0], _lastViewport[1], _lastViewport[2], _lastViewport[3]);
|
||||
OpenGl.Scissor(_lastScissorBox[0], _lastScissorBox[1], _lastScissorBox[2], _lastScissorBox[3]);
|
||||
}
|
||||
}
|
||||
|
||||
private struct Shader : IDisposable
|
||||
{
|
||||
public Shader()
|
||||
{
|
||||
Program = BuildProgram();
|
||||
Locations.Tex = Program.GetUniformLocation("Texture"u8);
|
||||
Locations.Projection = Program.GetUniformLocation("Projection"u8);
|
||||
Locations.Position = OpenGl.GetAttribLocation(Program, "Position"u8);
|
||||
Locations.Uv = OpenGl.GetAttribLocation(Program, "UV"u8);
|
||||
Locations.Color = OpenGl.GetAttribLocation(Program, "Color"u8);
|
||||
}
|
||||
|
||||
public void Use()
|
||||
{
|
||||
Program.Use();
|
||||
}
|
||||
|
||||
public readonly GlProgram Program;
|
||||
public readonly AttributeLocations Locations;
|
||||
|
||||
public struct AttributeLocations
|
||||
{
|
||||
public int Tex;
|
||||
public int Projection;
|
||||
public int Position;
|
||||
public int Uv;
|
||||
public int Color;
|
||||
}
|
||||
|
||||
private static GlProgram BuildProgram()
|
||||
{
|
||||
using var vertShaderHandle = OpenGl
|
||||
.CreateShader(GlShaderType.Vertex)
|
||||
.SetSource(ShaderSource.Vert)
|
||||
.Compile();
|
||||
|
||||
using var fragShaderHandle = OpenGl
|
||||
.CreateShader(GlShaderType.Fragment)
|
||||
.SetSource(ShaderSource.Frag)
|
||||
.Compile();
|
||||
|
||||
var shaderHandle = OpenGl.CreateProgram().Attach(vertShaderHandle, fragShaderHandle).Link();
|
||||
|
||||
OpenGl.DetachShader(shaderHandle, vertShaderHandle);
|
||||
OpenGl.DetachShader(shaderHandle, fragShaderHandle);
|
||||
|
||||
return shaderHandle;
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Program.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private static class ShaderSource
|
||||
{
|
||||
public const string Vert = """
|
||||
#version 410 core
|
||||
layout (location = 0) in vec2 Position;
|
||||
layout (location = 1) in vec2 UV;
|
||||
layout (location = 2) in vec4 Color;
|
||||
uniform mat4 Projection;
|
||||
out vec2 Frag_UV;
|
||||
out vec4 Frag_Color;
|
||||
void main()
|
||||
{
|
||||
Frag_UV = UV;
|
||||
Frag_Color = Color;
|
||||
gl_Position = Projection * vec4(Position.xy,0,1);
|
||||
}
|
||||
""";
|
||||
|
||||
public const string Frag = """
|
||||
#version 410 core
|
||||
in vec2 Frag_UV;
|
||||
in vec4 Frag_Color;
|
||||
uniform sampler2D Texture;
|
||||
layout (location = 0) out vec4 Out_Color;
|
||||
void main()
|
||||
{
|
||||
Out_Color = Frag_Color * texture(Texture, Frag_UV.st);
|
||||
}
|
||||
""";
|
||||
}
|
||||
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
// MULTI-VIEWPORT / PLATFORM INTERFACE SUPPORT
|
||||
// This is an _advanced_ and _optional_ feature, allowing the backend to create and handle multiple viewports simultaneously.
|
||||
// If you are new to dear imgui or creating a new binding for dear imgui, it is recommended that you completely ignore this section first..
|
||||
//--------------------------------------------------------------------------------------------------------
|
||||
|
||||
[UnmanagedCallersOnly(CallConvs = [typeof(CallConvCdecl)])]
|
||||
private static unsafe void RenderWindow(ImGuiViewport* viewport)
|
||||
{
|
||||
if (!viewport->Flags.HasFlag(ImGuiViewportFlags.NoRendererClear))
|
||||
{
|
||||
OpenGl.ClearColor(new float4(float3.Zero, 1.0f));
|
||||
OpenGl.Clear(GlClearBit.Color);
|
||||
}
|
||||
|
||||
var handle = GCHandle.FromIntPtr(ImGui.GetIO().BackendRendererUserData);
|
||||
if (handle.Target is not OpenGlBackend backend)
|
||||
throw new Exception("Failed to retrieve OpenGL backend");
|
||||
|
||||
backend.RenderDrawData(viewport->DrawData);
|
||||
}
|
||||
|
||||
private static unsafe void InitMultiViewportSupport()
|
||||
{
|
||||
var platformIo = ImGui.GetPlatformIO();
|
||||
delegate* unmanaged[Cdecl]<ImGuiViewport*, void> renderWindowFunction = &RenderWindow;
|
||||
platformIo.Renderer_RenderWindow = (nint)renderWindowFunction;
|
||||
}
|
||||
|
||||
private static void ShutdownMultiViewportSupport()
|
||||
{
|
||||
ImGui.DestroyPlatformWindows();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,424 @@
|
|||
using Brutal.VulkanApi;
|
||||
using Brutal.VulkanApi.Abstractions;
|
||||
|
||||
namespace Brutal.ImGuiApi.Backends;
|
||||
|
||||
public partial class VulkanBackend
|
||||
{
|
||||
private static class Helpers
|
||||
{
|
||||
public static unsafe VkSurfaceFormatKHR SelectSurfaceFormat(
|
||||
PhysicalDevice physicalDevice,
|
||||
VkSurfaceKHR surface,
|
||||
ReadOnlySpan<VkFormat> requestFormats,
|
||||
VkColorSpaceKHR requestColorSpace
|
||||
)
|
||||
{
|
||||
Assert(!requestFormats.IsEmpty);
|
||||
|
||||
// Per Spec Format and View Format are expected to be the same unless VK_IMAGE_CREATE_MUTABLE_BIT was set at image creation
|
||||
// Assuming that the default behavior is without setting this bit, there is no need for separate Swapchain image and image view format
|
||||
// Additionally several new color spaces were introduced with Vulkan Spec v1.0.40,
|
||||
// hence we must make sure that a format with the mostly available color space, VK_COLOR_SPACE_SRGB_NONLINEAR_KHR, is found and used.
|
||||
var surfaceFormatCount = physicalDevice.GetSurfaceFormatsKHR_Count(surface);
|
||||
Span<VkSurfaceFormatKHR> formats = stackalloc VkSurfaceFormatKHR[surfaceFormatCount];
|
||||
physicalDevice.GetSurfaceFormatsKHR_Write(surface, formats);
|
||||
|
||||
// First check if only one format, VK_FORMAT_UNDEFINED, is available, which would imply that any format is available
|
||||
if (formats.Length is 1)
|
||||
{
|
||||
if (formats[0].Format is VkFormat.Undefined)
|
||||
return new VkSurfaceFormatKHR { Format = requestFormats[0], ColorSpace = requestColorSpace };
|
||||
|
||||
// No point in searching another format
|
||||
return formats[0];
|
||||
}
|
||||
|
||||
// Request several formats, the first found will be used
|
||||
foreach (var t in requestFormats)
|
||||
foreach (var format in formats)
|
||||
if (format.Format == t && format.ColorSpace == requestColorSpace)
|
||||
return format;
|
||||
|
||||
// If none of the requested image formats could be found, use the first available
|
||||
return formats[0];
|
||||
}
|
||||
|
||||
public static unsafe VkPresentModeKHR SelectPresentMode(
|
||||
PhysicalDevice physicalDevice,
|
||||
VkSurfaceKHR surface,
|
||||
ReadOnlySpan<VkPresentModeKHR> requestModes
|
||||
)
|
||||
{
|
||||
Assert(!requestModes.IsEmpty);
|
||||
|
||||
// Request a certain mode and confirm that it is available. If not use VK_PRESENT_MODE_FIFO_KHR which is mandatory
|
||||
var numModes = physicalDevice.GetSurfacePresentModesKHR_Count(surface);
|
||||
Span<VkPresentModeKHR> modes = stackalloc VkPresentModeKHR[numModes];
|
||||
physicalDevice.GetSurfacePresentModesKHR_Write(surface, modes);
|
||||
|
||||
foreach (var requestMode in requestModes)
|
||||
foreach (var mode in modes)
|
||||
if (requestMode == mode)
|
||||
return requestMode;
|
||||
|
||||
return VkPresentModeKHR.FifoKHR; // Always available
|
||||
}
|
||||
|
||||
// TODO: Can we pass command pool?
|
||||
public static unsafe void CreateOrResizeWindow(
|
||||
PhysicalDevice physicalDevice,
|
||||
Device device,
|
||||
WindowImpl* window,
|
||||
Queue queue,
|
||||
int queueFamily,
|
||||
int width,
|
||||
int height,
|
||||
int minImageCount
|
||||
)
|
||||
{
|
||||
CreateWindowSwapChain(physicalDevice, device, window, width, height, minImageCount);
|
||||
CreateWindowCommandBuffers(physicalDevice, device, window, queueFamily);
|
||||
|
||||
// FIXME: to submit the command buffer, we need a queue. In the examples folder, the ImGui_ImplVulkanH_CreateOrResizeWindow function is called
|
||||
// before the ImGui_ImplVulkan_Init function, so we don't have access to the queue yet. Here we have the queue_family that we can use to grab
|
||||
// a queue from the device and submit the command buffer. It would be better to have access to the queue as suggested in the FIXME below.
|
||||
var commandPool = device.CreateCommandPool(
|
||||
new VkCommandPoolCreateInfo
|
||||
{
|
||||
QueueFamilyIndex = queueFamily,
|
||||
Flags = VkCommandPoolCreateFlags.ResetCommandBufferBit,
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
var fence = device.CreateFence(new VkFenceCreateInfo { Flags = 0 }, null);
|
||||
|
||||
var commandBuffer = device.AllocateCommandBuffer(
|
||||
new VkCommandBufferAllocateInfo { CommandPool = commandPool, Level = VkCommandBufferLevel.Primary }
|
||||
);
|
||||
|
||||
commandBuffer.Begin(new VkCommandBufferBeginInfo { Flags = VkCommandBufferUsageFlags.OneTimeSubmitBit });
|
||||
|
||||
// Transition the images to the correct layout for rendering
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
{
|
||||
var barrier = new VkImageMemoryBarrier
|
||||
{
|
||||
Image = window->Frames[i].Backbuffer,
|
||||
OldLayout = VkImageLayout.Undefined,
|
||||
NewLayout = VkImageLayout.PresentSrcKHR,
|
||||
SrcQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
|
||||
DstQueueFamilyIndex = VK.QUEUE_FAMILY_IGNORED,
|
||||
SubresourceRange = new VkImageSubresourceRange
|
||||
{
|
||||
AspectMask = VkImageAspectFlags.ColorBit,
|
||||
LevelCount = 1,
|
||||
LayerCount = 1,
|
||||
},
|
||||
};
|
||||
commandBuffer.PipelineBarrier(
|
||||
VkPipelineStageFlags.BottomOfPipeBit,
|
||||
VkPipelineStageFlags.ColorAttachmentOutputBit,
|
||||
VkDependencyFlags.None,
|
||||
[],
|
||||
[],
|
||||
[barrier]
|
||||
);
|
||||
}
|
||||
|
||||
commandBuffer.End();
|
||||
|
||||
queue.Submit([], [], [commandBuffer], [], fence);
|
||||
device.WaitForFences([fence], true, -1);
|
||||
|
||||
// Destroy command buffer and fence and command pool
|
||||
device.DestroyCommandPool(commandPool, null);
|
||||
device.DestroyFence(fence, null);
|
||||
}
|
||||
|
||||
public static unsafe void DestroyWindow(Instance instance, Device device, WindowImpl* window)
|
||||
{
|
||||
// TODO: ???
|
||||
device.WaitIdle(); // FIXME: We could wait on the Queue if we had the queue in wd-> (otherwise VulkanH functions can't use globals)
|
||||
//vkQueueWaitIdle(bd->Queue);
|
||||
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
DestroyFrame(device, &window->Frames.DataRaw[i]);
|
||||
for (var i = 0; i < window->SemaphoreCount; i++)
|
||||
DestroyFrameSemaphores(device, &window->FrameSemaphores.DataRaw[i]);
|
||||
window->Frames.Clear();
|
||||
window->FrameSemaphores.Clear();
|
||||
device.DestroyRenderPass(window->RenderPass, null);
|
||||
device.DestroySwapchainKHR(window->Swapchain, null);
|
||||
instance.DestroySurfaceKHR(window->Surface, null);
|
||||
|
||||
*window = default;
|
||||
}
|
||||
|
||||
// Also destroy old swap chain and in-flight frames data, if any.
|
||||
private static unsafe void CreateWindowSwapChain(
|
||||
PhysicalDevice physicalDevice,
|
||||
Device device,
|
||||
WindowImpl* window,
|
||||
int width,
|
||||
int height,
|
||||
int minImageCount
|
||||
)
|
||||
{
|
||||
var oldSwapchain = window->Swapchain;
|
||||
window->Swapchain = default;
|
||||
// TODO: NOOOOOOO
|
||||
device.WaitIdle();
|
||||
|
||||
// We don't use ImGui_ImplVulkanH_DestroyWindow() because we want to preserve the old swapchain to create the new one.
|
||||
// Destroy old Framebuffer
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
DestroyFrame(device, &window->Frames.DataRaw[i]);
|
||||
for (var i = 0; i < window->SemaphoreCount; i++)
|
||||
DestroyFrameSemaphores(device, &window->FrameSemaphores.DataRaw[i]);
|
||||
window->Frames.Clear();
|
||||
window->FrameSemaphores.Clear();
|
||||
window->ImageCount = 0;
|
||||
if (window->RenderPass.IsNotNull())
|
||||
device.DestroyRenderPass(window->RenderPass, null);
|
||||
|
||||
// If min image count was not specified, request different count of images dependent on selected present mode
|
||||
if (minImageCount is 0)
|
||||
minImageCount = GetMinImageCountFromPresentMode(window->PresentMode);
|
||||
|
||||
// Create Swapchain
|
||||
{
|
||||
var cap = physicalDevice.GetSurfaceCapabilitiesKHR(window->Surface);
|
||||
|
||||
var info = new VkSwapchainCreateInfoKHR
|
||||
{
|
||||
Surface = window->Surface,
|
||||
MinImageCount = minImageCount,
|
||||
ImageFormat = window->SurfaceFormat.Format,
|
||||
ImageColorSpace = window->SurfaceFormat.ColorSpace,
|
||||
ImageArrayLayers = 1,
|
||||
ImageUsage = VkImageUsageFlags.ColorAttachmentBit,
|
||||
ImageSharingMode = VkSharingMode.Exclusive, // Assume that graphics family == present family
|
||||
PreTransform = cap.SupportedTransforms.HasFlag(VkSurfaceTransformFlagsKHR.IdentityBitKHR)
|
||||
? VkSurfaceTransformFlagsKHR.IdentityBitKHR
|
||||
: cap.CurrentTransform,
|
||||
CompositeAlpha = VkCompositeAlphaFlagsKHR.OpaqueBitKHR,
|
||||
PresentMode = window->PresentMode,
|
||||
Clipped = true,
|
||||
OldSwapchain = oldSwapchain,
|
||||
};
|
||||
if (info.MinImageCount < cap.MinImageCount)
|
||||
info.MinImageCount = cap.MinImageCount;
|
||||
else if (cap.MaxImageCount != 0 && info.MinImageCount > cap.MaxImageCount)
|
||||
info.MinImageCount = cap.MaxImageCount;
|
||||
if (cap.CurrentExtent.Width == -1)
|
||||
{
|
||||
window->Width = width;
|
||||
window->Height = height;
|
||||
info.ImageExtent.Width = width;
|
||||
info.ImageExtent.Height = height;
|
||||
}
|
||||
else
|
||||
{
|
||||
window->Width = cap.CurrentExtent.Width;
|
||||
window->Height = cap.CurrentExtent.Height;
|
||||
info.ImageExtent.Width = cap.CurrentExtent.Width;
|
||||
info.ImageExtent.Height = cap.CurrentExtent.Height;
|
||||
}
|
||||
window->Swapchain = device.CreateSwapchainKHR(info, null);
|
||||
window->ImageCount = device.GetSwapchainImagesKHR_Count(window->Swapchain);
|
||||
Span<VkImage> backBuffers = stackalloc VkImage[window->ImageCount];
|
||||
Assert(window->ImageCount >= minImageCount);
|
||||
device.GetSwapchainImagesKHR_Write(window->Swapchain, backBuffers);
|
||||
|
||||
window->SemaphoreCount = window->ImageCount + 1;
|
||||
window->Frames.Count = window->ImageCount;
|
||||
window->FrameSemaphores.Count = window->SemaphoreCount;
|
||||
// TODO: Do we need to zero out this memory?
|
||||
// memset(window->Frames.Data, 0, window->Frames.size_in_bytes());
|
||||
// memset(window->FrameSemaphores.Data, 0, window->FrameSemaphores.size_in_bytes());
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
window->Frames.Data[i].Backbuffer = backBuffers[i];
|
||||
}
|
||||
if (oldSwapchain.IsNotNull())
|
||||
device.DestroySwapchainKHR(oldSwapchain, null);
|
||||
|
||||
// Create the Render Pass
|
||||
{
|
||||
var attachment = new VkAttachmentDescription
|
||||
{
|
||||
Format = window->SurfaceFormat.Format,
|
||||
Samples = VkSampleCountFlags._1Bit,
|
||||
LoadOp = window->ClearEnable ? VkAttachmentLoadOp.Clear : VkAttachmentLoadOp.DontCare,
|
||||
StoreOp = VkAttachmentStoreOp.Store,
|
||||
StencilLoadOp = VkAttachmentLoadOp.DontCare,
|
||||
StencilStoreOp = VkAttachmentStoreOp.DontCare,
|
||||
InitialLayout = VkImageLayout.Undefined,
|
||||
FinalLayout = VkImageLayout.PresentSrcKHR,
|
||||
};
|
||||
var colorAttachment = new VkAttachmentReference
|
||||
{
|
||||
Attachment = 0,
|
||||
Layout = VkImageLayout.ColorAttachmentOptimal,
|
||||
};
|
||||
var subPass = new VkSubpassDescription
|
||||
{
|
||||
PipelineBindPoint = VkPipelineBindPoint.Graphics,
|
||||
ColorAttachmentCount = 1,
|
||||
ColorAttachments = &colorAttachment,
|
||||
};
|
||||
var dependency = new VkSubpassDependency
|
||||
{
|
||||
SrcSubpass = VK.SUBPASS_EXTERNAL,
|
||||
DstSubpass = 0,
|
||||
SrcStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
|
||||
DstStageMask = VkPipelineStageFlags.ColorAttachmentOutputBit,
|
||||
SrcAccessMask = 0,
|
||||
DstAccessMask = VkAccessFlags.ColorAttachmentWriteBit,
|
||||
};
|
||||
|
||||
window->RenderPass = device.CreateRenderPass(
|
||||
new VkRenderPassCreateInfo
|
||||
{
|
||||
AttachmentCount = 1,
|
||||
Attachments = &attachment,
|
||||
SubpassCount = 1,
|
||||
Subpasses = &subPass,
|
||||
DependencyCount = 1,
|
||||
Dependencies = &dependency,
|
||||
},
|
||||
null
|
||||
);
|
||||
|
||||
// We do not create a pipeline by default as this is also used by examples' main.cpp,
|
||||
// but secondary viewport in multi-viewport mode may want to create one with:
|
||||
//ImGui_ImplVulkan_CreatePipeline(device, allocator, VK_NULL_HANDLE, window->RenderPass, VK_SAMPLE_COUNT_1_BIT, &window->Pipeline, v->Subpass);
|
||||
}
|
||||
|
||||
// Create The Image Views
|
||||
{
|
||||
var info = new VkImageViewCreateInfo
|
||||
{
|
||||
ViewType = VkImageViewType._2D,
|
||||
Format = window->SurfaceFormat.Format,
|
||||
Components = new VkComponentMapping
|
||||
{
|
||||
R = VkComponentSwizzle.R,
|
||||
G = VkComponentSwizzle.G,
|
||||
B = VkComponentSwizzle.B,
|
||||
A = VkComponentSwizzle.A,
|
||||
},
|
||||
SubresourceRange = new VkImageSubresourceRange
|
||||
{
|
||||
AspectMask = VkImageAspectFlags.ColorBit,
|
||||
LevelCount = 1,
|
||||
LayerCount = 1,
|
||||
},
|
||||
};
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
{
|
||||
var frame = &window->Frames.DataRaw[i];
|
||||
info.Image = frame->Backbuffer;
|
||||
frame->BackbufferView = device.CreateImageView(info, null);
|
||||
}
|
||||
}
|
||||
|
||||
// Create Framebuffer
|
||||
{
|
||||
VkImageView attachment;
|
||||
var info = new VkFramebufferCreateInfo
|
||||
{
|
||||
RenderPass = window->RenderPass,
|
||||
AttachmentCount = 1,
|
||||
Attachments = &attachment,
|
||||
Width = window->Width,
|
||||
Height = window->Height,
|
||||
Layers = 1,
|
||||
};
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
{
|
||||
var frame = &window->Frames.DataRaw[i];
|
||||
attachment = frame->BackbufferView;
|
||||
frame->Framebuffer = device.CreateFramebuffer(info, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static int GetMinImageCountFromPresentMode(VkPresentModeKHR presentMode)
|
||||
{
|
||||
return presentMode switch
|
||||
{
|
||||
VkPresentModeKHR.MailboxKHR => 3,
|
||||
VkPresentModeKHR.FifoKHR => 2,
|
||||
VkPresentModeKHR.FifoRelaxedKHR => 2,
|
||||
VkPresentModeKHR.ImmediateKHR => 1,
|
||||
_ => 1,
|
||||
};
|
||||
}
|
||||
|
||||
private static unsafe void CreateWindowCommandBuffers(
|
||||
PhysicalDevice physicalDevice,
|
||||
Device device,
|
||||
WindowImpl* window,
|
||||
int queueFamily
|
||||
)
|
||||
{
|
||||
Assert(physicalDevice.IsNotNull() && device.IsNotNull());
|
||||
|
||||
// Create Command Buffers
|
||||
for (var i = 0; i < window->ImageCount; i++)
|
||||
{
|
||||
var frame = &window->Frames.DataRaw[i];
|
||||
|
||||
// TODO: Seriously, each frame has its own command pool?
|
||||
frame->CommandPool = device.CreateCommandPool(
|
||||
new VkCommandPoolCreateInfo { QueueFamilyIndex = queueFamily },
|
||||
null
|
||||
);
|
||||
|
||||
frame->CommandBuffer = device.AllocateCommandBuffer(
|
||||
new VkCommandBufferAllocateInfo
|
||||
{
|
||||
CommandPool = frame->CommandPool,
|
||||
Level = VkCommandBufferLevel.Primary,
|
||||
}
|
||||
);
|
||||
|
||||
frame->Fence = device.CreateFence(
|
||||
new VkFenceCreateInfo { Flags = VkFenceCreateFlags.SignaledBit },
|
||||
null
|
||||
);
|
||||
}
|
||||
|
||||
for (var i = 0; i < window->SemaphoreCount; i++)
|
||||
{
|
||||
var semaphores = &window->FrameSemaphores.DataRaw[i];
|
||||
{
|
||||
var createInfo = new VkSemaphoreCreateInfo();
|
||||
semaphores->ImageAcquiredSemaphore = device.CreateSemaphore(createInfo, null);
|
||||
semaphores->RenderCompleteSemaphore = device.CreateSemaphore(createInfo, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static unsafe void DestroyFrame(Device device, Frame* frame)
|
||||
{
|
||||
device.DestroyFence(frame->Fence, null);
|
||||
device.DestroyCommandPool(frame->CommandPool, null);
|
||||
frame->Fence = default;
|
||||
frame->CommandBuffer = default;
|
||||
frame->CommandPool = default;
|
||||
|
||||
device.DestroyImageView(frame->BackbufferView, null);
|
||||
device.DestroyFramebuffer(frame->Framebuffer, null);
|
||||
}
|
||||
|
||||
private static unsafe void DestroyFrameSemaphores(Device device, FrameSemaphores* semaphores)
|
||||
{
|
||||
device.DestroySemaphore(semaphores->ImageAcquiredSemaphore, null);
|
||||
device.DestroySemaphore(semaphores->RenderCompleteSemaphore, null);
|
||||
semaphores->ImageAcquiredSemaphore = semaphores->RenderCompleteSemaphore = default;
|
||||
}
|
||||
}
|
||||
}
|
||||
1590
brutal.imgui/Brutal.ImGui.Backends/RendererBackends/VulkanBackend.cs
Normal file
1590
brutal.imgui/Brutal.ImGui.Backends/RendererBackends/VulkanBackend.cs
Normal file
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue