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