19 Commits
Author SHA1 Message Date
whoswhip 3c227396a3 fix: autolabeling save paths 2025-08-14 03:37:59 -04:00
whoswhip 5800221000 Update README.md 2025-08-14 03:14:22 -04:00
whoswhip 03596041d3 chore: better image for readme 2025-08-14 03:13:33 -04:00
whoswhip c4013a2adc chore: update spectrum image in readme 2025-08-14 03:12:15 -04:00
whoswhip 181e234bb2 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
2025-08-14 03:08:59 -04:00
whoswhip e2aaf54216 chore(deps): update nuget packages 2025-08-13 00:13:35 -04:00
whoswhip 0fbc91fde4 feat(config): add TriggerBot and DebugMode properties
- Added `TriggerBot` and `DebugMode` properties to the `Config` class.
- Introduced performance tracking with `iterationCount`, `totalTime`, and `stopwatch` in `Program.cs`.
- Modified key state check to restart the stopwatch for accurate timing.
- Adjusted contour area threshold from `100` to `50` for better processing.
- Implemented logging for iterations and average FPS when `DebugMode` is enabled.
- Added UI checkbox in the `Renderer` class to toggle `DebugMode`.
2025-07-19 07:57:48 -04:00
whoswhip d8a71f9d91 fix(logs): optimize log entry retrieval
Refactor the log entry retrieval in Renderer.cs to use the
LogManager's LogEntries collection directly instead of
converting it to a list. This change improves performance
by reducing overhead, especially for larger collections.
2025-07-19 07:56:39 -04:00
whoswhip c4075c4894 feat: replace POINT struct and add trigger bot feature
Refactor `InputManager.cs` to use the built-in `Point` struct for improved readability. Introduced a new `ClickMouse` method to manage mouse click events based on the current position and trigger bot functionality. Updated `Renderer.cs` to add a checkbox for enabling/disabling the trigger bot in the user interface.
2025-07-19 07:56:24 -04:00
whoswhip 07de8e3012 Merge branch 'master' of https://github.com/whoswhip/Spectrum 2025-07-17 20:01:15 -04:00
whoswhip dce1f835f0 feat(config): add MenuKey for dynamic menu toggling
- Introduced `MenuKey` property in `Config.cs` for user-defined menu toggling.
- Updated key state checks in `Program.cs` to utilize `MenuKey`.
- Refactored keybind handling in `Renderer.cs` to use dictionaries for "Aiming" and "Menu Key".
- Enhanced UI to allow dynamic keybind setting and listening.
- Changed tab item name from "Misc." to "Settings".
2025-07-17 20:00:44 -04:00
whoswhip 3ff7bee7c7 Update README.md 2025-07-17 19:59:48 -04:00
whoswhip f89fd135b4 feat: enhance color management and detection options 2025-07-17 19:46:53 -04:00
whoswhip 51744ca9c7 fix(renderer): improve child window layout in logs
Updated the `ImGui.BeginChild` call to include the
`ImGuiChildFlags.AlwaysUseWindowPadding` flag for better
layout behavior. Removed unnecessary indentation
operations for log entries, streamlining the rendering
process.
2025-07-16 23:00:42 -04:00
whoswhip 4b4cebd517 fix: create directories before loading configs 2025-07-16 22:57:24 -04:00
whoswhip 55bc1e9c3a feat: use imgui for UI and refactor configurations
- Updated `AutoLabeling.cs` to use `LogManager` for error logging and a new `mainConfig` object for configuration settings.
- Transformed `Config.cs` into a generic `ConfigManager<T>` class, encapsulating settings in a new `ConfigData` class for better organization.
- Enhanced `InputManager.cs` to utilize the new configuration structure and added smoothing functionality for mouse movement.
- Modified `Program.cs` to initialize `mainConfig` and `colorConfig`, improving key event handling.
- Updated `Spectrum.csproj` to target `net8.0-windows` and added new package references.
- Created `FodyWeavers.xml` to include the `Costura` weaver for dependency embedding.
- Introduced `LogManager.cs` for centralized logging functionality.
- Added `Renderer.cs` for rendering overlays with ImGui, integrating with the new configuration system.
2025-07-16 22:52:02 -04:00
whoswhip 859e2e1b43 Update README.md 2025-07-07 02:42:09 -04:00
whoswhip dd13b99249 Clean up code 2025-06-18 13:41:31 -04:00
whoswhip f8b90d7b63 Optimizations and fix memory leak/build up by disposing the mats 2025-06-17 21:11:01 -04:00
17 changed files with 3042 additions and 654 deletions
+6 -46
View File
@@ -1,55 +1,15 @@
# Spectrum
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
<img width="600" height="502" alt="Spectrum Menu" src="https://upld.zip/d9Z8Evjm.png" />
## Features
- Extensive configuration file
- Dataset collection
- Multiple mouse movement paths
## Configuration
On first run, a default configuration file is created.
### Parameters
#### `ImageSettings`
`ImageWidth`: 1 - ScreenSize (Default: 640)
`ImageHeight`: 1 - ScreenSize (Default: 640)
#### `OffsetSettings
`YOffsetPercent`: 0.0 - 1 (Default: 0.8)
`XOffsetPercent`: 0.0 - 1 (Default: 0.5)
#### `AimSettings`
`EnableAim`: true or false (Default: true)
`ClosestToMouse`: true or false (Default: true)
`Keybind`: 1 - 254 (Default: 6), these are [virtual key codes](https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes)
`Sensitivity`: 0.1 - 2 (Default: 0.5)
`AimMovementType`: CubicBezier, Linear & Adaptive (Default: CubicBezier)
#### `DisplaySettings`
`ShowDetectionWindow`: true or false (Default: true)
#### `DataCollectionSettings`
`CollectData`: true or false (Default: false)
`AutoLabel`: true or false (Default: false), this is dependent on `CollectData`
`BackgroundImageInterval`: 1 - 100 (Default: 10)
#### `ColorSettings`
`UpperHSV`
- `Val0`: 0 - 255 (Default: 150) Hue
- `Val1`: 0 - 255 (Default: 255) Saturation
- `Val2`: 0 - 255 (Default: 229) Value
- `Val3`: 0 (Default: 0) ?
`LowerHSV`
- `Val0`: 0 - 255 (Default: 150) Hue
- `Val1`: 0 - 255 (Default: 255) Saturation
- `Val2`: 0 - 255 (Default: 229) Value
- `Val3`: 0 (Default: 0) ?
- IMGui Menu
- FOV Overlay
- Detection Overlay
- Triggerbot
- Makcu Support
## Dataset Collection
When `CollectData` and `AutoLabel` are enabled, Spectrum automatically generates:
+134 -208
View File
@@ -1,257 +1,183 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OpenCvSharp;
using System.Numerics;
using System.Security.Cryptography.X509Certificates;
using LogLevel = Spectrum.LogManager.LogLevel;
namespace Spectrum
{
public static class Config
public class ConfigManager<T> where T : new()
{
private static FileSystemWatcher? _configWatcher;
#region Variables
private readonly string _fileName;
private FileSystemWatcher? _watcher;
private T _data;
public enum MovementType
public T Data => _data;
public ConfigManager(string fileName)
{
Linear,
CubicBezier,
QuadraticBezier,
Adaptive
_fileName = fileName;
_data = new T();
LoadConfig();
}
// Image settings
public static int ImageWidth { get; set; } = 640;
public static int ImageHeight { get; set; } = 640;
// Offset settings
public static double YOffsetPercent { get; set; } = 0.8;
public static double XOffsetPercent { get; set; } = 0.5;
// Aim settings
public static bool EnableAim { get; set; } = true;
public static bool ClosestToMouse { get; set; } = true; // if false it will use the center of the screen
public static int Keybind { get; set; } = 0x06; // first side button on mouse
public static double Sensitivity { get; set; } = 0.5;
public static MovementType AimMovementType { get; set; } = MovementType.CubicBezier;
// Display settings
public static bool ShowDetectionWindow { get; set; } = true;
// Data collection settings
public static bool CollectData { get; set; } = false;
public static bool AutoLabel { get; set; } = false; // collect data needs to be enabled
public static int BackgroundImageInterval { get; set; } = 10; // after 10 loops with no detection, save a background image
// Color settings
public static Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
public static Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
#endregion
public static void LoadConfig(bool silent = false)
public void LoadConfig(bool silent = false)
{
if (File.Exists("config.json"))
if (File.Exists(_fileName))
{
string config_content = File.ReadAllText("config.json");
try
{
var config = JObject.Parse(config_content);
bool error = false;
var imageSettings = config["ImageSettings"];
ImageWidth = imageSettings?["ImageWidth"]?.Value<int>() ?? config["ImageWidth"]?.Value<int>() ?? ImageWidth;
ImageHeight = imageSettings?["ImageHeight"]?.Value<int>() ?? config["ImageHeight"]?.Value<int>() ?? ImageHeight;
var offsetSettings = config["OffsetSettings"];
YOffsetPercent = offsetSettings?["YOffsetPercent"]?.Value<double>() ?? config["YOffsetPercent"]?.Value<double>() ?? YOffsetPercent;
XOffsetPercent = offsetSettings?["XOffsetPercent"]?.Value<double>() ?? config["XOffsetPercent"]?.Value<double>() ?? XOffsetPercent;
var aimSettings = config["AimSettings"];
EnableAim = aimSettings?["EnableAim"]?.Value<bool>() ?? config["EnableAim"]?.Value<bool>() ?? EnableAim;
ClosestToMouse = aimSettings?["ClosestToMouse"]?.Value<bool>() ?? config["ClosestToMouse"]?.Value<bool>() ?? ClosestToMouse;
Keybind = aimSettings?["Keybind"]?.Value<int>() ?? config["Keybind"]?.Value<int>() ?? Keybind;
Sensitivity = aimSettings?["Sensitivity"]?.Value<double>() ?? config["Sensitivity"]?.Value<double>() ?? Sensitivity;
AimMovementType = aimSettings?["AimMovementType"]?.Value<string>() switch
{
"Linear" => MovementType.Linear,
"CubicBezier" => MovementType.CubicBezier,
"Adaptive" => MovementType.Adaptive,
_ => AimMovementType
};
var displaySettings = config["DisplaySettings"];
ShowDetectionWindow = displaySettings?["ShowDetectionWindow"]?.Value<bool>() ?? config["ShowDetectionWindow"]?.Value<bool>() ?? ShowDetectionWindow;
var dataSettings = config["DataCollectionSettings"];
CollectData = dataSettings?["CollectData"]?.Value<bool>() ?? config["CollectData"]?.Value<bool>() ?? CollectData;
AutoLabel = dataSettings?["AutoLabel"]?.Value<bool>() ?? config["AutoLabel"]?.Value<bool>() ?? AutoLabel;
BackgroundImageInterval = dataSettings?["BackgroundImageInterval"]?.Value<int>() ?? config["BackgroundImageInterval"]?.Value<int>() ?? BackgroundImageInterval;
var colorSettings = config["ColorSettings"];
UpperHSV = colorSettings?["UpperHSV"]?.ToObject<Scalar>() ?? config["UpperHSV"]?.ToObject<Scalar>() ?? UpperHSV;
LowerHSV = colorSettings?["LowerHSV"]?.ToObject<Scalar>() ?? config["LowerHSV"]?.ToObject<Scalar>() ?? LowerHSV;
if (ImageWidth <= 0 || ImageHeight <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid image dimensions in config.json, using default values.");
Console.ResetColor();
ImageWidth = 640;
ImageHeight = 640;
error = true;
}
if (YOffsetPercent < 0 || YOffsetPercent > 1 || XOffsetPercent < 0 || XOffsetPercent > 1)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid offset percentages in config.json, using default values.");
Console.ResetColor();
YOffsetPercent = 0.8;
XOffsetPercent = 0.5;
error = true;
}
if (Keybind < 0 || Keybind > 255)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid keybind in config.json, using default value.");
Console.ResetColor();
Keybind = 0x06;
error = true;
}
if (Sensitivity < 0 || Sensitivity > 2)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid sensitivity in config.json, using default value.");
Console.ResetColor();
Sensitivity = 0.5;
error = true;
}
if (AutoLabel && !CollectData )
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] AutoLabel is enabled but CollectData is not. Disabling AutoLabel.");
Console.ResetColor();
AutoLabel = false;
error = true;
}
if (BackgroundImageInterval <= 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Invalid BackgroundImageInterval in config.json, using default value.");
Console.ResetColor();
error = true;
}
if (error)
SaveConfig();
if (!silent)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Configuration loaded successfully.");
Console.ResetColor();
}
var json = File.ReadAllText(_fileName);
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info);
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Error parsing config.json, using default values.");
Console.ResetColor();
LogManager.Log($"Failed to parse {_fileName}, using default values.", LogLevel.Error);
_data = new T();
SaveConfig();
}
}
else
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] config.json not found, using default values.");
Console.ResetColor();
LogManager.Log($"{_fileName} not found, creating a new one with default values.", LogLevel.Error);
_data = new T();
SaveConfig();
}
} public static void SaveConfig()
{
var config = new JObject
{
["ImageSettings"] = new JObject
{
["ImageWidth"] = ImageWidth,
["ImageHeight"] = ImageHeight
},
["OffsetSettings"] = new JObject
{
["YOffsetPercent"] = YOffsetPercent,
["XOffsetPercent"] = XOffsetPercent
},
["AimSettings"] = new JObject
{
["EnableAim"] = EnableAim,
["ClosestToMouse"] = ClosestToMouse,
["Keybind"] = Keybind,
["Sensitivity"] = Sensitivity,
["AimMovementType"] = AimMovementType.ToString()
},
["DisplaySettings"] = new JObject
{
["ShowDetectionWindow"] = ShowDetectionWindow
},
["DataCollectionSettings"] = new JObject
{
["CollectData"] = CollectData,
["AutoLabel"] = AutoLabel,
["BackgroundImageInterval"] = BackgroundImageInterval
},
["ColorSettings"] = new JObject
{
["UpperHSV"] = JToken.FromObject(UpperHSV),
["LowerHSV"] = JToken.FromObject(LowerHSV)
}
}; File.WriteAllText("config.json", config.ToString(Formatting.Indented));
}
public static void StartFileWatcher()
public void SaveConfig()
{
if (_configWatcher != null)
return;
File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented));
}
_configWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), "config.json")
public void StartFileWatcher()
{
if (_watcher != null) return;
_watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName)
{
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
};
_configWatcher.Changed += OnConfigFileChanged;
_configWatcher.EnableRaisingEvents = true;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] File watcher started for config.json");
Console.ResetColor();
_watcher.Changed += OnConfigFileChanged;
_watcher.EnableRaisingEvents = true;
LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info);
}
public static void StopFileWatcher()
public void StopFileWatcher()
{
if (_configWatcher != null)
{
_configWatcher.EnableRaisingEvents = false;
_configWatcher.Changed -= OnConfigFileChanged;
_configWatcher.Dispose();
_configWatcher = null;
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("[INFO] File watcher stopped for config.json");
Console.ResetColor();
}
if (_watcher == null) return;
_watcher.EnableRaisingEvents = false;
_watcher.Changed -= OnConfigFileChanged;
_watcher.Dispose();
_watcher = null;
LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info);
}
private static void OnConfigFileChanged(object sender, FileSystemEventArgs e)
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
{
Thread.Sleep(100);
try
{
LoadConfig(true);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Configuration automatically reloaded due to file change.");
Console.ResetColor();
LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info);
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"[ERROR] Failed to reload configuration: {ex.Message}");
Console.ResetColor();
LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error);
}
}
}
public enum MovementType
{
Linear,
CubicBezier,
QuadraticBezier,
Adaptive
}
public 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;
public double XOffsetPercent { get; set; } = 0.5;
// Aim settings
public bool EnableAim { get; set; } = true;
public bool ClosestToMouse { get; set; } = true;
public Keys Keybind { get; set; } = Keys.XButton2;
public double Sensitivity { get; set; } = 0.5;
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
public bool EmaSmoothening { get; set; } = true;
public double EmaSmootheningFactor { get; set; } = 0.1;
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 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
public bool CollectData { get; set; } = false;
public bool AutoLabel { get; set; } = false;
public int BackgroundImageInterval { get; set; } = 10;
// Color settings
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
// Misc
public bool DebugMode { get; set; } = false;
}
public class ColorData
{
public List<ColorInfo> Colors { get; set; } = new List<ColorInfo>();
}
public class ColorInfo
{
public string Name { get; set; }
public Scalar Upper { get; set; }
public Scalar Lower { get; set; }
public ColorInfo(string name, Scalar upper, Scalar lower)
{
Name = name;
Upper = upper;
Lower = lower;
}
}
}
@@ -1,13 +1,9 @@
using OpenCvSharp;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LogLevel = Spectrum.LogManager.LogLevel;
namespace Spectrum
namespace Spectrum.Detection
{
public static class AutoLabeling
{
@@ -18,6 +14,8 @@ namespace Spectrum
private static Task? backgroundTask;
private static readonly ConcurrentQueue<LabelingData> labelingQueue = new ConcurrentQueue<LabelingData>();
private static readonly ConcurrentQueue<BackgroundImageData> backgroundQueue = new ConcurrentQueue<BackgroundImageData>();
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
public static bool Started = false;
private static List<YoloBoundingBox> GetBoundingBoxes(OpenCvSharp.Point[][] contours, int imageWidth, int imageHeight)
{
@@ -52,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)
{
@@ -59,22 +60,22 @@ namespace Spectrum
}
File.WriteAllText(path, labelContent.ToString());
}
catch
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to save labels to " + path);
Console.ResetColor();
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)
{
Console.WriteLine($"Error saving image: {ex.Message}");
LogManager.Log($"[ERROR] Failed to save image: {ex.Message}", LogLevel.Error);
}
}
@@ -90,9 +91,7 @@ namespace Spectrum
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to process labeling data.");
Console.ResetColor();
LogManager.Log("[ERROR] Failed to process labeling data.", LogLevel.Error);
}
}
@@ -104,9 +103,7 @@ namespace Spectrum
}
catch
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERROR] Failed to process background image data.");
Console.ResetColor();
LogManager.Log("[ERROR] Failed to process background image data.", LogLevel.Error);
}
}
@@ -114,9 +111,15 @@ namespace Spectrum
}
}
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
{
if (!Config.AutoLabel || filteredContours.Length == 0)
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
return;
if (labelingQueue.Count > 250)
return;
Mat clone = mat.Clone();
@@ -130,12 +133,12 @@ namespace Spectrum
public static void AddBackgroundImage(Mat mat, bool detected)
{
if (!Config.AutoLabel)
return;
detectionAttemps++;
if (detectionAttemps < Config.BackgroundImageInterval || detected)
if (detectionAttemps < mainConfig.Data.BackgroundImageInterval || detected)
return;
if (backgroundQueue.Count > 250)
return;
Mat clone = mat.Clone();
@@ -161,8 +164,8 @@ namespace Spectrum
string imageFileName = $"image_{imageCount:D6}.jpg";
string labelFileName = $"image_{imageCount:D6}.txt";
string imagePath = Path.Combine("dataset/images", imageFileName);
string labelPath = Path.Combine("dataset/labels", labelFileName);
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
string labelPath = Path.Combine("bin/dataset/labels", labelFileName);
SaveMatAsImage(data.Mat, imagePath);
@@ -186,7 +189,7 @@ namespace Spectrum
lock (lockObject)
{
string imageFileName = $"image_{imageCount:D6}.jpg";
string imagePath = Path.Combine("dataset/images", imageFileName);
string imagePath = Path.Combine("bin/dataset/images", imageFileName);
SaveMatAsImage(data.Mat, imagePath);
@@ -204,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));
}
@@ -211,6 +216,9 @@ namespace Spectrum
{
if (cancellationTokenSource == null)
return;
LogManager.Log("Stopping auto labeling...", LogLevel.Info);
Started = false;
cancellationTokenSource.Cancel();
backgroundTask?.Wait();
cancellationTokenSource.Dispose();
+225
View File
@@ -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<IDXGIFactory1>();
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<IDXGIOutput1>().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<ID3D11Texture2D>();
_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);
}
}
}
+261
View File
@@ -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<ConfigData> 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<int> indices)>();
for (int i = 0; i < contours.Length; i++)
{
var rect = Cv2.BoundingRect(contours[i]);
contourRects.Add((rect, new List<int> { 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<int>();
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<OpenCvSharp.Point[]>();
foreach (var (rect, indices) in contourRects)
{
var points = new List<OpenCvSharp.Point>();
foreach (var idx in indices)
{
points.AddRange(contours[idx]);
}
var hull = Cv2.ConvexHull(points);
mergedContours.Add(hull);
}
return mergedContours.ToArray();
}
}
}
+3
View File
@@ -0,0 +1,3 @@
<Weavers xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="FodyWeavers.xsd">
<Costura />
</Weavers>
@@ -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<bool> 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<bool> 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);
}
}
}
@@ -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<MakcuMouseButton, bool> _buttonStates = new Dictionary<MakcuMouseButton, bool>();
public event Action<MakcuMouseButton, bool> 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<int, MakcuMouseButton> {
{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<MakcuMouseButton, bool> GetCurrentButtonStates()
{ lock (_buttonStates) { return new Dictionary<MakcuMouseButton, bool>(_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.");
}
}
}
@@ -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);
}
}
}
+326
View File
@@ -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<ConfigData> 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<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
{
var tcs = new TaskCompletionSource<Keys>(TaskCreationOptions.RunContinuationsAsynchronously);
Action<MakcuMouseButton, bool>? 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
};
}
}
}
+96
View File
@@ -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);
}
}
}
-107
View File
@@ -1,107 +0,0 @@
using System.Drawing;
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 struct POINT
{
public int X;
public int Y;
}
// 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);
}
public static void MoveMouse(Point target)
{
POINT reference = new POINT();
if (Config.ClosestToMouse)
{
GetCursorPos(out reference);
}
else
{
// center of the screen
reference.X = SystemHelper.GetPrimaryScreenSize().Width / 2;
reference.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
}
Point start = new Point(reference.X, reference.Y);
Point end = new Point(target.X, target.Y);
Point newPosition = Config.AimMovementType switch
{
Config.MovementType.CubicBezier => CubicBezierMovement(start, end, Config.Sensitivity),
Config.MovementType.Linear => LinearInterpolation(start, end, Config.Sensitivity),
Config.MovementType.Adaptive => AdaptiveMovement(start, end, Config.Sensitivity),
Config.MovementType.QuadraticBezier => CurvedMovement(start, end, Config.Sensitivity),
_ => end
};
int deltaX = newPosition.X - reference.X;
int deltaY = newPosition.Y - reference.Y;
mouse_event(0x0001, (uint)(deltaX), (uint)(deltaY), 0, 0);
}
}
}
+81
View File
@@ -0,0 +1,81 @@
using System.Diagnostics;
using System.Text;
namespace Spectrum
{
public class LogManager
{
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
public enum LogLevel
{
Debug,
Info,
Warning,
Error,
Critical
}
public class LogEntry
{
public DateTime Timestamp { get; set; }
public LogLevel Level { get; set; }
public string Message { get; set; }
public LogEntry(LogLevel level, string message)
{
Timestamp = DateTime.Now;
Level = level;
Message = message;
}
public override string ToString()
{
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
}
}
private static List<LogEntry> _logEntries = new List<LogEntry>();
public static IReadOnlyList<LogEntry> 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));
}
public static void SaveLog(string filePath)
{
try
{
var logContent = new StringBuilder();
foreach (var entry in _logEntries)
{
logContent.AppendLine(entry.ToString());
}
File.WriteAllText(filePath, logContent.ToString());
Log($"Log saved to {filePath}", LogLevel.Info);
}
catch (Exception ex)
{
Log($"Failed to save log: {ex.Message}", LogLevel.Error);
}
}
public static void ClearLog()
{
_logEntries.Clear();
Log("Log cleared.", LogLevel.Info);
}
public static void OpenLogFolder()
{
Process.Start(new ProcessStartInfo
{
FileName = "explorer.exe",
Arguments = Directory.GetCurrentDirectory(),
UseShellExecute = true
});
}
}
}
+56 -260
View File
@@ -1,284 +1,80 @@
using OpenCvSharp;
using OpenCvSharp.Internal.Vectors;
using System.Drawing;
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;
public static ConfigManager<ConfigData> mainConfig = new ConfigManager<ConfigData>("bin\\configs\\config.json");
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
public static long iterationCount = 0;
public static long totalTime = 0;
private static DetectionManager? detectionManager;
public static CaptureManager SharedCaptureManager { get; } = new CaptureManager();
static void Main()
{
Config.LoadConfig();
Config.StartFileWatcher();
Thread renderThread = new Thread(() =>
{
try
{
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);
}
catch (Exception ex)
{
LogManager.Log($"Failed to start renderer: {ex.Message}", LogManager.LogLevel.Error);
}
});
renderThread.Start();
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();
bounds = new Rectangle(
(screenSize.Width - Config.ImageWidth) / 2,
(screenSize.Height - Config.ImageHeight) / 2,
Config.ImageWidth,
Config.ImageHeight
);
mainConfig.LoadConfig();
mainConfig.StartFileWatcher();
if (Config.ShowDetectionWindow)
{
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
Cv2.WaitKey(1);
}
if (Config.AutoLabel)
if (mainConfig.Data.AutoLabel)
{
AutoLabeling.StartLabeling();
}
Directory.CreateDirectory("dataset");
Directory.CreateDirectory("dataset/images");
Directory.CreateDirectory("dataset/labels");
while (true)
if (colorConfig.Data.Colors.Count == 0)
{
if (Console.KeyAvailable)
{
var key = Console.ReadKey(true).Key;
if (key == ConsoleKey.Escape)
{
if (Config.ShowDetectionWindow)
{
Cv2.DestroyAllWindows();
}
Config.StopFileWatcher();
Environment.Exit(0);
}
else if (key == ConsoleKey.O)
{
try
{
string configFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.json");
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = configFilePath,
UseShellExecute = true,
CreateNoWindow = true
});
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Opened config file in default application.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.WriteLine($"Failed to open config file: {ex.Message}");
}
}
else if (key == ConsoleKey.F1)
{
Config.ShowDetectionWindow = !Config.ShowDetectionWindow;
if (Config.ShowDetectionWindow)
{
Cv2.NamedWindow("Spectrum Detection", WindowFlags.AutoSize);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Enabled detection window.");
}
else
{
Cv2.DestroyAllWindows();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[INFO] Disabled detection window.");
}
Console.ResetColor();
}
else if (key == ConsoleKey.F2)
{
Config.AutoLabel = !Config.AutoLabel;
if (Config.AutoLabel)
{
Config.CollectData = true;
AutoLabeling.StartLabeling();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Enabled auto-labeling.");
}
else
{
AutoLabeling.StopLabeling();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[INFO] Disabled auto-labeling.");
}
Console.ResetColor();
}
else if (key == ConsoleKey.F3)
{
Config.CollectData = !Config.CollectData;
if (Config.CollectData)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Enabled data collection.");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[INFO] Disabled data collection.");
}
Console.ResetColor();
}
else if (key == ConsoleKey.F4)
{
Config.EnableAim = !Config.EnableAim;
if (Config.EnableAim)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Enabled aiming.");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[INFO] Disabled aiming.");
}
Console.ResetColor();
}
else if (key == ConsoleKey.F5)
{
Config.ClosestToMouse = !Config.ClosestToMouse;
if (Config.ClosestToMouse)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("[INFO] Enabled closest to mouse aiming.");
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[INFO] Disabled closest to mouse aiming.");
}
Console.ResetColor();
}
else if (key == ConsoleKey.H || key == ConsoleKey.Help)
{
Console.WriteLine("Spectrum Keybinds:");
Console.WriteLine("F1: Toggle detection window");
Console.WriteLine("F2: Toggle auto-labeling");
Console.WriteLine("F3: Toggle data collection");
Console.WriteLine("F4: Toggle aiming");
Console.WriteLine("F5: Toggle closest to mouse aiming");
Console.WriteLine("O: Open config file in default application");
Console.WriteLine("ESC: Exit the application");
Console.WriteLine("H: Show this help message");
}
else
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("[WARNING] Unrecognized key pressed. Press H for help.");
Console.ResetColor();
}
}
if (SystemHelper.GetAsyncKeyState(Config.Keybind) < 0)
{
var screenshot = CaptureScreenshot(bounds);
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
Mat drawing = mat.Clone(); // clone for drawing
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV); // convert to hsv
Cv2.InRange(mat, Config.LowerHSV, Config.UpperHSV, mat); // apply mask
Cv2.Dilate(mat, mat, null, iterations: 2); // dilate to fill gaps
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary); // threshold to binary
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 100).ToArray();
if (filteredContours.Length > 0)
{
int refX = bounds.X + bounds.Width / 2;
int refY = bounds.Y + (int)(bounds.Height * Config.YOffsetPercent);
double minDist = double.MaxValue;
OpenCvSharp.Point[]? closestContour = null;
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
foreach (var contour in filteredContours)
{
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 (closestContour != null)
{
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - Config.XOffsetPercent));
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - Config.YOffsetPercent));
int targetX = groupX + bounds.X;
int targetY = groupY + bounds.Y;
if (Config.AutoLabel)
{
AutoLabeling.AddToQueue(drawing, bounds, filteredContours);
AutoLabeling.AddBackgroundImage(drawing, true);
}
if (!Config.AutoLabel && Config.CollectData)
{
AutoLabeling.AddBackgroundImage(drawing, false);
}
if (Config.EnableAim)
{
InputManager.MoveMouse(new System.Drawing.Point(targetX, targetY));
}
if (Config.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);
}
}
}
else if (Config.ShowDetectionWindow)
{
Cv2.ImShow("Spectrum Detection", drawing);
Cv2.WaitKey(1);
}
}
else
{
if (Config.ShowDetectionWindow)
{
Cv2.WaitKey(1);
}
else
{
Thread.Sleep(1);
}
}
colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(150, 255, 229), new Scalar(150, 255, 229)));
colorConfig.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
colorConfig.SaveConfig();
colorConfig.LoadConfig(true);
mainConfig.LoadConfig(true);
}
}
public static Bitmap CaptureScreenshot(Rectangle bounds)
{
Bitmap bitmap = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bitmap))
Thread.Sleep(1000);
if (renderer == null)
{
g.CopyFromScreen(bounds.Location, System.Drawing.Point.Empty, bounds.Size);
LogManager.Log("Renderer failed to initialize. Exiting application.", LogManager.LogLevel.Error);
return;
}
return bitmap;
detectionManager = new DetectionManager(renderer);
}
}
public static class SystemHelper
+1058
View File
File diff suppressed because it is too large Load Diff
+16 -4
View File
@@ -1,21 +1,33 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishAot>true</PublishAot>
<PublishAot>False</PublishAot>
<InvariantGlobalization>true</InvariantGlobalization>
<UseWindowsForms>True</UseWindowsForms>
<AllowUnsafeBlocks>True</AllowUnsafeBlocks>
<TargetFrameworks></TargetFrameworks>
<Platforms>AnyCPU;x64</Platforms>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ClickableTransparentOverlay" Version="11.1.0" />
<PackageReference Include="Costura.Fody" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="OpenCvSharp4" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.runtime.win" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
<PackageReference Include="System.Drawing.Common" Version="9.0.6" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
<PackageReference Include="System.Drawing.Common" Version="9.0.8" />
<PackageReference Include="System.IO.Ports" Version="9.0.8" />
</ItemGroup>
</Project>
+6
View File
@@ -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