From 181e234bb24fa55ea697f9452242447f3c2a757e Mon Sep 17 00:00:00 2001 From: whoswhip Date: Thu, 14 Aug 2025 03:08:59 -0400 Subject: [PATCH] massive overhaul - split code into folders and separate files (Detection & Input) - triggerbot - ui overhaul - panes - filled sliders - improved layout - capture methods (directx and gdi) - input methods (mouse event & makcu) - fix autolabeling there is likely some that i forgot, but there is quite alot --- Spectrum/Config.cs | 26 +- Spectrum/{ => Detection}/AutoLabeling.cs | 22 +- Spectrum/Detection/CaptureManager.cs | 225 ++++ Spectrum/Detection/DetectionManager.cs | 261 ++++ .../Input/InputLibraries/Makcu/MakcuMain.cs | 115 ++ .../Input/InputLibraries/Makcu/MakcuMouse.cs | 598 +++++++++ .../InputLibraries/MouseEvent/MouseMain.cs | 24 + Spectrum/Input/InputManager.cs | 326 +++++ Spectrum/Input/MovementPaths.cs | 96 ++ Spectrum/InputManager.cs | 184 --- Spectrum/LogManager.cs | 8 + Spectrum/Program.cs | 310 +---- Spectrum/Renderer.cs | 1106 ++++++++++++----- Spectrum/Spectrum.csproj | 4 + Spectrum/Spectrum.sln | 6 + 15 files changed, 2524 insertions(+), 787 deletions(-) rename Spectrum/{ => Detection}/AutoLabeling.cs (91%) create mode 100644 Spectrum/Detection/CaptureManager.cs create mode 100644 Spectrum/Detection/DetectionManager.cs create mode 100644 Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs create mode 100644 Spectrum/Input/InputLibraries/Makcu/MakcuMouse.cs create mode 100644 Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs create mode 100644 Spectrum/Input/InputManager.cs create mode 100644 Spectrum/Input/MovementPaths.cs delete mode 100644 Spectrum/InputManager.cs diff --git a/Spectrum/Config.cs b/Spectrum/Config.cs index 693bf96..d382e5b 100644 --- a/Spectrum/Config.cs +++ b/Spectrum/Config.cs @@ -96,12 +96,28 @@ namespace Spectrum QuadraticBezier, Adaptive } + public enum MovementMethod + { + MouseEvent, + Makcu + } + public enum FovType + { + Circle, + Rectangle + } + public enum CaptureMethod + { + GDI, + DirectX + } public class ConfigData { // Image settings public int ImageWidth { get; set; } = 640; public int ImageHeight { get; set; } = 640; + public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX; // Offset settings public double YOffsetPercent { get; set; } = 0.8; @@ -115,15 +131,23 @@ namespace Spectrum public MovementType AimMovementType { get; set; } = MovementType.Adaptive; public bool EmaSmoothening { get; set; } = true; public double EmaSmootheningFactor { get; set; } = 0.1; + + public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent; + + // Triggerbot settings public bool TriggerBot { get; set; } = false; + public Keys TriggerKey { get; set; } = Keys.XButton2; + public int TriggerDelay { get; set; } = 50; // milliseconds + public int TriggerRadius { get; set; } = 15; // pixels + public int TriggerDuration { get; set; } = 100; // milliseconds // Display settings - public bool ShowDetectionWindow { get; set; } = true; public bool DrawDetections { get; set; } = true; public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); public bool ShowMenu { get; set; } = true; public Keys MenuKey { get; set; } = Keys.Insert; public bool DrawFOV { get; set; } = false; + public FovType FOVType { get; set; } = FovType.Rectangle; public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f); // Data collection settings diff --git a/Spectrum/AutoLabeling.cs b/Spectrum/Detection/AutoLabeling.cs similarity index 91% rename from Spectrum/AutoLabeling.cs rename to Spectrum/Detection/AutoLabeling.cs index 91282ef..a98f873 100644 --- a/Spectrum/AutoLabeling.cs +++ b/Spectrum/Detection/AutoLabeling.cs @@ -3,7 +3,7 @@ using System.Collections.Concurrent; using System.Text; using LogLevel = Spectrum.LogManager.LogLevel; -namespace Spectrum +namespace Spectrum.Detection { public static class AutoLabeling { @@ -15,6 +15,7 @@ namespace Spectrum private static readonly ConcurrentQueue labelingQueue = new ConcurrentQueue(); private static readonly ConcurrentQueue backgroundQueue = new ConcurrentQueue(); private static ConfigManager mainConfig = Program.mainConfig; + public static bool Started = false; private static List GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight) { @@ -49,6 +50,9 @@ namespace Spectrum { try { + if (!Directory.Exists(Path.GetDirectoryName(path))) + Directory.CreateDirectory(Path.GetDirectoryName(path)!); + var labelContent = new StringBuilder(); foreach (var box in boundingBoxes) { @@ -56,15 +60,17 @@ namespace Spectrum } File.WriteAllText(path, labelContent.ToString()); } - catch + catch (Exception ex) { - LogManager.Log("[ERROR] Failed to save labels.", LogLevel.Error); + LogManager.Log($"[ERROR] Failed to save labels. Error: {ex.Message}", LogLevel.Error); } } private static void SaveMatAsImage(Mat mat, string path) { try { + if (!Directory.Exists(Path.GetDirectoryName(path))) + Directory.CreateDirectory(Path.GetDirectoryName(path)!); Cv2.ImWrite(path, mat); } catch (Exception ex) @@ -108,6 +114,8 @@ namespace Spectrum public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours) { + + LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug); if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0) return; @@ -125,9 +133,6 @@ namespace Spectrum public static void AddBackgroundImage(Mat mat, bool detected) { - if (!mainConfig.Data.AutoLabel) - return; - detectionAttemps++; if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected) @@ -202,6 +207,8 @@ namespace Spectrum { if (cancellationTokenSource != null) return; + LogManager.Log("Starting auto labeling...", LogLevel.Info); + Started = true; cancellationTokenSource = new CancellationTokenSource(); backgroundTask = Task.Run(() => LabelingLoop(cancellationTokenSource.Token)); } @@ -209,6 +216,9 @@ namespace Spectrum { if (cancellationTokenSource == null) return; + + LogManager.Log("Stopping auto labeling...", LogLevel.Info); + Started = false; cancellationTokenSource.Cancel(); backgroundTask?.Wait(); cancellationTokenSource.Dispose(); diff --git a/Spectrum/Detection/CaptureManager.cs b/Spectrum/Detection/CaptureManager.cs new file mode 100644 index 0000000..3c9fd99 --- /dev/null +++ b/Spectrum/Detection/CaptureManager.cs @@ -0,0 +1,225 @@ +using System.Drawing.Imaging; +using Vortice.Direct3D; +using Vortice.Direct3D11; +using Vortice.DXGI; +using Size = System.Drawing.Size; +using Rectangle = System.Drawing.Rectangle; +using Point = System.Drawing.Point; + +namespace Spectrum.Detection +{ + public class CaptureManager : IDisposable + { + private readonly object _sync = new(); + private ID3D11Device? _device; + private ID3D11DeviceContext? _context; + private IDXGIOutputDuplication? _duplication; + private ID3D11Texture2D? _stagingTex; + private Size _desktopSize; + public bool IsDirectXAvailable { get; private set; } + public bool IsInitialized => _device != null && _duplication != null && _stagingTex != null; + + public bool TryInitialize(int adapterIndex = 0, int outputIndex = 0) + { + lock (_sync) + { + try + { + DisposeDxgiResources(); + + using var factory = DXGI.CreateDXGIFactory1(); + if (factory.EnumAdapters1(adapterIndex, out var adapter).Failure) + return false; + if (adapter.EnumOutputs(outputIndex, out var output).Failure) + { + adapter.Dispose(); + return false; + } + + var hr = D3D11.D3D11CreateDevice( + adapter, + DriverType.Unknown, + DeviceCreationFlags.BgraSupport, + new[] + { + FeatureLevel.Level_12_1, + FeatureLevel.Level_12_0, + FeatureLevel.Level_11_1, + FeatureLevel.Level_11_0 + }, + out _device); + + if (hr.Failure || _device == null) + { + output.Dispose(); + adapter.Dispose(); + return false; + } + + _context = _device.ImmediateContext; + + _duplication = output.QueryInterface().DuplicateOutput(_device); + var desc = output.Description; + _desktopSize = new Size(desc.DesktopCoordinates.Right - desc.DesktopCoordinates.Left, + desc.DesktopCoordinates.Bottom - desc.DesktopCoordinates.Top); + + output.Dispose(); + adapter.Dispose(); + + EnsureStagingTexture(_desktopSize); + + IsDirectXAvailable = true; + return true; + } + catch + { + IsDirectXAvailable = false; + DisposeDxgiResources(); + return false; + } + } + } + + public Bitmap? CaptureScreenshotDirectX(Rectangle bounds) + { + lock (_sync) + { + if (!IsInitialized) + { + if (!TryInitialize()) + return null; + } + + bounds = Rectangle.Intersect(new Rectangle(Point.Empty, _desktopSize), bounds); + if (bounds.Width <= 0 || bounds.Height <= 0) return null; + + EnsureStagingTexture(_desktopSize); + + IDXGIResource? desktopResource = null; + bool frameAcquired = false; + try + { + var result = _duplication!.AcquireNextFrame(16, out var frameInfo, out desktopResource); + if (result.Failure) + { + if (result.Code == unchecked((int)Vortice.DXGI.ResultCode.AccessLost) || + result.Code == unchecked((int)Vortice.DXGI.ResultCode.DeviceRemoved)) + { + TryInitialize(); + } + return null; + } + frameAcquired = true; + + using var fullTex = desktopResource.QueryInterface(); + + _context!.CopySubresourceRegion( + _stagingTex!, + 0, + bounds.X, + bounds.Y, + 0, + fullTex, + 0, + new Vortice.Mathematics.Box(bounds.X, bounds.Y, 0, bounds.Right, bounds.Bottom, 1) + ); + + var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); + var map = _context.Map(_stagingTex!, 0, MapMode.Read, Vortice.Direct3D11.MapFlags.None); + var bmpData = bmp.LockBits(new Rectangle(0, 0, bounds.Width, bounds.Height), + ImageLockMode.WriteOnly, + PixelFormat.Format32bppArgb); + + try + { + unsafe + { + byte* srcBase = (byte*)map.DataPointer + bounds.Y * map.RowPitch + bounds.X * 4; + int srcStride = map.RowPitch; + int dstStride = bmpData.Stride; + int rowBytes = bounds.Width * 4; + + byte* dst = (byte*)bmpData.Scan0; + byte* src = srcBase; + for (int y = 0; y < bounds.Height; y++) + { + Buffer.MemoryCopy(src, dst, rowBytes, rowBytes); + src += srcStride; + dst += dstStride; + } + } + } + finally + { + bmp.UnlockBits(bmpData); + _context.Unmap(_stagingTex!, 0); + } + + return bmp; + } + finally + { + desktopResource?.Dispose(); + if (frameAcquired) + { + try { _duplication?.ReleaseFrame(); } catch { } + } + } + } + } + + private void EnsureStagingTexture(Size desktopSize) + { + if (_device == null) return; + if (_stagingTex != null && + _stagingTex.Description.Width == desktopSize.Width && + _stagingTex.Description.Height == desktopSize.Height) + return; + + _stagingTex?.Dispose(); + _stagingTex = _device.CreateTexture2D(new Texture2DDescription + { + Width = desktopSize.Width, + Height = desktopSize.Height, + MipLevels = 1, + ArraySize = 1, + Format = Format.B8G8R8A8_UNorm, + SampleDescription = new(1, 0), + Usage = ResourceUsage.Staging, + CPUAccessFlags = CpuAccessFlags.Read, + BindFlags = BindFlags.None + }); + } + + public Bitmap? CaptureScreenshotGdi(Rectangle bounds) + { + var bmp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); + using var g = Graphics.FromImage(bmp); + g.CopyFromScreen(bounds.Location, Point.Empty, bounds.Size, CopyPixelOperation.SourceCopy); + return bmp; + } + public bool TryInitializeDirectX(int adapterIndex = 0, int outputIndex = 0) => TryInitialize(adapterIndex, outputIndex); + + private void DisposeDxgiResources() + { + _duplication?.Dispose(); + _stagingTex?.Dispose(); + _context?.Dispose(); + _device?.Dispose(); + _duplication = null; + _stagingTex = null; + _context = null; + _device = null; + IsDirectXAvailable = false; + } + + public void Dispose() + { + lock (_sync) + { + DisposeDxgiResources(); + } + GC.SuppressFinalize(this); + } + } +} \ No newline at end of file diff --git a/Spectrum/Detection/DetectionManager.cs b/Spectrum/Detection/DetectionManager.cs new file mode 100644 index 0000000..70435ac --- /dev/null +++ b/Spectrum/Detection/DetectionManager.cs @@ -0,0 +1,261 @@ +using OpenCvSharp; +using Spectrum.Input; +using System.Diagnostics; + +namespace Spectrum.Detection +{ + class DetectionManager + { + private long iterationCount = 0; + private long totalTime = 0; + private Stopwatch stopwatch = new Stopwatch(); + private Rectangle bounds = new Rectangle(0, 0, 0, 0); + private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize(); + private ConfigManager mainConfig = Program.mainConfig; + private Renderer? renderer; + private Thread? _detectionThread; + private DateTime lastMenuToggle = DateTime.MinValue; + private readonly CaptureManager _captureManager; + + public DetectionManager(Renderer renderer) + { + this.renderer = renderer; + _captureManager = Program.SharedCaptureManager; + _detectionThread = new Thread(DetectionLoop) + { + IsBackground = true, + Name = "Spectrum Detection Thread", + Priority = ThreadPriority.AboveNormal + }; + _detectionThread.Start(); + } + + private void DetectionLoop() + { + while (true) + { + try + { + if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey)) + { + stopwatch.Restart(); + bounds = new Rectangle( + (screenSize.Width - mainConfig.Data.ImageWidth) / 2, + (screenSize.Height - mainConfig.Data.ImageHeight) / 2, + mainConfig.Data.ImageWidth, + mainConfig.Data.ImageHeight + ); + var screenshot = null as Bitmap; + if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable) + screenshot = _captureManager.CaptureScreenshotDirectX(bounds); + else + { + if (_captureManager.IsInitialized) + _captureManager.Dispose(); + screenshot = _captureManager.CaptureScreenshotGdi(bounds); + } + + if (screenshot == null) + { + LogManager.Log("Capture returned null screenshot. Skipping iteration.", LogManager.LogLevel.Debug); + Thread.Sleep(2); + continue; + } + Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); + Mat drawing = mat.Clone(); + Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); + Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat); + Cv2.Dilate(mat, mat, null, iterations: 2); + Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); + + Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); + + var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray(); + + var processedContours = MergeOverlappingContours(filteredContours); + + if (processedContours.Length > 0) + { + int refX = bounds.X + bounds.Width / 2; + int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent); + + double minDist = double.MaxValue; + OpenCvSharp.Point[]? closestContour = null; + int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0; + + foreach (var contour in processedContours) + { + int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; + foreach (var point in contour) + { + if (point.X < minX) minX = point.X; + if (point.Y < minY) minY = point.Y; + if (point.X > maxX) maxX = point.X; + if (point.Y > maxY) maxY = point.Y; + } + int centerX = (minX + maxX) / 2; + int centerY = (minY + maxY) / 2; + + int absCenterX = centerX + bounds.X; + int absCenterY = centerY + bounds.Y; + double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2)); + + if (dist < minDist) + { + minDist = dist; + closestContour = contour; + bestMinX = minX; + bestMinY = minY; + bestMaxX = maxX; + bestMaxY = maxY; + } + + if (renderer != null && mainConfig.Data.DrawDetections) + { + var _rect = new Rectangle( + minX + bounds.X, + minY + bounds.Y, + (maxX - minX + 1), + (maxY - minY + 1) + ); + renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f); + } + } + + if (closestContour != null) + { + int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent)); + int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent)); + int targetX = groupX + bounds.X; + int targetY = groupY + bounds.Y; + + if (mainConfig.Data.AutoLabel) + { + AutoLabeling.AddToQueue(drawing, bounds, processedContours); + AutoLabeling.AddBackgroundImage(drawing, true); + } + if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData) + { + AutoLabeling.AddBackgroundImage(drawing, false); + } + + InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY)); + + if (mainConfig.Data.EnableAim) + { + InputManager.MoveMouse(); + } + if (mainConfig.Data.TriggerBot) + { + var _ = InputManager.ClickMouse(); + } + } + if (mainConfig.Data.DebugMode) + { + iterationCount++; + totalTime += stopwatch.ElapsedMilliseconds; + } + } + else if (mainConfig.Data.CollectData) + { + if (mainConfig.Data.CollectData) + AutoLabeling.AddBackgroundImage(drawing, false); + } + screenshot?.Dispose(); + mat.Dispose(); + drawing.Dispose(); + + if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel)) + { + AutoLabeling.StartLabeling(); + } + else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel) + { + AutoLabeling.StopLabeling(); + } + + if (iterationCount >= 1000 && mainConfig.Data.DebugMode) + { + LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info); + int fps = (int)(iterationCount * 1000 / totalTime); + LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info); + LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info); + iterationCount = 0; + totalTime = 0; + } + } + else if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey)) + { + var now = DateTime.Now; + if ((now - lastMenuToggle).TotalMilliseconds > 175) + { + mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu; + lastMenuToggle = now; + } + } + } + catch (Exception ex) + { + LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error); + Thread.Sleep(5); + } + finally + { + Thread.Sleep(1); + } + } + } + OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) + { + var contourRects = new List<(Rect rect, List indices)>(); + for (int i = 0; i < contours.Length; i++) + { + var rect = Cv2.BoundingRect(contours[i]); + contourRects.Add((rect, new List { i })); + } + bool merged; + do + { + merged = false; + for (int i = 0; i < contourRects.Count; i++) + { + var (rectA, indicesA) = contourRects[i]; + for (int j = i + 1; j < contourRects.Count; j++) + { + var (rectB, indicesB) = contourRects[j]; + if (rectA.IntersectsWith(rectB)) + { + var newRect = new Rect( + Math.Min(rectA.X, rectB.X), + Math.Min(rectA.Y, rectB.Y), + Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X), + Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y) + ); + var newIndices = new List(); + newIndices.AddRange(indicesA); + newIndices.AddRange(indicesB); + contourRects[i] = (newRect, newIndices); + contourRects.RemoveAt(j); + merged = true; + break; + } + } + if (merged) break; + } + } while (merged); + + var mergedContours = new List(); + foreach (var (rect, indices) in contourRects) + { + var points = new List(); + foreach (var idx in indices) + { + points.AddRange(contours[idx]); + } + var hull = Cv2.ConvexHull(points); + mergedContours.Add(hull); + } + return mergedContours.ToArray(); + } + } +} \ No newline at end of file diff --git a/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs b/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs new file mode 100644 index 0000000..a116347 --- /dev/null +++ b/Spectrum/Input/InputLibraries/Makcu/MakcuMain.cs @@ -0,0 +1,115 @@ +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 (Exception ex) + { + _isMakcuLoaded = false; + if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected) + { + MakcuInstance.Close(); + } + return false; + } + } + + public static async Task Load() => await InitializeMakcuDevice(); + + public static void Unload() + { + UnsubscribeFromButtonEvents(); + if (MakcuInstance != null) + { + 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 new file mode 100644 index 0000000..ea0a8cd --- /dev/null +++ b/Spectrum/Input/InputLibraries/Makcu/MakcuMouse.cs @@ -0,0 +1,598 @@ +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 object(); + private bool _isInitializedAndConnected = false; + private Thread _listenerThread; + private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false); + private volatile bool _pauseListener = false; + + private readonly Dictionary _buttonStates = new Dictionary(); + + 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 null; + } + + if (availablePorts == null || !availablePorts.Any()) + { + Log("No COM ports available according to SerialPort.GetPortNames()."); + return null; + } + + 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 null; + } + + + 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 StringBuilder(); + 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.Any() ? 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 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/InputLibraries/MouseEvent/MouseMain.cs b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs new file mode 100644 index 0000000..34499bf --- /dev/null +++ b/Spectrum/Input/InputLibraries/MouseEvent/MouseMain.cs @@ -0,0 +1,24 @@ +using System.Runtime.InteropServices; + +namespace Spectrum.Input.InputLibraries.MouseEvent +{ + public class MouseMain + { + [DllImport("user32.dll")] + private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); + + public static void Move(int x, int y) + { + mouse_event(0x0001, (uint)x, (uint)y, 0, 0); + } + + public static void ClickDown() + { + mouse_event(0x0002, 0, 0, 0, 0); + } + public static void ClickUp() + { + mouse_event(0x0004, 0, 0, 0, 0); + } + } +} diff --git a/Spectrum/Input/InputManager.cs b/Spectrum/Input/InputManager.cs new file mode 100644 index 0000000..5a92446 --- /dev/null +++ b/Spectrum/Input/InputManager.cs @@ -0,0 +1,326 @@ +using Spectrum.Input.InputLibraries.Makcu; +using System.Diagnostics; +using System.Runtime.InteropServices; +using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain; + +namespace Spectrum.Input +{ + public static class InputManager + { + [DllImport("user32.dll")] + private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); + + [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 long _lastMoveTicks = 0; + private static readonly double _dtRef = 1.0 / 120.0; + + private static double GetDeltaSeconds() + { + long now = Stopwatch.GetTimestamp(); + if (_lastMoveTicks == 0) + { + _lastMoveTicks = now; + return _dtRef; + } + long deltaTicks = now - _lastMoveTicks; + _lastMoveTicks = now; + double dt = (double)deltaTicks / Stopwatch.Frequency; + + if (dt < 0.0001) dt = 0.0001; // 10k fps cap + if (dt > 0.05) dt = 0.05; // 20 fps floor + return dt; + } + + private static double TimeScaleFactor(double baseFactor, double deltaSeconds) + { + if (baseFactor <= 0) return 0; + if (baseFactor >= 1) return 1; + double k = deltaSeconds / _dtRef; + return 1 - Math.Pow(1 - baseFactor, k); + } + + public static void MoveMouse() + { + Point reference = new Point(); + if (mainConfig.Data.ClosestToMouse) + { + GetCursorPos(out reference); + } + else + { + reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2; + reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2; + } + + Point start = new Point(reference.X, reference.Y); + Point end = new Point(lastDetection.X, lastDetection.Y); + + double dt = GetDeltaSeconds(); + double effSensitivity = TimeScaleFactor(mainConfig.Data.Sensitivity, dt); + + Point newPosition = mainConfig.Data.AimMovementType switch + { + MovementType.CubicBezier => MovementPaths.CubicBezierMovement(start, end, effSensitivity), + MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity), + MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity), + MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity), + _ => end + }; + + if (mainConfig.Data.EmaSmoothening) + { + double emaAlpha = TimeScaleFactor(mainConfig.Data.EmaSmootheningFactor, dt); + newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha)); + newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha)); + } + + int deltaX = newPosition.X - reference.X; + int deltaY = newPosition.Y - reference.Y; + + if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return; + if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight) + return; + + switch (mainConfig.Data.MovementMethod) + { + case MovementMethod.MouseEvent: + MouseEvent.Move(deltaX, deltaY); + break; + case MovementMethod.Makcu: + if (EnsureMakcuReady()) + MakcuMain.MakcuInstance.Move(deltaX, deltaY); + else + MouseEvent.Move(deltaX, deltaY); + break; + default: + MouseEvent.Move(deltaX, deltaY); + break; + } + } + + public static async Task ClickMouse() + { + if (!mainConfig.Data.TriggerBot) + return; + if (!IsKeyOrMouseDown(mainConfig.Data.TriggerKey) || mainConfig.Data.TriggerKey == Keys.None) + return; + + var currentPosition = new Point(); + if (mainConfig.Data.ClosestToMouse) + { + GetCursorPos(out currentPosition); + } + else + { + currentPosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2; + currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2; + } + + if (mainConfig.Data.TriggerDelay > 0) + await Task.Delay(mainConfig.Data.TriggerDelay); + + int radius = mainConfig.Data.TriggerRadius; + + if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius) + { + switch (mainConfig.Data.MovementMethod) + { + case MovementMethod.MouseEvent: + MouseEvent.ClickDown(); + break; + case MovementMethod.Makcu: + if (EnsureMakcuReady()) + MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left); + else + MouseEvent.ClickDown(); + break; + default: + MouseEvent.ClickDown(); + break; + } + await Task.Delay(mainConfig.Data.TriggerDuration); + switch (mainConfig.Data.MovementMethod) + { + case MovementMethod.MouseEvent: + MouseEvent.ClickUp(); + break; + case MovementMethod.Makcu: + if (EnsureMakcuReady()) + MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left); + else + MouseEvent.ClickUp(); + break; + default: + MouseEvent.ClickUp(); + break; + } + } + else + { + var dist = Math.Sqrt(Math.Pow(currentPosition.X - lastDetection.X, 2) + Math.Pow(currentPosition.Y - lastDetection.Y, 2)); + } + } + + public static void SetLastDetection(Point point) + { + lastDetection = point; + } + + [DllImport("user32.dll")] + private static extern short GetAsyncKeyState(int vKey); + + private static readonly Keys[] MouseKeys = + { + Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2 + }; + + public static Task ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null) + { + var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + Action? makcuHandler = null; + bool subscribedToMakcu = false; + if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady()) + { + makcuHandler = (btn, isPressed) => + { + if (!isPressed) return; + var key = MapMakcuButtonToKeys(btn); + if (key.HasValue) + { + tcs.TrySetResult(key.Value); + } + }; + MakcuMain.MakcuInstance.ButtonStateChanged += makcuHandler; + subscribedToMakcu = true; + } + + var thread = new Thread(() => + { + try + { + while (true) + { + if (tcs.Task.IsCompleted) + { + return; + } + for (int key = 0x08; key <= 0xFE; key++) + { + if ((GetAsyncKeyState(key) & 0x8000) != 0) + { + tcs.TrySetResult((Keys)key); + return; + } + } + + foreach (var mouseKey in MouseKeys) + { + if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0) + { + tcs.TrySetResult(mouseKey); + return; + } + } + + if (cancellationToken?.IsCancellationRequested == true) + { + tcs.TrySetCanceled(); + return; + } + Thread.Sleep(10); + } + } + finally + { + if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null) + { + try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { } + } + } + }) + { IsBackground = true }; + + tcs.Task.ContinueWith(_ => + { + if (subscribedToMakcu && makcuHandler != null && MakcuMain.MakcuInstance != null) + { + try { MakcuMain.MakcuInstance.ButtonStateChanged -= makcuHandler; } catch { } + } + }, TaskScheduler.Default); + + thread.Start(); + 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 Keys? MapMakcuButtonToKeys(MakcuMouseButton btn) + { + return btn switch + { + MakcuMouseButton.Left => Keys.LButton, + MakcuMouseButton.Right => Keys.RButton, + MakcuMouseButton.Middle => Keys.MButton, + MakcuMouseButton.Mouse4 => Keys.XButton1, + MakcuMouseButton.Mouse5 => Keys.XButton2, + _ => null + }; + } + + public static bool IsKeyOrMouseDown(Keys key) + { + if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && MakcuMain.MakcuInstance?.IsInitializedAndConnected == true) + { + var makcuBtn = MapKeysToMakcuButton(key); + if (makcuBtn.HasValue) + { + try + { + var states = MakcuMain.MakcuInstance.GetCurrentButtonStates(); + + return states.TryGetValue(makcuBtn.Value, out var pressed) && pressed; + } + catch { } + } + } + return (GetAsyncKeyState((int)key) & 0x8000) != 0; ; + } + + private static MakcuMouseButton? MapKeysToMakcuButton(Keys key) + { + return key switch + { + Keys.LButton => MakcuMouseButton.Left, + Keys.RButton => MakcuMouseButton.Right, + Keys.MButton => MakcuMouseButton.Middle, + Keys.XButton1 => MakcuMouseButton.Mouse4, + Keys.XButton2 => MakcuMouseButton.Mouse5, + _ => null + }; + } + } +} diff --git a/Spectrum/Input/MovementPaths.cs b/Spectrum/Input/MovementPaths.cs new file mode 100644 index 0000000..42bd85a --- /dev/null +++ b/Spectrum/Input/MovementPaths.cs @@ -0,0 +1,96 @@ + +namespace Spectrum.Input +{ + public class MovementPaths + { + private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t); + public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t) + { + t = Clamp01(t); + double u = 1 - t; + double tt = t * t; + double uu = u * u; + + double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X; + double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y; + + return new Point((int)Math.Round(x), (int)Math.Round(y)); + } + public static Point CubicBezierMovement(Point start, Point end, double t) + { + t = Clamp01(t); + Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3); + Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3); + return CubicBezier(start, end, control1, control2, t); + } + + public static Point CubicBezierCurvedMovement(Point start, Point end, double t, double curvature = 0.25) + { + t = Clamp01(t); + curvature = Math.Max(0, Math.Min(1, curvature)); + double dx = end.X - start.X; + double dy = end.Y - start.Y; + double dist = Math.Sqrt(dx * dx + dy * dy); + if (dist == 0) return start; + double nx = -dy / dist; + double ny = dx / dist; + double offset = dist * curvature; + var control1 = new Point((int)Math.Round(start.X + dx / 3 + nx * offset), (int)Math.Round(start.Y + dy / 3 + ny * offset)); + var control2 = new Point((int)Math.Round(start.X + 2 * dx / 3 + nx * offset), (int)Math.Round(start.Y + 2 * dy / 3 + ny * offset)); + return CubicBezier(start, end, control1, control2, t); + } + + public static Point LinearInterpolation(Point start, Point end, double t) + { + t = Clamp01(t); + int x = (int)Math.Round(start.X + t * (end.X - start.X)); + int y = (int)Math.Round(start.Y + t * (end.Y - start.Y)); + return new Point(x, y); + } + + public static Point CurvedMovement(Point start, Point end, double t) + { + t = Clamp01(t); + Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200); + return QuadraticBezier(start, end, control, t); + } + public static Point QuadraticBezier(Point start, Point end, Point control, double t) + { + t = Clamp01(t); + double u = 1 - t; + double tt = t * t; + double uu = u * u; + double x = uu * start.X + 2 * u * t * control.X + tt * end.X; + double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y; + return new Point((int)Math.Round(x), (int)Math.Round(y)); + } + + public static Point AdaptiveMovement(Point start, Point end, double sensitivity) + { + double dx = end.X - start.X; + double dy = end.Y - start.Y; + double distance = Math.Sqrt(dx * dx + dy * dy); + if (distance == 0) return start; + double stepSize = Math.Max(0, sensitivity) * distance; + stepSize = Math.Min(stepSize, distance); + double directionX = dx / distance; + double directionY = dy / distance; + int newX = (int)Math.Round(start.X + directionX * stepSize); + int newY = (int)Math.Round(start.Y + directionY * stepSize); + return new Point(newX, newY); + } + public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) + { + smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor)); + return currentValue * smoothingFactor + previousValue * (1 - smoothingFactor); + } + + public static Point EmaSmoothing(Point previous, Point current, double smoothingFactor) + { + smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor)); + int x = (int)Math.Round(EmaSmoothing(previous.X, current.X, smoothingFactor)); + int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor)); + return new Point(x, y); + } + } +} diff --git a/Spectrum/InputManager.cs b/Spectrum/InputManager.cs deleted file mode 100644 index 8577174..0000000 --- a/Spectrum/InputManager.cs +++ /dev/null @@ -1,184 +0,0 @@ -using System.Runtime.InteropServices; - -namespace Spectrum -{ - public static class InputManager - { - [DllImport("user32.dll")] - private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo); - - [DllImport("user32.dll")] - private static extern bool GetCursorPos(out Point lpPoint); - private static ConfigManager mainConfig = Program.mainConfig; - private static Point lastDetection = new Point(); - - // AIMMY V2 CODE - https://github.com/Babyhamsta/Aimmy/blob/2e906552673e359ded90383c5e97d79c8f38a2f2/Aimmy2/InputLogic/MouseManager.cs#L34-L50 - private static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t) - { - double u = 1 - t; - double tt = t * t; - double uu = u * u; - - double x = uu * u * start.X + 3 * uu * t * control1.X + 3 * u * tt * control2.X + tt * t * end.X; - double y = uu * u * start.Y + 3 * uu * t * control1.Y + 3 * u * tt * control2.Y + tt * t * end.Y; - - return new Point((int)x, (int)y); - } - private static Point CubicBezierMovement(Point start, Point end, double t) - { - Point control1 = new Point(start.X + (end.X - start.X) / 3, start.Y + (end.Y - start.Y) / 3); - Point control2 = new Point(start.X + 2 * (end.X - start.X) / 3, start.Y + 2 * (end.Y - start.Y) / 3); - return CubicBezier(start, end, control1, control2, t); - } - - private static Point LinearInterpolation(Point start, Point end, double t) - { - int x = (int)(start.X + t * (end.X - start.X)); - int y = (int)(start.Y + t * (end.Y - start.Y)); - return new Point(x, y); - } - - private static Point CurvedMovement(Point start, Point end, double t) - { - Point control = new Point((start.X + end.X) / 2, (start.Y + end.Y) / 2 - 200); - return QuadraticBezier(start, end, control, t); - } - private static Point QuadraticBezier(Point start, Point end, Point control, double t) - { - double u = 1 - t; - double tt = t * t; - double uu = u * u; - double x = uu * start.X + 2 * u * t * control.X + tt * end.X; - double y = uu * start.Y + 2 * u * t * control.Y + tt * end.Y; - return new Point((int)x, (int)y); - } - - private static Point AdaptiveMovement(Point start, Point end, double sensitivity) - { - double distance = Math.Sqrt(Math.Pow(end.X - start.X, 2) + Math.Pow(end.Y - start.Y, 2)); - double stepSize = distance * sensitivity; - - double directionX = (end.X - start.X) / distance; - double directionY = (end.Y - start.Y) / distance; - - int newX = (int)(start.X + directionX * stepSize); - int newY = (int)(start.Y + directionY * stepSize); - return new Point(newX, newY); - } - private static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor) => (currentValue * smoothingFactor) + (previousValue * (1 - smoothingFactor)); - - public static void MoveMouse(Point target) - { - Point reference = new Point(); - if (mainConfig.Data.ClosestToMouse) - { - GetCursorPos(out reference); - } - else - { - // center of the screen - reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2; - reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2; - } - - lastDetection = target; - - Point start = new Point(reference.X, reference.Y); - Point end = new Point(target.X, target.Y); - Point newPosition = mainConfig.Data.AimMovementType switch - { - MovementType.CubicBezier => CubicBezierMovement(start, end, mainConfig.Data.Sensitivity), - MovementType.Linear => LinearInterpolation(start, end, mainConfig.Data.Sensitivity), - MovementType.Adaptive => AdaptiveMovement(start, end, mainConfig.Data.Sensitivity), - MovementType.QuadraticBezier => CurvedMovement(start, end, mainConfig.Data.Sensitivity), - _ => end - }; - - if (mainConfig.Data.EmaSmoothening) - { - newPosition.X = (int)EmaSmoothing(reference.X, newPosition.X, mainConfig.Data.EmaSmootheningFactor); - newPosition.Y = (int)EmaSmoothing(reference.Y, newPosition.Y, mainConfig.Data.EmaSmootheningFactor); - } - - int deltaX = newPosition.X - reference.X; - int deltaY = newPosition.Y - reference.Y; - - if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return; - if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight) - return; - - mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0); - ClickMouse(); - } - - public static void ClickMouse() - { - if (!mainConfig.Data.TriggerBot) - return; - - var currentMousePosition = new Point(); - if (mainConfig.Data.ClosestToMouse) - { - GetCursorPos(out currentMousePosition); - } - else - { - // center of the screen - currentMousePosition.X = SystemHelper.GetPrimaryScreenSize().Width / 2; - currentMousePosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2; - } - - if (Math.Abs(currentMousePosition.X - lastDetection.X) < 25 && Math.Abs(currentMousePosition.Y - lastDetection.Y) < 25) - { - mouse_event(0x0002, 0, 0, 0, 0); - Thread.Sleep(5); - mouse_event(0x0004, 0, 0, 0, 0); - } - } - [DllImport("user32.dll")] - private static extern short GetAsyncKeyState(int vKey); - - private static readonly Keys[] MouseKeys = - { - Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2 - }; - - public static Task ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null) - { - var tcs = new TaskCompletionSource(); - var thread = new Thread(() => - { - while (true) - { - for (int key = 0x08; key <= 0xFE; key++) - { - if ((GetAsyncKeyState(key) & 0x8000) != 0) - { - tcs.TrySetResult((Keys)key); - return; - } - } - foreach (var mouseKey in MouseKeys) - { - if ((GetAsyncKeyState((int)mouseKey) & 0x8000) != 0) - { - tcs.TrySetResult(mouseKey); - return; - } - } - if (cancellationToken?.IsCancellationRequested == true) - { - tcs.TrySetCanceled(); - return; - } - Thread.Sleep(10); - } - }) - { - IsBackground = true - }; - thread.Start(); - return tcs.Task; - } - } -} diff --git a/Spectrum/LogManager.cs b/Spectrum/LogManager.cs index b893c65..7f40b22 100644 --- a/Spectrum/LogManager.cs +++ b/Spectrum/LogManager.cs @@ -1,10 +1,12 @@ using System.Diagnostics; using System.Text; + namespace Spectrum { public class LogManager { + private static ConfigManager mainConfig = Program.mainConfig; public enum LogLevel { Debug, @@ -33,6 +35,12 @@ namespace Spectrum public static IReadOnlyList LogEntries => _logEntries.AsReadOnly(); public static void Log(string message, LogLevel level = LogLevel.Info) { + if (string.IsNullOrWhiteSpace(message)) return; + if (mainConfig == null) + mainConfig = Program.mainConfig; + if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached)) + return; + string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}"; Debug.WriteLine(logMessage); _logEntries.Add(new LogEntry(level, message)); diff --git a/Spectrum/Program.cs b/Spectrum/Program.cs index 5f3877e..8c466ad 100644 --- a/Spectrum/Program.cs +++ b/Spectrum/Program.cs @@ -1,29 +1,33 @@ using OpenCvSharp; -using System.Diagnostics; -using System.Drawing.Imaging; +using Spectrum.Detection; using System.Runtime.InteropServices; namespace Spectrum { class Program { - static Rectangle bounds = new Rectangle(0, 0, 0, 0); static Renderer? renderer = null; - private static DateTime lastMenuToggle = DateTime.MinValue; public static ConfigManager mainConfig = new ConfigManager("bin\\configs\\config.json"); public static ConfigManager colorConfig = new ConfigManager("bin\\configs\\colors.json"); public static long iterationCount = 0; public static long totalTime = 0; - private static Stopwatch stopwatch = new Stopwatch(); + private static DetectionManager? detectionManager; + public static CaptureManager SharedCaptureManager { get; } = new CaptureManager(); + static void Main() { - Thread renderThread = new Thread(() => { try { - renderer = new Renderer(); + renderer = new Renderer(SharedCaptureManager); + bool dxok = SharedCaptureManager.TryInitializeDirectX(); + if (!dxok) + { + LogManager.Log("Failed to initialize DirectX. Falling back to gdi.", LogManager.LogLevel.Warning); + mainConfig.Data.CaptureMethod = CaptureMethod.GDI; + } renderer.Run(); LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info); } @@ -34,22 +38,20 @@ namespace Spectrum }); renderThread.Start(); - Directory.CreateDirectory("bin"); - Directory.CreateDirectory("bin/dataset"); - Directory.CreateDirectory("bin/dataset/images"); - Directory.CreateDirectory("bin/dataset/labels"); - Directory.CreateDirectory("bin/logs"); - Directory.CreateDirectory("bin/configs"); + string[] dirs = { "bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs" }; + foreach (var dir in dirs) + { + if (!Directory.Exists(dir)) + { + Directory.CreateDirectory(dir); + LogManager.Log($"Created directory: {dir}", LogManager.LogLevel.Info); + } + } var screenSize = SystemHelper.GetPrimaryScreenSize(); mainConfig.LoadConfig(); mainConfig.StartFileWatcher(); - if (mainConfig.Data.ShowDetectionWindow) - { - Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize); - Cv2.WaitKey(1); - } if (mainConfig.Data.AutoLabel) { AutoLabeling.StartLabeling(); @@ -64,275 +66,15 @@ namespace Spectrum mainConfig.LoadConfig(true); } - while (true) + Thread.Sleep(1000); + + if (renderer == null) { - if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.Keybind) < 0) - { - stopwatch.Restart(); - bounds = new Rectangle( - (screenSize.Width - mainConfig.Data.ImageWidth) / 2, - (screenSize.Height - mainConfig.Data.ImageHeight) / 2, - mainConfig.Data.ImageWidth, - mainConfig.Data.ImageHeight - ); - var screenshot = CaptureScreenshot(bounds); - Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot); - Mat drawing = mat.Clone(); - Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); - Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat); - Cv2.Dilate(mat, mat, null, iterations: 2); - Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); - - Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple); - - var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray(); - - var mergedContours = MergeOverlappingContours(filteredContours); - - var processedContours = mergedContours.Select(ShrinkWideContour).ToArray(); - - if (processedContours.Length > 0) - { - int refX = bounds.X + bounds.Width / 2; - int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent); - - double minDist = double.MaxValue; - OpenCvSharp.Point[]? closestContour = null; - int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0; - - foreach (var contour in processedContours) - { - int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue; - foreach (var point in contour) - { - if (point.X < minX) minX = point.X; - if (point.Y < minY) minY = point.Y; - if (point.X > maxX) maxX = point.X; - if (point.Y > maxY) maxY = point.Y; - } - int centerX = (minX + maxX) / 2; - int centerY = (minY + maxY) / 2; - - int absCenterX = centerX + bounds.X; - int absCenterY = centerY + bounds.Y; - double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2)); - - if (dist < minDist) - { - minDist = dist; - closestContour = contour; - bestMinX = minX; - bestMinY = minY; - bestMaxX = maxX; - bestMaxY = maxY; - } - - if (renderer != null && mainConfig.Data.DrawDetections) - { - var _rect = new Rectangle( - minX + bounds.X, - minY + bounds.Y, - (maxX - minX + 1), - (maxY - minY + 1) - ); - renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f); - } - } - - if (closestContour != null) - { - int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent)); - int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent)); - int targetX = groupX + bounds.X; - int targetY = groupY + bounds.Y; - - if (mainConfig.Data.AutoLabel) - { - AutoLabeling.AddToQueue(drawing, bounds, processedContours); - AutoLabeling.AddBackgroundImage(drawing, true); - } - if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData) - { - AutoLabeling.AddBackgroundImage(drawing, false); - } - - if (mainConfig.Data.EnableAim) - { - InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY)); - } - - if (mainConfig.Data.ShowDetectionWindow) - { - Cv2.Rectangle(drawing, new OpenCvSharp.Point(bestMinX, bestMinY), new OpenCvSharp.Point(bestMaxX, bestMaxY), Scalar.Blue, 2); - Cv2.ImShow("Spectrum Detection", drawing); - Cv2.WaitKey(1); - } - } - if (mainConfig.Data.DebugMode) - { - iterationCount++; - totalTime += stopwatch.ElapsedMilliseconds; - } - } - else if (mainConfig.Data.ShowDetectionWindow || mainConfig.Data.CollectData) - { - Cv2.ImShow("Spectrum Detection", drawing); - Cv2.WaitKey(1); - if (mainConfig.Data.CollectData) - AutoLabeling.AddBackgroundImage(drawing, false); - } - screenshot?.Dispose(); - mat.Dispose(); - drawing.Dispose(); - - if (iterationCount >= 1000 && mainConfig.Data.DebugMode) - { - LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info); - int fps = (int)(iterationCount * 1000 / totalTime); - LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info); - iterationCount = 0; - totalTime = 0; - } - } - else if (SystemHelper.GetAsyncKeyState((int)mainConfig.Data.MenuKey) < 0) - { - var now = DateTime.Now; - if ((now - lastMenuToggle).TotalMilliseconds > 175) - { - mainConfig.Data.ShowMenu = !mainConfig.Data.ShowMenu; - lastMenuToggle = now; - } - } - else - { - if (mainConfig.Data.ShowDetectionWindow) - { - Cv2.WaitKey(1); - } - else if (!mainConfig.Data.ShowDetectionWindow) - { - if (Cv2.GetWindowProperty("Spectrum Detection", WindowPropertyFlags.Visible) >= 0) - { - Cv2.DestroyAllWindows(); - } - } - - } - } - } - - static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours) - { - var contourRects = new List<(Rect rect, List indices)>(); - for (int i = 0; i < contours.Length; i++) - { - var rect = Cv2.BoundingRect(contours[i]); - contourRects.Add((rect, new List { i })); - } - bool merged; - do - { - merged = false; - for (int i = 0; i < contourRects.Count; i++) - { - var (rectA, indicesA) = contourRects[i]; - for (int j = i + 1; j < contourRects.Count; j++) - { - var (rectB, indicesB) = contourRects[j]; - if (rectA.IntersectsWith(rectB)) - { - var newRect = new Rect( - Math.Min(rectA.X, rectB.X), - Math.Min(rectA.Y, rectB.Y), - Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X), - Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y) - ); - var newIndices = new List(); - newIndices.AddRange(indicesA); - newIndices.AddRange(indicesB); - contourRects[i] = (newRect, newIndices); - contourRects.RemoveAt(j); - merged = true; - break; - } - } - if (merged) break; - } - } while (merged); - - var mergedContours = new List(); - foreach (var (rect, indices) in contourRects) - { - var points = new List(); - foreach (var idx in indices) - { - points.AddRange(contours[idx]); - } - var hull = Cv2.ConvexHull(points); - mergedContours.Add(hull); - } - return mergedContours.ToArray(); - } - - static OpenCvSharp.Point[] ShrinkWideContour(OpenCvSharp.Point[] contour) - { - var rect = Cv2.BoundingRect(contour); - double aspect = rect.Width / (double)rect.Height; - if (aspect <= 1.2) - return contour; - - int[] xs = contour.Select(p => p.X).ToArray(); - int minX = xs.Min(); - int maxX = xs.Max(); - - int binCount = Math.Max(10, (maxX - minX + 1) / 5); - int[] bins = new int[binCount]; - int binWidth = (int)Math.Ceiling((maxX - minX + 1) / (double)binCount); - - foreach (var pt in contour) - { - int binIdx = (pt.X - minX) / binWidth; - if (binIdx < 0) binIdx = 0; - if (binIdx >= binCount) binIdx = binCount - 1; - bins[binIdx]++; + LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error); + return; } - int maxMass = bins.Max(); - int left = 0, right = binCount - 1; - for (int i = 0; i < binCount; i++) - { - if (bins[i] == maxMass) - { - left = i; - break; - } - } - for (int i = binCount - 1; i >= 0; i--) - { - if (bins[i] == maxMass) - { - right = i; - break; - } - } - int cropMinX = minX + left * binWidth; - int cropMaxX = minX + (right + 1) * binWidth - 1; - - var shrunken = contour.Where(p => p.X >= cropMinX && p.X <= cropMaxX).ToArray(); - if (shrunken.Length < 3) - return contour; - - return Cv2.ConvexHull(shrunken); - } - - public static Bitmap CaptureScreenshot(Rectangle bounds) - { - Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb); - using (Graphics g = Graphics.FromImage(bitmap)) - { - g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size); - } - return bitmap; + detectionManager = new DetectionManager(renderer); } } public static class SystemHelper diff --git a/Spectrum/Renderer.cs b/Spectrum/Renderer.cs index f5315c5..054059c 100644 --- a/Spectrum/Renderer.cs +++ b/Spectrum/Renderer.cs @@ -1,9 +1,13 @@ using ClickableTransparentOverlay; using ImGuiNET; using OpenCvSharp; +using Spectrum.Input; +using Spectrum.Input.InputLibraries.Makcu; using System.Collections.Concurrent; using System.Diagnostics; using System.Numerics; +using System.Globalization; +using Spectrum.Detection; namespace Spectrum { @@ -12,6 +16,7 @@ namespace Spectrum static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize(); private List> drawCommands = new List>(); private readonly object drawCommandsLock = new object(); + private readonly CaptureManager _captureManager; private bool _vsync = true; private int _fpsLimit = 240; @@ -22,9 +27,11 @@ namespace Spectrum private ConfigManager mainConfig = Program.mainConfig; private ConfigManager colorConfig = Program.colorConfig; private string ColorName = "New Color"; + private static bool scrollToBottom = true; - public Renderer() : base("Spectrum", screenSize.width, screenSize.width) + public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width) { + _captureManager = captureManager; VSync = _vsync; FPSLimit = _fpsLimit; ImGui.CreateContext(); @@ -41,9 +48,9 @@ namespace Spectrum AddStyling(); - ImGui.SetNextWindowSize(new Vector2(600, 500), ImGuiCond.FirstUseEver); - ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 300, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver); - ImGui.SetNextWindowSizeConstraints(new Vector2(600, 500), new Vector2(float.MaxValue, float.MaxValue)); + ImGui.SetNextWindowSize(new Vector2(700, 500), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 350, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver); + ImGui.SetNextWindowSizeConstraints(new Vector2(700, 500), new Vector2(float.MaxValue, float.MaxValue)); ImGui.Begin("Spectrum", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar); ImGui.Text("Spectrum"); @@ -59,182 +66,82 @@ namespace Spectrum ImGui.BeginTabBar("##tabs"); if (ImGui.BeginTabItem("Aiming")) { - bool enableAiming = mainConfig.Data.EnableAim; - if (ImGui.Checkbox("##Enable Aiming", ref enableAiming)) - { - mainConfig.Data.EnableAim = enableAiming; - } + ImGuiExtensions.BeginPaneGroup("Aiming Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f); - ImGui.SameLine(); - if (!_waitingForKeybind.GetValueOrDefault("Aiming", false)) + if (ImGuiExtensions.BeginPane("Aim Assist")) { - if (ImGui.Button(mainConfig.Data.Keybind.ToString())) + bool enableAiming = mainConfig.Data.EnableAim; + if (ImGui.Checkbox("##Enable Aiming", ref enableAiming)) { - _waitingForKeybind["Aiming"] = true; - _pendingKeybind["Aiming"] = Keys.None; - _keybindTask["Aiming"] = Task.Run(async () => - { - var key = await InputManager.ListenForNextKeyOrMouseAsync(); - _pendingKeybind["Aiming"] = key; - }); + mainConfig.Data.EnableAim = enableAiming; } - } - else - { - ImGui.Button("Listening..."); - if (_pendingKeybind.GetValueOrDefault("Aiming", Keys.None) != Keys.None) + + ImGui.SameLine(); + ImGui.Text("Enable Aiming"); + + ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.Keybind.ToString()).X); + if (!_waitingForKeybind.GetValueOrDefault("Aiming", false)) { - mainConfig.Data.Keybind = _pendingKeybind["Aiming"]; - _pendingKeybind["Aiming"] = Keys.None; - _waitingForKeybind["Aiming"] = false; - } - } - ImGui.SameLine(); - ImGui.Text("Enable Aiming"); - - bool closestToMouse = mainConfig.Data.ClosestToMouse; - if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse)) - { - mainConfig.Data.ClosestToMouse = closestToMouse; - } - bool triggerBot = mainConfig.Data.TriggerBot; - if (ImGui.Checkbox("Trigger Bot", ref triggerBot)) - { - mainConfig.Data.TriggerBot = triggerBot; - } - - float sensitivity = (float)mainConfig.Data.Sensitivity; - if (ImGui.SliderFloat("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f")) - { - mainConfig.Data.Sensitivity = sensitivity; - } - - float EmaSmootheningFactor = (float)mainConfig.Data.EmaSmootheningFactor; - bool EmaSmoothening = mainConfig.Data.EmaSmoothening; - if (ImGui.Checkbox("Ema Smoothening", ref EmaSmoothening)) - { - mainConfig.Data.EmaSmoothening = EmaSmoothening; - } - - if (ImGui.SliderFloat("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f, "%.2f")) - { - mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor; - } - - MovementType AimPath = mainConfig.Data.AimMovementType; - if (ImGui.BeginCombo("Movement Type", AimPath.ToString())) - { - foreach (MovementType type in Enum.GetValues(typeof(MovementType))) - { - bool isSelected = (type == AimPath); - if (ImGui.Selectable(type.ToString(), isSelected)) + if (ImGui.Button($"{mainConfig.Data.Keybind.ToString()}###AimKeybind")) { - mainConfig.Data.AimMovementType = type; - } - if (isSelected) - { - ImGui.SetItemDefaultFocus(); - } - } - ImGui.EndCombo(); - } - - int YOffset = (int)(mainConfig.Data.YOffsetPercent * 100); - if (ImGui.SliderInt("Y Offset (%)", ref YOffset, 0, 100, "%d%%")) - { - mainConfig.Data.YOffsetPercent = ((double)YOffset / 100); - } - - int XOffset = (int)(mainConfig.Data.XOffsetPercent * 100); - if (ImGui.SliderInt("X Offset (%)", ref XOffset, 0, 100, "%d%%")) - { - mainConfig.Data.XOffsetPercent = ((double)XOffset / 100); - } - - ImGui.SeparatorText("Overlay Settings"); - - bool DrawFOV = mainConfig.Data.DrawFOV; - if (ImGui.Checkbox("##Draw FOV", ref DrawFOV)) - { - mainConfig.Data.DrawFOV = DrawFOV; - } - ImGui.SameLine(); - Vector4 FOVColor = mainConfig.Data.FOVColor; - if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) - { - mainConfig.Data.FOVColor = FOVColor; - } - ImGui.SameLine(); - ImGui.Text("Draw FOV"); - - bool DrawDetections = mainConfig.Data.DrawDetections; - if (ImGui.Checkbox("##Draw Detections", ref DrawDetections)) - { - mainConfig.Data.DrawDetections = DrawDetections; - } - ImGui.SameLine(); - Vector4 DetectionColor = mainConfig.Data.DetectionColor; - if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) - { - mainConfig.Data.DetectionColor = DetectionColor; - } - ImGui.SameLine(); - ImGui.Text("Draw Detections"); - - ImGui.EndTabItem(); - } - - if (ImGui.BeginTabItem("Detection")) - { - int ImageWidth = mainConfig.Data.ImageWidth; - if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width)) - { - if (ImageWidth < 1) - ImageWidth = 1; - else if (ImageWidth > screenSize.width) - ImageWidth = screenSize.width; - mainConfig.Data.ImageWidth = ImageWidth; - } - - int ImageHeight = mainConfig.Data.ImageHeight; - if (ImGui.InputInt("Image Height", ref ImageHeight, 1, screenSize.height)) - { - if (ImageHeight < 1) - ImageHeight = 1; - else if (ImageHeight > screenSize.height) - ImageHeight = screenSize.height; - mainConfig.Data.ImageHeight = ImageHeight; - } - - Scalar UpperHSV = mainConfig.Data.UpperHSV; - Vector3 UpperHSVVec3 = new Vector3((float)UpperHSV.Val0, (float)UpperHSV.Val1, (float)UpperHSV.Val2); - if (ImGui.InputFloat3("Upper HSV", ref UpperHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) - { - mainConfig.Data.UpperHSV = new Scalar(UpperHSVVec3.X, UpperHSVVec3.Y, UpperHSVVec3.Z); - } - - - Scalar LowerHSV = mainConfig.Data.LowerHSV; - Vector3 LowerHSVVec3 = new Vector3((float)LowerHSV.Val0, (float)LowerHSV.Val1, (float)LowerHSV.Val2); - if (ImGui.InputFloat3("Lower HSV", ref LowerHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) - { - mainConfig.Data.LowerHSV = new Scalar(LowerHSVVec3.X, LowerHSVVec3.Y, LowerHSVVec3.Z); - } - - List colors = colorConfig.Data.Colors; - if (colors.Count != 0) - { - if (ImGui.BeginCombo("Colors", mainConfig.Data.SelectedColor)) - { - foreach (ColorInfo color in colors) - { - bool isSelected = (color.Name == mainConfig.Data.SelectedColor); - if (ImGui.Selectable(color.Name, isSelected)) + _waitingForKeybind["Aiming"] = true; + _pendingKeybind["Aiming"] = Keys.None; + _keybindTask["Aiming"] = Task.Run(async () => { - mainConfig.Data.SelectedColor = color.Name; - mainConfig.Data.UpperHSV = color.Upper; - mainConfig.Data.LowerHSV = color.Lower; - ColorName = color.Name; + var key = await InputManager.ListenForNextKeyOrMouseAsync(); + _pendingKeybind["Aiming"] = key; + }); + } + } + else + { + ImGui.Button("Listening... ###AimListening"); + if (_pendingKeybind.GetValueOrDefault("Aiming", Keys.None) != Keys.None) + { + mainConfig.Data.Keybind = _pendingKeybind["Aiming"]; + _pendingKeybind["Aiming"] = Keys.None; + _waitingForKeybind["Aiming"] = false; + } + } + + bool closestToMouse = mainConfig.Data.ClosestToMouse; + if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse)) + { + mainConfig.Data.ClosestToMouse = closestToMouse; + } + + float sensitivity = (float)mainConfig.Data.Sensitivity; + if (ImGuiExtensions.SliderFill("Sensitivity", ref sensitivity, 0.1f, 2.0f, "%.1f")) + { + mainConfig.Data.Sensitivity = sensitivity; + } + + float EmaSmootheningFactor = (float)mainConfig.Data.EmaSmootheningFactor; + bool EmaSmoothening = mainConfig.Data.EmaSmoothening; + if (ImGui.Checkbox("Ema Smoothening", ref EmaSmoothening)) + { + mainConfig.Data.EmaSmoothening = EmaSmoothening; + } + + if (EmaSmoothening) + { + if (ImGuiExtensions.SliderFill("Ema Smoothening Factor", ref EmaSmootheningFactor, 0.01f, 1.0f)) + { + mainConfig.Data.EmaSmootheningFactor = EmaSmootheningFactor; + } + } + + ImGui.TextUnformatted("Movement Type"); + ImGui.SetNextItemWidth(-1); + MovementType AimPath = mainConfig.Data.AimMovementType; + if (ImGui.BeginCombo("##Movement Type", AimPath.ToString())) + { + foreach (MovementType type in Enum.GetValues(typeof(MovementType))) + { + bool isSelected = (type == AimPath); + if (ImGui.Selectable(type.ToString(), isSelected)) + { + mainConfig.Data.AimMovementType = type; } if (isSelected) { @@ -243,173 +150,457 @@ namespace Spectrum } ImGui.EndCombo(); } + + float YOffset = (int)(mainConfig.Data.YOffsetPercent * 100); + if (ImGuiExtensions.SliderFill("Y Offset (%)", ref YOffset, 0, 100, "%d%%")) + { + mainConfig.Data.YOffsetPercent = ((double)YOffset / 100); + } + + float XOffset = (int)(mainConfig.Data.XOffsetPercent * 100); + if (ImGuiExtensions.SliderFill("X Offset (%)", ref XOffset, 0, 100, "%d%%")) + { + mainConfig.Data.XOffsetPercent = ((double)XOffset / 100); + } + + ImGui.SeparatorText("Overlay Settings"); + + bool DrawFOV = mainConfig.Data.DrawFOV; + if (ImGui.Checkbox("##Draw FOV", ref DrawFOV)) + { + mainConfig.Data.DrawFOV = DrawFOV; + } + + ImGui.SameLine(); + ImGui.Text("Draw FOV"); + + ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); + Vector4 FOVColor = mainConfig.Data.FOVColor; + if (ImGui.ColorEdit4("FOV Color", ref FOVColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + { + mainConfig.Data.FOVColor = FOVColor; + } + + bool DrawDetections = mainConfig.Data.DrawDetections; + if (ImGui.Checkbox("##Draw Detections", ref DrawDetections)) + { + mainConfig.Data.DrawDetections = DrawDetections; + } + ImGui.SameLine(); + ImGui.Text("Draw Detections"); + + ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12); + Vector4 DetectionColor = mainConfig.Data.DetectionColor; + if (ImGui.ColorEdit4("Draw Color", ref DetectionColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel)) + { + mainConfig.Data.DetectionColor = DetectionColor; + } + + if (DrawFOV) + { + ImGui.TextUnformatted("FOV Type"); + ImGui.SetNextItemWidth(-1); + FovType fovType = mainConfig.Data.FOVType; + if (ImGui.BeginCombo("##FOV Type", fovType.ToString())) + { + foreach (FovType type in Enum.GetValues(typeof(FovType))) + { + bool isSelected = (type == fovType); + if (ImGui.Selectable(type.ToString(), isSelected)) + { + mainConfig.Data.FOVType = type; + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); + } + } + ImGuiExtensions.EndPane(); } - ImGui.InputText("##ColorNameInput", ref ColorName, 32); - ImGui.SameLine(); - if (ImGui.Button("Delete Color")) + if (ImGuiExtensions.BeginPane("Triggerbot")) { - if (colors.Any(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase))) + bool triggerBot = mainConfig.Data.TriggerBot; + if (ImGui.Checkbox("Enabled", ref triggerBot)) { - colors.RemoveAll(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase)); - colorConfig.SaveConfig(); - mainConfig.Data.SelectedColor = "Arsenal [Magenta]"; - mainConfig.Data.UpperHSV = new Scalar(150, 255, 229); - mainConfig.Data.LowerHSV = new Scalar(150, 255, 229); + mainConfig.Data.TriggerBot = triggerBot; } - else + ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.TriggerKey.ToString()).X); + if (!_waitingForKeybind.GetValueOrDefault("Trigger Key", false)) { - LogManager.Log($"Color '{mainConfig.Data.SelectedColor}' does not exist.", LogManager.LogLevel.Warning); + if (ImGui.Button($"{mainConfig.Data.TriggerKey.ToString()}###TriggerKeybind")) + { + _waitingForKeybind["Trigger Key"] = true; + _pendingKeybind["Trigger Key"] = Keys.None; + _keybindTask["Trigger Key"] = Task.Run(async () => + { + var key = await InputManager.ListenForNextKeyOrMouseAsync(); + _pendingKeybind["Trigger Key"] = key; + }); + } } + else if (triggerBot) + { + ImGui.Button("Listening... ###TriggerListening"); + if (_pendingKeybind.GetValueOrDefault("Trigger Key", Keys.None) != Keys.None) + { + mainConfig.Data.TriggerKey = _pendingKeybind["Trigger Key"]; + _pendingKeybind["Trigger Key"] = Keys.None; + _waitingForKeybind["Trigger Key"] = false; + } + } + + if (triggerBot) + { + int triggerDelay = mainConfig.Data.TriggerDelay; + if (ImGuiExtensions.SliderFill("Trigger Delay (ms)", ref triggerDelay, 1, 1000)) + { + mainConfig.Data.TriggerDelay = triggerDelay; + } + + int triggerRadius = mainConfig.Data.TriggerRadius; + if (ImGuiExtensions.SliderFill("Trigger Radius (px)", ref triggerRadius, 1, 100)) + { + mainConfig.Data.TriggerRadius = triggerRadius; + } + + int triggerDuration = mainConfig.Data.TriggerDuration; + if (ImGuiExtensions.SliderFill("Trigger Duration (ms)", ref triggerDuration, 1, 1000)) + { + mainConfig.Data.TriggerDuration = triggerDuration; + } + } + ImGuiExtensions.EndPane(); } - ImGui.SameLine(); - if (ImGui.Button("Save Color")) + + ImGuiExtensions.EndPaneGroup(); + + ImGui.EndTabItem(); + } + + if (ImGui.BeginTabItem("Detection")) + { + ImGuiExtensions.BeginPaneGroup("Detection Panes", 1, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f); + + if (ImGuiExtensions.BeginPane("Detection Settings")) { - var color = new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV); - if (!string.IsNullOrEmpty(ColorName) && !colors.Any(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase))) + int ImageWidth = mainConfig.Data.ImageWidth; + if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width)) + { + if (ImageWidth < 1) + ImageWidth = 1; + else if (ImageWidth > screenSize.width) + ImageWidth = screenSize.width; + mainConfig.Data.ImageWidth = ImageWidth; + } + + int ImageHeight = mainConfig.Data.ImageHeight; + if (ImGui.InputInt("Image Height", ref ImageHeight, 1, screenSize.height)) + { + if (ImageHeight < 1) + ImageHeight = 1; + else if (ImageHeight > screenSize.height) + ImageHeight = screenSize.height; + mainConfig.Data.ImageHeight = ImageHeight; + } + + Scalar UpperHSV = mainConfig.Data.UpperHSV; + Vector3 UpperHSVVec3 = new Vector3((float)UpperHSV.Val0, (float)UpperHSV.Val1, (float)UpperHSV.Val2); + if (ImGui.InputFloat3("Upper HSV", ref UpperHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) + { + mainConfig.Data.UpperHSV = new Scalar(UpperHSVVec3.X, UpperHSVVec3.Y, UpperHSVVec3.Z); + } + + + Scalar LowerHSV = mainConfig.Data.LowerHSV; + Vector3 LowerHSVVec3 = new Vector3((float)LowerHSV.Val0, (float)LowerHSV.Val1, (float)LowerHSV.Val2); + if (ImGui.InputFloat3("Lower HSV", ref LowerHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal)) + { + mainConfig.Data.LowerHSV = new Scalar(LowerHSVVec3.X, LowerHSVVec3.Y, LowerHSVVec3.Z); + } + + List colors = colorConfig.Data.Colors; + if (colors.Count != 0) + { + if (ImGui.BeginCombo("Colors", mainConfig.Data.SelectedColor)) + { + foreach (ColorInfo color in colors) + { + bool isSelected = (color.Name == mainConfig.Data.SelectedColor); + if (ImGui.Selectable(color.Name, isSelected)) + { + mainConfig.Data.SelectedColor = color.Name; + mainConfig.Data.UpperHSV = color.Upper; + mainConfig.Data.LowerHSV = color.Lower; + ColorName = color.Name; + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); + } + } + + ImGui.InputText("##ColorNameInput", ref ColorName, 32); + ImGui.SameLine(); + if (ImGui.Button("Delete Color")) { - colors.Add(color); - colorConfig.SaveConfig(); - mainConfig.Data.SelectedColor = ColorName; + if (colors.Any(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase))) + { + colors.RemoveAll(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase)); + colorConfig.SaveConfig(); + mainConfig.Data.SelectedColor = "Arsenal [Magenta]"; + mainConfig.Data.UpperHSV = new Scalar(150, 255, 229); + mainConfig.Data.LowerHSV = new Scalar(150, 255, 229); + } + else + { + LogManager.Log($"Color '{mainConfig.Data.SelectedColor}' does not exist.", LogManager.LogLevel.Warning); + } } - else + ImGui.SameLine(); + if (ImGui.Button("Save Color")) { - LogManager.Log($"Color with name '{ColorName}' already exists or is empty.", LogManager.LogLevel.Warning); + var color = new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV); + if (!string.IsNullOrEmpty(ColorName)) + { + colors.Add(color); + colorConfig.SaveConfig(); + mainConfig.Data.SelectedColor = ColorName; + } + else + { + LogManager.Log($"Colorname is empty.", LogManager.LogLevel.Warning); + } } } + ImGuiExtensions.EndPane(); ImGui.EndTabItem(); } if (ImGui.BeginTabItem("Settings")) { - bool ShowDetectionWindow = mainConfig.Data.ShowDetectionWindow; - if (ImGui.Checkbox("Show Detection Window", ref ShowDetectionWindow)) - { - mainConfig.Data.ShowDetectionWindow = ShowDetectionWindow; - } + ImGuiExtensions.BeginPaneGroup("Settings Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f); - bool CollectData = mainConfig.Data.CollectData; - if (ImGui.Checkbox("Collect Data", ref CollectData)) + if (ImGuiExtensions.BeginPane("Settings")) { - mainConfig.Data.CollectData = CollectData; - } - - bool AutoLabel = mainConfig.Data.AutoLabel; - if (ImGui.Checkbox("Auto Label", ref AutoLabel)) - { - if (!CollectData && AutoLabel) - mainConfig.Data.CollectData = true; - - mainConfig.Data.AutoLabel = AutoLabel; - } - - if (ImGui.Checkbox("VSync", ref _vsync)) - { - VSync = _vsync; - } - - bool DebugMode = mainConfig.Data.DebugMode; - if (ImGui.Checkbox("Debug Mode", ref DebugMode)) - { - mainConfig.Data.DebugMode = DebugMode; - } - - if (ImGui.SliderInt("FPS Limit", ref _fpsLimit, 30, 480, "%d")) - { - FPSLimit = _fpsLimit; - } - int BackgroundImageInterval = mainConfig.Data.BackgroundImageInterval; - if (ImGui.InputInt("Background Image Interval", ref BackgroundImageInterval, 1, 500)) - { - if (BackgroundImageInterval < 1) - BackgroundImageInterval = 1; - else if (BackgroundImageInterval > 500) - BackgroundImageInterval = 500; - - mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval; - } - - if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false)) - { - if (ImGui.Button(mainConfig.Data.MenuKey.ToString())) + ImGui.TextUnformatted("Movement Method"); + ImGui.SetNextItemWidth(-1); + MovementMethod movementMethod = mainConfig.Data.MovementMethod; + if (ImGui.BeginCombo("##Movement Method", movementMethod.ToString())) { - _waitingForKeybind["Menu Key"] = true; - _pendingKeybind["Menu Key"] = Keys.None; - _keybindTask["Menu Key"] = Task.Run(async () => + foreach (MovementMethod method in Enum.GetValues(typeof(MovementMethod))) { - var key = await InputManager.ListenForNextKeyOrMouseAsync(); - _pendingKeybind["Menu Key"] = key; - }); + bool isSelected = (method == movementMethod); + if (ImGui.Selectable(method.ToString(), isSelected)) + { + mainConfig.Data.MovementMethod = method; + switch (method) + { + case MovementMethod.Makcu: + { + var ok = MakcuMain.Load().GetAwaiter().GetResult(); + if (!ok) + { + LogManager.Log("Makcu failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning); + mainConfig.Data.MovementMethod = MovementMethod.MouseEvent; + MakcuMain.Unload(); + } + break; + } + default: + MakcuMain.Unload(); + break; + } + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); } - } - else - { - ImGui.Button("Listening..."); - if (_pendingKeybind.GetValueOrDefault("Menu Key", Keys.None) != Keys.None) - { - mainConfig.Data.MenuKey = _pendingKeybind["Menu Key"]; - _pendingKeybind["Menu Key"] = Keys.None; - _waitingForKeybind["Menu Key"] = false; - } - } - ImGui.SameLine(); - ImGui.Text("Menu Keybind"); - if (ImGui.Button("Save Configs")) - { - mainConfig.SaveConfig(); - colorConfig.SaveConfig(); - } - ImGui.SameLine(); - if (ImGui.Button("Open Folder")) - { - string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\configs"); - if (Directory.Exists(folderPath)) + ImGui.TextUnformatted("Capture Method"); + ImGui.SetNextItemWidth(-1); + CaptureMethod captureMethod = mainConfig.Data.CaptureMethod; + if (ImGui.BeginCombo("##Capture Method", captureMethod.ToString())) { - Process.Start(new ProcessStartInfo + foreach (CaptureMethod method in Enum.GetValues(typeof(CaptureMethod))) { - FileName = "explorer.exe", - Arguments = folderPath, - UseShellExecute = true - }); + bool isSelected = (method == captureMethod); + if (ImGui.Selectable(method.ToString(), isSelected)) + { + CaptureMethod _method = method; + if (method == CaptureMethod.DirectX) + { + bool dxOk = _captureManager.TryInitializeDirectX(); + if (!dxOk) + { + LogManager.Log("DirectX capture failed to initialize. Falling back to GDI.", LogManager.LogLevel.Warning); + _method = CaptureMethod.GDI; + } + } + mainConfig.Data.CaptureMethod = _method; + } + if (isSelected) + { + ImGui.SetItemDefaultFocus(); + } + } + ImGui.EndCombo(); + } + + bool CollectData = mainConfig.Data.CollectData; + if (ImGui.Checkbox("Collect Data", ref CollectData)) + { + mainConfig.Data.CollectData = CollectData; + } + + bool AutoLabel = mainConfig.Data.AutoLabel; + if (ImGui.Checkbox("Auto Label", ref AutoLabel)) + { + if (!CollectData && AutoLabel) + mainConfig.Data.CollectData = true; + + mainConfig.Data.AutoLabel = AutoLabel; + } + + if (ImGui.Checkbox("VSync", ref _vsync)) + { + VSync = _vsync; + } + + bool DebugMode = mainConfig.Data.DebugMode; + if (ImGui.Checkbox("Debug Mode", ref DebugMode)) + { + mainConfig.Data.DebugMode = DebugMode; + } + + if (!VSync) + { + if (ImGuiExtensions.SliderFill("FPS Limit", ref _fpsLimit, 30, 480)) + { + FPSLimit = _fpsLimit; + } + } + + ImGui.TextUnformatted("Background Image Interval"); + ImGui.SetNextItemWidth(-1); + int BackgroundImageInterval = mainConfig.Data.BackgroundImageInterval; + if (ImGui.InputInt("##Background Image Interval", ref BackgroundImageInterval, 1, 1000)) + { + if (BackgroundImageInterval < 1) + BackgroundImageInterval = 1; + else if (BackgroundImageInterval > 1000) + BackgroundImageInterval = 1000; + + mainConfig.Data.BackgroundImageInterval = BackgroundImageInterval; + } + + if (!_waitingForKeybind.GetValueOrDefault("Menu Key", false)) + { + if (ImGui.Button(mainConfig.Data.MenuKey.ToString())) + { + _waitingForKeybind["Menu Key"] = true; + _pendingKeybind["Menu Key"] = Keys.None; + _keybindTask["Menu Key"] = Task.Run(async () => + { + var key = await InputManager.ListenForNextKeyOrMouseAsync(); + _pendingKeybind["Menu Key"] = key; + }); + } } else { - LogManager.Log($"Directory doesnt exist: {folderPath}", LogManager.LogLevel.Error); + ImGui.Button("Listening..."); + if (_pendingKeybind.GetValueOrDefault("Menu Key", Keys.None) != Keys.None) + { + mainConfig.Data.MenuKey = _pendingKeybind["Menu Key"]; + _pendingKeybind["Menu Key"] = Keys.None; + _waitingForKeybind["Menu Key"] = false; + } } + ImGui.SameLine(); + ImGui.Text("Menu Keybind"); + + if (ImGui.Button("Save Configs")) + { + mainConfig.SaveConfig(); + colorConfig.SaveConfig(); + } + ImGui.SameLine(); + if (ImGui.Button("Open Folder")) + { + string folderPath = Path.Combine(Directory.GetCurrentDirectory(), "bin\\configs"); + if (Directory.Exists(folderPath)) + { + Process.Start(new ProcessStartInfo + { + FileName = "explorer.exe", + Arguments = folderPath, + UseShellExecute = true + }); + } + else + { + LogManager.Log($"Directory doesnt exist: {folderPath}", LogManager.LogLevel.Error); + } + } + ImGuiExtensions.EndPane(); } - ImGui.SeparatorText("Logs"); - ImGui.BeginChild("Logs", new Vector2(0, -34), ImGuiChildFlags.AlwaysUseWindowPadding); - - var _LogEntries = LogManager.LogEntries; - foreach (var log in _LogEntries) + if (ImGuiExtensions.BeginPane("Logs")) { - ImGui.Text(log.ToString()); + ImGui.BeginChild("Logs", new Vector2(0, -34), ImGuiChildFlags.None, ImGuiWindowFlags.HorizontalScrollbar); + + float scrollY = ImGui.GetScrollY(); + float scrollMaxY = ImGui.GetScrollMaxY(); + bool isAtBottom = (scrollY >= scrollMaxY - 1.0f); + + var _LogEntries = LogManager.LogEntries.ToArray(); + foreach (var log in _LogEntries) + { + ImGui.Text(log.ToString()); + } + + if (scrollToBottom || isAtBottom) + { + ImGui.SetScrollHereY(1.0f); + scrollToBottom = false; + } + + ImGui.EndChild(); + ImGui.Dummy(new Vector2(0, 1)); + + if (ImGui.Button("Save Logs")) + { + LogManager.SaveLog($"bin\\logs\\{DateTime.Now.ToString("MM-dd_HH-mm-ss")}_spectrum_log.txt"); + } + + ImGui.SameLine(); + + if (ImGui.Button("Clear Logs")) + { + LogManager.ClearLog(); + } + + ImGui.SameLine(); + + if (ImGui.Button("Open Log Folder")) + { + LogManager.OpenLogFolder(); + } + ImGuiExtensions.EndPane(); } - ImGui.EndChild(); - ImGui.Dummy(new Vector2(0, 1)); - if (ImGui.Button("Save Logs")) - { - LogManager.SaveLog($"bin\\logs\\{DateTime.Now.ToString("MM-dd_HH-mm-ss")}_spectrum_log.txt"); - } - - ImGui.SameLine(); - - if (ImGui.Button("Clear Logs")) - { - LogManager.ClearLog(); - } - - ImGui.SameLine(); - - if (ImGui.Button("Open Log Folder")) - { - LogManager.OpenLogFolder(); - } ImGui.EndTabItem(); } @@ -428,12 +619,19 @@ namespace Spectrum if (mainConfig.Data.DrawFOV) { - AddRect(new Rectangle( - ((screenSize.width - mainConfig.Data.ImageWidth) / 2) - 1, - ((screenSize.height - mainConfig.Data.ImageHeight) / 2) - 1, - mainConfig.Data.ImageWidth + 2, - mainConfig.Data.ImageHeight + 2 - ), mainConfig.Data.FOVColor); + if (mainConfig.Data.FOVType == FovType.Rectangle) + { + AddRect(new Rectangle( + ((screenSize.width - mainConfig.Data.ImageWidth) / 2) - 1, + ((screenSize.height - mainConfig.Data.ImageHeight) / 2) - 1, + mainConfig.Data.ImageWidth + 2, + mainConfig.Data.ImageHeight + 2 + ), mainConfig.Data.FOVColor); + } + else if (mainConfig.Data.FOVType == FovType.Circle) + { + AddCircle(new Vector2(screenSize.width / 2, screenSize.height / 2), mainConfig.Data.ImageWidth / 2, mainConfig.Data.FOVColor, 100, 1.0f); + } } List> _drawCommands; @@ -469,6 +667,8 @@ namespace Spectrum style.WindowPadding = new Vector2(8, 8); style.FramePadding = new Vector2(6, 3); style.ItemSpacing = new Vector2(8, 4); + style.ScrollbarRounding = 6.0f; + style.ScrollbarSize = 12.0f; colors[(int)ImGuiCol.WindowBg] = new Vector4(0.10f, 0.10f, 0.12f, 1.0f); colors[(int)ImGuiCol.ChildBg] = new Vector4(0.12f, 0.12f, 0.14f, 1.0f); @@ -525,7 +725,10 @@ namespace Spectrum colors[(int)ImGuiCol.NavWindowingDimBg] = new Vector4(0.20f, 0.20f, 0.20f, 0.20f); colors[(int)ImGuiCol.ModalWindowDimBg] = new Vector4(0.10f, 0.10f, 0.10f, 0.35f); - + colors[(int)ImGuiCol.ScrollbarBg] = new Vector4(0.15f, 0.15f, 0.18f, 1.0f); + colors[(int)ImGuiCol.ScrollbarGrab] = new Vector4(0.31f, 0.31f, 0.34f, 1.0f); + 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) { @@ -554,16 +757,23 @@ namespace Spectrum } } - public void AddText(Vector2 pos, Vector4 color, string text) + public void AddText(Vector2 pos, Vector4 color, string text, int fontSize = 16) { if (string.IsNullOrEmpty(text)) return; lock (drawCommandsLock) { - drawCommands.Add(drawList => drawList.AddText(pos, ColorFromVector4(color), text)); + drawCommands.Add(drawList => drawList.AddText(ImGui.GetFont(), fontSize, pos, ColorFromVector4(color), text)); } } + public Vector2 GetTextWidth(string text, int fontSize = 16) + { + if (string.IsNullOrEmpty(text)) + return new Vector2(0, 0); + return ImGui.CalcTextSize(text, 0, text.Length, fontSize); + } + private static uint ColorFromVector4(Vector4 color) { int r = (int)(Math.Clamp(color.X, 0f, 1f) * 255.0f); @@ -573,4 +783,276 @@ namespace Spectrum return (uint)((a << 24) | (b << 16) | (g << 8) | r); } } -} + public static class ImGuiExtensions + { + private static readonly Dictionary _sliderEditBuffers = new(); + public static bool SliderFill(string label, ref float value, float min, float max, string format = "%.2f") + { + bool changed = false; + + string FormatValue(float v) + { + if (string.IsNullOrEmpty(format)) + return v.ToString(CultureInfo.InvariantCulture); + + bool percent = format.Contains("%%"); + string core = format.Replace("%%", ""); + + string result; + if (core.Contains("%d")) + { + result = ((int)Math.Round(v)).ToString(CultureInfo.InvariantCulture); + } + else + { + int pos = core.IndexOf("%."); + if (pos >= 0) + { + int fPos = core.IndexOf('f', pos + 2); + if (fPos > pos) + { + string digits = core.Substring(pos + 2, fPos - (pos + 2)); + if (int.TryParse(digits, out int prec)) + result = v.ToString("F" + prec, CultureInfo.InvariantCulture); + else + result = v.ToString("F2", CultureInfo.InvariantCulture); + } + else + result = v.ToString("F2", CultureInfo.InvariantCulture); + } + else if (core.Contains("%f")) + { + result = v.ToString("F2", CultureInfo.InvariantCulture); + } + else + { + result = v.ToString(core, CultureInfo.InvariantCulture); + } + } + if (percent) result += "%"; + return result; + } + + ImGui.TextUnformatted(label); + string valueStr = FormatValue(value); + ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(valueStr).X + 12); + ImGui.TextUnformatted(valueStr); + + float sliderWidth = ImGui.GetContentRegionAvail().X; + float sliderHeight = ImGui.GetFrameHeight(); + + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero); + ImGui.InvisibleButton("##" + label, new Vector2(sliderWidth, sliderHeight)); + bool active = ImGui.IsItemActive(); + bool activated = ImGui.IsItemActivated(); + var io = ImGui.GetIO(); + + if (activated && (io.KeyCtrl)) + { + string popupId = $"##SliderFillEditPopup_{label}"; + string seed = value.ToString(CultureInfo.InvariantCulture); + if (!_sliderEditBuffers.ContainsKey(label)) + _sliderEditBuffers[label] = seed; + ImGui.OpenPopup(popupId); + } + + if (active && !io.KeyCtrl) + { + float mouseDelta = ImGui.GetIO().MousePos.X - ImGui.GetItemRectMin().X; + float newValue = min + (mouseDelta / sliderWidth) * (max - min); + newValue = Math.Clamp(newValue, min, max); + if (format.Contains("%d")) + { + newValue = (int)Math.Round(newValue); + } + else + { + int pos = format.IndexOf("%."); + if (pos >= 0) + { + int fPos = format.IndexOf('f', pos + 2); + if (fPos > pos) + { + string digits = format.Substring(pos + 2, fPos - (pos + 2)); + if (int.TryParse(digits, out int prec)) + newValue = (float)Math.Round(newValue, prec); + } + } + } + if (Math.Abs(newValue - value) > float.Epsilon) + { + value = newValue; + changed = true; + } + } + + string popupIdOuter = $"##SliderFillEditPopup_{label}"; + if (ImGui.BeginPopup(popupIdOuter)) + { + ImGui.TextUnformatted(label); + ImGui.Separator(); + ImGui.PushItemWidth(-1); + string buffer = value.ToString(CultureInfo.InvariantCulture); + ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 4)); + var inputFlags = ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.CharsNoBlank; + if (ImGui.InputText($"##SliderFillEdit_{label}", ref buffer, 32, inputFlags)) + { + string parseStr = buffer.Trim(); + if (parseStr.EndsWith("%")) parseStr = parseStr.TrimEnd('%'); + if (float.TryParse(parseStr, NumberStyles.Float, CultureInfo.InvariantCulture, out float typed)) + { + float clamped = Math.Clamp(typed, min, max); + if (Math.Abs(clamped - value) > float.Epsilon) + { + value = clamped; + changed = true; + } + } + ImGui.CloseCurrentPopup(); + } + ImGui.PopStyleVar(); + + _sliderEditBuffers[label] = buffer; + if (ImGui.IsKeyPressed(ImGuiKey.Escape)) + { + ImGui.CloseCurrentPopup(); + } + ImGui.PopItemWidth(); + ImGui.EndPopup(); + } + + var drawList = ImGui.GetWindowDrawList(); + Vector2 p0 = ImGui.GetItemRectMin(); + Vector2 p1 = ImGui.GetItemRectMax(); + + drawList.AddRectFilled(p0, p1, ImGui.GetColorU32(ImGuiCol.FrameBg), 4f); + + float fillWidth = ((value - min) / (max - min)) * (p1.X - p0.X); + drawList.AddRectFilled(p0, new Vector2(p0.X + fillWidth, p1.Y), ImGui.GetColorU32(ImGuiCol.SliderGrabActive), 4f); + + ImGui.PopStyleVar(); + + return changed; + } + + public static bool SliderFill(string label, ref int value, int min, int max) + { + float temp = value; + bool changed = SliderFill(label, ref temp, min, max, ""); + if (changed) + value = (int)Math.Round(temp); + return changed; + } + private class PaneGroupState + { + public string Id = ""; + public int Count; + public float Spacing; + public int Index; + public float Width; + public Vector2? Padding; + public ImGuiChildFlags ChildFlags; + public ImGuiWindowFlags WindowFlags; + public float Height; + } + + private static readonly Stack _paneGroups = new(); + private static readonly Stack _paneInnerStack = new(); + + public static void BeginPaneGroup(string id, int count, float spacing = 12f, + Vector2? padding = null, + ImGuiChildFlags childFlags = ImGuiChildFlags.None, + ImGuiWindowFlags windowFlags = ImGuiWindowFlags.None, + float height = 0f) + { + if (count < 1) count = 1; + var avail = ImGui.GetContentRegionAvail(); + float width = (avail.X - spacing * (count - 1)) / count; + _paneGroups.Push(new PaneGroupState + { + Id = id, + Count = count, + Spacing = spacing, + Index = 0, + Width = width, + Padding = padding, + ChildFlags = childFlags, + WindowFlags = windowFlags, + Height = height <= 0 ? avail.Y : height + }); + } + + public static bool BeginPane(string localId, bool showHeader = true) + { + var g = _paneGroups.Peek(); + if (g.Index > 0) + ImGui.SameLine(0, g.Spacing); + + string outerId = $"{g.Id}_{g.Index}_{localId}_OUTER"; + bool outerOpen = ImGui.BeginChild(outerId, new Vector2(g.Width, g.Height), ImGuiChildFlags.None); + if (!outerOpen) + { + ImGui.EndChild(); + _paneInnerStack.Push(false); + return false; + } + + var style = ImGui.GetStyle(); + float padX = (g.Padding?.X ?? style.WindowPadding.X); + float padY = (g.Padding?.Y ?? style.WindowPadding.Y); + + float headerHeight = 0f; + if (showHeader) + { + string headerText = localId; + float textHeight = ImGui.GetTextLineHeight(); + headerHeight = textHeight + style.FramePadding.Y * 2f; + + Vector2 headerMin = ImGui.GetCursorScreenPos(); + + Vector2 headerMax = new Vector2(headerMin.X + g.Width, headerMin.Y + headerHeight); + + var drawList = ImGui.GetWindowDrawList(); + uint bgCol = ImGui.GetColorU32(ImGuiCol.FrameBg); + uint borderCol = ImGui.GetColorU32(ImGuiCol.Border); + drawList.AddRectFilled(headerMin, headerMax, bgCol, style.ChildRounding); + drawList.AddLine(new Vector2(headerMin.X, headerMax.Y - 1), new Vector2(headerMax.X, headerMax.Y - 1), borderCol); + drawList.AddRect(headerMin, headerMax, borderCol, style.ChildRounding); + + ImGui.SetCursorPos(new Vector2(padX, style.FramePadding.Y)); + ImGui.TextUnformatted(headerText); + } + + float innerHeight = g.Height - headerHeight; + if (innerHeight < 0) innerHeight = 0; + ImGui.SetCursorPos(new Vector2(0, headerHeight)); + + bool pushedPad = false; + if (g.Padding.HasValue) + { + ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, g.Padding.Value); + pushedPad = true; + } + + bool innerOpen = ImGui.BeginChild($"{outerId}_INNER", new Vector2(0, innerHeight), ImGuiChildFlags.AlwaysUseWindowPadding); + _paneInnerStack.Push(pushedPad); + return innerOpen; + } + + public static void EndPane() + { + var g = _paneGroups.Peek(); + bool hadPad = _paneInnerStack.Pop(); + ImGui.EndChild(); // inner + if (hadPad) ImGui.PopStyleVar(); + ImGui.EndChild(); // outer + g.Index++; + } + + public static void EndPaneGroup() + { + var g = _paneGroups.Pop(); + g.Index = g.Count; + } + } +} \ No newline at end of file diff --git a/Spectrum/Spectrum.csproj b/Spectrum/Spectrum.csproj index 65a0e5a..3ae5f2d 100644 --- a/Spectrum/Spectrum.csproj +++ b/Spectrum/Spectrum.csproj @@ -8,6 +8,9 @@ False true True + True + + AnyCPU;x64 @@ -24,6 +27,7 @@ + diff --git a/Spectrum/Spectrum.sln b/Spectrum/Spectrum.sln index 6665c7d..591aad7 100644 --- a/Spectrum/Spectrum.sln +++ b/Spectrum/Spectrum.sln @@ -7,13 +7,19 @@ EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.ActiveCfg = Debug|x64 + {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Debug|x64.Build.0 = Debug|x64 {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.ActiveCfg = Release|Any CPU {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|Any CPU.Build.0 = Release|Any CPU + {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.ActiveCfg = Release|x64 + {C33459B7-8D67-9FB2-0CDB-25002B06AE60}.Release|x64.Build.0 = Release|x64 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE