From 55bc1e9c3ac7da826d11a8ae8082f9926ad750b7 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Wed, 16 Jul 2025 22:52:02 -0400 Subject: [PATCH] feat: use imgui for UI and refactor configurations - Updated `AutoLabeling.cs` to use `LogManager` for error logging and a new `mainConfig` object for configuration settings. - Transformed `Config.cs` into a generic `ConfigManager` class, encapsulating settings in a new `ConfigData` class for better organization. - Enhanced `InputManager.cs` to utilize the new configuration structure and added smoothing functionality for mouse movement. - Modified `Program.cs` to initialize `mainConfig` and `colorConfig`, improving key event handling. - Updated `Spectrum.csproj` to target `net8.0-windows` and added new package references. - Created `FodyWeavers.xml` to include the `Costura` weaver for dependency embedding. - Introduced `LogManager.cs` for centralized logging functionality. - Added `Renderer.cs` for rendering overlays with ImGui, integrating with the new configuration system. --- Spectrum/AutoLabeling.cs | 23 +- Spectrum/Config.cs | 314 ++++++++---------------- Spectrum/FodyWeavers.xml | 3 + Spectrum/InputManager.cs | 72 +++++- Spectrum/LogManager.cs | 73 ++++++ Spectrum/Program.cs | 365 +++++++++++++++------------- Spectrum/Renderer.cs | 510 +++++++++++++++++++++++++++++++++++++++ Spectrum/Spectrum.csproj | 16 +- 8 files changed, 974 insertions(+), 402 deletions(-) create mode 100644 Spectrum/FodyWeavers.xml create mode 100644 Spectrum/LogManager.cs create mode 100644 Spectrum/Renderer.cs diff --git a/Spectrum/AutoLabeling.cs b/Spectrum/AutoLabeling.cs index 5177ba5..91282ef 100644 --- a/Spectrum/AutoLabeling.cs +++ b/Spectrum/AutoLabeling.cs @@ -1,7 +1,7 @@ using OpenCvSharp; using System.Collections.Concurrent; -using System.Drawing; using System.Text; +using LogLevel = Spectrum.LogManager.LogLevel; namespace Spectrum { @@ -14,6 +14,7 @@ namespace Spectrum private static Task? backgroundTask; private static readonly ConcurrentQueue labelingQueue = new ConcurrentQueue(); private static readonly ConcurrentQueue backgroundQueue = new ConcurrentQueue(); + private static ConfigManager mainConfig = Program.mainConfig; private static List GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight) { @@ -57,9 +58,7 @@ namespace Spectrum } catch { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Failed to save labels to " + path); - Console.ResetColor(); + LogManager.Log("[ERROR] Failed to save labels.", LogLevel.Error); } } private static void SaveMatAsImage(Mat mat, string path) @@ -70,7 +69,7 @@ namespace Spectrum } catch (Exception ex) { - Console.WriteLine($"Error saving image: {ex.Message}"); + LogManager.Log($"[ERROR] Failed to save image: {ex.Message}", LogLevel.Error); } } @@ -86,9 +85,7 @@ namespace Spectrum } catch { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Failed to process labeling data."); - Console.ResetColor(); + LogManager.Log("[ERROR] Failed to process labeling data.", LogLevel.Error); } } @@ -100,9 +97,7 @@ namespace Spectrum } catch { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Failed to process background image data."); - Console.ResetColor(); + LogManager.Log("[ERROR] Failed to process background image data.", LogLevel.Error); } } @@ -113,7 +108,7 @@ namespace Spectrum public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours) { - if (!Config.AutoLabel || filteredContours.Length == 0) + if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0) return; if (labelingQueue.Count > 250) @@ -130,12 +125,12 @@ namespace Spectrum public static void AddBackgroundImage(Mat mat, bool detected) { - if (!Config.AutoLabel) + if (!mainConfig.Data.AutoLabel) return; detectionAttemps++; - if (detectionAttemps < Config.BackgroundImageInterval || detected) + if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected) return; if (backgroundQueue.Count > 250) diff --git a/Spectrum/Config.cs b/Spectrum/Config.cs index d2f8367..a6f2344 100644 --- a/Spectrum/Config.cs +++ b/Spectrum/Config.cs @@ -1,258 +1,154 @@ using Newtonsoft.Json; -using Newtonsoft.Json.Linq; using OpenCvSharp; +using System.Numerics; +using System.Security.Cryptography.X509Certificates; +using LogLevel = Spectrum.LogManager.LogLevel; namespace Spectrum { - public static class Config + public class ConfigManager where T : new() { - private static FileSystemWatcher? _configWatcher; - #region Variables + private readonly string _fileName; + private FileSystemWatcher? _watcher; + private T _data; - public enum MovementType + public T Data => _data; + + public ConfigManager(string fileName) { - Linear, - CubicBezier, - QuadraticBezier, - Adaptive + _fileName = fileName; + _data = new T(); + LoadConfig(); } - // Image settings - public static int ImageWidth { get; set; } = 640; - public static int ImageHeight { get; set; } = 640; - // Offset settings - public static double YOffsetPercent { get; set; } = 0.8; - public static double XOffsetPercent { get; set; } = 0.5; - - // Aim settings - public static bool EnableAim { get; set; } = true; - public static bool ClosestToMouse { get; set; } = true; // if false it will use the center of the screen - public static int Keybind { get; set; } = 0x06; // first side button on mouse - public static double Sensitivity { get; set; } = 0.5; - public static MovementType AimMovementType { get; set; } = MovementType.Adaptive; - - // Display settings - public static bool ShowDetectionWindow { get; set; } = true; - - // Data collection settings - public static bool CollectData { get; set; } = false; - public static bool AutoLabel { get; set; } = false; // collect data needs to be enabled - public static int BackgroundImageInterval { get; set; } = 10; // after 10 loops with no detection, save a background image - - // Color settings - public static Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229); - public static Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229); - #endregion - - public static void LoadConfig(bool silent = false) + public void LoadConfig(bool silent = false) { - if (File.Exists("config.json")) + if (File.Exists(_fileName)) { - string config_content = File.ReadAllText("config.json"); try { - var config = JObject.Parse(config_content); - bool error = false; - - var imageSettings = config["ImageSettings"]; - ImageWidth = imageSettings?["ImageWidth"]?.Value() ?? config["ImageWidth"]?.Value() ?? ImageWidth; - ImageHeight = imageSettings?["ImageHeight"]?.Value() ?? config["ImageHeight"]?.Value() ?? ImageHeight; - - var offsetSettings = config["OffsetSettings"]; - YOffsetPercent = offsetSettings?["YOffsetPercent"]?.Value() ?? config["YOffsetPercent"]?.Value() ?? YOffsetPercent; - XOffsetPercent = offsetSettings?["XOffsetPercent"]?.Value() ?? config["XOffsetPercent"]?.Value() ?? XOffsetPercent; - - var aimSettings = config["AimSettings"]; - EnableAim = aimSettings?["EnableAim"]?.Value() ?? config["EnableAim"]?.Value() ?? EnableAim; - ClosestToMouse = aimSettings?["ClosestToMouse"]?.Value() ?? config["ClosestToMouse"]?.Value() ?? ClosestToMouse; - Keybind = aimSettings?["Keybind"]?.Value() ?? config["Keybind"]?.Value() ?? Keybind; - Sensitivity = aimSettings?["Sensitivity"]?.Value() ?? config["Sensitivity"]?.Value() ?? Sensitivity; - AimMovementType = aimSettings?["AimMovementType"]?.Value() switch - { - "Linear" => MovementType.Linear, - "CubicBezier" => MovementType.CubicBezier, - "Adaptive" => MovementType.Adaptive, - _ => AimMovementType - }; - - var displaySettings = config["DisplaySettings"]; - ShowDetectionWindow = displaySettings?["ShowDetectionWindow"]?.Value() ?? config["ShowDetectionWindow"]?.Value() ?? ShowDetectionWindow; - - var dataSettings = config["DataCollectionSettings"]; - CollectData = dataSettings?["CollectData"]?.Value() ?? config["CollectData"]?.Value() ?? CollectData; - AutoLabel = dataSettings?["AutoLabel"]?.Value() ?? config["AutoLabel"]?.Value() ?? AutoLabel; - BackgroundImageInterval = dataSettings?["BackgroundImageInterval"]?.Value() ?? config["BackgroundImageInterval"]?.Value() ?? BackgroundImageInterval; - - var colorSettings = config["ColorSettings"]; - UpperHSV = colorSettings?["UpperHSV"]?.ToObject() ?? config["UpperHSV"]?.ToObject() ?? UpperHSV; - LowerHSV = colorSettings?["LowerHSV"]?.ToObject() ?? config["LowerHSV"]?.ToObject() ?? LowerHSV; - - if (ImageWidth <= 0 || ImageHeight <= 0) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values."); - Console.ResetColor(); - ImageWidth = 640; - ImageHeight = 640; - error = true; - } - if (YOffsetPercent < 0 || YOffsetPercent > 1 || XOffsetPercent < 0 || XOffsetPercent > 1) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Invalid offset percentages in config.json, using default values."); - Console.ResetColor(); - YOffsetPercent = 0.8; - XOffsetPercent = 0.5; - error = true; - } - if (Keybind < 0 || Keybind > 255) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Invalid keybind in config.json, using default value."); - Console.ResetColor(); - Keybind = 0x06; - error = true; - } - if (Sensitivity < 0 || Sensitivity > 2) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Invalid sensitivity in config.json, using default value."); - Console.ResetColor(); - Sensitivity = 0.5; - error = true; - } - if (AutoLabel && !CollectData) - { - Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("[WARNING] AutoLabel is enabled but CollectData is not. Disabling AutoLabel."); - Console.ResetColor(); - AutoLabel = false; - error = true; - } - if (BackgroundImageInterval <= 0) - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Invalid BackgroundImageInterval in config.json, using default value."); - Console.ResetColor(); - error = true; - } - if (error) - SaveConfig(); - - if (!silent) - { - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Configuration loaded successfully."); - Console.ResetColor(); - } + var json = File.ReadAllText(_fileName); + _data = JsonConvert.DeserializeObject(json) ?? new T(); + if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info); } catch { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[ERROR] Error parsing config.json, using default values."); - Console.ResetColor(); + LogManager.Log($"Failed to parse {_fileName}, using default values.", LogLevel.Error); + _data = new T(); SaveConfig(); } } else { - Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("[WARNING] config.json not found, using default values."); - Console.ResetColor(); + LogManager.Log($"{_fileName} not found, creating a new one with default values.", LogLevel.Error); + _data = new T(); SaveConfig(); } } - public static void SaveConfig() + + public void SaveConfig() { - var config = new JObject - { - ["ImageSettings"] = new JObject - { - ["ImageWidth"] = ImageWidth, - ["ImageHeight"] = ImageHeight - }, - ["OffsetSettings"] = new JObject - { - ["YOffsetPercent"] = YOffsetPercent, - ["XOffsetPercent"] = XOffsetPercent - }, - ["AimSettings"] = new JObject - { - ["EnableAim"] = EnableAim, - ["ClosestToMouse"] = ClosestToMouse, - ["Keybind"] = Keybind, - ["Sensitivity"] = Sensitivity, - ["AimMovementType"] = AimMovementType.ToString() - }, - ["DisplaySettings"] = new JObject - { - ["ShowDetectionWindow"] = ShowDetectionWindow - }, - ["DataCollectionSettings"] = new JObject - { - ["CollectData"] = CollectData, - ["AutoLabel"] = AutoLabel, - ["BackgroundImageInterval"] = BackgroundImageInterval - }, - ["ColorSettings"] = new JObject - { - ["UpperHSV"] = JToken.FromObject(UpperHSV), - ["LowerHSV"] = JToken.FromObject(LowerHSV) - } - }; File.WriteAllText("config.json", config.ToString(Formatting.Indented)); + File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented)); } - public static void StartFileWatcher() + public void StartFileWatcher() { - if (_configWatcher != null) - return; + if (_watcher != null) return; - _configWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "config.json") + _watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size }; - - _configWatcher.Changed += OnConfigFileChanged; - _configWatcher.EnableRaisingEvents = true; - - Console.ForegroundColor = ConsoleColor.Cyan; - Console.WriteLine("[INFO] File watcher started for config.json"); - Console.ResetColor(); + _watcher.Changed += OnConfigFileChanged; + _watcher.EnableRaisingEvents = true; + LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info); } - public static void StopFileWatcher() + public void StopFileWatcher() { - if (_configWatcher != null) - { - _configWatcher.EnableRaisingEvents = false; - _configWatcher.Changed -= OnConfigFileChanged; - _configWatcher.Dispose(); - _configWatcher = null; - - Console.ForegroundColor = ConsoleColor.Cyan; - Console.WriteLine("[INFO] File watcher stopped for config.json"); - Console.ResetColor(); - } + if (_watcher == null) return; + _watcher.EnableRaisingEvents = false; + _watcher.Changed -= OnConfigFileChanged; + _watcher.Dispose(); + _watcher = null; + LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info); } - private static void OnConfigFileChanged(object sender, FileSystemEventArgs e) + private void OnConfigFileChanged(object sender, FileSystemEventArgs e) { Thread.Sleep(100); - try { LoadConfig(true); - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Configuration automatically reloaded due to file change."); - Console.ResetColor(); + LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info); } catch (Exception ex) { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine($"[ERROR] Failed to reload configuration: {ex.Message}"); - Console.ResetColor(); + LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error); } } - } -} + + public enum MovementType + { + Linear, + CubicBezier, + QuadraticBezier, + Adaptive + } + public class ConfigData + { + + // Image settings + public int ImageWidth { get; set; } = 640; + public int ImageHeight { get; set; } = 640; + + // Offset settings + public double YOffsetPercent { get; set; } = 0.8; + public double XOffsetPercent { get; set; } = 0.5; + + // Aim settings + public bool EnableAim { get; set; } = true; + public bool ClosestToMouse { get; set; } = true; + public Keys Keybind { get; set; } = Keys.XButton2; + public double Sensitivity { get; set; } = 0.5; + public MovementType AimMovementType { get; set; } = MovementType.Adaptive; + public bool EmaSmoothening { get; set; } = true; + public double EmaSmootheningFactor { get; set; } = 0.1; + + // Display settings + public bool ShowDetectionWindow { get; set; } = true; + public bool DrawDetections { get; set; } = true; + public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); + public bool ShowMenu { get; set; } = true; + public bool DrawFOV { get; set; } = false; + public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); + + // Data collection settings + public bool CollectData { get; set; } = false; + public bool AutoLabel { get; set; } = false; + public int BackgroundImageInterval { get; set; } = 10; + + // Color settings + public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229); + public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229); + public string SelectedColor { get; set; } = "Arsenal [Magenta]"; + } + public class ColorData + { + public List Colors { get; set; } = new List(); + } + + public class ColorInfo + { + public string Name { get; set; } + public Scalar Upper { get; set; } + public Scalar Lower { get; set; } + public ColorInfo(string name, Scalar upper, Scalar lower) + { + Name = name; + Upper = upper; + Lower = lower; + } + } +} \ No newline at end of file diff --git a/Spectrum/FodyWeavers.xml b/Spectrum/FodyWeavers.xml new file mode 100644 index 0000000..5029e70 --- /dev/null +++ b/Spectrum/FodyWeavers.xml @@ -0,0 +1,3 @@ + + + \ No newline at end of file diff --git a/Spectrum/InputManager.cs b/Spectrum/InputManager.cs index 0945707..e48a68f 100644 --- a/Spectrum/InputManager.cs +++ b/Spectrum/InputManager.cs @@ -1,5 +1,4 @@ -using System.Drawing; -using System.Runtime.InteropServices; +using System.Runtime.InteropServices; namespace Spectrum { @@ -10,6 +9,7 @@ namespace Spectrum [DllImport("user32.dll")] private static extern bool GetCursorPos(out POINT lpPoint); + private static ConfigManager mainConfig = Program.mainConfig; private struct POINT { @@ -69,11 +69,12 @@ namespace Spectrum int newY = (int)(start.Y + directionY * stepSize); return new Point(newX, newY); } + private static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) => (currentValue * smoothingFactor) + (previousValue * (1 - smoothingFactor)); public static void MoveMouse(Point target) { POINT reference = new POINT(); - if (Config.ClosestToMouse) + if (mainConfig.Data.ClosestToMouse) { GetCursorPos(out reference); } @@ -88,20 +89,75 @@ namespace Spectrum Point start = new Point(reference.X, reference.Y); Point end = new Point(target.X, target.Y); - Point newPosition = Config.AimMovementType switch + Point newPosition = mainConfig.Data.AimMovementType switch { - Config.MovementType.CubicBezier => CubicBezierMovement(start, end, Config.Sensitivity), - Config.MovementType.Linear => LinearInterpolation(start, end, Config.Sensitivity), - Config.MovementType.Adaptive => AdaptiveMovement(start, end, Config.Sensitivity), - Config.MovementType.QuadraticBezier => CurvedMovement(start, end, Config.Sensitivity), + MovementType.CubicBezier => CubicBezierMovement(start, end, mainConfig.Data.Sensitivity), + MovementType.Linear => LinearInterpolation(start, end, mainConfig.Data.Sensitivity), + MovementType.Adaptive => AdaptiveMovement(start, end, mainConfig.Data.Sensitivity), + MovementType.QuadraticBezier => CurvedMovement(start, end, mainConfig.Data.Sensitivity), _ => end }; + if (mainConfig.Data.EmaSmoothening) + { + newPosition.X = (int)EmaSmoothing(reference.X, newPosition.X, mainConfig.Data.EmaSmootheningFactor); + newPosition.Y = (int)EmaSmoothing(reference.Y, newPosition.Y, mainConfig.Data.EmaSmootheningFactor); + } + int deltaX = newPosition.X - reference.X; int deltaY = newPosition.Y - reference.Y; + if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return; + if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight) + return; + mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0); } + [DllImport("user32.dll")] + private static extern short GetAsyncKeyState(int vKey); + + private static readonly Keys[] MouseKeys = + { + Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2 + }; + + public static Task ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null) + { + var tcs = new TaskCompletionSource(); + var thread = new Thread(() => + { + while (true) + { + for (int key = 0x08; key <= 0xFE; key++) + { + if ((GetAsyncKeyState(key) & 0x8000) != 0) + { + tcs.TrySetResult((Keys)key); + return; + } + } + foreach (var mouseKey in MouseKeys) + { + if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0) + { + tcs.TrySetResult(mouseKey); + return; + } + } + if (cancellationToken?.IsCancellationRequested == true) + { + tcs.TrySetCanceled(); + return; + } + Thread.Sleep(10); + } + }) + { + IsBackground = true + }; + thread.Start(); + return tcs.Task; + } } } diff --git a/Spectrum/LogManager.cs b/Spectrum/LogManager.cs new file mode 100644 index 0000000..b893c65 --- /dev/null +++ b/Spectrum/LogManager.cs @@ -0,0 +1,73 @@ +using System.Diagnostics; +using System.Text; + +namespace Spectrum +{ + public class LogManager + { + public enum LogLevel + { + Debug, + Info, + Warning, + Error, + Critical + } + public class LogEntry + { + public DateTime Timestamp { get; set; } + public LogLevel Level { get; set; } + public string Message { get; set; } + public LogEntry(LogLevel level, string message) + { + Timestamp = DateTime.Now; + Level = level; + Message = message; + } + public override string ToString() + { + return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}"; + } + } + private static List _logEntries = new List(); + public static IReadOnlyList LogEntries => _logEntries.AsReadOnly(); + public static void Log(string message, LogLevel level = LogLevel.Info) + { + string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}"; + Debug.WriteLine(logMessage); + _logEntries.Add(new LogEntry(level, message)); + } + public static void SaveLog(string filePath) + { + try + { + var logContent = new StringBuilder(); + foreach (var entry in _logEntries) + { + logContent.AppendLine(entry.ToString()); + } + File.WriteAllText(filePath, logContent.ToString()); + Log($"Log saved to {filePath}", LogLevel.Info); + } + catch (Exception ex) + { + Log($"Failed to save log: {ex.Message}", LogLevel.Error); + } + } + public static void ClearLog() + { + _logEntries.Clear(); + Log("Log cleared.", LogLevel.Info); + } + + public static void OpenLogFolder() + { + Process.Start(new ProcessStartInfo + { + FileName = "explorer.exe", + Arguments = Directory.GetCurrentDirectory(), + UseShellExecute = true + }); + } + } +} \ No newline at end of file diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index 79fdc2f..b749b6f 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -1,5 +1,4 @@ using OpenCvSharp; -using System.Drawing; using System.Drawing.Imaging; using System.Runtime.InteropServices; @@ -8,190 +7,94 @@ namespace Spectrum class Program { static Rectangle bounds = new Rectangle(0, 0, 0, 0); + static Renderer? renderer = null; + private static DateTime lastMenuToggle = DateTime.MinValue; + public static ConfigManager mainConfig = new ConfigManager("bin\\configs\\config.json"); + public static ConfigManager colorConfig = new ConfigManager("bin\\configs\\colors.json"); static void Main() { - Config.LoadConfig(); - Config.StartFileWatcher(); + Thread renderThread = new Thread(() => + { + try + { + renderer = new Renderer(); + renderer.Run(); + LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info); + } + catch (Exception ex) + { + LogManager.Log($"Failed to start renderer: {ex.Message}", LogManager.LogLevel.Error); + } + }); + renderThread.Start(); + + mainConfig.LoadConfig(); + mainConfig.StartFileWatcher(); var screenSize = SystemHelper.GetPrimaryScreenSize(); - bounds = new Rectangle( - (screenSize.Width - Config.ImageWidth) / 2, - (screenSize.Height - Config.ImageHeight) / 2, - Config.ImageWidth, - Config.ImageHeight - ); - if (Config.ShowDetectionWindow) + if (mainConfig.Data.ShowDetectionWindow) { Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize); Cv2.WaitKey(1); } - if (Config.AutoLabel) + if (mainConfig.Data.AutoLabel) { AutoLabeling.StartLabeling(); } - Directory.CreateDirectory("dataset"); - Directory.CreateDirectory("dataset/images"); - Directory.CreateDirectory("dataset/labels"); + Directory.CreateDirectory("bin"); + Directory.CreateDirectory("bin/dataset"); + Directory.CreateDirectory("bin/dataset/images"); + Directory.CreateDirectory("bin/dataset/labels"); + Directory.CreateDirectory("bin/logs"); + Directory.CreateDirectory("bin/configs"); + + if (colorConfig.Data.Colors.Count == 0) + { + colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(150, 255, 229), new Scalar(150, 255, 229))); + colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255))); + colorConfig.SaveConfig(); + colorConfig.LoadConfig(true); + mainConfig.LoadConfig(true); + } while (true) { - if (Console.KeyAvailable) - { - var key = Console.ReadKey(true).Key; - if (key == ConsoleKey.Escape) - { - if (Config.ShowDetectionWindow) - { - Cv2.DestroyAllWindows(); - } - Config.StopFileWatcher(); - Environment.Exit(0); - } - else if (key == ConsoleKey.O) - { - try - { - string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json"); - System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo - { - FileName = configFilePath, - UseShellExecute = true, - CreateNoWindow = true - }); - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Opened config file in default application."); - Console.ResetColor(); - } - catch (Exception ex) - { - Console.WriteLine($"Failed to open config file: {ex.Message}"); - } - } - else if (key == ConsoleKey.F1) - { - Config.ShowDetectionWindow = !Config.ShowDetectionWindow; - if (Config.ShowDetectionWindow) - { - Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize); - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Enabled detection window."); - } - else - { - Cv2.DestroyAllWindows(); - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[INFO] Disabled detection window."); - } - Console.ResetColor(); - } - else if (key == ConsoleKey.F2) - { - Config.AutoLabel = !Config.AutoLabel; - if (Config.AutoLabel) - { - Config.CollectData = true; - AutoLabeling.StartLabeling(); - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Enabled auto-labeling."); - } - else - { - AutoLabeling.StopLabeling(); - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[INFO] Disabled auto-labeling."); - } - Console.ResetColor(); - } - else if (key == ConsoleKey.F3) - { - Config.CollectData = !Config.CollectData; - if (Config.CollectData) - { - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Enabled data collection."); - } - else - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[INFO] Disabled data collection."); - } - Console.ResetColor(); - } - else if (key == ConsoleKey.F4) - { - Config.EnableAim = !Config.EnableAim; - if (Config.EnableAim) - { - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Enabled aiming."); - } - else - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[INFO] Disabled aiming."); - } - Console.ResetColor(); - } - else if (key == ConsoleKey.F5) - { - Config.ClosestToMouse = !Config.ClosestToMouse; - if (Config.ClosestToMouse) - { - Console.ForegroundColor = ConsoleColor.Green; - Console.WriteLine("[INFO] Enabled closest to mouse aiming."); - } - else - { - Console.ForegroundColor = ConsoleColor.Red; - Console.WriteLine("[INFO] Disabled closest to mouse aiming."); - } - Console.ResetColor(); - } - else if (key == ConsoleKey.H || key == ConsoleKey.Help) - { - Console.WriteLine("Spectrum Keybinds:"); - Console.WriteLine("F1: Toggle detection window"); - Console.WriteLine("F2: Toggle auto-labeling"); - Console.WriteLine("F3: Toggle data collection"); - Console.WriteLine("F4: Toggle aiming"); - Console.WriteLine("F5: Toggle closest to mouse aiming"); - Console.WriteLine("O: Open config file in default application"); - Console.WriteLine("ESC: Exit the application"); - Console.WriteLine("H: Show this help message"); - } - else - { - Console.ForegroundColor = ConsoleColor.Yellow; - Console.WriteLine("[WARNING] Unrecognized key pressed. Press H for help."); - Console.ResetColor(); - } - } - - if (SystemHelper.GetAsyncKeyState(Config.Keybind) < 0) + if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.Keybind) < 0) { + bounds = new Rectangle( + (screenSize.Width - mainConfig.Data.ImageWidth) / 2, + (screenSize.Height - mainConfig.Data.ImageHeight) / 2, + mainConfig.Data.ImageWidth, + mainConfig.Data.ImageHeight + ); var screenshot = CaptureScreenshot(bounds); Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); - Mat drawing = mat.Clone(); // clone for drawing - Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); // convert to hsv - Cv2.InRange(mat, Config.LowerHSV, Config.UpperHSV, mat); // apply mask - Cv2.Dilate(mat, mat, null, iterations: 2); // dilate to fill gaps - Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); // threshold to binary + Mat drawing = mat.Clone(); + Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); + Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat); + Cv2.Dilate(mat, mat, null, iterations: 2); + Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray(); - if (filteredContours.Length > 0) + + var mergedContours = MergeOverlappingContours(filteredContours); + + var processedContours = mergedContours.Select(ShrinkWideContour).ToArray(); + + if (processedContours.Length > 0) { int refX = bounds.X + bounds.Width / 2; - int refY = bounds.Y + (int)(bounds.Height * Config.YOffsetPercent); + int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent); double minDist = double.MaxValue; OpenCvSharp.Point[]? closestContour = null; int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0; - foreach (var contour in filteredContours) + foreach (var contour in processedContours) { int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; foreach (var point in contour) @@ -217,31 +120,42 @@ namespace Spectrum bestMaxX = maxX; bestMaxY = maxY; } + + if (renderer != null && mainConfig.Data.DrawDetections) + { + var _rect = new Rectangle( + minX + bounds.X, + minY + bounds.Y, + (maxX - minX + 1), + (maxY - minY + 1) + ); + renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f); + } } if (closestContour != null) { - int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - Config.XOffsetPercent)); - int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - Config.YOffsetPercent)); + int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent)); + int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent)); int targetX = groupX + bounds.X; int targetY = groupY + bounds.Y; - if (Config.AutoLabel) + if (mainConfig.Data.AutoLabel) { - AutoLabeling.AddToQueue(drawing, bounds, filteredContours); + AutoLabeling.AddToQueue(drawing, bounds, processedContours); AutoLabeling.AddBackgroundImage(drawing, true); } - if (!Config.AutoLabel && Config.CollectData) + if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData) { AutoLabeling.AddBackgroundImage(drawing, false); } - if (Config.EnableAim) + if (mainConfig.Data.EnableAim) { InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY)); } - if (Config.ShowDetectionWindow) + if (mainConfig.Data.ShowDetectionWindow) { Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2); Cv2.ImShow("Spectrum Detection", drawing); @@ -249,31 +163,148 @@ namespace Spectrum } } } - else if (Config.ShowDetectionWindow || Config.CollectData) + else if (mainConfig.Data.ShowDetectionWindow || mainConfig.Data.CollectData) { Cv2.ImShow("Spectrum Detection", drawing); Cv2.WaitKey(1); - if (Config.CollectData) + if (mainConfig.Data.CollectData) AutoLabeling.AddBackgroundImage(drawing, false); } screenshot?.Dispose(); mat.Dispose(); drawing.Dispose(); } + else if (SystemHelper.GetAsyncKeyState(0x2D) < 0) + { + var now = DateTime.Now; + if ((now - lastMenuToggle).TotalMilliseconds > 200) + { + mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu; + lastMenuToggle = now; + } + } else { - if (Config.ShowDetectionWindow) + if (mainConfig.Data.ShowDetectionWindow) { Cv2.WaitKey(1); } - else + else if (!mainConfig.Data.ShowDetectionWindow) { - Thread.Sleep(1); + if (Cv2.GetWindowProperty("Spectrum Detection", WindowPropertyFlags.Visible) >= 0) + { + Cv2.DestroyAllWindows(); + } } } } } + + static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) + { + var contourRects = new List<(Rect rect, List indices)>(); + for (int i = 0; i < contours.Length; i++) + { + var rect = Cv2.BoundingRect(contours[i]); + contourRects.Add((rect, new List { i })); + } + bool merged; + do + { + merged = false; + for (int i = 0; i < contourRects.Count; i++) + { + var (rectA, indicesA) = contourRects[i]; + for (int j = i + 1; j < contourRects.Count; j++) + { + var (rectB, indicesB) = contourRects[j]; + if (rectA.IntersectsWith(rectB)) + { + var newRect = new Rect( + Math.Min(rectA.X, rectB.X), + Math.Min(rectA.Y, rectB.Y), + Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X), + Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y) + ); + var newIndices = new List(); + newIndices.AddRange(indicesA); + newIndices.AddRange(indicesB); + contourRects[i] = (newRect, newIndices); + contourRects.RemoveAt(j); + merged = true; + break; + } + } + if (merged) break; + } + } while (merged); + + var mergedContours = new List(); + foreach (var (rect, indices) in contourRects) + { + var points = new List(); + foreach (var idx in indices) + { + points.AddRange(contours[idx]); + } + var hull = Cv2.ConvexHull(points); + mergedContours.Add(hull); + } + return mergedContours.ToArray(); + } + + static OpenCvSharp.Point[] ShrinkWideContour(OpenCvSharp.Point[] contour) + { + var rect = Cv2.BoundingRect(contour); + double aspect = rect.Width / (double)rect.Height; + if (aspect <= 1.2) + return contour; + + int[] xs = contour.Select(p => p.X).ToArray(); + int minX = xs.Min(); + int maxX = xs.Max(); + + int binCount = Math.Max(10, (maxX - minX + 1) / 5); + int[] bins = new int[binCount]; + int binWidth = (int)Math.Ceiling((maxX - minX + 1) / (double)binCount); + + foreach (var pt in contour) + { + int binIdx = (pt.X - minX) / binWidth; + if (binIdx < 0) binIdx = 0; + if (binIdx >= binCount) binIdx = binCount - 1; + bins[binIdx]++; + } + + int maxMass = bins.Max(); + int left = 0, right = binCount - 1; + for (int i = 0; i < binCount; i++) + { + if (bins[i] == maxMass) + { + left = i; + break; + } + } + for (int i = binCount - 1; i >= 0; i--) + { + if (bins[i] == maxMass) + { + right = i; + break; + } + } + int cropMinX = minX + left * binWidth; + int cropMaxX = minX + (right + 1) * binWidth - 1; + + var shrunken = contour.Where(p => p.X >= cropMinX && p.X <= cropMaxX).ToArray(); + if (shrunken.Length < 3) + return contour; + + return Cv2.ConvexHull(shrunken); + } + public static Bitmap CaptureScreenshot(Rectangle bounds) { Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); diff --git a/Spectrum/Renderer.cs b/Spectrum/Renderer.cs new file mode 100644 index 0000000..d4c08ea --- /dev/null +++ b/Spectrum/Renderer.cs @@ -0,0 +1,510 @@ +using ClickableTransparentOverlay; +using ImGuiNET; +using OpenCvSharp; +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Numerics; + +namespace Spectrum +{ + class Renderer : Overlay + { + static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize(); + private List> drawCommands = new List>(); + private readonly object drawCommandsLock = new object(); + + private bool _vsync = true; + private int _fpsLimit = 240; + private Keys _pendingKeybind = Keys.None; + private bool _waitingForKeybind = false; + private Task? _keybindTask = null; + private readonly ConcurrentQueue _keybindResults = new(); + private ConfigManager mainConfig = Program.mainConfig; + private ConfigManager colorConfig = Program.colorConfig; + + public Renderer() : base("Spectrum", screenSize.width, screenSize.width) + { + VSync = _vsync; + FPSLimit = _fpsLimit; + ImGui.CreateContext(); + var io = ImGui.GetIO(); + io.Fonts.Clear(); + io.Fonts.AddFontFromFileTTF("C:\\Windows\\Fonts\\Arial.ttf", 16.0f); + } + override protected void Render() + { + if (mainConfig.Data.DrawDetections || mainConfig.Data.DrawFOV) + RenderOverlay(); + if (!mainConfig.Data.ShowMenu) + return; + + AddStyling(); + + ImGui.SetNextWindowSize(new Vector2(600, 500), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 300, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowSizeConstraints(new Vector2(600, 500), new Vector2(float.MaxValue, float.MaxValue)); + + ImGui.Begin("Spectrum", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar); + ImGui.Text("Spectrum"); + ImGui.SameLine(); + float currentWidth = ImGui.GetWindowWidth(); + ImGui.SetCursorPosX(currentWidth - 30); + if (ImGui.Button("X", new Vector2(22, 22))) + { + Close(); + Environment.Exit(0); + } + + ImGui.BeginTabBar("##tabs"); + if (ImGui.BeginTabItem("Aiming")) + { + bool enableAiming = mainConfig.Data.EnableAim; + if (ImGui.Checkbox("##Enable Aiming", ref enableAiming)) + { + mainConfig.Data.EnableAim = enableAiming; + } + + ImGui.SameLine(); + if (!_waitingForKeybind) + { + if (ImGui.Button(mainConfig.Data.Keybind.ToString())) + { + _waitingForKeybind = true; + _pendingKeybind = Keys.None; + _keybindTask = Task.Run(async () => + { + var key = await InputManager.ListenForNextKeyOrMouseAsync(); + _pendingKeybind = key; + }); + } + } + else + { + ImGui.Button("Listening..."); + if (_pendingKeybind != Keys.None) + { + mainConfig.Data.Keybind = _pendingKeybind; + _pendingKeybind = Keys.None; + _waitingForKeybind = false; + } + } + ImGui.SameLine(); + ImGui.Text("Enable Aiming"); + + bool closestToMouse = mainConfig.Data.ClosestToMouse; + if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse)) + { + mainConfig.Data.ClosestToMouse = closestToMouse; + } + + float sensitivity = (float)mainConfig.Data.Sensitivity; + if (ImGui.SliderFloat("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f")) + { + mainConfig.Data.Sensitivity = sensitivity; + } + + float EmaSmootheningFactor = (float)mainConfig.Data.EmaSmootheningFactor; + bool EmaSmoothening = mainConfig.Data.EmaSmoothening; + if (ImGui.Checkbox("Ema Smoothening", ref EmaSmoothening)) + { + mainConfig.Data.EmaSmoothening = EmaSmoothening; + } + + if (ImGui.SliderFloat("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f, "%.2f")) + { + mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor; + } + + MovementType AimPath = mainConfig.Data.AimMovementType; + if (ImGui.BeginCombo("Movement Type", AimPath.ToString())) + { + foreach (MovementType type in Enum.GetValues(typeof(MovementType))) + { + bool isSelected = (type == AimPath); + if (ImGui.Selectable(type.ToString(), isSelected)) + { + mainConfig.Data.AimMovementType = type; + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); + } + + int YOffset = (int)(mainConfig.Data.YOffsetPercent * 100); + if (ImGui.SliderInt("Y Offset (%)", ref YOffset, 0, 100, "%d%%")) + { + mainConfig.Data.YOffsetPercent = ((double)YOffset / 100); + } + + int XOffset = (int)(mainConfig.Data.XOffsetPercent * 100); + if (ImGui.SliderInt("X Offset (%)", ref XOffset, 0, 100, "%d%%")) + { + mainConfig.Data.XOffsetPercent = ((double)XOffset / 100); + } + + ImGui.SeparatorText("Overlay Settings"); + + bool DrawFOV = mainConfig.Data.DrawFOV; + if (ImGui.Checkbox("##Draw FOV", ref DrawFOV)) + { + mainConfig.Data.DrawFOV = DrawFOV; + } + ImGui.SameLine(); + Vector4 FOVColor = mainConfig.Data.FOVColor; + if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + { + mainConfig.Data.FOVColor = FOVColor; + } + ImGui.SameLine(); + ImGui.Text("Draw FOV"); + + ImGui.EndTabItem(); + } + + if (ImGui.BeginTabItem("Detection")) + { + int ImageWidth = mainConfig.Data.ImageWidth; + if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width)) + { + if (ImageWidth < 1) + ImageWidth = 1; + else if (ImageWidth > screenSize.width) + ImageWidth = screenSize.width; + mainConfig.Data.ImageWidth = ImageWidth; + } + + int ImageHeight = mainConfig.Data.ImageHeight; + if (ImGui.InputInt("Image Height", ref ImageHeight, 1, screenSize.height)) + { + if (ImageHeight < 1) + ImageHeight = 1; + else if (ImageHeight > screenSize.height) + ImageHeight = screenSize.height; + mainConfig.Data.ImageHeight = ImageHeight; + } + + Scalar UpperHSV = mainConfig.Data.UpperHSV; + Vector3 UpperHSVVec3 = new Vector3((float)UpperHSV.Val0, (float)UpperHSV.Val1, (float)UpperHSV.Val2); + if (ImGui.InputFloat3("Upper HSV", ref UpperHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) + { + mainConfig.Data.UpperHSV = new Scalar(UpperHSVVec3.X, UpperHSVVec3.Y, UpperHSVVec3.Z); + } + + + Scalar LowerHSV = mainConfig.Data.LowerHSV; + Vector3 LowerHSVVec3 = new Vector3((float)LowerHSV.Val0, (float)LowerHSV.Val1, (float)LowerHSV.Val2); + if (ImGui.InputFloat3("Lower HSV", ref LowerHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) + { + mainConfig.Data.LowerHSV = new Scalar(LowerHSVVec3.X, LowerHSVVec3.Y, LowerHSVVec3.Z); + } + + List colors = colorConfig.Data.Colors; + if (colors.Count != 0) + { + if (ImGui.BeginCombo("Colors", mainConfig.Data.SelectedColor)) + { + foreach (ColorInfo color in colors) + { + bool isSelected = (color.Name == mainConfig.Data.SelectedColor); + if (ImGui.Selectable(color.Name, isSelected)) + { + mainConfig.Data.SelectedColor = color.Name; + mainConfig.Data.UpperHSV = color.Upper; + mainConfig.Data.LowerHSV = color.Lower; + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); + } + } + + bool DrawDetections = mainConfig.Data.DrawDetections; + if (ImGui.Checkbox("##Draw Detections", ref DrawDetections)) + { + mainConfig.Data.DrawDetections = DrawDetections; + } + ImGui.SameLine(); + Vector4 DetectionColor = mainConfig.Data.DetectionColor; + if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + { + mainConfig.Data.DetectionColor = DetectionColor; + } + ImGui.SameLine(); + ImGui.Text("Draw Detections"); + + ImGui.EndTabItem(); + } + + if (ImGui.BeginTabItem("Misc.")) + { + bool ShowDetectionWindow = mainConfig.Data.ShowDetectionWindow; + if (ImGui.Checkbox("Show Detection Window", ref ShowDetectionWindow)) + { + mainConfig.Data.ShowDetectionWindow = ShowDetectionWindow; + } + + bool CollectData = mainConfig.Data.CollectData; + if (ImGui.Checkbox("Collect Data", ref CollectData)) + { + mainConfig.Data.CollectData = CollectData; + } + + bool AutoLabel = mainConfig.Data.AutoLabel; + if (ImGui.Checkbox("Auto Label", ref AutoLabel)) + { + if (!CollectData && AutoLabel) + mainConfig.Data.CollectData = true; + + mainConfig.Data.AutoLabel = AutoLabel; + } + + int BackgroundImageInterval = mainConfig.Data.BackgroundImageInterval; + if (ImGui.InputInt("Background Image Interval", ref BackgroundImageInterval, 1, 500)) + { + if (BackgroundImageInterval < 1) + BackgroundImageInterval = 1; + else if (BackgroundImageInterval > 500) + BackgroundImageInterval = 500; + + mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval; + } + + + if (ImGui.Checkbox("VSync", ref _vsync)) + { + VSync = _vsync; + } + + if (ImGui.SliderInt("FPS Limit", ref _fpsLimit, 30, 480, "%d")) + { + FPSLimit = _fpsLimit; + } + + if (ImGui.Button("Save Configs")) + { + mainConfig.SaveConfig(); + colorConfig.SaveConfig(); + } + ImGui.SameLine(); + if (ImGui.Button("Open Folder")) + { + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\configs"); + if (Directory.Exists(folderPath)) + { + Process.Start(new ProcessStartInfo + { + FileName = "explorer.exe", + Arguments = folderPath, + UseShellExecute = true + }); + } + else + { + LogManager.Log($"Directory doesnt exist: {folderPath}", LogManager.LogLevel.Error); + } + } + ImGui.SeparatorText("Logs"); + + ImGui.BeginChild("Logs", new Vector2(0, -34)); + ImGui.Dummy(new Vector2(0, 4)); + + var _LogEntries = LogManager.LogEntries.ToList(); + foreach (var log in _LogEntries) + { + ImGui.Indent(8); + ImGui.Text(log.ToString()); + ImGui.Unindent(8); + } + + ImGui.Dummy(new Vector2(0, 4)); + ImGui.EndChild(); + ImGui.Dummy(new Vector2(0, 1)); + + if (ImGui.Button("Save Logs")) + { + LogManager.SaveLog($"bin\\logs\\{DateTime.Now.ToString("MM-dd_HH-mm-ss")}_spectrum_log.txt"); + } + + ImGui.SameLine(); + + if (ImGui.Button("Clear Logs")) + { + LogManager.ClearLog(); + } + + ImGui.SameLine(); + + if (ImGui.Button("Open Log Folder")) + { + LogManager.OpenLogFolder(); + } + + ImGui.EndTabItem(); + } + + ImGui.EndTabBar(); + + ImGui.End(); + } + + protected void RenderOverlay() + { + ImGui.SetNextWindowSize(new Vector2(screenSize.width, screenSize.height), ImGuiCond.Always); + ImGui.SetNextWindowPos(new Vector2(0, 0), ImGuiCond.Always); + ImGui.Begin("Overlay", ImGuiWindowFlags.NoDecoration | ImGuiWindowFlags.NoInputs | ImGuiWindowFlags.AlwaysAutoResize | ImGuiWindowFlags.NoBackground | ImGuiWindowFlags.NoFocusOnAppearing | ImGuiWindowFlags.NoNavFocus); + var drawList = ImGui.GetWindowDrawList(); + + if (mainConfig.Data.DrawFOV) + { + AddRect(new Rectangle( + ((screenSize.width - mainConfig.Data.ImageWidth) / 2) - 1, + ((screenSize.height - mainConfig.Data.ImageHeight) / 2) - 1, + mainConfig.Data.ImageWidth + 2, + mainConfig.Data.ImageHeight + 2 + ), mainConfig.Data.FOVColor); + } + + List> _drawCommands; + lock (drawCommandsLock) + { + _drawCommands = drawCommands.ToList(); + drawCommands.Clear(); + } + + foreach (var cmd in _drawCommands) + { + cmd?.Invoke(drawList); + } + + ImGui.End(); + } + private void AddStyling() + { + var style = ImGui.GetStyle(); + var colors = style.Colors; + + style.WindowRounding = 4.0f; + style.FrameRounding = 3.0f; + style.ScrollbarRounding = 3.0f; + style.GrabRounding = 3.0f; + style.FrameBorderSize = 1.0f; + style.WindowBorderSize = 1.0f; + style.PopupRounding = 4.0f; + style.TabRounding = 3.0f; + style.ChildRounding = 3.0f; + style.PopupBorderSize = 1.0f; + style.GrabMinSize = 20.0f; + style.WindowPadding = new Vector2(8, 8); + style.FramePadding = new Vector2(6, 3); + style.ItemSpacing = new Vector2(8, 4); + + colors[(int)ImGuiCol.WindowBg] = new Vector4(0.10f, 0.10f, 0.12f, 1.0f); + colors[(int)ImGuiCol.ChildBg] = new Vector4(0.12f, 0.12f, 0.14f, 1.0f); + colors[(int)ImGuiCol.PopupBg] = new Vector4(0.11f, 0.11f, 0.12f, 1.0f); + colors[(int)ImGuiCol.Border] = new Vector4(0.23f, 0.23f, 0.25f, 0.50f); + colors[(int)ImGuiCol.BorderShadow] = new Vector4(0.00f, 0.00f, 0.00f, 0.00f); + + colors[(int)ImGuiCol.FrameBg] = new Vector4(0.17f, 0.17f, 0.20f, 1.0f); + colors[(int)ImGuiCol.FrameBgHovered] = new Vector4(0.22f, 0.22f, 0.26f, 1.0f); + colors[(int)ImGuiCol.FrameBgActive] = new Vector4(0.22f, 0.22f, 0.27f, 1.0f); + + colors[(int)ImGuiCol.TitleBg] = new Vector4(0.10f, 0.10f, 0.12f, 1.0f); + colors[(int)ImGuiCol.TitleBgActive] = new Vector4(0.15f, 0.15f, 0.18f, 1.0f); + colors[(int)ImGuiCol.TitleBgCollapsed] = new Vector4(0.12f, 0.12f, 0.14f, 1.0f); + + colors[(int)ImGuiCol.MenuBarBg] = new Vector4(0.15f, 0.15f, 0.17f, 1.0f); + + colors[(int)ImGuiCol.CheckMark] = new Vector4(0.80f, 0.80f, 0.80f, 1.0f); + colors[(int)ImGuiCol.SliderGrab] = new Vector4(0.31f, 0.31f, 0.34f, 1.0f); + colors[(int)ImGuiCol.SliderGrabActive] = new Vector4(0.43f, 0.43f, 0.45f, 1.0f); + colors[(int)ImGuiCol.Button] = new Vector4(0.17f, 0.17f, 0.20f, 1.0f); + colors[(int)ImGuiCol.ButtonHovered] = new Vector4(0.24f, 0.24f, 0.28f, 1.0f); + colors[(int)ImGuiCol.ButtonActive] = new Vector4(0.29f, 0.29f, 0.33f, 1.0f); + + colors[(int)ImGuiCol.Header] = new Vector4(0.14f, 0.14f, 0.16f, 1.0f); + colors[(int)ImGuiCol.HeaderHovered] = new Vector4(0.20f, 0.20f, 0.22f, 1.0f); + colors[(int)ImGuiCol.HeaderActive] = new Vector4(0.24f, 0.24f, 0.26f, 1.0f); + + colors[(int)ImGuiCol.Separator] = new Vector4(0.23f, 0.23f, 0.25f, 0.5f); + colors[(int)ImGuiCol.SeparatorHovered] = new Vector4(0.33f, 0.33f, 0.35f, 0.78f); + colors[(int)ImGuiCol.SeparatorActive] = new Vector4(0.32f, 0.32f, 0.35f, 1.0f); + + colors[(int)ImGuiCol.ResizeGrip] = new Vector4(0.23f, 0.23f, 0.25f, 0.2f); + colors[(int)ImGuiCol.ResizeGripHovered] = new Vector4(0.33f, 0.33f, 0.36f, 0.7f); + colors[(int)ImGuiCol.ResizeGripActive] = new Vector4(0.36f, 0.36f, 0.39f, 0.9f); + + colors[(int)ImGuiCol.Tab] = new Vector4(0.13f, 0.13f, 0.15f, 1.0f); + colors[(int)ImGuiCol.TabHovered] = new Vector4(0.18f, 0.18f, 0.20f, 1.0f); + colors[(int)ImGuiCol.TabSelected] = new Vector4(0.22f, 0.22f, 0.25f, 1.0f); + colors[(int)ImGuiCol.TabDimmed] = new Vector4(0.13f, 0.13f, 0.15f, 1.0f); + colors[(int)ImGuiCol.TabDimmedSelected] = new Vector4(0.18f, 0.18f, 0.20f, 1.0f); + + colors[(int)ImGuiCol.Text] = new Vector4(0.85f, 0.85f, 0.88f, 1.0f); + colors[(int)ImGuiCol.TextDisabled] = new Vector4(0.48f, 0.48f, 0.52f, 1.0f); + + colors[(int)ImGuiCol.PlotLines] = new Vector4(0.61f, 0.61f, 0.62f, 1.0f); + colors[(int)ImGuiCol.PlotLinesHovered] = new Vector4(0.80f, 0.80f, 0.81f, 1.0f); + colors[(int)ImGuiCol.PlotHistogram] = new Vector4(0.61f, 0.61f, 0.62f, 1.0f); + colors[(int)ImGuiCol.PlotHistogramHovered] = new Vector4(0.80f, 0.80f, 0.81f, 1.0f); + + colors[(int)ImGuiCol.DragDropTarget] = new Vector4(0.90f, 0.90f, 0.90f, 0.90f); + + colors[(int)ImGuiCol.NavWindowingHighlight] = new Vector4(0.70f, 0.70f, 0.70f, 0.70f); + colors[(int)ImGuiCol.NavWindowingDimBg] = new Vector4(0.20f, 0.20f, 0.20f, 0.20f); + colors[(int)ImGuiCol.ModalWindowDimBg] = new Vector4(0.10f, 0.10f, 0.10f, 0.35f); + + + } + public void AddRect(Rectangle rect, Vector4 color, float thickness = 1.0f) + { + lock (drawCommandsLock) + { + drawCommands.Add(drawList => drawList.AddRect(new Vector2(rect.Left, rect.Top), new Vector2(rect.Right, rect.Bottom), ColorFromVector4(color), 0, 0, thickness)); + } + } + + public void AddLine(Vector2 p1, Vector2 p2, Vector4 color, float thickness = 1.0f) + { + lock (drawCommandsLock) + { + drawCommands.Add(drawList => drawList.AddLine(p1, p2, ColorFromVector4(color), thickness)); + } + } + + public void AddCircle(Vector2 center, float radius, Vector4 color, int numSegments = 0, float thickness = 1.0f) + { + if (numSegments <= 0) + numSegments = (int)(Math.Max(1, radius / 2.0f)); + + lock (drawCommandsLock) + { + drawCommands.Add(drawList => drawList.AddCircle(center, radius, ColorFromVector4(color), numSegments, thickness)); + } + } + + public void AddText(Vector2 pos, Vector4 color, string text) + { + if (string.IsNullOrEmpty(text)) + return; + lock (drawCommandsLock) + { + drawCommands.Add(drawList => drawList.AddText(pos, ColorFromVector4(color), text)); + } + } + + private static uint ColorFromVector4(Vector4 color) + { + int r = (int)(Math.Clamp(color.X, 0f, 1f) * 255.0f); + int g = (int)(Math.Clamp(color.Y, 0f, 1f) * 255.0f); + int b = (int)(Math.Clamp(color.Z, 0f, 1f) * 255.0f); + int a = (int)(Math.Clamp(color.W, 0f, 1f) * 255.0f); + return (uint)((a << 24) | (b << 16) | (g << 8) | r); + } + } +} diff --git a/Spectrum/Spectrum.csproj b/Spectrum/Spectrum.csproj index 406129d..5606306 100644 --- a/Spectrum/Spectrum.csproj +++ b/Spectrum/Spectrum.csproj @@ -1,21 +1,29 @@  - Exe - net8.0 + WinExe + net8.0-windows enable enable - true + False true + True + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + - + +