diff --git a/.gitignore b/.gitignore index 9491a2f..150d4ab 100644 --- a/.gitignore +++ b/.gitignore @@ -360,4 +360,5 @@ MigrationBackup/ .ionide/ # Fody - auto-generated XML schema -FodyWeavers.xsd \ No newline at end of file +FodyWeavers.xsd +Spectrum/imgui.ini diff --git a/Spectrum/Assets/copy.png b/Spectrum/Assets/copy.png new file mode 100644 index 0000000..8458884 Binary files /dev/null and b/Spectrum/Assets/copy.png differ diff --git a/Spectrum/Config.cs b/Spectrum/Config.cs index 26d6cd4..c20efd8 100644 --- a/Spectrum/Config.cs +++ b/Spectrum/Config.cs @@ -1,29 +1,34 @@ using Newtonsoft.Json; using OpenCvSharp; +using Spectrum.Utilities; using System.Numerics; -using LogLevel = Spectrum.LogManager.LogLevel; +using LogLevel = Spectrum.Utilities.LogManager.LogLevel; namespace Spectrum { public class ConfigManager where T : new() { - private readonly string _defaultFilename; + private readonly string _defaultFilePath; private readonly string _configDirectory; private FileSystemWatcher? _fileWatcher; private FileSystemWatcher? _directoryWatcher; private T _data; private string _currentConfigName; - private List _availableConfigs; + private string _currentFilePath; + private readonly List _availableConfigs; public T Data => _data; public string CurrentConfigName => _currentConfigName; public IReadOnlyList AvailableConfigs => _availableConfigs.AsReadOnly(); - public ConfigManager(string fileName, string configDirectory = "configs") + public ConfigManager(string defaultFilePath, string configDirectory = "") { - _defaultFilename = fileName; - _configDirectory = configDirectory; - _currentConfigName = Path.GetFileNameWithoutExtension(fileName); + _defaultFilePath = defaultFilePath; + _configDirectory = string.IsNullOrWhiteSpace(configDirectory) + ? Path.GetDirectoryName(defaultFilePath) ?? "configs" + : configDirectory; + _currentConfigName = Path.GetFileNameWithoutExtension(defaultFilePath); + _currentFilePath = defaultFilePath; _data = new T(); _availableConfigs = []; @@ -40,7 +45,7 @@ namespace Spectrum public void LoadConfig(string filename = "") { if (string.IsNullOrEmpty(filename)) - filename = _defaultFilename; + filename = _defaultFilePath; try { @@ -51,6 +56,7 @@ namespace Spectrum var json = File.ReadAllText(filename); _data = JsonConvert.DeserializeObject(json) ?? new T(); _currentConfigName = Path.GetFileNameWithoutExtension(filename); + _currentFilePath = filename; } catch { @@ -71,17 +77,24 @@ namespace Spectrum LogManager.Log($"Error loading config {filename}: {ex.Message}", LogLevel.Error); _data = new T(); } + + if (_fileWatcher != null) + { + StopFileWatcher(); + StartFileWatcher(); + } } public void SaveConfig(string filename = "") { if (string.IsNullOrEmpty(filename)) - filename = _defaultFilename; + filename = _defaultFilePath; try { File.WriteAllText(filename, JsonConvert.SerializeObject(_data, Formatting.Indented)); _currentConfigName = Path.GetFileNameWithoutExtension(filename); + _currentFilePath = filename; } catch (Exception ex) { @@ -135,6 +148,7 @@ namespace Spectrum .Select(Path.GetFileNameWithoutExtension) .Where(name => !string.IsNullOrEmpty(name)) .Cast() + .Where(name => !name.Equals(Path.GetFileNameWithoutExtension(_defaultFilePath), StringComparison.OrdinalIgnoreCase)) .ToList(); _availableConfigs.Clear(); @@ -259,7 +273,9 @@ namespace Spectrum { if (_fileWatcher != null) return; - _fileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _defaultFilename) + var directory = Path.GetDirectoryName(_currentFilePath) ?? Directory.GetCurrentDirectory(); + var fileName = Path.GetFileName(_currentFilePath); + _fileWatcher = new FileSystemWatcher(directory, fileName) { NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size }; @@ -281,11 +297,11 @@ namespace Spectrum Thread.Sleep(100); try { - LoadConfig(); + LoadConfig(_currentFilePath); } catch (Exception ex) { - LogManager.Log($"Failed to reload configuration for {_defaultFilename}: {ex.Message}", LogLevel.Error); + LogManager.Log($"Failed to reload configuration for {_currentFilePath}: {ex.Message}", LogLevel.Error); } } @@ -296,6 +312,181 @@ namespace Spectrum } } + public class ColorConfigManager + { + private readonly string _colorsDirectory; + private readonly List _colors; + private readonly object _lock = new(); + private int _version; + private FileSystemWatcher? _directoryWatcher; + + public IReadOnlyList Colors => GetColorsSnapshot(); + public int Version => _version; + + public ColorConfigManager(string colorsDirectory) + { + _colorsDirectory = colorsDirectory; + _colors = []; + + if (!Directory.Exists(_colorsDirectory)) + Directory.CreateDirectory(_colorsDirectory); + + Reload(); + StartDirectoryWatcher(); + } + + public void Reload() + { + try + { + if (!Directory.Exists(_colorsDirectory)) + return; + + var loadedColors = new List(); + var files = Directory.GetFiles(_colorsDirectory, "*.json") + .OrderBy(f => f, StringComparer.OrdinalIgnoreCase) + .ToList(); + + foreach (var file in files) + { + try + { + var json = File.ReadAllText(file); + var color = JsonConvert.DeserializeObject(json); + if (color == null) + continue; + if (string.IsNullOrWhiteSpace(color.Name)) + color.Name = Path.GetFileNameWithoutExtension(file); + loadedColors.RemoveAll(c => c.Name.Equals(color.Name, StringComparison.OrdinalIgnoreCase)); + loadedColors.Add(color); + } + catch (Exception ex) + { + LogManager.Log($"Failed to load color config {file}: {ex.Message}", LogLevel.Error); + } + } + + lock (_lock) + { + _colors.Clear(); + _colors.AddRange(loadedColors); + _version++; + } + } + catch (Exception ex) + { + LogManager.Log($"Error loading colors: {ex.Message}", LogLevel.Error); + } + } + + public ColorInfo? GetColor(string name) + { + if (string.IsNullOrWhiteSpace(name)) + return null; + + lock (_lock) + { + return _colors.Find(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase)); + } + } + + private List GetColorsSnapshot() + { + lock (_lock) + { + return [.. _colors]; + } + } + + public bool SaveColor(ColorInfo color) + { + if (string.IsNullOrWhiteSpace(color.Name)) + { + LogManager.Log("Color name cannot be empty.", LogLevel.Error); + return false; + } + + try + { + var filePath = GetColorFilePath(color.Name); + File.WriteAllText(filePath, JsonConvert.SerializeObject(color, Formatting.Indented)); + Reload(); + return true; + } + catch (Exception ex) + { + LogManager.Log($"Error saving color {color.Name}: {ex.Message}", LogLevel.Error); + return false; + } + } + + public bool DeleteColor(string name) + { + if (string.IsNullOrWhiteSpace(name)) + { + LogManager.Log("Color name cannot be empty.", LogLevel.Error); + return false; + } + + try + { + var filePath = GetColorFilePath(name); + if (!File.Exists(filePath)) + { + LogManager.Log($"Color {name} not found.", LogLevel.Error); + return false; + } + + File.Delete(filePath); + Reload(); + return true; + } + catch (Exception ex) + { + LogManager.Log($"Error deleting color {name}: {ex.Message}", LogLevel.Error); + return false; + } + } + + private string GetColorFilePath(string colorName) + { + var safeName = string.Join("_", colorName.Split(Path.GetInvalidFileNameChars(), StringSplitOptions.RemoveEmptyEntries)); + if (string.IsNullOrWhiteSpace(safeName)) + safeName = "color"; + return Path.Combine(_colorsDirectory, $"{safeName}.json"); + } + + private void StartDirectoryWatcher() + { + try + { + if (_directoryWatcher != null) return; + + _directoryWatcher = new FileSystemWatcher(_colorsDirectory, "*.json") + { + NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite + }; + + _directoryWatcher.Created += OnDirectoryChanged; + _directoryWatcher.Deleted += OnDirectoryChanged; + _directoryWatcher.Renamed += OnDirectoryChanged; + _directoryWatcher.Changed += OnDirectoryChanged; + _directoryWatcher.EnableRaisingEvents = true; + + } + catch (Exception ex) + { + LogManager.Log($"Error starting color directory watcher: {ex.Message}", LogLevel.Error); + } + } + + private void OnDirectoryChanged(object sender, FileSystemEventArgs e) + { + Thread.Sleep(50); + Reload(); + } + } + #region Enums public enum MovementType { @@ -308,8 +499,8 @@ namespace Spectrum public enum MovementMethod { MouseEvent, - Makcu, - Arduino + Arduino, + HID } public enum FovType { @@ -403,6 +594,7 @@ namespace Spectrum public bool CollectData { get; set; } = false; public bool AutoLabel { get; set; } = false; public int BackgroundImageInterval { get; set; } = 10; + public int LabeledImageInterval { get; set; } = 5; #endregion #region Color Settings @@ -414,28 +606,19 @@ namespace Spectrum #region Misc public bool DebugMode { get; set; } = false; public bool AntiCapture { get; set; } = false; + public int MinAreaPx { get; set; } = 100; #endregion } - public class ColorData - { - public List Colors { get; set; } = []; - } - public class ColorInfo(string name, Scalar upper, Scalar lower) { public string Name { get; set; } = name; public Scalar Upper { get; set; } = upper; public Scalar Lower { get; set; } = lower; } - public class Keybind + public class Keybind(Keys key, KeybindType type) { - public Keys Key { get; set; } + public Keys Key { get; set; } = key; - public KeybindType Type { get; set; } - public Keybind(Keys key, KeybindType type) - { - Key = key; - Type = type; - } + public KeybindType Type { get; set; } = type; } } \ No newline at end of file diff --git a/Spectrum/Detection/AutoLabeling.cs b/Spectrum/Detection/AutoLabeling.cs index dada3c5..5723ec3 100644 --- a/Spectrum/Detection/AutoLabeling.cs +++ b/Spectrum/Detection/AutoLabeling.cs @@ -1,7 +1,8 @@ using OpenCvSharp; +using Spectrum.Utilities; using System.Collections.Concurrent; using System.Text; -using LogLevel = Spectrum.LogManager.LogLevel; +using LogLevel = Spectrum.Utilities.LogManager.LogLevel; namespace Spectrum.Detection { @@ -9,12 +10,13 @@ namespace Spectrum.Detection { private static int imageCount = 0; private static int detectionAttemps = 0; - private static readonly object lockObject = new object(); + private static int labeledImageAttempts = 0; + private static readonly object lockObject = new(); private static CancellationTokenSource? cancellationTokenSource; 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 readonly ConcurrentQueue labelingQueue = new(); + private static readonly ConcurrentQueue backgroundQueue = new(); + private static readonly ConfigManager mainConfig = Program.mainConfig; public static bool Started = false; private static List GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight) @@ -117,6 +119,13 @@ namespace Spectrum.Detection if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0) return; + labeledImageAttempts++; + + if (labeledImageAttempts < mainConfig.Data.LabeledImageInterval) + return; + + labeledImageAttempts = 0; + if (labelingQueue.Count > 250) return; @@ -136,6 +145,8 @@ namespace Spectrum.Detection if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected) return; + detectionAttemps = 0; + if (backgroundQueue.Count > 250) return; diff --git a/Spectrum/Detection/DetectionManager.cs b/Spectrum/Detection/DetectionManager.cs index 1571bf3..71fb889 100644 --- a/Spectrum/Detection/DetectionManager.cs +++ b/Spectrum/Detection/DetectionManager.cs @@ -1,23 +1,27 @@ using OpenCvSharp; using Spectrum.Input; +using Spectrum.Utilities; using System.Diagnostics; +using System.Drawing.Imaging; namespace Spectrum.Detection { class DetectionManager { - private readonly Stopwatch stopwatch = new Stopwatch(); - private Rectangle bounds = new Rectangle(0, 0, 0, 0); - private readonly (int Width, int Height) screenSize = Win32.GetPrimaryScreenSize(); - private readonly int minArea; + private readonly Stopwatch stopwatch = new(); + private Rectangle bounds = new(0, 0, 0, 0); + private readonly Rectangle monitorBounds = Program.MonitorBounds; private readonly ConfigManager mainConfig = Program.mainConfig; private readonly Renderer? renderer; private readonly Thread? _detectionThread; private DateTime lastMenuToggle = DateTime.MinValue; private readonly CaptureManager _captureManager; - private readonly Queue processTimes = new Queue(100); - private DateTime lastFpsUpdate = DateTime.Now; - private int frameCount = 0; + private Mat? hsvBuffer; + private Mat? maskBuffer; + private Mat? bgrBuffer; + private OpenCvSharp.Size bufferSize; + private OpenCvSharp.Size bgrBufferSize; + private static void AddTiming(string name, long ticks) => Program.Timings.Add(name, ticks); public DetectionManager(Renderer renderer) { @@ -29,7 +33,6 @@ namespace Spectrum.Detection Name = "Spectrum Detection Thread", Priority = ThreadPriority.AboveNormal }; - minArea = (100 / 1440) * screenSize.Height; _detectionThread.Start(); } @@ -40,26 +43,29 @@ namespace Spectrum.Detection var config = mainConfig.Data; try { - if (InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) + if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && !config.ShowMenu) { - if (config.DebugMode) stopwatch.Restart(); + var t0 = Stopwatch.GetTimestamp(); renderer?.ClearDetectionDrawCommands(); + AddTiming("Clear Draw Commands", Stopwatch.GetTimestamp() - t0); if (!config.ClosestToMouse) { bounds = new Rectangle( - (screenSize.Width - config.ImageWidth) / 2, - (screenSize.Height - config.ImageHeight) / 2, + monitorBounds.X + (monitorBounds.Width - config.ImageWidth) / 2, + monitorBounds.Y + (monitorBounds.Height - config.ImageHeight) / 2, config.ImageWidth, config.ImageHeight ); } else { + var tCursor = Stopwatch.GetTimestamp(); _ = InputManager.GetCursorPos(out System.Drawing.Point mousePos); + AddTiming("Get Cursor Pos", Stopwatch.GetTimestamp() - tCursor); bounds = new Rectangle( mousePos.X - (config.ImageWidth / 2), mousePos.Y - (config.ImageHeight / 2), @@ -68,8 +74,7 @@ namespace Spectrum.Detection ); } - var screenRect = new Rectangle(0, 0, screenSize.Width, screenSize.Height); - bounds = Rectangle.Intersect(bounds, screenRect); + bounds = Rectangle.Intersect(bounds, monitorBounds); if (bounds.Width <= 0 || bounds.Height <= 0) { renderer?.CommitDetectionDrawCommands(); @@ -78,16 +83,24 @@ namespace Spectrum.Detection } Bitmap? screenshot = null; + var tCapture = Stopwatch.GetTimestamp(); if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable) { - screenshot = _captureManager.CaptureScreenshotDirectX(bounds); + var dxBounds = new Rectangle( + bounds.X - monitorBounds.X, + bounds.Y - monitorBounds.Y, + bounds.Width, + bounds.Height + ); + screenshot = _captureManager.CaptureScreenshotDirectX(dxBounds); } else { if (_captureManager.IsInitialized) _captureManager.Dispose(); - screenshot = _captureManager.CaptureScreenshotGdi(bounds); + screenshot = CaptureManager.CaptureScreenshotGdi(bounds); } + AddTiming("Screen Capture", Stopwatch.GetTimestamp() - tCapture); if (screenshot == null) { @@ -96,21 +109,40 @@ namespace Spectrum.Detection continue; } - Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); + var tMat = Stopwatch.GetTimestamp(); + Mat mat = ConvertBitmapToMat(screenshot); screenshot.Dispose(); + AddTiming("Bitmap to Mat", Stopwatch.GetTimestamp() - tMat); - Mat? drawing = (config.AutoLabel || config.CollectData) ? mat.Clone() : null; + EnsureBuffers(mat.Size()); - Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); - Cv2.InRange(mat, config.LowerHSV, config.UpperHSV, mat); - Cv2.Dilate(mat, mat, null, iterations: 2); - Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); + var tConvert = Stopwatch.GetTimestamp(); + Cv2.CvtColor(mat, hsvBuffer!, ColorConversionCodes.BGR2HSV); + AddTiming("Color Conversion", Stopwatch.GetTimestamp() - tConvert); - Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); + var tRange = Stopwatch.GetTimestamp(); + Cv2.InRange(hsvBuffer!, config.LowerHSV, config.UpperHSV, maskBuffer!); + AddTiming("Range Check", Stopwatch.GetTimestamp() - tRange); - var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= minArea).ToArray(); + var tDilate = Stopwatch.GetTimestamp(); + Cv2.Dilate(maskBuffer!, maskBuffer!, null, iterations: 2); + AddTiming("Dilation", Stopwatch.GetTimestamp() - tDilate); + var tThresh = Stopwatch.GetTimestamp(); + Cv2.Threshold(maskBuffer!, maskBuffer!, 127, 255, ThresholdTypes.Binary); + AddTiming("Thresholding", Stopwatch.GetTimestamp() - tThresh); + + var tContours = Stopwatch.GetTimestamp(); + Cv2.FindContours(maskBuffer!, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); + AddTiming("Find Contours", Stopwatch.GetTimestamp() - tContours); + + var tFilter = Stopwatch.GetTimestamp(); + var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= config.MinAreaPx).ToArray(); + AddTiming("Filter Contours", Stopwatch.GetTimestamp() - tFilter); + + var tMerge = Stopwatch.GetTimestamp(); var processedContours = MergeOverlappingContours(filteredContours); + AddTiming("Merge Contours", Stopwatch.GetTimestamp() - tMerge); if (processedContours.Length > 0) { @@ -123,6 +155,7 @@ namespace Spectrum.Detection bool shouldDrawDetections = config.DrawDetections && renderer != null; + var tProcess = Stopwatch.GetTimestamp(); foreach (var contour in processedContours) { var rect = Cv2.BoundingRect(contour); @@ -154,6 +187,7 @@ namespace Spectrum.Detection renderer!.AddRect(_rect, config.DetectionColor, 1.0f); } } + AddTiming("Process Contours", Stopwatch.GetTimestamp() - tProcess); if (closestContour != null) { @@ -201,14 +235,14 @@ namespace Spectrum.Detection } } - if (config.AutoLabel && drawing != null) + if (config.AutoLabel) { - AutoLabeling.AddToQueue(drawing, bounds, processedContours); - AutoLabeling.AddBackgroundImage(drawing, true); + AutoLabeling.AddToQueue(mat, bounds, processedContours); + AutoLabeling.AddBackgroundImage(mat, true); } - if (!config.AutoLabel && config.CollectData && drawing != null) + if (!config.AutoLabel && config.CollectData) { - AutoLabeling.AddBackgroundImage(drawing, false); + AutoLabeling.AddBackgroundImage(mat, false); } InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY)); @@ -220,7 +254,9 @@ namespace Spectrum.Detection if (config.EnableAim && InputManager.IsKeyOrMouseDown(config.Keybind)) { + var tMove = Stopwatch.GetTimestamp(); InputManager.MoveMouse(); + AddTiming("Mouse Movement", Stopwatch.GetTimestamp() - tMove); } if (config.TriggerBot) { @@ -232,17 +268,14 @@ namespace Spectrum.Detection } } } - else if (config.CollectData && drawing != null) + else if (config.CollectData) { - AutoLabeling.AddBackgroundImage(drawing, false); + AutoLabeling.AddBackgroundImage(mat, false); MovementPaths.ResetWindMouse(); } renderer?.CommitDetectionDrawCommands(); - mat.Dispose(); - drawing?.Dispose(); - if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel)) AutoLabeling.StartLabeling(); else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel) @@ -251,22 +284,7 @@ namespace Spectrum.Detection if (config.DebugMode) { stopwatch.Stop(); - double processTime = stopwatch.Elapsed.TotalMilliseconds; - processTimes.Enqueue(processTime); - if (processTimes.Count > 100) - processTimes.Dequeue(); - - frameCount++; - var now = DateTime.Now; - var timeSinceLastUpdate = (now - lastFpsUpdate).TotalSeconds; - if (timeSinceLastUpdate >= 1.0) - { - int fps = (int)(frameCount / timeSinceLastUpdate); - double avgProcessTime = processTimes.Count > 0 ? processTimes.Average() : 0; - Program.statistics = (fps, avgProcessTime); - frameCount = 0; - lastFpsUpdate = now; - } + AddTiming("Frame", stopwatch.ElapsedTicks); } } else @@ -343,7 +361,7 @@ namespace Spectrum.Detection } while (merged); var mergedContours = new List(contourRects.Count); - foreach (var (rect, indices) in contourRects) + foreach (var (_, indices) in contourRects) { var pointsList = new List(indices.Count * 10); foreach (var idx in indices) @@ -353,7 +371,57 @@ namespace Spectrum.Detection var hull = Cv2.ConvexHull(pointsList); mergedContours.Add(hull); } - return mergedContours.ToArray(); + return [.. mergedContours]; + } + + private void EnsureBuffers(OpenCvSharp.Size size) + { + if (size == bufferSize && hsvBuffer != null && maskBuffer != null) + return; + + hsvBuffer?.Dispose(); + maskBuffer?.Dispose(); + + hsvBuffer = new Mat(size, MatType.CV_8UC3); + maskBuffer = new Mat(size, MatType.CV_8UC1); + bufferSize = size; + } + + private Mat ConvertBitmapToMat(Bitmap bitmap) + { + var size = new OpenCvSharp.Size(bitmap.Width, bitmap.Height); + if (bgrBuffer == null || size != bgrBufferSize) + { + bgrBuffer?.Dispose(); + bgrBuffer = new Mat(size, MatType.CV_8UC4); + bgrBufferSize = size; + } + + var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height); + var bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); + try + { + unsafe + { + byte* src = (byte*)bmpData.Scan0; + byte* dst = bgrBuffer!.DataPointer; + int srcStride = bmpData.Stride; + int dstStride = (int)bgrBuffer.Step(); + int rowBytes = bitmap.Width * 4; + for (int y = 0; y < bitmap.Height; y++) + { + Buffer.MemoryCopy(src, dst, rowBytes, rowBytes); + src += srcStride; + dst += dstStride; + } + } + } + finally + { + bitmap.UnlockBits(bmpData); + } + + return bgrBuffer!; } } } \ No newline at end of file diff --git a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs index df91340..68328f1 100644 --- a/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs +++ b/Spectrum/Input/InputLibraries/Arduino/ArduinoMain.cs @@ -1,6 +1,7 @@ -using System.Diagnostics; +using Spectrum.Utilities; +using System.Diagnostics; using System.IO.Ports; -using LogLevel = Spectrum.LogManager.LogLevel; +using LogLevel = Spectrum.Utilities.LogManager.LogLevel; namespace Spectrum.Input.InputLibraries.Arduino { diff --git a/Spectrum/Input/InputLibraries/HID/HIDMain.cs b/Spectrum/Input/InputLibraries/HID/HIDMain.cs new file mode 100644 index 0000000..22963a6 --- /dev/null +++ b/Spectrum/Input/InputLibraries/HID/HIDMain.cs @@ -0,0 +1,321 @@ +using HidSharp; +using Spectrum.Utilities; +using LogLevel = Spectrum.Utilities.LogManager.LogLevel; + +namespace Spectrum.Input.InputLibraries.HID +{ + internal class HIDMain(int? vid = null, int? pid = null) + { + readonly int[] ExpectedVIDs = + [ + 0x046D, + 0x1532, + 0x1038, + 0x1B1C, + 0x0B05, + 0x0951, + 0x258A, + 0x3057 + ]; + + public static readonly byte BUTTON_LEFT = 0x01; + public static readonly byte BUTTON_RIGHT = 0x02; + public static readonly byte BUTTON_MIDDLE = 0x04; + public static readonly byte BUTTON_BACK = 0x08; + public static readonly byte BUTTON_FORWARD = 0x10; + + const byte CMD_MOVE = 0x01; + const byte CMD_CLICK = 0x02; + const byte CMD_PRESS = 0x03; + const byte CMD_RELEASE = 0x04; + const byte CMD_SCROLL = 0x05; + const byte CMD_PING = 0x09; + + const byte HID_REPORT_ID_VENDOR = 0x06; + const int FEATURE_REPORT_SIZE = 64; + const int PING_TIMEOUT_MS = 500; + + int vid = vid ?? 0, pid = pid ?? 0; + HidDevice? device; + HidStream? stream; + private readonly object _syncLock = new(); + + IEnumerable FindDevice() + { + var devices = DeviceList.Local.GetHidDevices(); + foreach (var device in devices) + { + try + { + string name; + try { name = device.GetProductName(); } + catch { name = ""; } + LogManager.Log($"HIDMain: Found device: VID={device.VendorID:X4}, PID={device.ProductID:X4}, Name={name}", LogLevel.Debug); + } + catch (Exception e) + { + LogManager.Log($"HIDMain: Error accessing device info: {e.Message}", LogLevel.Debug); + } + + } + return devices.Where(device => + { + try + { + return + ExpectedVIDs.Contains(device.VendorID) && + (vid == 0 || device.VendorID == vid) && + (pid == 0 || device.ProductID == pid) && + device.GetMaxFeatureReportLength() == FEATURE_REPORT_SIZE; + } + catch + { + return false; + } + }); + } + + private static bool TestDeviceWithPing(HidDevice dev, HidStream testStream) + { + try + { + byte[] pingPayload = [0x70, 0x69, 0x6E, 0x67, 0x70, 0x6F, 0x6E, 0x67]; + byte[] pingPacket = new byte[FEATURE_REPORT_SIZE]; + pingPacket[0] = HID_REPORT_ID_VENDOR; + pingPacket[1] = CMD_PING; + Array.Copy(pingPayload, 0, pingPacket, 2, pingPayload.Length); + + LogManager.Log($"HIDMain: Sending ping to {dev.GetProductName()}...", LogLevel.Debug); + + testStream.SetFeature(pingPacket); + Thread.Sleep(50); + + byte[] response = new byte[FEATURE_REPORT_SIZE]; + testStream.ReadTimeout = PING_TIMEOUT_MS; + + int bytesRead = testStream.Read(response, 0, response.Length); + + if (bytesRead > 0) + { + LogManager.Log($"HIDMain: Received {bytesRead} bytes from {dev.GetProductName()}", LogLevel.Debug); + + if (response[1] == CMD_PING) + { + bool payloadMatches = true; + for (int i = 0; i < pingPayload.Length; i++) + { + if (response[2 + i] != pingPayload[i]) + { + payloadMatches = false; + break; + } + } + + if (payloadMatches) + { + LogManager.Log($"HIDMain: Ping successful for {dev.GetProductName()}", LogLevel.Debug); + return true; + } + else + { + string responseString = ""; + for (int i = 0; i < bytesRead; i++) + { + responseString += $"0x{response[i]:X2} "; + } + LogManager.Log($"HIDMain: Ping response payload mismatch for {dev.GetProductName()}: {responseString}", LogLevel.Debug); + } + } + else + { + string responseString = ""; + for (int i = 0; i < bytesRead; i++) + { + responseString += $"0x{response[i]:X2} "; + } + LogManager.Log($"HIDMain: Unexpected response from {dev.GetProductName()}: {responseString}", LogLevel.Debug); + } + } + else + { + LogManager.Log($"HIDMain: No response from {dev.GetProductName()}", LogLevel.Debug); + } + } + catch (TimeoutException) + { + LogManager.Log($"HIDMain: Ping timeout for {dev.GetProductName()}", LogLevel.Debug); + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Ping error for {dev.GetProductName()}: {ex.Message}", LogLevel.Debug); + } + + return false; + } + + public bool Init() + { + lock (_syncLock) + { + if (stream != null && device != null) + { + LogManager.Log("HIDMain: Device already initialized.", LogLevel.Debug); + return true; + } + + LogManager.Log("HIDMain: Scanning for devices", LogLevel.Debug); + var candidates = FindDevice().ToList(); + + if (candidates.Count == 0) + { + LogManager.Log("HIDMain: No gaming mouse emulator vendor interface found.", LogLevel.Warning); + return false; + } + + foreach (var dev in candidates) + { + try + { + LogManager.Log($"HIDMain: Testing device: {dev.GetProductName()} (VID:PID {dev.VendorID:X4}:{dev.ProductID:X4})", LogLevel.Debug); + + if (dev.TryOpen(out stream)) + { + if (TestDeviceWithPing(dev, stream)) + { + device = dev; + vid = dev.VendorID; + pid = dev.ProductID; + LogManager.Log($"HIDMain: Connected successfully to {dev.GetProductName()}", LogLevel.Info); + return true; + } + else + { + LogManager.Log($"HIDMain: Device {dev.GetProductName()} did not respond to ping", LogLevel.Debug); + stream.Close(); + stream.Dispose(); + stream = null; + } + } + else + { + LogManager.Log($"HIDMain: Could not open device {dev.GetProductName()}", LogLevel.Debug); + } + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Error testing device: {ex.Message}", LogLevel.Debug); + stream?.Close(); + stream?.Dispose(); + stream = null; + } + } + + LogManager.Log("HIDMain: Failed to connect to any gaming mouse emulator.", LogLevel.Warning); + return false; + } + } + + private bool SendFeatureReport(byte[] data) + { + lock (_syncLock) + { + if (stream == null || device == null) + { + LogManager.Log("HIDMain: Device not connected.", LogLevel.Warning); + return false; + } + + try + { + byte[] report = new byte[FEATURE_REPORT_SIZE]; + report[0] = HID_REPORT_ID_VENDOR; + + int copyLength = Math.Min(data.Length, FEATURE_REPORT_SIZE - 1); + Array.Copy(data, 0, report, 1, copyLength); + + stream.SetFeature(report); + Thread.Sleep(10); + return true; + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Error sending feature report: {ex.Message}", LogLevel.Warning); + return false; + } + } + } + + public bool Move(int x, int y) + { + x = Math.Clamp(x, -127, 127); + y = Math.Clamp(y, -127, 127); + + byte xByte = unchecked((byte)x); + byte yByte = unchecked((byte)y); + + byte[] data = [CMD_MOVE, xByte, yByte]; + bool success = SendFeatureReport(data); + + return success; + } + + public bool Click(byte button) + { + byte[] data = [CMD_CLICK, button]; + bool success = SendFeatureReport(data); + + return success; + } + + public bool Press(byte button) + { + byte[] data = [CMD_PRESS, button]; + bool success = SendFeatureReport(data); + + return success; + } + + public bool Release(byte button) + { + byte[] data = [CMD_RELEASE, button]; + bool success = SendFeatureReport(data); + + return success; + } + + public bool Scroll(int amount) + { + amount = Math.Clamp(amount, -127, 127); + byte amountByte = unchecked((byte)amount); + + byte[] data = [CMD_SCROLL, amountByte]; + bool success = SendFeatureReport(data); + + return success; + } + + public void Close() + { + lock (_syncLock) + { + try + { + stream?.Close(); + stream?.Dispose(); + LogManager.Log("HIDMain: Connection closed.", LogLevel.Debug); + } + catch (Exception ex) + { + LogManager.Log($"HIDMain: Error closing connection: {ex.Message}", LogLevel.Debug); + } + finally + { + stream = null; + device = null; + } + } + } + + public bool IsConnected => stream != null && device != null; + } +} diff --git a/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs b/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs deleted file mode 100644 index 7113d22..0000000 --- a/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs +++ /dev/null @@ -1,112 +0,0 @@ -using LogLevel = Spectrum.LogManager.LogLevel; - -namespace Spectrum.Input.InputLibraries.Makcu -{ - internal class MakcuMain - { - public static MakcuMouse? MakcuInstance { get; private set; } - - private static bool _isMakcuLoaded = false; - - private static bool _isSubscribedToButtonEvents = false; - - private const bool DefaultDebugLoggingForInternalCreation = false; - private const bool DefaultSendInitCommandsForInternalCreation = true; - - public static void ConfigureMakcuInstance(bool debugEnabled, bool sendInitCmds) - { - - LogManager.Log($"MakcuMain: Configuring MakcuInstance. Debug: {debugEnabled}, SendInitCmds: {sendInitCmds}", LogLevel.Debug); - UnsubscribeFromButtonEvents(); - MakcuInstance?.Dispose(); - - MakcuInstance = new MakcuMouse(debugEnabled, sendInitCmds); - _isMakcuLoaded = false; - } - - private static async Task InitializeMakcuDevice() - { - if (_isMakcuLoaded && MakcuInstance != null && MakcuInstance.IsInitializedAndConnected) - { - LogManager.Log("MakcuMain: InitializeMakcuDevice called, but Makcu is already loaded and connected.", LogLevel.Debug); - return true; - } - - if (MakcuInstance == null) - { - ConfigureMakcuInstance(true, DefaultSendInitCommandsForInternalCreation); - } - - try - { - if (MakcuInstance == null || !MakcuInstance.Init()) - { - _isMakcuLoaded = false; - return false; - } - - string? version = MakcuInstance.GetKmVersion(); - - _isMakcuLoaded = true; - - SubscribeToButtonEvents(); - - return true; - } - catch - { - _isMakcuLoaded = false; - if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected) - { - MakcuInstance.Close(); - } - return false; - } - } - - public static async Task Load() => await InitializeMakcuDevice(); - - public static void Unload() - { - UnsubscribeFromButtonEvents(); - MakcuInstance?.Close(); - _isMakcuLoaded = false; - LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug); - } - - private static void SubscribeToButtonEvents() - { - if (MakcuInstance != null && !_isSubscribedToButtonEvents) - { - MakcuInstance.ButtonStateChanged += OnMakcuButtonStateChanged; - _isSubscribedToButtonEvents = true; - LogManager.Log("MakcuMain: Subscribed to MakcuInstance.ButtonStateChanged events.", LogLevel.Debug); - } - } - - private static void UnsubscribeFromButtonEvents() - { - if (MakcuInstance != null && _isSubscribedToButtonEvents) - { - MakcuInstance.ButtonStateChanged -= OnMakcuButtonStateChanged; - _isSubscribedToButtonEvents = false; - LogManager.Log("MakcuMain: Unsubscribed from MakcuInstance.ButtonStateChanged events.", LogLevel.Debug); - } - } - - private static void OnMakcuButtonStateChanged(MakcuMouseButton button, bool isPressed) - { - - string state = isPressed ? "Pressed" : "Released"; - LogManager.Log($"{button} physical {state}!", LogLevel.Debug); - } - public static void DisposeInstance() - { - Unload(); - MakcuInstance?.Dispose(); - MakcuInstance = null; - _isMakcuLoaded = false; - LogManager.Log("MakcuMain: MakcuMouse instance disposed (null).", LogLevel.Debug); - } - } -} diff --git a/Spectrum/Input/InputLibraries/Makcu/MakcuMouse.cs b/Spectrum/Input/InputLibraries/Makcu/MakcuMouse.cs deleted file mode 100644 index c7f3308..0000000 --- a/Spectrum/Input/InputLibraries/Makcu/MakcuMouse.cs +++ /dev/null @@ -1,598 +0,0 @@ -using System.Diagnostics; -using System.IO.Ports; -using System.Text; -using LogLevel = Spectrum.LogManager.LogLevel; - -/// https://github.com/sdfgasfgr/Aimmy-Makcu/blob/master/Aimmy2/MouseMovementLibraries/MakcuSupport/MakcuMouse.cs - -namespace Spectrum.Input.InputLibraries.Makcu -{ - public enum MakcuMouseButton - { - Left = 0, Right = 1, Middle = 2, Mouse4 = 3, Mouse5 = 4 - } - - public class MakcuMouse : IDisposable - { - private static readonly byte[] BaudChangeCommand = [0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00]; - - private SerialPort? _serialPort; - private readonly bool _debugLogging; - private readonly bool _sendInitCommands; - - private readonly object _serialLock = new(); - private bool _isInitializedAndConnected = false; - private Thread? _listenerThread; - private ManualResetEventSlim _stopListenerEvent = new(false); - private volatile bool _pauseListener = false; - - private readonly Dictionary _buttonStates = []; - - public event Action? ButtonStateChanged; - - public string? PortName { get; private set; } - public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200); - public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen; - - - public MakcuMouse(bool debugLogging = false, bool sendInitCommands = true) - { - _debugLogging = debugLogging; - _sendInitCommands = sendInitCommands; - foreach (MakcuMouseButton btn in Enum.GetValues(typeof(MakcuMouseButton))) - { - _buttonStates[btn] = false; - } - } - - private void Log(string message) - { - if (_debugLogging) - { - LogManager.Log($"[MakcuMouse {DateTime.Now:HH:mm:ss}] {message}", LogLevel.Debug); - } - } - - - private string FindComPortInternal() - { - Log("Searching for COM port for Makcu device using SerialPort.GetPortNames() and connection test..."); - string[] availablePorts; - try - { - availablePorts = SerialPort.GetPortNames(); - } - catch (Exception ex) - { - Log($"Error getting COM port list: {ex.Message}. Cannot continue search."); - return ""; - } - - if (availablePorts == null || availablePorts.Length == 0) - { - Log("No COM ports available according to SerialPort.GetPortNames()."); - return ""; - } - - Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one..."); - - foreach (string portName in availablePorts) - { - Log($"Testing port: {portName}"); - SerialPort? testPort = null; - try - { - - testPort = new SerialPort(portName, 115200) - { - ReadTimeout = 250, - WriteTimeout = 500, - DtrEnable = true, - RtsEnable = true - }; - testPort.Open(); - Log($"Port {portName} opened at 115200 baud."); - - Log($"Sending command to change baudrate to 4M on {portName}."); - testPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length); - testPort.BaseStream.Flush(); - Thread.Sleep(150); - - testPort.Close(); - testPort.BaudRate = 4000000; - testPort.Open(); - Log($"Port {portName} reopened at 4000000 baud."); - - testPort.DiscardInBuffer(); - testPort.Write("km.version()\r\n"); - Log($"Command 'km.version()' sent to {portName}. Waiting for response..."); - - string response = ""; - try - { - response = testPort.ReadLine().Trim(); - } - catch (TimeoutException) - { - Log($"Timeout waiting for 'km.version()' response on {portName}. Probably not the Makcu device."); - testPort.Close(); - continue; - } - - Log($"Response from 'km.version()' on {portName}: '{response}'"); - - if (!string.IsNullOrEmpty(response) && (response.Contains("KMBOX") || response.Contains("Makcu") || response.Contains("MAKCU") || response.StartsWith('v') || char.IsDigit(response.FirstOrDefault()))) - { - Log($"Makcu device found on port: {portName}! Version response: '{response}'"); - testPort.Close(); - return portName; - } - else - { - Log($"Response from 'km.version()' on {portName} does not seem to be from a Makcu device. Response: '{response}'"); - } - - testPort.Close(); - } - catch (UnauthorizedAccessException ex) - { - Log($"Unauthorized access error on {portName}: {ex.Message} (Port might be in use)."); - } - catch (TimeoutException ex) - { - Log($"Timeout on {portName} (possibly during baud rate change or write): {ex.Message}"); - } - catch (Exception ex) - { - Log($"Failed to test port {portName}: {ex.GetType().Name} - {ex.Message}"); - } - finally - { - if (testPort != null && testPort.IsOpen) - { - testPort.Close(); - } - testPort?.Dispose(); - } - } - - Log("Makcu device not found on any available COM ports after connection test."); - return ""; - } - - - private bool OpenSerialPort(string portNameToOpen, int baudRate) - { - try - { - _serialPort?.Close(); - _serialPort?.Dispose(); - - Log($"Attempting to open {portNameToOpen} at {baudRate} baud."); - _serialPort = new SerialPort(portNameToOpen, baudRate) - { - ReadTimeout = 100, - WriteTimeout = 500, - DtrEnable = true, - RtsEnable = true - }; - _serialPort.Open(); - PortName = portNameToOpen; - return true; - } - catch (Exception ex) - { - Log($"Failed to open {portNameToOpen} at {baudRate} baud. Error: {ex.Message}"); - _serialPort?.Dispose(); _serialPort = null; return false; - } - } - - private bool ChangeBaudRateTo4M() - { - if (_serialPort == null || !_serialPort.IsOpen) - { - Log("ChangeBaudRateTo4M: _serialPort is null or not open."); - return false; - } - Log("Sending command to change baudrate to 4M."); - try - { - _serialPort.Write(BaudChangeCommand, 0, BaudChangeCommand.Length); - _serialPort.BaseStream.Flush(); - Thread.Sleep(150); - - string currentPortName = _serialPort.PortName; - _serialPort.Close(); - - _serialPort.BaudRate = 4000000; - _serialPort.Open(); - - Log("Successfully changed to 4M baud."); return true; - } - catch (Exception ex) - { - Log($"Error changing baudrate to 4M: {ex.Message}"); - - _serialPort?.Close(); - return false; - } - } - - public bool Init() - { - lock (_serialLock) - { - if (_isInitializedAndConnected) { Log("MakcuMouse is already initialized."); return true; } - - string portToUse = FindComPortInternal(); - if (string.IsNullOrEmpty(portToUse)) - { Log("Init failed: Could not find a valid COM port for Makcu."); return false; } - - - if (!OpenSerialPort(portToUse, 115200)) - { Log($"Init failed: Could not open port {portToUse} at 115200 baud."); return false; } - - if (!ChangeBaudRateTo4M()) - { Log("Init failed: Could not change to 4M baud."); Close(); return false; } - - _isInitializedAndConnected = true; - PortName = portToUse; - - if (_sendInitCommands) - { - if (!SendCommandInternal("km.buttons(1)", false, out _)) - { Log("Init failed: Could not send 'km.buttons(1)'."); Close(); return false; } - - _stopListenerEvent.Reset(); - _listenerThread = new Thread(() => ListenForButtonEvents(_debugLogging)) - { IsBackground = true, Name = "MakcuButtonListener" }; - _listenerThread.Start(); - } - Log($"MakcuMouse initialized successfully on port {PortName} at {BaudRate} baud."); return true; - } - } - - private bool SendCommandInternal(string command, bool expectResponse, out string? responseText, int responseTimeoutMs = 200) - { - responseText = null; - if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen) - { - Log($"Error in SendCommand: Connection not open or initialized. Command: {command}"); - return false; - } - - lock (_serialLock) - { - if (!_serialPort.IsOpen) - { - Log($"Error in SendCommand (lock): Port not open. Command: {command}"); - return false; - } - - _pauseListener = true; - int originalReadTimeout = _serialPort.ReadTimeout; - - try - { - if (expectResponse) - { - _serialPort.ReadTimeout = responseTimeoutMs; - _serialPort.DiscardInBuffer(); - } - - Log($"Sending: {command}"); - _serialPort.Write(command + "\r\n"); - - if (expectResponse) - { - var stopwatch = Stopwatch.StartNew(); - StringBuilder sb = new(); - string commandTrimmed = command.Trim(); - bool firstLineIsEcho = true; - - while (stopwatch.ElapsedMilliseconds < responseTimeoutMs) - { - try - { - string line = _serialPort.ReadLine().Trim(); - if (!string.IsNullOrEmpty(line)) - { - Log($"Received (raw): {line}"); - if (line.Equals(commandTrimmed, StringComparison.OrdinalIgnoreCase) && firstLineIsEcho) - { - firstLineIsEcho = false; - continue; - } - if (line.Equals("OK", StringComparison.OrdinalIgnoreCase)) - { - if (sb.Length > 0) continue; - } - if (sb.Length > 0) sb.Append('\n'); - sb.Append(line); - } - if (_serialPort.BytesToRead == 0 && sb.Length > 0) - { - Thread.Sleep(15); - if (_serialPort.BytesToRead == 0) break; - } - } - catch (TimeoutException) - { - Log($"ReadLine() timeout in SendCommandInternal for '{command}'."); - break; - } - catch (InvalidOperationException ioe) { Log($"InvalidOperationException in ReadLine (SendCommandInternal): {ioe.Message}"); _isInitializedAndConnected = false; Close(); return false; } - catch (Exception ex) { Log($"Exception in ReadLine (SendCommandInternal): {ex.Message}"); break; } - } - stopwatch.Stop(); - responseText = sb.ToString().Trim(); - Log($"Final response for '{command}': '{responseText}' (Time: {stopwatch.ElapsedMilliseconds}ms)"); - return true; - } - return true; - } - catch (TimeoutException tex) - { - Log($"General timeout in SendCommandInternal for '{command}': {tex.Message}"); - return false; - } - catch (InvalidOperationException ioe) - { - Log($"General InvalidOperationException in SendCommandInternal (possibly port closed): {ioe.Message}"); - _isInitializedAndConnected = false; Close(); - return false; - } - catch (Exception ex) - { - Log($"General exception in SendCommandInternal for '{command}': {ex.Message}"); - return false; - } - finally - { - _pauseListener = false; - if (expectResponse) - { - _serialPort.ReadTimeout = originalReadTimeout; - } - } - } - } - - private void ListenForButtonEvents(bool debug) - { - Log("Listener thread started. (PACKET PARSING MODE)"); - byte lastMask = 0x00; // <<-- CAMBIO CLAVE: Inicializar como todos los botones liberados - var buttonMap = new Dictionary { - {0, MakcuMouseButton.Left}, {1, MakcuMouseButton.Right}, {2, MakcuMouseButton.Middle}, - {3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5} - }; - - byte[] packetHeader = [0x6B, 0x6D, 0x2E]; - int currentHeaderIndex = 0; - - while (!_stopListenerEvent.IsSet) - { - if (!IsInitializedAndConnected || _pauseListener || _serialPort == null || !_serialPort.IsOpen) - { - Thread.Sleep(20); - currentHeaderIndex = 0; - continue; - } - - try - { - if (_serialPort.BytesToRead > 0) - { - byte byteRead = (byte)_serialPort.ReadByte(); - - if (byteRead == packetHeader[currentHeaderIndex]) - { - currentHeaderIndex++; - if (currentHeaderIndex == packetHeader.Length) - { - if (debug) Log($"Listener: Packet header {string.Join(",", packetHeader.Select(b => b.ToString("X2")))} detected!"); - - if (_serialPort.BytesToRead > 0) - { - byte currentMask = (byte)_serialPort.ReadByte(); - if (debug) Log($"Listener: Potential button mask byte: 0x{currentMask:X2}"); - - if (currentMask <= 0b00011111) - { - if (currentMask != lastMask) - { - if (debug) Log($"Listener: Processing button mask. New: 0x{currentMask:X2}, Prev: 0x{lastMask:X2}"); - byte changedBits = (byte)(currentMask ^ lastMask); - - lock (_buttonStates) - { - foreach (var pair in buttonMap) - { - if ((changedBits & (1 << pair.Key)) != 0) - { - bool isPressed = (currentMask & (1 << pair.Key)) != 0; - _buttonStates[pair.Value] = isPressed; - if (debug) Log($"Listener: ---> EVENT: Button: {pair.Value}, IsPressed: {isPressed}"); - try - { - ButtonStateChanged?.Invoke(pair.Value, isPressed); - } - catch (Exception ex) - { - Log($"Exception in ButtonStateChanged handler: {ex.Message}"); - } - } - } - } - lastMask = currentMask; - if (debug) - { - var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray(); - Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Length != 0 ? string.Join(", ", pressedButtons) : "None")}"); - } - } - } - - int expectedTailBytes = 2; - for (int i = 0; i < expectedTailBytes; i++) - { - if (_serialPort.BytesToRead > 0) - { - byte consumedByte = (byte)_serialPort.ReadByte(); - if (debug) Log($"Listener: Consumed tail byte {i + 1}: 0x{consumedByte:X2}"); - } - else - { - if (debug) Log($"Listener: Expected tail byte {i + 1} but no data. Packet might be short."); - break; - } - } - } - else - { - if (debug) Log("Listener: Header found, but no data for button mask byte. Packet might be short."); - } - currentHeaderIndex = 0; - } - } - else - { - if (currentHeaderIndex > 0 && debug) - { - Log($"Listener: Byte 0x{byteRead:X2} broke header sequence at index {currentHeaderIndex}. Resetting search."); - } - currentHeaderIndex = 0; - if (byteRead == packetHeader[0]) - { - currentHeaderIndex = 1; - } - } - } - else - { - Thread.Sleep(1); - } - } - catch (TimeoutException) - { - if (debug) Log("Listener: TimeoutException during serial read."); - currentHeaderIndex = 0; - } - catch (InvalidOperationException ex) - { - Log($"Listener: InvalidOperationException (port probably closed): {ex.Message}. Stopping listener."); - _isInitializedAndConnected = false; - currentHeaderIndex = 0; - break; - } - catch (Exception ex) - { - Log($"Error in listener: {ex.GetType().Name} - {ex.Message}"); - currentHeaderIndex = 0; - Thread.Sleep(100); - } - } - Log("Listener thread terminated."); - } - - public bool Press(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(1)", false, out _); - public bool Release(MakcuMouseButton button) => SendCommandInternal($"km.{GetButtonString(button)}(0)", false, out _); - public bool Move(int x, int y) => SendCommandInternal($"km.move({x},{y})", false, out _); - public bool MoveSmooth(int x, int y, int segments) => SendCommandInternal($"km.move({x},{y},{segments})", false, out _); - public bool MoveBezier(int x, int y, int segments, int ctrlX, int ctrlY) => SendCommandInternal($"km.move({x},{y},{segments},{ctrlX},{ctrlY})", false, out _); - public bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _); - - public string? GetKmVersion() - { - return SendCommandInternal("km.version()", true, out string? response, 500) ? response : null; - } - private static string GetButtonString(MakcuMouseButton button) - { - switch (button) - { - case MakcuMouseButton.Left: return "left"; - case MakcuMouseButton.Right: return "right"; - case MakcuMouseButton.Middle: return "middle"; - default: throw new ArgumentException($"Button {button} not supported for direct press/release actions (left/right/middle)."); - } - } - private string GetButtonLockString(MakcuMouseButton button) - { - switch (button) - { - case MakcuMouseButton.Left: return "ml"; - case MakcuMouseButton.Right: return "mr"; - case MakcuMouseButton.Middle: return "mm"; - case MakcuMouseButton.Mouse4: return "ms1"; - case MakcuMouseButton.Mouse5: return "ms2"; - default: throw new ArgumentException($"Button not supported for lock/catch: {button}"); - } - } - public Dictionary GetCurrentButtonStates() - { lock (_buttonStates) { return new Dictionary(_buttonStates); } } - - public int GetCurrentButtonMask() - { - int mask = 0; - lock (_buttonStates) - { - if (_buttonStates.TryGetValue(MakcuMouseButton.Left, out bool l) && l) mask |= (1 << (int)MakcuMouseButton.Left); - if (_buttonStates.TryGetValue(MakcuMouseButton.Right, out bool r) && r) mask |= (1 << (int)MakcuMouseButton.Right); - if (_buttonStates.TryGetValue(MakcuMouseButton.Middle, out bool m) && m) mask |= (1 << (int)MakcuMouseButton.Middle); - if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse4, out bool m4) && m4) mask |= (1 << (int)MakcuMouseButton.Mouse4); - if (_buttonStates.TryGetValue(MakcuMouseButton.Mouse5, out bool m5) && m5) mask |= (1 << (int)MakcuMouseButton.Mouse5); - } - return mask; - } - - private bool _disposedValue; - protected virtual void Dispose(bool disposing) - { - if (!_disposedValue) - { - if (disposing) - { - Close(); - _stopListenerEvent?.Dispose(); - } - _disposedValue = true; - } - } - public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } - ~MakcuMouse() { Dispose(false); } - - public void Close() - { - Log("Closing MakcuMouse connection..."); - _isInitializedAndConnected = false; - - if (_listenerThread != null) - { - _stopListenerEvent.Set(); - if (_listenerThread.IsAlive) - { - if (!_listenerThread.Join(TimeSpan.FromSeconds(1))) - { - Log("Listener thread did not terminate in time."); - } - } - _listenerThread = null; - } - lock (_serialLock) - { - if (_serialPort != null) - { - if (_serialPort.IsOpen) - { - try { _serialPort.Close(); } - catch (Exception ex) { Log($"Error closing port: {ex.Message}"); } - } - _serialPort.Dispose(); - _serialPort = null; - } - } - PortName = null; - Log("MakcuMouse connection closed."); - } - } -} diff --git a/Spectrum/Input/InputManager.cs b/Spectrum/Input/InputManager.cs index 88695c8..3840a86 100644 --- a/Spectrum/Input/InputManager.cs +++ b/Spectrum/Input/InputManager.cs @@ -1,5 +1,6 @@ using Spectrum.Input.InputLibraries.Arduino; -using Spectrum.Input.InputLibraries.Makcu; +using Spectrum.Input.InputLibraries.HID; +using Spectrum.Utilities; using System.Diagnostics; using System.Runtime.InteropServices; using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain; @@ -10,12 +11,14 @@ namespace Spectrum.Input { [DllImport("user32.dll")] public static extern bool GetCursorPos(out Point lpPoint); - private static ConfigManager mainConfig = Program.mainConfig; - private static Point lastDetection = new Point(); - private static Rectangle lastDetectionBox = new Rectangle(); + private static readonly ConfigManager mainConfig = Program.mainConfig; + private static Point lastDetection = new(); + private static Point _prevEnd = new(); + private static Rectangle lastDetectionBox = new(); private static long _lastMoveTicks = 0; private static readonly double _dtRef = 1.0 / 120.0; private static bool isSpraying = false; + private static readonly HIDMain? hid = Program.HIDMain; private static double GetDeltaSeconds() { @@ -40,7 +43,7 @@ namespace Spectrum.Input if (baseFactor >= 1) { double k = deltaSeconds / _dtRef; - return baseFactor * k; + return Math.Pow(baseFactor, 3) * k; } double kLow = deltaSeconds / _dtRef; return 1 - Math.Pow(1 - baseFactor, kLow); @@ -56,19 +59,27 @@ namespace Spectrum.Input } else { - reference.X = Win32.GetPrimaryScreenSize().Width / 2; - reference.Y = Win32.GetPrimaryScreenSize().Height / 2; + var bounds = Program.MonitorBounds; + reference.X = bounds.X + bounds.Width / 2; + reference.Y = bounds.Y + bounds.Height / 2; } - Point start = new Point(reference.X, reference.Y); - Point end = new Point(lastDetection.X, lastDetection.Y); + Point start = new(reference.X, reference.Y); + Point end = new(lastDetection.X, lastDetection.Y); double dt = GetDeltaSeconds(); + + double tDist = Math.Sqrt(Math.Pow(end.X - _prevEnd.X, 2) + Math.Pow(end.Y - _prevEnd.Y, 2)); + if (tDist > 150 || dt > 0.1) MovementPaths.ResetWindMouse(); + _prevEnd = end; + double effSensitivity = TimeScaleFactor(config.Sensitivity, dt); bool insideBoundingBox = lastDetectionBox.Contains(start); + var tPath = Stopwatch.GetTimestamp(); Point newPosition = CalculateMovement(start, end, effSensitivity, config.AimMovementType, insideBoundingBox); + Program.Timings.Add("Movement Path", Stopwatch.GetTimestamp() - tPath); if (config.EmaSmoothening) { @@ -80,6 +91,15 @@ namespace Spectrum.Input int deltaX = newPosition.X - reference.X; int deltaY = newPosition.Y - reference.Y; + double maxMove = config.ClosestToMouse ? 75.0 : 120.0; + double moveDist = Math.Sqrt(deltaX * deltaX + deltaY * deltaY); + if (moveDist > maxMove) + { + double r = maxMove / moveDist; + deltaX = (int)Math.Round(deltaX * r); + deltaY = (int)Math.Round(deltaY * r); + } + if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return; if (deltaX > config.ImageWidth || deltaX < -config.ImageWidth || deltaY > config.ImageHeight || deltaY < -config.ImageHeight) return; @@ -89,15 +109,15 @@ namespace Spectrum.Input case MovementMethod.MouseEvent: MouseEvent.Move(deltaX, deltaY); break; - case MovementMethod.Makcu: - if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null) - MakcuMain.MakcuInstance.Move(deltaX, deltaY); - else - MouseEvent.Move(deltaX, deltaY); - break; case MovementMethod.Arduino: ArduinoMain.Move(deltaX, deltaY); break; + case MovementMethod.HID: + if (hid != null && hid.IsConnected) + hid.Move(deltaX, deltaY); + else + LogManager.Log($"Hid is null: {hid == null} | hid is connected: {hid?.IsConnected}"); + break; default: MouseEvent.Move(deltaX, deltaY); break; @@ -112,17 +132,25 @@ namespace Spectrum.Input MovementType.Linear => MovementPaths.LinearInterpolation(start, end, sensitivity), MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, sensitivity), MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, sensitivity), - MovementType.WindMouse => MovementPaths.WindMouse(start, end, - mainConfig.Data.WindMouseGravity, - mainConfig.Data.WindMouseWind, - mainConfig.Data.WindMouseMaxStep, - sensitivity, - mainConfig.Data.WindMouseOvershoot, - insideBoundingBox), + MovementType.WindMouse => TrackWindMouse(start, end, sensitivity, insideBoundingBox), _ => MovementPaths.LinearInterpolation(start, end, sensitivity), }; } + private static Point TrackWindMouse(Point start, Point end, double sensitivity, bool insideBoundingBox) + { + var t0 = Stopwatch.GetTimestamp(); + var result = MovementPaths.WindMouse(start, end, + mainConfig.Data.WindMouseGravity, + mainConfig.Data.WindMouseWind, + mainConfig.Data.WindMouseMaxStep, + sensitivity, + mainConfig.Data.WindMouseOvershoot, + insideBoundingBox); + Program.Timings.Add("WindMouse", Stopwatch.GetTimestamp() - t0); + return result; + } + public static async Task ClickMouse() { var config = mainConfig.Data; @@ -138,8 +166,9 @@ namespace Spectrum.Input } else { - currentPosition.X = Win32.GetPrimaryScreenSize().Width / 2; - currentPosition.Y = Win32.GetPrimaryScreenSize().Height / 2; + var bounds = Program.MonitorBounds; + currentPosition.X = bounds.X + bounds.Width / 2; + currentPosition.Y = bounds.Y + bounds.Height / 2; } if (config.TriggerDelay > 0 && !config.TriggerRandomDelay) @@ -192,15 +221,13 @@ namespace Spectrum.Input case MovementMethod.MouseEvent: MouseEvent.ClickDown(); break; - case MovementMethod.Makcu: - if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null) - MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left); - else - MouseEvent.ClickDown(); - break; case MovementMethod.Arduino: ArduinoMain.ClickDown(); break; + case MovementMethod.HID: + if (hid != null && hid.IsConnected) + hid.Press(HIDMain.BUTTON_LEFT); + break; default: MouseEvent.ClickDown(); break; @@ -213,15 +240,13 @@ namespace Spectrum.Input case MovementMethod.MouseEvent: MouseEvent.ClickUp(); break; - case MovementMethod.Makcu: - if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null) - MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left); - else - MouseEvent.ClickUp(); - break; case MovementMethod.Arduino: ArduinoMain.ClickUp(); break; + case MovementMethod.HID: + if (hid != null && hid.IsConnected) + hid.Release(HIDMain.BUTTON_LEFT); + break; default: MouseEvent.ClickUp(); break; @@ -244,32 +269,6 @@ namespace Spectrum.Input { var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - Action? makcuHandler = null; - bool subscribedToMakcu = false; - - void UnsubscribeMakcu() - { - if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null) - { - try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { } - } - } - - if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady() && MakcuMain.MakcuInstance != null) - { - makcuHandler = (btn, isPressed) => - { - if (!isPressed) return; - var key = makcuToKeysMap.GetValueOrDefault(btn); - if (key != Keys.None) - { - tcs.TrySetResult(key); - } - }; - MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler; - subscribedToMakcu = true; - } - CancellationTokenRegistration ctr = default; if (cancellationToken?.CanBeCanceled == true) { @@ -279,7 +278,6 @@ namespace Spectrum.Input _ = tcs.Task.ContinueWith(_ => { try { ctr.Dispose(); } catch { } - UnsubscribeMakcu(); }, TaskScheduler.Default); Task.Run(() => @@ -321,59 +319,18 @@ namespace Spectrum.Input } finally { - UnsubscribeMakcu(); } }); return tcs.Task; } - private static bool EnsureMakcuReady() - { - try - { - if (MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true; - var ok = MakcuMain.Load().GetAwaiter().GetResult(); - if (ok && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) return true; - - LogManager.Log("Makcu not ready. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - MakcuMain.Unload(); - mainConfig.Data.MovementMethod = MovementMethod.MouseEvent; - return false; - } - catch - { - LogManager.Log("Makcu initialization threw an exception. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - MakcuMain.Unload(); - mainConfig.Data.MovementMethod = MovementMethod.MouseEvent; - return false; - } - } - private static Dictionary makcuToKeysMap = new() - { - { MakcuMouseButton.Left, Keys.LButton }, - { MakcuMouseButton.Right, Keys.RButton }, - { MakcuMouseButton.Middle, Keys.MButton }, - { MakcuMouseButton.Mouse4, Keys.XButton1 }, - { MakcuMouseButton.Mouse5, Keys.XButton2 } - }; - public static bool IsKeyOrMouseDown(Keys key) { - if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) - { - var makcuBtn = makcuToKeysMap.FirstOrDefault(x => x.Value == key).Key; - try - { - var states = MakcuMain.MakcuInstance.GetCurrentButtonStates(); - return states.TryGetValue(makcuBtn, out var pressed) && pressed; - } - catch { } - } - return (GetAsyncKeyState((int)key) & 0x8000) != 0; ; + return (GetAsyncKeyState((int)key) & 0x8000) != 0; } - private static readonly Dictionary _keybindToggleStates = new(); + private static readonly Dictionary _keybindToggleStates = []; public static bool IsKeyOrMouseDown(Keybind keybind) { diff --git a/Spectrum/Input/MovementPaths.cs b/Spectrum/Input/MovementPaths.cs index f6a6c0d..22afe2f 100644 --- a/Spectrum/Input/MovementPaths.cs +++ b/Spectrum/Input/MovementPaths.cs @@ -144,7 +144,7 @@ } private static bool _isOvershooting = false; - private static Point _overshootTarget = new Point(0, 0); + private static Point _overshootTarget = new(0, 0); public static Point WindMouse(Point start, Point end, double gravity = 9.0, double wind = 3.0, double maxStep = 10.0, double sensitivity = 1.0, bool enableOvershoot = false, bool insideBoundingBox = false) diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index d729d5b..74c32d5 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -1,26 +1,49 @@ using OpenCvSharp; using Spectrum.Detection; +using Spectrum.Input.InputLibraries.HID; +using Spectrum.Utilities; +using System.CommandLine; namespace Spectrum { class Program { static Renderer? renderer = null; - public static ConfigManager mainConfig = new ConfigManager("bin\\configs\\config.json"); - public static ConfigManager colorConfig = new ConfigManager("bin\\configs\\colors.json"); + public static ConfigManager mainConfig = new("bin\\configs\\default.json", "bin\\configs"); + public static ColorConfigManager colorConfig = new("bin\\configs\\colors"); + public static HIDMain HIDMain = new(); private static DetectionManager? detectionManager; - public static (int fps, double avgProcessTime) statistics = (0, 0); public static CaptureManager SharedCaptureManager { get; } = new CaptureManager(); + public static TimingStats Timings { get; } = new TimingStats(); + public static int MonitorIndex { get; private set; } = 1; + public static Rectangle MonitorBounds { get; private set; } = Screen.PrimaryScreen?.Bounds ?? Screen.AllScreens[0].Bounds; - - static void Main() + static int Main(string[] args) { - Thread renderThread = new Thread(() => + var monitorOption = new Option(["--monitor", "-m"], () => 1); + var debugOption = new Option(["--debug", "-d"], () => false); + var rootCommand = new RootCommand(); + rootCommand.AddOption(monitorOption); + rootCommand.AddOption(debugOption); + rootCommand.SetHandler((monitor, debug) => Run(monitor, debug), monitorOption, debugOption); + return rootCommand.Invoke(args); + } + + private static void Run(int monitor, bool debug) + { + LogManager.SetDebugOverride(debug); + if (debug && !System.Diagnostics.Debugger.IsAttached) + Win32.EnsureConsoleAttached(); + ConfigureMonitor(monitor); + LogManager.Log($"Monitor arg: {monitor}", LogManager.LogLevel.Debug); + LogManager.Log($"Monitor index: {MonitorIndex}", LogManager.LogLevel.Debug); + LogManager.Log($"Monitor bounds: {MonitorBounds.X},{MonitorBounds.Y} {MonitorBounds.Width}x{MonitorBounds.Height}", LogManager.LogLevel.Debug); + Thread renderThread = new(() => { try { renderer = new Renderer(SharedCaptureManager); - bool dxok = SharedCaptureManager.TryInitializeDirectX(); + bool dxok = SharedCaptureManager.TryInitializeDirectX(0, MonitorIndex - 1); if (!dxok) { LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning); @@ -35,7 +58,7 @@ namespace Spectrum }); renderThread.Start(); - string[] dirs = ["bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs"]; + string[] dirs = ["bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs", "bin/configs/colors"]; foreach (var dir in dirs) { if (!Directory.Exists(dir)) @@ -50,12 +73,10 @@ namespace Spectrum AutoLabeling.StartLabeling(); } - if (colorConfig.Data.Colors.Count == 0) + if (colorConfig.Colors.Count == 0) { - colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(179, 255, 255), new Scalar(150, 255, 255))); - colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255))); - colorConfig.SaveConfig(); - colorConfig.LoadConfig(); + colorConfig.SaveColor(new ColorInfo("Arsenal [Magenta]", new Scalar(179, 255, 255), new Scalar(150, 255, 255))); + colorConfig.SaveColor(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255))); mainConfig.LoadConfig(); } @@ -69,5 +90,59 @@ namespace Spectrum detectionManager = new DetectionManager(renderer); } + + private static void ConfigureMonitor(int monitor) + { + var screens = Screen.AllScreens; + if (screens.Length == 0) + return; + + var index = monitor < 1 ? 1 : monitor; + LogManager.Log($"Detected monitors: {screens.Length}", LogManager.LogLevel.Debug); + for (int i = 0; i < screens.Length; i++) + LogManager.Log($"Monitor {i + 1}: {screens[i].DeviceName} {screens[i].Bounds.X},{screens[i].Bounds.Y} {screens[i].Bounds.Width}x{screens[i].Bounds.Height}", LogManager.LogLevel.Debug); + + var selected = GetScreenByDeviceNumber(screens, index); + if (selected == null) + { + if (index > screens.Length) + index = 1; + selected = screens[index - 1]; + } + + MonitorIndex = index; + MonitorBounds = selected.Bounds; + } + + private static Screen? GetScreenByDeviceNumber(Screen[] screens, int index) + { + foreach (var screen in screens) + { + var number = TryGetDisplayNumber(screen.DeviceName); + if (number.HasValue && number.Value == index) + return screen; + } + + return null; + } + + private static int? TryGetDisplayNumber(string deviceName) + { + if (string.IsNullOrWhiteSpace(deviceName)) + return null; + + int i = deviceName.Length - 1; + while (i >= 0 && char.IsDigit(deviceName[i])) + i--; + + if (i == deviceName.Length - 1) + return null; + + var numberText = deviceName[(i + 1)..]; + if (int.TryParse(numberText, out var value)) + return value; + + return null; + } } } \ No newline at end of file diff --git a/Spectrum/Renderer/Renderer.HSVRangeWindow.cs b/Spectrum/Renderer/Renderer.HSVRangeWindow.cs index 5517649..1984687 100644 --- a/Spectrum/Renderer/Renderer.HSVRangeWindow.cs +++ b/Spectrum/Renderer/Renderer.HSVRangeWindow.cs @@ -2,6 +2,7 @@ using OpenCvSharp; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; +using Spectrum.Utilities; using System.Numerics; namespace Spectrum @@ -207,18 +208,7 @@ namespace Spectrum { if (!string.IsNullOrWhiteSpace(_colorName)) { - var existingColor = Program.colorConfig.Data.Colors.Find(c => c.Name == _colorName); - if (existingColor != null) - { - existingColor.Lower = _lowerHSV; - existingColor.Upper = _upperHSV; - LogManager.Log($"Updated existing color: {_colorName}", LogManager.LogLevel.Info); - } - else - { - Program.colorConfig.Data.Colors.Add(new ColorInfo(_colorName, _upperHSV, _lowerHSV)); - } - Program.colorConfig.SaveConfig(); + Program.colorConfig.SaveColor(new ColorInfo(_colorName, _upperHSV, _lowerHSV)); _colorName = ""; } else diff --git a/Spectrum/Renderer/Renderer.ImGuiExtensions.cs b/Spectrum/Renderer/Renderer.ImGuiExtensions.cs index a8b52c2..b493844 100644 --- a/Spectrum/Renderer/Renderer.ImGuiExtensions.cs +++ b/Spectrum/Renderer/Renderer.ImGuiExtensions.cs @@ -399,7 +399,7 @@ namespace Spectrum }); } - public static bool BeginPane(string localId, bool showHeader = true) + public static bool BeginPane(string localId, bool showHeader = true, float headerRightWidth = 0f, Action? headerRight = null) { var g = _paneGroups.Peek(); if (g.Index > 0) @@ -438,6 +438,14 @@ namespace Spectrum ImGui.SetCursorPos(new Vector2(padX, style.FramePadding.Y)); ImGui.TextUnformatted(headerText); + if (headerRight != null && headerRightWidth > 0f) + { + float rightX = g.Width - padX - headerRightWidth; + if (rightX < padX) + rightX = padX; + ImGui.SetCursorPos(new Vector2(rightX, style.FramePadding.Y)); + headerRight(); + } } float innerHeight = g.Height - headerHeight; diff --git a/Spectrum/Renderer/Renderer.MovementPreviewWindow.cs b/Spectrum/Renderer/Renderer.MovementPreviewWindow.cs index 57b9a93..bb0de4e 100644 --- a/Spectrum/Renderer/Renderer.MovementPreviewWindow.cs +++ b/Spectrum/Renderer/Renderer.MovementPreviewWindow.cs @@ -102,8 +102,8 @@ namespace Spectrum { var (prevPoint, prevSpeed) = _previewPath[i - 1]; var (currPoint, currSpeed) = _previewPath[i]; - Vector2 p1 = new Vector2(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y); - Vector2 p2 = new Vector2(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y); + Vector2 p1 = new(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y); + Vector2 p2 = new(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y); double avgSpeed = (prevSpeed + currSpeed) / 2.0; float normalizedSpeed = (float)(avgSpeed / maxSpeed); diff --git a/Spectrum/Renderer/Renderer.cs b/Spectrum/Renderer/Renderer.cs index 684c905..45c59ac 100644 --- a/Spectrum/Renderer/Renderer.cs +++ b/Spectrum/Renderer/Renderer.cs @@ -4,7 +4,9 @@ using OpenCvSharp; using Spectrum.Detection; using Spectrum.Input; using Spectrum.Input.InputLibraries.Arduino; -using Spectrum.Input.InputLibraries.Makcu; +using Spectrum.Utilities; +using SixLabors.ImageSharp; +using SixLabors.ImageSharp.PixelFormats; using System.Collections.Concurrent; using System.Diagnostics; using System.Numerics; @@ -13,38 +15,94 @@ namespace Spectrum { partial class Renderer : Overlay { - static (int width, int height) screenSize = Win32.GetPrimaryScreenSize(); - private List> detectionDrawCommands = new List>(); - private List> activeDrawCommands = new List>(); - private readonly object detectionDrawLock = new object(); + static (int width, int height) screenSize = (0, 0); + private List> detectionDrawCommands = []; + private List> activeDrawCommands = []; + private readonly object detectionDrawLock = new(); private readonly CaptureManager _captureManager; private bool _vsync = true; private int _fpsLimit = 240; - private readonly Dictionary _waitingForKeybind = new(); - private readonly Dictionary _pendingKeybind = new(); - private readonly Dictionary _keybindTask = new(); + private readonly Dictionary _waitingForKeybind = []; + private readonly Dictionary _pendingKeybind = []; + private readonly Dictionary _keybindTask = []; private readonly ConcurrentQueue _keybindResults = new(); - private ConfigManager mainConfig = Program.mainConfig; - private ConfigManager colorConfig = Program.colorConfig; + private readonly ConfigManager mainConfig = Program.mainConfig; + private readonly ColorConfigManager colorConfig = Program.colorConfig; private string ColorName = "New Color"; private static bool scrollToBottom = true; private ColorInfo? selectedColor = null; + private int _colorConfigVersion = -1; private string configName = "New Config"; private string? selectedConfigName = null; + private bool _windowPositioned = false; + private Image? _copyIconImage = null; + private IntPtr _copyIconTextureId = IntPtr.Zero; - public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width) + private static Vector2 ToOverlay(Vector2 point) { + var bounds = Program.MonitorBounds; + return new Vector2(point.X - bounds.X, point.Y - bounds.Y); + } + + private static string? ResolveAssetPath(string fileName) + { + string basePath = AppContext.BaseDirectory; + string basePathCandidate = Path.Combine(basePath, fileName); + if (File.Exists(basePathCandidate)) + return basePathCandidate; + string cwdCandidate = Path.Combine(Directory.GetCurrentDirectory(), fileName); + if (File.Exists(cwdCandidate)) + return cwdCandidate; + return null; + } + + private bool TryLoadImageTexture(string key, string fileName, ref Image? image, ref IntPtr textureId) + { + if (textureId != IntPtr.Zero) + return true; + + string? imagePath = ResolveAssetPath(fileName); + if (string.IsNullOrEmpty(imagePath)) + return false; + + image?.Dispose(); + image = SixLabors.ImageSharp.Image.Load(imagePath); + AddOrGetImagePointer(key, image, false, out textureId); + return textureId != IntPtr.Zero; + } + + public Renderer(CaptureManager captureManager) : base("Spectrum", Program.MonitorBounds.Width, Program.MonitorBounds.Height) + { + screenSize = (Program.MonitorBounds.Width, Program.MonitorBounds.Height); _captureManager = captureManager; VSync = _vsync; FPSLimit = _fpsLimit; + ImGui.CreateContext(); + var io = ImGui.GetIO(); io.Fonts.Clear(); io.Fonts.AddFontFromFileTTF("C:\\Windows\\Fonts\\Arial.ttf", 16.0f); + + var bounds = Program.MonitorBounds; + if (window != null) + Win32.SetWindowBounds(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height); + + LogManager.Log($"Renderer monitor bounds: {bounds.X},{bounds.Y} {bounds.Width}x{bounds.Height}", LogManager.LogLevel.Debug); + LogManager.Log($"Renderer screen size: {screenSize.width}x{screenSize.height}", LogManager.LogLevel.Debug); + } override protected void Render() { + if (!_windowPositioned && window != null) + { + var bounds = Program.MonitorBounds; + Win32.SetWindowBounds(window.Handle, bounds.X, bounds.Y, bounds.Width, bounds.Height); + screenSize = (bounds.Width, bounds.Height); + _windowPositioned = true; + LogManager.Log($"Renderer window positioned: {bounds.X},{bounds.Y} {bounds.Width}x{bounds.Height}", LogManager.LogLevel.Debug); + } var config = mainConfig.Data; if (config.DrawDetections || config.DrawFOV || config.DebugMode || config.DrawAimPoint) RenderOverlay(); @@ -399,6 +457,10 @@ namespace Spectrum if (ImGuiExtensions.SliderFill("Threshold", ref Threshold, 1, 255)) config.Threshold = Threshold; + int minAreaPx = config.MinAreaPx; + if (ImGuiExtensions.SliderFill("Min Area (px)", ref minAreaPx, 1, 10000)) + config.MinAreaPx = minAreaPx; + if (ImGui.Button("Open HSV Range Selector")) _showHSVRangeWindow = true; @@ -407,13 +469,31 @@ namespace Spectrum if (ImGuiExtensions.BeginPane("Color Configs")) { - List colors = colorConfig.Data.Colors; + if (colorConfig.Version != _colorConfigVersion) + { + _colorConfigVersion = colorConfig.Version; + if (!string.IsNullOrWhiteSpace(config.SelectedColor)) + { + var updatedColor = colorConfig.GetColor(config.SelectedColor); + if (updatedColor != null) + { + selectedColor = updatedColor; + ColorName = updatedColor.Name; + config.UpperHSV = updatedColor.Upper; + config.LowerHSV = updatedColor.Lower; + } + } + } + + List colors = [.. colorConfig.Colors]; + if (selectedColor != null) + selectedColor = colors.Find(c => c.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase)); ImGui.PushStyleColor(ImGuiCol.ChildBg, new Vector4(0.110f, 0.110f, 0.125f, 1.000f)); ImGui.BeginChild("##DColorConfigsChild", new Vector2(0, ImGui.GetContentRegionAvail().Y / 2), ImGuiChildFlags.None); ImGui.Dummy(new Vector2(0, 4)); foreach (var color in colors) { - if (ImGui.Selectable(" " + color.Name, selectedColor == color)) + if (ImGui.Selectable(" " + color.Name, selectedColor != null && color.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase))) { selectedColor = color; ColorName = color.Name; @@ -426,7 +506,7 @@ namespace Spectrum ImGui.SetNextItemWidth(-1); ImGui.InputTextWithHint("##ColorName", "Color Name", ref ColorName, 100); - Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22); + Vector2 size = new((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22); if (ImGui.Button("Load Color", size)) { if (selectedColor != null) @@ -441,16 +521,11 @@ namespace Spectrum ImGui.SameLine(); if (ImGui.Button("Save Color", size)) { - if (colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)) is ColorInfo existingColor) + if (!string.IsNullOrWhiteSpace(ColorName)) { - existingColor.Upper = config.UpperHSV; - existingColor.Lower = config.LowerHSV; - } - else - { - colors.Add(new ColorInfo(ColorName, config.UpperHSV, config.LowerHSV)); - colorConfig.SaveConfig(); - selectedColor = colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)); + var colorToSave = new ColorInfo(ColorName, config.UpperHSV, config.LowerHSV); + if (colorConfig.SaveColor(colorToSave)) + selectedColor = colorConfig.GetColor(ColorName); } } ImGui.SameLine(); @@ -458,24 +533,24 @@ namespace Spectrum { if (selectedColor != null) { - int currentIndex = colors.IndexOf(selectedColor); - colors.RemoveAll(c => c.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase)); - colorConfig.SaveConfig(); - if (colors.Count > 0) + var deletedName = selectedColor.Name; + int currentIndex = colors.FindIndex(c => c.Name.Equals(deletedName, StringComparison.OrdinalIgnoreCase)); + if (colorConfig.DeleteColor(deletedName)) { - if (selectedColor.Name == config.SelectedColor) + colors = [.. colorConfig.Colors]; + if (colors.Count > 0) { - int nextIndex = Math.Max(0, currentIndex - 1); - selectedColor = colors[currentIndex - 1]; + int nextIndex = Math.Clamp(currentIndex - 1, 0, colors.Count - 1); + selectedColor = colors[nextIndex]; config.SelectedColor = selectedColor.Name; config.UpperHSV = selectedColor.Upper; config.LowerHSV = selectedColor.Lower; ColorName = selectedColor.Name; } - } - else - { - selectedColor = null; + else + { + selectedColor = null; + } } } } @@ -513,7 +588,7 @@ namespace Spectrum ImGui.SetNextItemWidth(-1); ImGui.InputTextWithHint("##ConfigName", "Config Name", ref configName, 100); - Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22); + Vector2 size = new((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22); if (ImGui.Button("Load Config", size)) { @@ -560,7 +635,7 @@ namespace Spectrum ImGui.InputText("##CurrentConfig", ref currentConfig, 256, ImGuiInputTextFlags.ReadOnly); ImGui.PopStyleColor(); - Vector2 fullSize = new Vector2(ImGui.GetContentRegionAvail().X, 22); + Vector2 fullSize = new(ImGui.GetContentRegionAvail().X, 22); if (ImGui.Button("Save Current to Default", fullSize)) mainConfig.SaveConfig(); @@ -571,7 +646,7 @@ namespace Spectrum if (ImGui.Button("Open Configs Folder", fullSize)) { - string configDir = Path.Combine(Directory.GetCurrentDirectory(), "configs"); + string configDir = Path.Combine(Directory.GetCurrentDirectory(), "bin", "configs"); if (Directory.Exists(configDir)) { Process.Start(new ProcessStartInfo @@ -602,31 +677,21 @@ namespace Spectrum ImGui.TextUnformatted("Movement Method"); ImGui.SetNextItemWidth(-1); MovementMethod movementMethod = config.MovementMethod; - if (ImGui.BeginCombo("##Movement Method", FormatText(movementMethod.ToString()))) + if (ImGui.BeginCombo("##Movement Method", movementMethod != MovementMethod.HID + ? FormatText(movementMethod.ToString()) : movementMethod.ToString())) { foreach (MovementMethod method in Enum.GetValues(typeof(MovementMethod))) { - bool isSelected = (method == movementMethod); - if (ImGui.Selectable(FormatText(method.ToString()), isSelected)) + bool isSelected = method == movementMethod; + if (ImGui.Selectable(method != MovementMethod.HID ? FormatText(method.ToString()) : method.ToString(), isSelected)) { config.MovementMethod = method; switch (method) { - case MovementMethod.Makcu: - { - ArduinoMain.Close(); - var ok = MakcuMain.Load().GetAwaiter().GetResult(); - if (!ok) - { - LogManager.Log("Makcu failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); - config.MovementMethod = MovementMethod.MouseEvent; - MakcuMain.Unload(); - } - break; - } case MovementMethod.Arduino: { - MakcuMain.Unload(); + if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) + Program.HIDMain.Close(); var ok = ArduinoMain.Load(); if (!ok) { @@ -636,9 +701,24 @@ namespace Spectrum } break; } + case MovementMethod.HID: + { + try + { + if (Program.HIDMain?.IsConnected == false) + Program.HIDMain.Init(); + } + catch (Exception ex) + { + LogManager.Log($"HID failed to initialize: {ex.Message}. Falling back to MouseEvent.", LogManager.LogLevel.Warning); + config.MovementMethod = MovementMethod.MouseEvent; + } + break; + } default: ArduinoMain.Close(); - MakcuMain.Unload(); + if (Program.HIDMain != null && Program.HIDMain.IsConnected == true) + Program.HIDMain.Close(); break; } } @@ -704,9 +784,9 @@ namespace Spectrum if (ImGui.Checkbox("Anti-Capture", ref AntiCapture)) { config.AntiCapture = AntiCapture; - if (AntiCapture) + if (AntiCapture && window != null) Win32.EnableAntiCapture(window.Handle); - else + else if (window != null) Win32.DisableAntiCapture(window.Handle); } @@ -722,6 +802,17 @@ namespace Spectrum config.BackgroundImageInterval = BackgroundImageInterval; } + ImGui.TextUnformatted("Labeled Image Interval"); + ImGui.SetNextItemWidth(-1); + int LabeledImageInterval = config.LabeledImageInterval; + if (ImGui.InputInt("##Labeled Image Interval", ref LabeledImageInterval, 1, 1000)) + { + if (LabeledImageInterval < 1) + LabeledImageInterval = 1; + else if (LabeledImageInterval > 1000) + LabeledImageInterval = 1000; + config.LabeledImageInterval = LabeledImageInterval; + } if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false)) { @@ -752,7 +843,34 @@ namespace Spectrum ImGuiExtensions.EndPane(); } - if (ImGuiExtensions.BeginPane("Logs")) + var _LogEntries = LogManager.LogEntries; + _LogEntries = [.. _LogEntries]; + + if (ImGuiExtensions.BeginPane("Logs", true, 16f, () => + { + bool copyClicked = false; + if (TryLoadImageTexture("copy_icon", "assets/copy.png", ref _copyIconImage, ref _copyIconTextureId)) + { + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + copyClicked = ImGui.ImageButton("##CopyLogs", _copyIconTextureId, new Vector2(16, 16)); + ImGui.PopStyleVar(); + if (ImGui.IsItemHovered()) + ImGui.SetTooltip("Copy Logs"); + } + else + { + copyClicked = ImGui.Button("Copy"); + } + if (copyClicked) + { + var logText = new System.Text.StringBuilder(); + foreach (var log in _LogEntries) + { + logText.AppendLine(log.ToString()); + } + ImGui.SetClipboardText(logText.ToString()); + } + })) { ImGui.BeginChild("Logs", new Vector2(0, -34), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar); @@ -760,8 +878,6 @@ namespace Spectrum float scrollMaxY = ImGui.GetScrollMaxY(); bool isAtBottom = (scrollY >= scrollMaxY - 1.0f); - var _LogEntries = LogManager.LogEntries; - _LogEntries = [.. _LogEntries]; foreach (var log in _LogEntries) { ImGui.Text(log.ToString()); @@ -824,8 +940,9 @@ namespace Spectrum else { InputManager.GetCursorPos(out System.Drawing.Point mousePos); - topLeft = new(mousePos.X - (config.ImageWidth / 2), mousePos.Y - (config.ImageHeight / 2)); - bottomRight = new(mousePos.X + (config.ImageWidth / 2), mousePos.Y + (config.ImageHeight / 2)); + var local = ToOverlay(new Vector2(mousePos.X, mousePos.Y)); + topLeft = new(local.X - (config.ImageWidth / 2), local.Y - (config.ImageHeight / 2)); + bottomRight = new(local.X + (config.ImageWidth / 2), local.Y + (config.ImageHeight / 2)); } @@ -841,7 +958,7 @@ namespace Spectrum else { _ = InputManager.GetCursorPos(out System.Drawing.Point mousePos); - center = new(mousePos.X, mousePos.Y); + center = ToOverlay(new Vector2(mousePos.X, mousePos.Y)); } drawList.AddCircle(center, config.ImageWidth / 2, ImGui.GetColorU32(config.FOVColor), 100, 1.0f); @@ -850,12 +967,37 @@ namespace Spectrum if (config.DebugMode) { - var stats = Program.statistics; - double avgTime = Math.Round(stats.avgProcessTime, 2); - Vector2 textSize = ImGui.CalcTextSize($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms"); - drawList.AddRectFilled(new Vector2(10, 10), new Vector2(10 + textSize.X + 10, 10 + textSize.Y + 10), ImGui.GetColorU32(new Vector4(0, 0, 0, 0.8f)), 5.0f); + var frameStats = Program.Timings.GetSnapshot(["Frame"]).FirstOrDefault(); + double avgTime = frameStats == null ? 0 : Math.Round(frameStats.AverageTicks / Stopwatch.Frequency * 1000.0, 2); + int fps = frameStats == null || frameStats.AverageTicks <= 0 ? 0 : (int)Math.Round(Stopwatch.Frequency / frameStats.AverageTicks); + var lines = new List + { + $"FPS: {fps} | AVG Process Time: {avgTime}ms" + }; + + var stats = Program.Timings.GetSnapshot(); + stats = [.. stats.OrderByDescending(s => s.AverageTicks)]; + stats = [.. stats.Where(s => s.Name != "Frame")]; + foreach (var stat in stats) + lines.Add($"{stat.Name}: {FormatDuration(stat.AverageTicks)}"); + + float maxWidth = 0; + float totalHeight = 0; + foreach (var line in lines) + { + var size = ImGui.CalcTextSize(line); + if (size.X > maxWidth) + maxWidth = size.X; + totalHeight += size.Y + 4; + } + + drawList.AddRectFilled(new Vector2(10, 10), new Vector2(10 + maxWidth + 10, 10 + totalHeight + 10), ImGui.GetColorU32(new Vector4(0, 0, 0, 0.8f)), 5.0f); ImGui.SetCursorPos(new Vector2(15, 15)); - ImGui.TextUnformatted($"FPS: {stats.fps} | AVG Process Time: {avgTime}ms"); + foreach (var line in lines) + { + ImGui.SetCursorPosX(15); + ImGui.TextUnformatted(line); + } } List> _drawCommands; @@ -953,11 +1095,16 @@ namespace Spectrum colors[(int)ImGuiCol.ScrollbarGrabHovered] = new Vector4(0.43f, 0.43f, 0.45f, 1.0f); colors[(int)ImGuiCol.ScrollbarGrabActive] = new Vector4(0.50f, 0.50f, 0.52f, 1.0f); } - public void AddRect(Rectangle rect, Vector4 color, float thickness = 1.0f) + public void AddRect(System.Drawing.Rectangle rect, Vector4 color, float thickness = 1.0f) { lock (detectionDrawLock) { - detectionDrawCommands.Add(drawList => drawList.AddRect(new Vector2(rect.Left, rect.Top), new Vector2(rect.Right, rect.Bottom), ImGui.GetColorU32(color), 0, 0, thickness)); + var bounds = Program.MonitorBounds; + var left = rect.Left - bounds.X; + var top = rect.Top - bounds.Y; + var right = rect.Right - bounds.X; + var bottom = rect.Bottom - bounds.Y; + detectionDrawCommands.Add(drawList => drawList.AddRect(new Vector2(left, top), new Vector2(right, bottom), ImGui.GetColorU32(color), 0, 0, thickness)); } } @@ -965,7 +1112,9 @@ namespace Spectrum { lock (detectionDrawLock) { - detectionDrawCommands.Add(drawList => drawList.AddLine(p1, p2, ImGui.GetColorU32(color), thickness)); + var p1Local = ToOverlay(p1); + var p2Local = ToOverlay(p2); + detectionDrawCommands.Add(drawList => drawList.AddLine(p1Local, p2Local, ImGui.GetColorU32(color), thickness)); } } @@ -976,7 +1125,8 @@ namespace Spectrum lock (detectionDrawLock) { - detectionDrawCommands.Add(drawList => drawList.AddCircle(center, radius, ImGui.GetColorU32(color), numSegments, thickness)); + var local = ToOverlay(center); + detectionDrawCommands.Add(drawList => drawList.AddCircle(local, radius, ImGui.GetColorU32(color), numSegments, thickness)); } } public void AddCircleFilled(Vector2 center, float radius, Vector4 color, int numSegments = 0) @@ -985,7 +1135,8 @@ namespace Spectrum numSegments = (int)(Math.Max(1, radius / 2.0f)); lock (detectionDrawLock) { - detectionDrawCommands.Add(drawList => drawList.AddCircleFilled(center, radius, ImGui.GetColorU32(color), numSegments)); + var local = ToOverlay(center); + detectionDrawCommands.Add(drawList => drawList.AddCircleFilled(local, radius, ImGui.GetColorU32(color), numSegments)); } } @@ -995,7 +1146,8 @@ namespace Spectrum return; lock (detectionDrawLock) { - detectionDrawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ImGui.GetColorU32(color), text)); + var local = ToOverlay(pos); + detectionDrawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, local, ImGui.GetColorU32(color), text)); } } @@ -1004,7 +1156,7 @@ namespace Spectrum lock (detectionDrawLock) { activeDrawCommands = detectionDrawCommands; - detectionDrawCommands = new List>(); + detectionDrawCommands = []; } } @@ -1027,5 +1179,17 @@ namespace Spectrum { return string.Concat(text.Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString())); } + + private static string FormatDuration(double avgTicks) + { + double ns = avgTicks / Stopwatch.Frequency * 1_000_000_000.0; + if (ns >= 1_000_000_000) + return $"{Math.Round(ns / 1_000_000_000.0, 2)}s"; + if (ns >= 1_000_000) + return $"{Math.Round(ns / 1_000_000.0, 2)}ms"; + if (ns >= 1_000) + return $"{Math.Round(ns / 1_000.0, 2)}µs"; + return $"{Math.Round(ns, 2)}ns"; + } } } \ No newline at end of file diff --git a/Spectrum/Spectrum.csproj b/Spectrum/Spectrum.csproj index 3ae5f2d..0e8f5a3 100644 --- a/Spectrum/Spectrum.csproj +++ b/Spectrum/Spectrum.csproj @@ -19,6 +19,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -28,6 +29,11 @@ + + + + + diff --git a/Spectrum/LogManager.cs b/Spectrum/Utilities/LogManager.cs similarity index 75% rename from Spectrum/LogManager.cs rename to Spectrum/Utilities/LogManager.cs index 7e440b5..5e28647 100644 --- a/Spectrum/LogManager.cs +++ b/Spectrum/Utilities/LogManager.cs @@ -2,13 +2,14 @@ using System.Text; -namespace Spectrum +namespace Spectrum.Utilities { public class LogManager { - private static List _logEntries = new List(); - private static readonly object _logLock = new object(); + private static List _logEntries = []; + private static readonly object _logLock = new(); private static ConfigManager? mainConfig; + private static bool? debugOverride; public enum LogLevel { Debug, @@ -17,23 +18,22 @@ namespace Spectrum Error, Critical } - public class LogEntry + public class LogEntry(LogLevel level, string message) { - 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 DateTime Timestamp { get; set; } = DateTime.Now; + public LogLevel Level { get; set; } = level; + public string Message { get; set; } = message; + public override string ToString() { return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}"; } } public static IReadOnlyList LogEntries => _logEntries.AsReadOnly(); + public static void SetDebugOverride(bool enabled) + { + debugOverride = enabled; + } public static void Log(string message, LogLevel level = LogLevel.Info) { if (string.IsNullOrWhiteSpace(message)) return; @@ -43,6 +43,8 @@ namespace Spectrum } bool debugEnabled = Debugger.IsAttached; + if (debugOverride.HasValue) + debugEnabled = debugOverride.Value; try { debugEnabled = debugEnabled || (mainConfig?.Data?.DebugMode ?? false); @@ -54,12 +56,13 @@ namespace Spectrum { string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}"; Debug.WriteLine(logMessage); + if (debugEnabled && !Debugger.IsAttached) + { + try { Console.WriteLine(logMessage); } catch { } + } lock (_logLock) { - if (_logEntries == null) - { - _logEntries = new List(); - } + _logEntries ??= []; _logEntries.Add(new LogEntry(level, message)); } } diff --git a/Spectrum/Utilities/TimingStats.cs b/Spectrum/Utilities/TimingStats.cs new file mode 100644 index 0000000..e63283e --- /dev/null +++ b/Spectrum/Utilities/TimingStats.cs @@ -0,0 +1,71 @@ +namespace Spectrum.Utilities +{ + public sealed class TimingStats + { + private sealed class TimingEntry + { + public long TotalTicks; + public long Count; + } + + public sealed class TimingSnapshot(string name, long count, double averageTicks) + { + public string Name { get; } = name; + public long Count { get; } = count; + public double AverageTicks { get; } = averageTicks; + } + + private readonly object sync = new(); + private readonly Dictionary entries = []; + + public void Add(string name, long ticks) + { + if (string.IsNullOrWhiteSpace(name)) + return; + + lock (sync) + { + if (!entries.TryGetValue(name, out var entry)) + { + entry = new TimingEntry(); + entries[name] = entry; + } + entry.TotalTicks += ticks; + entry.Count++; + } + } + + public List GetSnapshot(IEnumerable? orderedNames = null) + { + lock (sync) + { + var result = new List(); + if (orderedNames == null) + { + foreach (var kvp in entries) + { + if (kvp.Value.Count == 0) continue; + result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count)); + } + return result; + } + + var used = new HashSet(); + foreach (var orderedName in orderedNames) + { + if (!entries.TryGetValue(orderedName, out var entry) || entry.Count == 0) + continue; + result.Add(new TimingSnapshot(orderedName, entry.Count, entry.TotalTicks / (double)entry.Count)); + used.Add(orderedName); + } + foreach (var kvp in entries) + { + if (used.Contains(kvp.Key) || kvp.Value.Count == 0) + continue; + result.Add(new TimingSnapshot(kvp.Key, kvp.Value.Count, kvp.Value.TotalTicks / (double)kvp.Value.Count)); + } + return result; + } + } + } +} diff --git a/Spectrum/Win32.cs b/Spectrum/Utilities/Win32.cs similarity index 60% rename from Spectrum/Win32.cs rename to Spectrum/Utilities/Win32.cs index b3cbea9..54143ee 100644 --- a/Spectrum/Win32.cs +++ b/Spectrum/Utilities/Win32.cs @@ -1,6 +1,6 @@ using System.Runtime.InteropServices; -namespace Spectrum +namespace Spectrum.Utilities { class Win32 { @@ -35,9 +35,22 @@ namespace Spectrum [DllImport("user32.dll")] private static extern bool SetWindowDisplayAffinity(IntPtr hwnd, uint dwAffinity); + [DllImport("user32.dll")] + private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); + + [DllImport("kernel32.dll")] + private static extern bool AttachConsole(int dwProcessId); + + [DllImport("kernel32.dll")] + private static extern bool AllocConsole(); + private const uint WDA_NONE = 0x00000000; private const uint WDA_MONITOR = 0x00000001; private const uint WDA_EXCLUDEFROMCAPTURE = 0x00000011; + private const uint SWP_NOSIZE = 0x0001; + private const uint SWP_NOZORDER = 0x0004; + private const uint SWP_NOACTIVATE = 0x0010; + private const int ATTACH_PARENT_PROCESS = -1; public static bool EnableAntiCapture(IntPtr windowHandle) { @@ -50,5 +63,21 @@ namespace Spectrum IsWindowHidden = false; return SetWindowDisplayAffinity(windowHandle, WDA_NONE); } + + public static void SetWindowPosition(IntPtr windowHandle, int x, int y) + { + SetWindowPos(windowHandle, IntPtr.Zero, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); + } + + public static void SetWindowBounds(IntPtr windowHandle, int x, int y, int width, int height) + { + SetWindowPos(windowHandle, IntPtr.Zero, x, y, width, height, SWP_NOZORDER | SWP_NOACTIVATE); + } + + public static void EnsureConsoleAttached() + { + if (!AttachConsole(ATTACH_PARENT_PROCESS)) + AllocConsole(); + } } }