mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e3f39a323
|
||
|
|
cce3b91be8
|
||
|
|
f1ca1ee9ee
|
||
|
|
f0014bc65d
|
||
|
|
a6f65b1f17
|
||
|
|
3f220c7de9
|
||
|
|
b556351010
|
||
|
|
f1d376174b
|
||
|
|
4a0af6bb1b | ||
|
|
bdf3be13ab
|
||
|
|
2fa0b4ac2d
|
||
|
|
ab0ca784f4
|
||
|
|
86d7e3ffbd
|
||
|
|
c14427bf81
|
||
|
|
5832f92edc
|
||
|
|
c92517af5c
|
||
|
|
0deecc8663
|
||
|
|
d0d417e6ab
|
@@ -1,6 +1,6 @@
|
|||||||
# Spectrum
|
# Spectrum
|
||||||
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
Spectrum is a semi-universal colorbot that uses C# and OpenCV for image processing.
|
||||||
<img width="600" height="502" alt="Spectrum Menu" src="https://upld.zip/d9Z8Evjm.png" />
|
<img width="700" height="603" alt="Spectrum Menu" src="https://upld.zip/PYRXWN5Y.png" />
|
||||||
## Features
|
## Features
|
||||||
- Extensive configuration file
|
- Extensive configuration file
|
||||||
- Dataset collection
|
- Dataset collection
|
||||||
|
|||||||
+307
-60
@@ -1,77 +1,279 @@
|
|||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using OpenCvSharp;
|
using OpenCvSharp;
|
||||||
using System.Numerics;
|
using System.Numerics;
|
||||||
using System.Security.Cryptography.X509Certificates;
|
|
||||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||||
|
|
||||||
namespace Spectrum
|
namespace Spectrum
|
||||||
{
|
{
|
||||||
public class ConfigManager<T> where T : new()
|
public class ConfigManager<T> where T : new()
|
||||||
{
|
{
|
||||||
private readonly string _fileName;
|
private readonly string _defaultFilename;
|
||||||
private FileSystemWatcher? _watcher;
|
private readonly string _configDirectory;
|
||||||
|
private FileSystemWatcher? _fileWatcher;
|
||||||
|
private FileSystemWatcher? _directoryWatcher;
|
||||||
private T _data;
|
private T _data;
|
||||||
|
private string _currentConfigName;
|
||||||
|
private List<string> _availableConfigs;
|
||||||
|
|
||||||
public T Data => _data;
|
public T Data => _data;
|
||||||
|
public string CurrentConfigName => _currentConfigName;
|
||||||
|
public IReadOnlyList<string> AvailableConfigs => _availableConfigs.AsReadOnly();
|
||||||
|
|
||||||
public ConfigManager(string fileName)
|
public ConfigManager(string fileName, string configDirectory = "configs")
|
||||||
{
|
{
|
||||||
_fileName = fileName;
|
_defaultFilename = fileName;
|
||||||
|
_configDirectory = configDirectory;
|
||||||
|
_currentConfigName = Path.GetFileNameWithoutExtension(fileName);
|
||||||
_data = new T();
|
_data = new T();
|
||||||
|
_availableConfigs = [];
|
||||||
|
|
||||||
|
if (!Directory.Exists(_configDirectory))
|
||||||
|
{
|
||||||
|
Directory.CreateDirectory(_configDirectory);
|
||||||
|
}
|
||||||
|
|
||||||
|
UpdateAvailableConfigs();
|
||||||
|
StartDirectoryWatcher();
|
||||||
LoadConfig();
|
LoadConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void LoadConfig(bool silent = false)
|
public void LoadConfig(string filename = "")
|
||||||
{
|
{
|
||||||
if (File.Exists(_fileName))
|
if (string.IsNullOrEmpty(filename))
|
||||||
|
filename = _defaultFilename;
|
||||||
|
|
||||||
|
try
|
||||||
{
|
{
|
||||||
try
|
if (File.Exists(filename))
|
||||||
{
|
{
|
||||||
var json = File.ReadAllText(_fileName);
|
try
|
||||||
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
|
{
|
||||||
if (!silent) LogManager.Log($"Loaded config {_fileName}.", LogLevel.Info);
|
var json = File.ReadAllText(filename);
|
||||||
|
_data = JsonConvert.DeserializeObject<T>(json) ?? new T();
|
||||||
|
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
LogManager.Log($"Failed to parse {filename}, using default values.", LogLevel.Error);
|
||||||
|
_data = new T();
|
||||||
|
SaveConfig();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
catch
|
else
|
||||||
{
|
{
|
||||||
LogManager.Log($"Failed to parse {_fileName}, using default values.", LogLevel.Error);
|
LogManager.Log($"{filename} not found, creating a new one with default values.", LogLevel.Error);
|
||||||
_data = new T();
|
_data = new T();
|
||||||
SaveConfig();
|
SaveConfig();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
LogManager.Log($"{_fileName} not found, creating a new one with default values.", LogLevel.Error);
|
LogManager.Log($"Error loading config {filename}: {ex.Message}", LogLevel.Error);
|
||||||
_data = new T();
|
_data = new T();
|
||||||
SaveConfig();
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void SaveConfig()
|
public void SaveConfig(string filename = "")
|
||||||
{
|
{
|
||||||
File.WriteAllText(_fileName, JsonConvert.SerializeObject(_data, Formatting.Indented));
|
if (string.IsNullOrEmpty(filename))
|
||||||
|
filename = _defaultFilename;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.WriteAllText(filename, JsonConvert.SerializeObject(_data, Formatting.Indented));
|
||||||
|
_currentConfigName = Path.GetFileNameWithoutExtension(filename);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error saving config {filename}: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public void SaveConfigToDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
SaveConfig(filePath);
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool LoadConfigFromDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {configName} not found in directory.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
LoadConfig(filePath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateAvailableConfigs()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (!Directory.Exists(_configDirectory))
|
||||||
|
{
|
||||||
|
_availableConfigs.Clear();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var configs = Directory.GetFiles(_configDirectory, "*.json")
|
||||||
|
.Select(Path.GetFileNameWithoutExtension)
|
||||||
|
.Where(name => !string.IsNullOrEmpty(name))
|
||||||
|
.Cast<string>()
|
||||||
|
.ToList();
|
||||||
|
|
||||||
|
_availableConfigs.Clear();
|
||||||
|
_availableConfigs.AddRange(configs);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating available configs: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StartDirectoryWatcher()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_directoryWatcher != null) return;
|
||||||
|
|
||||||
|
_directoryWatcher = new FileSystemWatcher(_configDirectory, "*.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 directory watcher: {ex.Message}", LogLevel.Error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void StopDirectoryWatcher()
|
||||||
|
{
|
||||||
|
if (_directoryWatcher == null) return;
|
||||||
|
|
||||||
|
_directoryWatcher.EnableRaisingEvents = false;
|
||||||
|
_directoryWatcher.Created -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Deleted -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Renamed -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Changed -= OnDirectoryChanged;
|
||||||
|
_directoryWatcher.Dispose();
|
||||||
|
_directoryWatcher = null;
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OnDirectoryChanged(object sender, FileSystemEventArgs e)
|
||||||
|
{
|
||||||
|
Thread.Sleep(50);
|
||||||
|
UpdateAvailableConfigs();
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool DeleteConfigFromDirectory(string configName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(configName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config name cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var filePath = Path.Combine(_configDirectory, $"{configName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(filePath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {configName} not found.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Delete(filePath);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error deleting config {configName}: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public bool RenameConfigInDirectory(string oldName, string newName)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(oldName) || string.IsNullOrEmpty(newName))
|
||||||
|
{
|
||||||
|
LogManager.Log("Config names cannot be empty.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var oldPath = Path.Combine(_configDirectory, $"{oldName}.json");
|
||||||
|
var newPath = Path.Combine(_configDirectory, $"{newName}.json");
|
||||||
|
|
||||||
|
if (!File.Exists(oldPath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {oldName} not found.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (File.Exists(newPath))
|
||||||
|
{
|
||||||
|
LogManager.Log($"Config {newName} already exists.", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
File.Move(oldPath, newPath);
|
||||||
|
if (_currentConfigName == oldName)
|
||||||
|
_currentConfigName = newName;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error renaming config: {ex.Message}", LogLevel.Error);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public void StartFileWatcher()
|
public void StartFileWatcher()
|
||||||
{
|
{
|
||||||
if (_watcher != null) return;
|
if (_fileWatcher != null) return;
|
||||||
|
|
||||||
_watcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _fileName)
|
_fileWatcher = new FileSystemWatcher(Directory.GetCurrentDirectory(), _defaultFilename)
|
||||||
{
|
{
|
||||||
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
|
NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size
|
||||||
};
|
};
|
||||||
_watcher.Changed += OnConfigFileChanged;
|
_fileWatcher.Changed += OnConfigFileChanged;
|
||||||
_watcher.EnableRaisingEvents = true;
|
_fileWatcher.EnableRaisingEvents = true;
|
||||||
LogManager.Log($"File watcher started for {_fileName}.", LogLevel.Info);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public void StopFileWatcher()
|
public void StopFileWatcher()
|
||||||
{
|
{
|
||||||
if (_watcher == null) return;
|
if (_fileWatcher == null) return;
|
||||||
_watcher.EnableRaisingEvents = false;
|
_fileWatcher.EnableRaisingEvents = false;
|
||||||
_watcher.Changed -= OnConfigFileChanged;
|
_fileWatcher.Changed -= OnConfigFileChanged;
|
||||||
_watcher.Dispose();
|
_fileWatcher.Dispose();
|
||||||
_watcher = null;
|
_fileWatcher = null;
|
||||||
LogManager.Log($"File watcher stopped for {_fileName}.", LogLevel.Info);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
|
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
|
||||||
@@ -79,27 +281,36 @@ namespace Spectrum
|
|||||||
Thread.Sleep(100);
|
Thread.Sleep(100);
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
LoadConfig(true);
|
LoadConfig();
|
||||||
LogManager.Log($"Configuration reloaded successfully for {_fileName}.", LogLevel.Info);
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
LogManager.Log($"Failed to reload configuration for {_fileName}: {ex.Message}", LogLevel.Error);
|
LogManager.Log($"Failed to reload configuration for {_defaultFilename}: {ex.Message}", LogLevel.Error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public void Dispose()
|
||||||
|
{
|
||||||
|
StopFileWatcher();
|
||||||
|
StopDirectoryWatcher();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#region Enums
|
||||||
public enum MovementType
|
public enum MovementType
|
||||||
{
|
{
|
||||||
Linear,
|
Linear,
|
||||||
CubicBezier,
|
CubicBezier,
|
||||||
QuadraticBezier,
|
QuadraticBezier,
|
||||||
Adaptive
|
Adaptive,
|
||||||
|
PerlinNoise,
|
||||||
|
WindMouse
|
||||||
}
|
}
|
||||||
public enum MovementMethod
|
public enum MovementMethod
|
||||||
{
|
{
|
||||||
MouseEvent,
|
MouseEvent,
|
||||||
Makcu
|
Makcu,
|
||||||
|
Arduino
|
||||||
}
|
}
|
||||||
public enum FovType
|
public enum FovType
|
||||||
{
|
{
|
||||||
@@ -111,73 +322,109 @@ namespace Spectrum
|
|||||||
GDI,
|
GDI,
|
||||||
DirectX
|
DirectX
|
||||||
}
|
}
|
||||||
|
public enum KeybindType
|
||||||
|
{
|
||||||
|
Hold,
|
||||||
|
Toggle,
|
||||||
|
Always
|
||||||
|
}
|
||||||
|
#endregion
|
||||||
public class ConfigData
|
public class ConfigData
|
||||||
{
|
{
|
||||||
|
|
||||||
// Image settings
|
#region Image Settings
|
||||||
public int ImageWidth { get; set; } = 640;
|
public int ImageWidth { get; set; } = 640;
|
||||||
public int ImageHeight { get; set; } = 640;
|
public int ImageHeight { get; set; } = 640;
|
||||||
|
public int Threshold { get; set; } = 200;
|
||||||
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
public CaptureMethod CaptureMethod { get; set; } = CaptureMethod.DirectX;
|
||||||
|
#endregion
|
||||||
|
|
||||||
// Offset settings
|
#region Offset Settings
|
||||||
public double YOffsetPercent { get; set; } = 0.8;
|
public double YOffsetPercent { get; set; } = 0.8;
|
||||||
public double XOffsetPercent { get; set; } = 0.5;
|
public double XOffsetPercent { get; set; } = 0.5;
|
||||||
|
public int YOffsetPixels { get; set; } = 100;
|
||||||
|
public int XOffsetPixels { get; set; } = 100;
|
||||||
|
public bool XPixelOffset { get; set; } = false;
|
||||||
|
public bool YPixelOffset { get; set; } = false;
|
||||||
|
#endregion
|
||||||
|
|
||||||
// Aim settings
|
#region Aim Settings
|
||||||
public bool EnableAim { get; set; } = true;
|
public bool EnableAim { get; set; } = true;
|
||||||
public bool ClosestToMouse { get; set; } = true;
|
public bool ClosestToMouse { get; set; } = true;
|
||||||
public Keys Keybind { get; set; } = Keys.XButton2;
|
public Keybind Keybind = new(Keys.XButton2, KeybindType.Hold);
|
||||||
public double Sensitivity { get; set; } = 0.5;
|
public double Sensitivity { get; set; } = 0.5;
|
||||||
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
|
public MovementType AimMovementType { get; set; } = MovementType.Adaptive;
|
||||||
public bool EmaSmoothening { get; set; } = true;
|
public bool EmaSmoothening { get; set; } = true;
|
||||||
public double EmaSmootheningFactor { get; set; } = 0.1;
|
public double EmaSmootheningFactor { get; set; } = 0.1;
|
||||||
|
|
||||||
public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
public MovementMethod MovementMethod { get; set; } = MovementMethod.MouseEvent;
|
||||||
|
|
||||||
// Triggerbot settings
|
public double WindMouseGravity { get; set; } = 9.0;
|
||||||
public bool TriggerBot { get; set; } = false;
|
public double WindMouseWind { get; set; } = 3.0;
|
||||||
public Keys TriggerKey { get; set; } = Keys.XButton2;
|
public double WindMouseMaxStep { get; set; } = 10.0;
|
||||||
public int TriggerDelay { get; set; } = 50; // milliseconds
|
public bool WindMouseOvershoot { get; set; } = false;
|
||||||
public int TriggerRadius { get; set; } = 15; // pixels
|
#endregion
|
||||||
public int TriggerDuration { get; set; } = 100; // milliseconds
|
|
||||||
|
|
||||||
// Display settings
|
#region Trigger Settings
|
||||||
|
public bool TriggerBot { get; set; } = false;
|
||||||
|
public Keybind TriggerKeybind = new(Keys.XButton1, KeybindType.Hold);
|
||||||
|
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||||
|
public int TriggerFov { get; set; } = 15; // pixels
|
||||||
|
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||||
|
public bool DrawTriggerFov { get; set; } = false;
|
||||||
|
public Vector4 TriggerRadiusColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
#endregion
|
||||||
|
|
||||||
|
#region Display Settings
|
||||||
public bool DrawDetections { get; set; } = true;
|
public bool DrawDetections { get; set; } = true;
|
||||||
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
public Vector4 DetectionColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
|
public bool HighlightTarget { get; set; } = false;
|
||||||
|
public Vector4 TargetColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
public bool ShowMenu { get; set; } = true;
|
public bool ShowMenu { get; set; } = true;
|
||||||
public Keys MenuKey { get; set; } = Keys.Insert;
|
public Keys MenuKey { get; set; } = Keys.Insert;
|
||||||
public bool DrawFOV { get; set; } = false;
|
public bool DrawFOV { get; set; } = false;
|
||||||
public FovType FOVType { get; set; } = FovType.Rectangle;
|
public FovType FOVType { get; set; } = FovType.Rectangle;
|
||||||
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
public Vector4 FOVColor { get; set; } = new Vector4(0.0f, 1.0f, 0.0f, 1.0f);
|
||||||
|
public bool DrawAimPoint { get; set; } = true;
|
||||||
|
public Vector4 AimPointColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||||
|
#endregion
|
||||||
|
|
||||||
// Data collection settings
|
#region Data Collection Settings
|
||||||
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;
|
||||||
|
#endregion
|
||||||
|
|
||||||
// Color settings
|
#region Color Settings
|
||||||
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
|
public Scalar UpperHSV { get; set; } = new Scalar(179, 255, 255);
|
||||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
|
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 255);
|
||||||
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||||
|
#endregion
|
||||||
|
|
||||||
// Misc
|
#region Misc
|
||||||
public bool DebugMode { get; set; } = false;
|
public bool DebugMode { get; set; } = false;
|
||||||
|
#endregion
|
||||||
}
|
}
|
||||||
public class ColorData
|
public class ColorData
|
||||||
{
|
{
|
||||||
public List<ColorInfo> Colors { get; set; } = new List<ColorInfo>();
|
public List<ColorInfo> Colors { get; set; } = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
public class ColorInfo
|
public class ColorInfo(string name, Scalar upper, Scalar lower)
|
||||||
{
|
{
|
||||||
public string Name { get; set; }
|
public string Name { get; set; } = name;
|
||||||
public Scalar Upper { get; set; }
|
public Scalar Upper { get; set; } = upper;
|
||||||
public Scalar Lower { get; set; }
|
public Scalar Lower { get; set; } = lower;
|
||||||
public ColorInfo(string name, Scalar upper, Scalar lower)
|
}
|
||||||
|
public class Keybind
|
||||||
|
{
|
||||||
|
public Keys Key { get; set; }
|
||||||
|
|
||||||
|
public KeybindType Type { get; set; }
|
||||||
|
public Keybind(Keys key, KeybindType type)
|
||||||
{
|
{
|
||||||
Name = name;
|
Key = key;
|
||||||
Upper = upper;
|
Type = type;
|
||||||
Lower = lower;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -114,8 +114,6 @@ namespace Spectrum.Detection
|
|||||||
|
|
||||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||||
{
|
{
|
||||||
|
|
||||||
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
|
|
||||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
using Vortice.Direct3D;
|
using Vortice.Direct3D;
|
||||||
using Vortice.Direct3D11;
|
using Vortice.Direct3D11;
|
||||||
using Vortice.DXGI;
|
using Vortice.DXGI;
|
||||||
using Size = System.Drawing.Size;
|
|
||||||
using Rectangle = System.Drawing.Rectangle;
|
|
||||||
using Point = System.Drawing.Point;
|
using Point = System.Drawing.Point;
|
||||||
|
using Rectangle = System.Drawing.Rectangle;
|
||||||
|
using Size = System.Drawing.Size;
|
||||||
|
|
||||||
namespace Spectrum.Detection
|
namespace Spectrum.Detection
|
||||||
{
|
{
|
||||||
@@ -40,13 +40,12 @@ namespace Spectrum.Detection
|
|||||||
adapter,
|
adapter,
|
||||||
DriverType.Unknown,
|
DriverType.Unknown,
|
||||||
DeviceCreationFlags.BgraSupport,
|
DeviceCreationFlags.BgraSupport,
|
||||||
new[]
|
[
|
||||||
{
|
|
||||||
FeatureLevel.Level_12_1,
|
FeatureLevel.Level_12_1,
|
||||||
FeatureLevel.Level_12_0,
|
FeatureLevel.Level_12_0,
|
||||||
FeatureLevel.Level_11_1,
|
FeatureLevel.Level_11_1,
|
||||||
FeatureLevel.Level_11_0
|
FeatureLevel.Level_11_0
|
||||||
},
|
],
|
||||||
out _device);
|
out _device);
|
||||||
|
|
||||||
if (hr.Failure || _device == null)
|
if (hr.Failure || _device == null)
|
||||||
|
|||||||
@@ -6,16 +6,18 @@ namespace Spectrum.Detection
|
|||||||
{
|
{
|
||||||
class DetectionManager
|
class DetectionManager
|
||||||
{
|
{
|
||||||
private long iterationCount = 0;
|
private readonly Stopwatch stopwatch = new Stopwatch();
|
||||||
private long totalTime = 0;
|
|
||||||
private Stopwatch stopwatch = new Stopwatch();
|
|
||||||
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
private Rectangle bounds = new Rectangle(0, 0, 0, 0);
|
||||||
private (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
private readonly (int Width, int Height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||||
private ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
private readonly int minArea;
|
||||||
private Renderer? renderer;
|
private readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
private Thread? _detectionThread;
|
private readonly Renderer? renderer;
|
||||||
|
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 DateTime lastFpsUpdate = DateTime.Now;
|
||||||
|
private int frameCount = 0;
|
||||||
|
|
||||||
public DetectionManager(Renderer renderer)
|
public DetectionManager(Renderer renderer)
|
||||||
{
|
{
|
||||||
@@ -27,6 +29,7 @@ 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();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -36,18 +39,48 @@ namespace Spectrum.Detection
|
|||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKey))
|
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.Keybind) || InputManager.IsKeyOrMouseDown(mainConfig.Data.TriggerKeybind))
|
||||||
{
|
{
|
||||||
stopwatch.Restart();
|
var config = mainConfig.Data;
|
||||||
bounds = new Rectangle(
|
if (config.DebugMode)
|
||||||
(screenSize.Width - mainConfig.Data.ImageWidth) / 2,
|
stopwatch.Restart();
|
||||||
(screenSize.Height - mainConfig.Data.ImageHeight) / 2,
|
|
||||||
mainConfig.Data.ImageWidth,
|
renderer?.ClearDetectionDrawCommands();
|
||||||
mainConfig.Data.ImageHeight
|
|
||||||
);
|
if (!config.ClosestToMouse)
|
||||||
var screenshot = null as Bitmap;
|
{
|
||||||
if (mainConfig.Data.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
bounds = new Rectangle(
|
||||||
|
(screenSize.Width - config.ImageWidth) / 2,
|
||||||
|
(screenSize.Height - config.ImageHeight) / 2,
|
||||||
|
config.ImageWidth,
|
||||||
|
config.ImageHeight
|
||||||
|
);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_ = InputManager.GetCursorPos(out System.Drawing.Point mousePos);
|
||||||
|
bounds = new Rectangle(
|
||||||
|
mousePos.X - (config.ImageWidth / 2),
|
||||||
|
mousePos.Y - (config.ImageHeight / 2),
|
||||||
|
config.ImageWidth,
|
||||||
|
config.ImageHeight
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
var screenRect = new Rectangle(0, 0, screenSize.Width, screenSize.Height);
|
||||||
|
bounds = Rectangle.Intersect(bounds, screenRect);
|
||||||
|
if (bounds.Width <= 0 || bounds.Height <= 0)
|
||||||
|
{
|
||||||
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
Thread.Sleep(2);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
Bitmap? screenshot = null;
|
||||||
|
if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
|
||||||
|
{
|
||||||
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
|
screenshot = _captureManager.CaptureScreenshotDirectX(bounds);
|
||||||
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
if (_captureManager.IsInitialized)
|
if (_captureManager.IsInitialized)
|
||||||
@@ -61,130 +94,181 @@ namespace Spectrum.Detection
|
|||||||
Thread.Sleep(2);
|
Thread.Sleep(2);
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(screenshot);
|
||||||
Mat drawing = mat.Clone();
|
screenshot.Dispose();
|
||||||
|
|
||||||
|
Mat? drawing = (config.AutoLabel || config.CollectData) ? mat.Clone() : null;
|
||||||
|
|
||||||
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2HSV);
|
||||||
Cv2.InRange(mat, mainConfig.Data.LowerHSV, mainConfig.Data.UpperHSV, mat);
|
Cv2.InRange(mat, config.LowerHSV, config.UpperHSV, mat);
|
||||||
Cv2.Dilate(mat, mat, null, iterations: 2);
|
Cv2.Dilate(mat, mat, null, iterations: 2);
|
||||||
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
Cv2.Threshold(mat, mat, 127, 255, ThresholdTypes.Binary);
|
||||||
|
|
||||||
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
Cv2.FindContours(mat, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
|
||||||
|
|
||||||
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= 50).ToArray();
|
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= minArea).ToArray();
|
||||||
|
|
||||||
var processedContours = MergeOverlappingContours(filteredContours);
|
var processedContours = MergeOverlappingContours(filteredContours);
|
||||||
|
|
||||||
if (processedContours.Length > 0)
|
if (processedContours.Length > 0)
|
||||||
{
|
{
|
||||||
int refX = bounds.X + bounds.Width / 2;
|
int refX = bounds.X + bounds.Width / 2;
|
||||||
int refY = bounds.Y + (int)(bounds.Height * mainConfig.Data.YOffsetPercent);
|
int refY = bounds.Y + (int)(bounds.Height * config.YOffsetPercent);
|
||||||
|
|
||||||
double minDist = double.MaxValue;
|
double minDistSquared = double.MaxValue;
|
||||||
OpenCvSharp.Point[]? closestContour = null;
|
OpenCvSharp.Point[]? closestContour = null;
|
||||||
int bestMinX = 0, bestMinY = 0, bestMaxX = 0, bestMaxY = 0;
|
Rect bestRect = default;
|
||||||
|
|
||||||
|
bool shouldDrawDetections = config.DrawDetections && renderer != null;
|
||||||
|
|
||||||
foreach (var contour in processedContours)
|
foreach (var contour in processedContours)
|
||||||
{
|
{
|
||||||
int minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
|
var rect = Cv2.BoundingRect(contour);
|
||||||
foreach (var point in contour)
|
|
||||||
{
|
int centerX = rect.X + rect.Width / 2;
|
||||||
if (point.X < minX) minX = point.X;
|
int centerY = rect.Y + rect.Height / 2;
|
||||||
if (point.Y < minY) minY = point.Y;
|
|
||||||
if (point.X > maxX) maxX = point.X;
|
|
||||||
if (point.Y > maxY) maxY = point.Y;
|
|
||||||
}
|
|
||||||
int centerX = (minX + maxX) / 2;
|
|
||||||
int centerY = (minY + maxY) / 2;
|
|
||||||
|
|
||||||
int absCenterX = centerX + bounds.X;
|
int absCenterX = centerX + bounds.X;
|
||||||
int absCenterY = centerY + bounds.Y;
|
int absCenterY = centerY + bounds.Y;
|
||||||
double dist = Math.Sqrt(Math.Pow(absCenterX - refX, 2) + Math.Pow(absCenterY - refY, 2));
|
|
||||||
|
|
||||||
if (dist < minDist)
|
double distSquared = (absCenterX - refX) * (absCenterX - refX) +
|
||||||
|
(absCenterY - refY) * (absCenterY - refY);
|
||||||
|
|
||||||
|
if (distSquared < minDistSquared)
|
||||||
{
|
{
|
||||||
minDist = dist;
|
minDistSquared = distSquared;
|
||||||
closestContour = contour;
|
closestContour = contour;
|
||||||
bestMinX = minX;
|
bestRect = rect;
|
||||||
bestMinY = minY;
|
|
||||||
bestMaxX = maxX;
|
|
||||||
bestMaxY = maxY;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
if (shouldDrawDetections)
|
||||||
{
|
{
|
||||||
var _rect = new Rectangle(
|
var _rect = new Rectangle(
|
||||||
minX + bounds.X,
|
rect.X + bounds.X,
|
||||||
minY + bounds.Y,
|
rect.Y + bounds.Y,
|
||||||
(maxX - minX + 1),
|
rect.Width,
|
||||||
(maxY - minY + 1)
|
rect.Height
|
||||||
);
|
);
|
||||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
renderer!.AddRect(_rect, config.DetectionColor, 1.0f);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (closestContour != null)
|
if (closestContour != null)
|
||||||
{
|
{
|
||||||
int groupX = (int)(bestMinX + (bestMaxX - bestMinX) * (1.0 - mainConfig.Data.XOffsetPercent));
|
|
||||||
int groupY = (int)(bestMinY + (bestMaxY - bestMinY) * (1.0 - mainConfig.Data.YOffsetPercent));
|
if (shouldDrawDetections && config.HighlightTarget)
|
||||||
|
{
|
||||||
|
var _rect = new Rectangle(
|
||||||
|
bestRect.X + bounds.X,
|
||||||
|
bestRect.Y + bounds.Y,
|
||||||
|
bestRect.Width,
|
||||||
|
bestRect.Height
|
||||||
|
);
|
||||||
|
renderer!.AddRect(_rect, config.TargetColor, 1.0f);
|
||||||
|
}
|
||||||
|
|
||||||
|
int groupX;
|
||||||
|
int groupY;
|
||||||
|
if (config.XPixelOffset)
|
||||||
|
groupX = bestRect.X + config.XOffsetPixels;
|
||||||
|
else
|
||||||
|
groupX = (int)(bestRect.X + bestRect.Width * config.XOffsetPercent);
|
||||||
|
if (config.YPixelOffset)
|
||||||
|
groupY = bestRect.Y + config.YOffsetPixels;
|
||||||
|
else
|
||||||
|
groupY = (int)(bestRect.Y + bestRect.Height * (1 - config.YOffsetPercent));
|
||||||
|
|
||||||
int targetX = groupX + bounds.X;
|
int targetX = groupX + bounds.X;
|
||||||
int targetY = groupY + bounds.Y;
|
int targetY = groupY + bounds.Y;
|
||||||
|
|
||||||
if (mainConfig.Data.AutoLabel)
|
if (config.DrawAimPoint)
|
||||||
|
{
|
||||||
|
renderer!.AddLine(new System.Numerics.Vector2(targetX - 10, targetY), new System.Numerics.Vector2(targetX + 10, targetY), config.AimPointColor, 2);
|
||||||
|
renderer!.AddLine(new System.Numerics.Vector2(targetX, targetY - 10), new System.Numerics.Vector2(targetX, targetY + 10), config.AimPointColor, 2);
|
||||||
|
renderer!.AddCircle(new System.Numerics.Vector2(targetX, targetY), 5, config.AimPointColor, 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (config.AutoLabel && drawing != null)
|
||||||
{
|
{
|
||||||
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
AutoLabeling.AddToQueue(drawing, bounds, processedContours);
|
||||||
AutoLabeling.AddBackgroundImage(drawing, true);
|
AutoLabeling.AddBackgroundImage(drawing, true);
|
||||||
}
|
}
|
||||||
if (!mainConfig.Data.AutoLabel && mainConfig.Data.CollectData)
|
if (!config.AutoLabel && config.CollectData && drawing != null)
|
||||||
{
|
{
|
||||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||||
}
|
}
|
||||||
|
|
||||||
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
InputManager.SetLastDetection(new System.Drawing.Point(targetX, targetY));
|
||||||
|
InputManager.SetLastDetectionBox(new Rectangle(
|
||||||
|
bestRect.X + bounds.X,
|
||||||
|
bestRect.Y + bounds.Y,
|
||||||
|
bestRect.Width,
|
||||||
|
bestRect.Height));
|
||||||
|
|
||||||
if (mainConfig.Data.EnableAim)
|
if (config.EnableAim)
|
||||||
{
|
{
|
||||||
InputManager.MoveMouse();
|
InputManager.MoveMouse();
|
||||||
}
|
}
|
||||||
if (mainConfig.Data.TriggerBot)
|
if (config.TriggerBot)
|
||||||
{
|
{
|
||||||
var _ = InputManager.ClickMouse();
|
var _ = InputManager.ClickMouse();
|
||||||
}
|
}
|
||||||
}
|
if (renderer != null && config.DrawTriggerFov && config.TriggerBot)
|
||||||
if (mainConfig.Data.DebugMode)
|
{
|
||||||
{
|
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100);
|
||||||
iterationCount++;
|
}
|
||||||
totalTime += stopwatch.ElapsedMilliseconds;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (mainConfig.Data.CollectData)
|
else if (config.CollectData && drawing != null)
|
||||||
{
|
{
|
||||||
if (mainConfig.Data.CollectData)
|
AutoLabeling.AddBackgroundImage(drawing, false);
|
||||||
AutoLabeling.AddBackgroundImage(drawing, false);
|
MovementPaths.ResetWindMouse();
|
||||||
}
|
}
|
||||||
screenshot?.Dispose();
|
|
||||||
mat.Dispose();
|
|
||||||
drawing.Dispose();
|
|
||||||
|
|
||||||
if (!AutoLabeling.Started && (mainConfig.Data.CollectData || mainConfig.Data.AutoLabel))
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
|
||||||
|
mat.Dispose();
|
||||||
|
drawing?.Dispose();
|
||||||
|
|
||||||
|
if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel))
|
||||||
{
|
{
|
||||||
AutoLabeling.StartLabeling();
|
AutoLabeling.StartLabeling();
|
||||||
}
|
}
|
||||||
else if (AutoLabeling.Started && !mainConfig.Data.CollectData && !mainConfig.Data.AutoLabel)
|
else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel)
|
||||||
{
|
{
|
||||||
AutoLabeling.StopLabeling();
|
AutoLabeling.StopLabeling();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (iterationCount >= 1000 && mainConfig.Data.DebugMode)
|
if (config.DebugMode)
|
||||||
{
|
{
|
||||||
LogManager.Log($"Processed {iterationCount} iterations in {totalTime} ms.", LogManager.LogLevel.Info);
|
stopwatch.Stop();
|
||||||
int fps = (int)(iterationCount * 1000 / totalTime);
|
double processTime = stopwatch.Elapsed.TotalMilliseconds;
|
||||||
LogManager.Log($"Average FPS: {fps}", LogManager.LogLevel.Info);
|
processTimes.Enqueue(processTime);
|
||||||
LogManager.Log($"Average time per iteration: {totalTime / iterationCount} ms", LogManager.LogLevel.Info);
|
if (processTimes.Count > 100)
|
||||||
iterationCount = 0;
|
processTimes.Dequeue();
|
||||||
totalTime = 0;
|
|
||||||
|
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 if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
|
else
|
||||||
|
{
|
||||||
|
renderer?.ClearDetectionDrawCommands();
|
||||||
|
renderer?.CommitDetectionDrawCommands();
|
||||||
|
MovementPaths.ResetWindMouse();
|
||||||
|
Thread.Sleep(5);
|
||||||
|
}
|
||||||
|
if (InputManager.IsKeyOrMouseDown(mainConfig.Data.MenuKey))
|
||||||
{
|
{
|
||||||
var now = DateTime.Now;
|
var now = DateTime.Now;
|
||||||
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
if ((now - lastMenuToggle).TotalMilliseconds > 175)
|
||||||
@@ -205,19 +289,23 @@ namespace Spectrum.Detection
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
static OpenCvSharp.Point[][] MergeOverlappingContours(OpenCvSharp.Point[][] contours)
|
||||||
{
|
{
|
||||||
var contourRects = new List<(Rect rect, List<int> indices)>();
|
if (contours.Length <= 1)
|
||||||
|
return contours;
|
||||||
|
|
||||||
|
var contourRects = new List<(Rect rect, List<int> indices)>(contours.Length);
|
||||||
for (int i = 0; i < contours.Length; i++)
|
for (int i = 0; i < contours.Length; i++)
|
||||||
{
|
{
|
||||||
var rect = Cv2.BoundingRect(contours[i]);
|
var rect = Cv2.BoundingRect(contours[i]);
|
||||||
contourRects.Add((rect, new List<int> { i }));
|
contourRects.Add((rect, new List<int> { i }));
|
||||||
}
|
}
|
||||||
|
|
||||||
bool merged;
|
bool merged;
|
||||||
do
|
do
|
||||||
{
|
{
|
||||||
merged = false;
|
merged = false;
|
||||||
for (int i = 0; i < contourRects.Count; i++)
|
for (int i = 0; i < contourRects.Count - 1; i++)
|
||||||
{
|
{
|
||||||
var (rectA, indicesA) = contourRects[i];
|
var (rectA, indicesA) = contourRects[i];
|
||||||
for (int j = i + 1; j < contourRects.Count; j++)
|
for (int j = i + 1; j < contourRects.Count; j++)
|
||||||
@@ -231,10 +319,8 @@ namespace Spectrum.Detection
|
|||||||
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
Math.Max(rectA.X + rectA.Width, rectB.X + rectB.Width) - Math.Min(rectA.X, rectB.X),
|
||||||
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
Math.Max(rectA.Y + rectA.Height, rectB.Y + rectB.Height) - Math.Min(rectA.Y, rectB.Y)
|
||||||
);
|
);
|
||||||
var newIndices = new List<int>();
|
indicesA.AddRange(indicesB);
|
||||||
newIndices.AddRange(indicesA);
|
contourRects[i] = (newRect, indicesA);
|
||||||
newIndices.AddRange(indicesB);
|
|
||||||
contourRects[i] = (newRect, newIndices);
|
|
||||||
contourRects.RemoveAt(j);
|
contourRects.RemoveAt(j);
|
||||||
merged = true;
|
merged = true;
|
||||||
break;
|
break;
|
||||||
@@ -244,15 +330,15 @@ namespace Spectrum.Detection
|
|||||||
}
|
}
|
||||||
} while (merged);
|
} while (merged);
|
||||||
|
|
||||||
var mergedContours = new List<OpenCvSharp.Point[]>();
|
var mergedContours = new List<OpenCvSharp.Point[]>(contourRects.Count);
|
||||||
foreach (var (rect, indices) in contourRects)
|
foreach (var (rect, indices) in contourRects)
|
||||||
{
|
{
|
||||||
var points = new List<OpenCvSharp.Point>();
|
var pointsList = new List<OpenCvSharp.Point>(indices.Count * 10);
|
||||||
foreach (var idx in indices)
|
foreach (var idx in indices)
|
||||||
{
|
{
|
||||||
points.AddRange(contours[idx]);
|
pointsList.AddRange(contours[idx]);
|
||||||
}
|
}
|
||||||
var hull = Cv2.ConvexHull(points);
|
var hull = Cv2.ConvexHull(pointsList);
|
||||||
mergedContours.Add(hull);
|
mergedContours.Add(hull);
|
||||||
}
|
}
|
||||||
return mergedContours.ToArray();
|
return mergedContours.ToArray();
|
||||||
|
|||||||
@@ -0,0 +1,191 @@
|
|||||||
|
using System.Diagnostics;
|
||||||
|
using System.IO.Ports;
|
||||||
|
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||||
|
|
||||||
|
namespace Spectrum.Input.InputLibraries.Arduino
|
||||||
|
{
|
||||||
|
class ArduinoMain
|
||||||
|
{
|
||||||
|
private static readonly byte PingCommand = 0x02;
|
||||||
|
private static readonly byte PingResponse = 0xAA;
|
||||||
|
private const int BaudRate = 115200;
|
||||||
|
private const int HandshakeTimeoutMs = 1500;
|
||||||
|
private const int OpenResetDelayMs = 1200;
|
||||||
|
private static SerialPort? serial;
|
||||||
|
private static readonly object sync = new();
|
||||||
|
|
||||||
|
public static bool Load()
|
||||||
|
{
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
if (serial != null && serial.IsOpen)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
serial = FindArduino();
|
||||||
|
if (serial != null)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Connected to Arduino on {serial.PortName}.", LogLevel.Info);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log("ArduinoMain: Failed to connect to Arduino.", LogLevel.Warning);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static SerialPort? FindArduino()
|
||||||
|
{
|
||||||
|
string[] candidates = SerialPort.GetPortNames();
|
||||||
|
|
||||||
|
if (candidates.Length == 0)
|
||||||
|
{
|
||||||
|
LogManager.Log("ArduinoMain: No serial ports detected.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach (string portName in candidates)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Probing {portName}…", LogLevel.Debug);
|
||||||
|
var sp = new SerialPort(portName, BaudRate)
|
||||||
|
{
|
||||||
|
ReadTimeout = 250,
|
||||||
|
WriteTimeout = 500,
|
||||||
|
DtrEnable = true,
|
||||||
|
RtsEnable = true
|
||||||
|
};
|
||||||
|
|
||||||
|
sp.Open();
|
||||||
|
|
||||||
|
Thread.Sleep(OpenResetDelayMs);
|
||||||
|
|
||||||
|
sp.DiscardInBuffer();
|
||||||
|
sp.DiscardOutBuffer();
|
||||||
|
|
||||||
|
sp.Write([PingCommand], 0, 1);
|
||||||
|
|
||||||
|
if (AwaitResponse(sp, PingResponse, HandshakeTimeoutMs))
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Handshake success on {portName}.", LogLevel.Debug);
|
||||||
|
return sp;
|
||||||
|
}
|
||||||
|
|
||||||
|
LogManager.Log($"ArduinoMain: No valid response on {portName}.", LogLevel.Debug);
|
||||||
|
sp.Close();
|
||||||
|
sp.Dispose();
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Probe failed on {portName}: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static bool AwaitResponse(SerialPort sp, byte expected, int timeoutMs)
|
||||||
|
{
|
||||||
|
var sw = Stopwatch.StartNew();
|
||||||
|
while (sw.ElapsedMilliseconds < timeoutMs)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
while (sp.BytesToRead > 0)
|
||||||
|
{
|
||||||
|
int b = sp.ReadByte();
|
||||||
|
if (b < 0) break;
|
||||||
|
LogManager.Log($"ArduinoMain: Received 0x{b:X2} (expect 0x{expected:X2}).", LogLevel.Debug);
|
||||||
|
if (b == expected)
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (TimeoutException) { }
|
||||||
|
Thread.Sleep(10);
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Close()
|
||||||
|
{
|
||||||
|
lock (sync)
|
||||||
|
{
|
||||||
|
if (serial != null)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
serial.Close();
|
||||||
|
serial.Dispose();
|
||||||
|
LogManager.Log("ArduinoMain: Serial port closed.", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Error closing port: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
finally
|
||||||
|
{
|
||||||
|
serial = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void Move(int x, int y)
|
||||||
|
{
|
||||||
|
SerialPort? sp;
|
||||||
|
lock (sync) sp = serial;
|
||||||
|
if (sp == null || !sp.IsOpen) return;
|
||||||
|
|
||||||
|
while (x != 0 || y != 0)
|
||||||
|
{
|
||||||
|
int stepX = Math.Max(-127, Math.Min(127, x));
|
||||||
|
int stepY = Math.Max(-127, Math.Min(127, y));
|
||||||
|
byte bX = unchecked((byte)stepX);
|
||||||
|
byte bY = unchecked((byte)stepY);
|
||||||
|
|
||||||
|
var packet = new byte[] { 0x01, bX, bY };
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sp.Write(packet, 0, packet.Length);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Move write failed: {ex.Message}", LogLevel.Debug);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
x -= stepX;
|
||||||
|
y -= stepY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public static void ClickDown(int button = 0x03)
|
||||||
|
{
|
||||||
|
SendClick(button, true);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ClickUp(int button = 0x03)
|
||||||
|
{
|
||||||
|
SendClick(button, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static void SendClick(int buttonBase, bool expectDown)
|
||||||
|
{
|
||||||
|
SerialPort? sp;
|
||||||
|
lock (sync) sp = serial;
|
||||||
|
if (sp == null || !sp.IsOpen) return;
|
||||||
|
|
||||||
|
if (buttonBase != 0x03 && buttonBase != 0x05)
|
||||||
|
throw new ArgumentException("Button must be 0x03 (left) or 0x05 (right).", nameof(buttonBase));
|
||||||
|
|
||||||
|
byte code = (byte)(expectDown ? buttonBase : (buttonBase + 1));
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
sp.Write([code], 0, 1);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"ArduinoMain: Click {(expectDown ? "down" : "up")} failed: {ex.Message}", LogLevel.Debug);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
#include <Mouse.h>
|
||||||
|
|
||||||
|
enum ParseState : uint8_t { WAIT_CMD, WAIT_MOVE_X, WAIT_MOVE_Y };
|
||||||
|
ParseState state = WAIT_CMD;
|
||||||
|
uint8_t cmd = 0;
|
||||||
|
int8_t moveX = 0, moveY = 0;
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
Serial.begin(115200);
|
||||||
|
delay(2000);
|
||||||
|
Mouse.begin();
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
while (Serial.available() > 0) {
|
||||||
|
int b = Serial.read();
|
||||||
|
if (b < 0) return;
|
||||||
|
|
||||||
|
switch (state) {
|
||||||
|
case WAIT_CMD:
|
||||||
|
cmd = (uint8_t)b;
|
||||||
|
switch (cmd) {
|
||||||
|
case 0x01: // move: need two more bytes
|
||||||
|
state = WAIT_MOVE_X;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x02:
|
||||||
|
Serial.write(0xAA); // ping
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x03: // left down
|
||||||
|
Mouse.press(MOUSE_LEFT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x04: // left up
|
||||||
|
Mouse.release(MOUSE_LEFT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x05: // right down
|
||||||
|
Mouse.press(MOUSE_RIGHT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 0x06: // right up
|
||||||
|
Mouse.release(MOUSE_RIGHT);
|
||||||
|
break;
|
||||||
|
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_MOVE_X:
|
||||||
|
moveX = (int8_t)b;
|
||||||
|
state = WAIT_MOVE_Y;
|
||||||
|
break;
|
||||||
|
|
||||||
|
case WAIT_MOVE_Y:
|
||||||
|
moveY = (int8_t)b;
|
||||||
|
Mouse.move(moveX, moveY, 0);
|
||||||
|
state = WAIT_CMD;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,7 +4,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
{
|
{
|
||||||
internal class MakcuMain
|
internal class MakcuMain
|
||||||
{
|
{
|
||||||
public static MakcuMouse MakcuInstance { get; private set; }
|
public static MakcuMouse? MakcuInstance { get; private set; }
|
||||||
|
|
||||||
private static bool _isMakcuLoaded = false;
|
private static bool _isMakcuLoaded = false;
|
||||||
|
|
||||||
@@ -45,7 +45,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
string version = MakcuInstance.GetKmVersion();
|
string? version = MakcuInstance.GetKmVersion();
|
||||||
|
|
||||||
_isMakcuLoaded = true;
|
_isMakcuLoaded = true;
|
||||||
|
|
||||||
@@ -53,7 +53,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
|
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch
|
||||||
{
|
{
|
||||||
_isMakcuLoaded = false;
|
_isMakcuLoaded = false;
|
||||||
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||||
@@ -69,10 +69,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
public static void Unload()
|
public static void Unload()
|
||||||
{
|
{
|
||||||
UnsubscribeFromButtonEvents();
|
UnsubscribeFromButtonEvents();
|
||||||
if (MakcuInstance != null)
|
MakcuInstance?.Close();
|
||||||
{
|
|
||||||
MakcuInstance.Close();
|
|
||||||
}
|
|
||||||
_isMakcuLoaded = false;
|
_isMakcuLoaded = false;
|
||||||
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,23 +14,23 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
|
|
||||||
public class MakcuMouse : IDisposable
|
public class MakcuMouse : IDisposable
|
||||||
{
|
{
|
||||||
private static readonly byte[] BaudChangeCommand = { 0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00 };
|
private static readonly byte[] BaudChangeCommand = [0xDE, 0xAD, 0x05, 0x00, 0xA5, 0x00, 0x09, 0x3D, 0x00];
|
||||||
|
|
||||||
private SerialPort _serialPort;
|
private SerialPort? _serialPort;
|
||||||
private readonly bool _debugLogging;
|
private readonly bool _debugLogging;
|
||||||
private readonly bool _sendInitCommands;
|
private readonly bool _sendInitCommands;
|
||||||
|
|
||||||
private readonly object _serialLock = new object();
|
private readonly object _serialLock = new();
|
||||||
private bool _isInitializedAndConnected = false;
|
private bool _isInitializedAndConnected = false;
|
||||||
private Thread _listenerThread;
|
private Thread? _listenerThread;
|
||||||
private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false);
|
private ManualResetEventSlim _stopListenerEvent = new(false);
|
||||||
private volatile bool _pauseListener = false;
|
private volatile bool _pauseListener = false;
|
||||||
|
|
||||||
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = new Dictionary<MakcuMouseButton, bool>();
|
private readonly Dictionary<MakcuMouseButton, bool> _buttonStates = [];
|
||||||
|
|
||||||
public event Action<MakcuMouseButton, bool> ButtonStateChanged;
|
public event Action<MakcuMouseButton, bool>? ButtonStateChanged;
|
||||||
|
|
||||||
public string PortName { get; private set; }
|
public string? PortName { get; private set; }
|
||||||
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
|
public int BaudRate => _serialPort?.BaudRate ?? (_isInitializedAndConnected ? 4000000 : 115200);
|
||||||
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
public bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
||||||
|
|
||||||
@@ -65,13 +65,13 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
|
Log($"Error getting COM port list: {ex.Message}. Cannot continue search.");
|
||||||
return null;
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
if (availablePorts == null || !availablePorts.Any())
|
if (availablePorts == null || availablePorts.Length == 0)
|
||||||
{
|
{
|
||||||
Log("No COM ports available according to SerialPort.GetPortNames().");
|
Log("No COM ports available according to SerialPort.GetPortNames().");
|
||||||
return null;
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
||||||
@@ -79,7 +79,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
foreach (string portName in availablePorts)
|
foreach (string portName in availablePorts)
|
||||||
{
|
{
|
||||||
Log($"Testing port: {portName}");
|
Log($"Testing port: {portName}");
|
||||||
SerialPort testPort = null;
|
SerialPort? testPort = null;
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
|
|
||||||
@@ -121,7 +121,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
|
|
||||||
Log($"Response from 'km.version()' on {portName}: '{response}'");
|
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())))
|
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}'");
|
Log($"Makcu device found on port: {portName}! Version response: '{response}'");
|
||||||
testPort.Close();
|
testPort.Close();
|
||||||
@@ -157,7 +157,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
}
|
}
|
||||||
|
|
||||||
Log("Makcu device not found on any available COM ports after connection test.");
|
Log("Makcu device not found on any available COM ports after connection test.");
|
||||||
return null;
|
return "";
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -252,7 +252,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private bool SendCommandInternal(string command, bool expectResponse, out string responseText, int responseTimeoutMs = 200)
|
private bool SendCommandInternal(string command, bool expectResponse, out string? responseText, int responseTimeoutMs = 200)
|
||||||
{
|
{
|
||||||
responseText = null;
|
responseText = null;
|
||||||
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
||||||
@@ -286,7 +286,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
if (expectResponse)
|
if (expectResponse)
|
||||||
{
|
{
|
||||||
var stopwatch = Stopwatch.StartNew();
|
var stopwatch = Stopwatch.StartNew();
|
||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new();
|
||||||
string commandTrimmed = command.Trim();
|
string commandTrimmed = command.Trim();
|
||||||
bool firstLineIsEcho = true;
|
bool firstLineIsEcho = true;
|
||||||
|
|
||||||
@@ -307,7 +307,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
{
|
{
|
||||||
if (sb.Length > 0) continue;
|
if (sb.Length > 0) continue;
|
||||||
}
|
}
|
||||||
if (sb.Length > 0) sb.Append("\n");
|
if (sb.Length > 0) sb.Append('\n');
|
||||||
sb.Append(line);
|
sb.Append(line);
|
||||||
}
|
}
|
||||||
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
||||||
@@ -367,7 +367,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
||||||
};
|
};
|
||||||
|
|
||||||
byte[] packetHeader = { 0x6B, 0x6D, 0x2E };
|
byte[] packetHeader = [0x6B, 0x6D, 0x2E];
|
||||||
int currentHeaderIndex = 0;
|
int currentHeaderIndex = 0;
|
||||||
|
|
||||||
while (!_stopListenerEvent.IsSet)
|
while (!_stopListenerEvent.IsSet)
|
||||||
@@ -428,7 +428,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
if (debug)
|
if (debug)
|
||||||
{
|
{
|
||||||
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
||||||
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Any() ? string.Join(", ", pressedButtons) : "None")}");
|
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Length != 0 ? string.Join(", ", pressedButtons) : "None")}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -502,11 +502,11 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
|||||||
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 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 bool Scroll(int delta) => SendCommandInternal($"km.wheel({delta})", false, out _);
|
||||||
|
|
||||||
public string GetKmVersion()
|
public string? GetKmVersion()
|
||||||
{
|
{
|
||||||
return SendCommandInternal("km.version()", true, out string response, 500) ? response : null;
|
return SendCommandInternal("km.version()", true, out string? response, 500) ? response : null;
|
||||||
}
|
}
|
||||||
private string GetButtonString(MakcuMouseButton button)
|
private static string GetButtonString(MakcuMouseButton button)
|
||||||
{
|
{
|
||||||
switch (button)
|
switch (button)
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
using Spectrum.Input.InputLibraries.Makcu;
|
using Spectrum.Input.InputLibraries.Arduino;
|
||||||
|
using Spectrum.Input.InputLibraries.Makcu;
|
||||||
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;
|
||||||
@@ -7,13 +8,11 @@ namespace Spectrum.Input
|
|||||||
{
|
{
|
||||||
public static class InputManager
|
public static class InputManager
|
||||||
{
|
{
|
||||||
[DllImport("user32.dll")]
|
|
||||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
[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 ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||||
private static Point lastDetection = new Point();
|
private static Point lastDetection = new Point();
|
||||||
|
private static Rectangle lastDetectionBox = new Rectangle();
|
||||||
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;
|
||||||
|
|
||||||
@@ -37,15 +36,20 @@ namespace Spectrum.Input
|
|||||||
private static double TimeScaleFactor(double baseFactor, double deltaSeconds)
|
private static double TimeScaleFactor(double baseFactor, double deltaSeconds)
|
||||||
{
|
{
|
||||||
if (baseFactor <= 0) return 0;
|
if (baseFactor <= 0) return 0;
|
||||||
if (baseFactor >= 1) return 1;
|
if (baseFactor >= 1)
|
||||||
double k = deltaSeconds / _dtRef;
|
{
|
||||||
return 1 - Math.Pow(1 - baseFactor, k);
|
double k = deltaSeconds / _dtRef;
|
||||||
|
return baseFactor * k;
|
||||||
|
}
|
||||||
|
double kLow = deltaSeconds / _dtRef;
|
||||||
|
return 1 - Math.Pow(1 - baseFactor, kLow);
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void MoveMouse()
|
public static void MoveMouse()
|
||||||
{
|
{
|
||||||
|
var config = mainConfig.Data;
|
||||||
Point reference = new Point();
|
Point reference = new Point();
|
||||||
if (mainConfig.Data.ClosestToMouse)
|
if (config.ClosestToMouse)
|
||||||
{
|
{
|
||||||
GetCursorPos(out reference);
|
GetCursorPos(out reference);
|
||||||
}
|
}
|
||||||
@@ -59,20 +63,30 @@ namespace Spectrum.Input
|
|||||||
Point end = new Point(lastDetection.X, lastDetection.Y);
|
Point end = new Point(lastDetection.X, lastDetection.Y);
|
||||||
|
|
||||||
double dt = GetDeltaSeconds();
|
double dt = GetDeltaSeconds();
|
||||||
double effSensitivity = TimeScaleFactor(mainConfig.Data.Sensitivity, dt);
|
double effSensitivity = TimeScaleFactor(config.Sensitivity, dt);
|
||||||
|
|
||||||
Point newPosition = mainConfig.Data.AimMovementType switch
|
bool insideBoundingBox = lastDetectionBox.Contains(start);
|
||||||
|
|
||||||
|
Point newPosition = config.AimMovementType switch
|
||||||
{
|
{
|
||||||
MovementType.CubicBezier => MovementPaths.CubicBezierMovement(start, end, effSensitivity),
|
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(start, end, effSensitivity),
|
||||||
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||||
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
||||||
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
||||||
_ => end
|
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, effSensitivity),
|
||||||
|
MovementType.WindMouse => MovementPaths.WindMouse(start, end,
|
||||||
|
config.WindMouseGravity,
|
||||||
|
config.WindMouseWind,
|
||||||
|
config.WindMouseMaxStep,
|
||||||
|
effSensitivity,
|
||||||
|
config.WindMouseOvershoot,
|
||||||
|
insideBoundingBox),
|
||||||
|
_ => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||||
};
|
};
|
||||||
|
|
||||||
if (mainConfig.Data.EmaSmoothening)
|
if (config.EmaSmoothening)
|
||||||
{
|
{
|
||||||
double emaAlpha = TimeScaleFactor(mainConfig.Data.EmaSmootheningFactor, dt);
|
double emaAlpha = TimeScaleFactor(config.EmaSmootheningFactor, dt);
|
||||||
newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha));
|
newPosition.X = (int)Math.Round(MovementPaths.EmaSmoothing(reference.X, newPosition.X, emaAlpha));
|
||||||
newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha));
|
newPosition.Y = (int)Math.Round(MovementPaths.EmaSmoothing(reference.Y, newPosition.Y, emaAlpha));
|
||||||
}
|
}
|
||||||
@@ -81,20 +95,23 @@ namespace Spectrum.Input
|
|||||||
int deltaY = newPosition.Y - reference.Y;
|
int deltaY = newPosition.Y - reference.Y;
|
||||||
|
|
||||||
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
if (Math.Abs(deltaX) < 1 && Math.Abs(deltaY) < 1) return;
|
||||||
if (deltaX > mainConfig.Data.ImageWidth || deltaX < -mainConfig.Data.ImageWidth || deltaY > mainConfig.Data.ImageHeight || deltaY < -mainConfig.Data.ImageHeight)
|
if (deltaX > config.ImageWidth || deltaX < -config.ImageWidth || deltaY > config.ImageHeight || deltaY < -config.ImageHeight)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
switch (mainConfig.Data.MovementMethod)
|
switch (config.MovementMethod)
|
||||||
{
|
{
|
||||||
case MovementMethod.MouseEvent:
|
case MovementMethod.MouseEvent:
|
||||||
MouseEvent.Move(deltaX, deltaY);
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
break;
|
break;
|
||||||
case MovementMethod.Makcu:
|
case MovementMethod.Makcu:
|
||||||
if (EnsureMakcuReady())
|
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||||
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
||||||
else
|
else
|
||||||
MouseEvent.Move(deltaX, deltaY);
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
break;
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.Move(deltaX, deltaY);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
MouseEvent.Move(deltaX, deltaY);
|
MouseEvent.Move(deltaX, deltaY);
|
||||||
break;
|
break;
|
||||||
@@ -103,13 +120,14 @@ namespace Spectrum.Input
|
|||||||
|
|
||||||
public static async Task ClickMouse()
|
public static async Task ClickMouse()
|
||||||
{
|
{
|
||||||
if (!mainConfig.Data.TriggerBot)
|
var config = mainConfig.Data;
|
||||||
|
if (!config.TriggerBot)
|
||||||
return;
|
return;
|
||||||
if (!IsKeyOrMouseDown(mainConfig.Data.TriggerKey) || mainConfig.Data.TriggerKey == Keys.None)
|
if (!IsKeyOrMouseDown(config.TriggerKeybind) || config.TriggerKeybind.Key == Keys.None)
|
||||||
return;
|
return;
|
||||||
|
|
||||||
var currentPosition = new Point();
|
var currentPosition = new Point();
|
||||||
if (mainConfig.Data.ClosestToMouse)
|
if (config.ClosestToMouse)
|
||||||
{
|
{
|
||||||
GetCursorPos(out currentPosition);
|
GetCursorPos(out currentPosition);
|
||||||
}
|
}
|
||||||
@@ -119,40 +137,46 @@ namespace Spectrum.Input
|
|||||||
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
currentPosition.Y = SystemHelper.GetPrimaryScreenSize().Height / 2;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mainConfig.Data.TriggerDelay > 0)
|
if (config.TriggerDelay > 0)
|
||||||
await Task.Delay(mainConfig.Data.TriggerDelay);
|
await Task.Delay(config.TriggerDelay);
|
||||||
|
|
||||||
int radius = mainConfig.Data.TriggerRadius;
|
int radius = config.TriggerFov;
|
||||||
|
|
||||||
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
|
if (Math.Abs(currentPosition.X - lastDetection.X) < radius && Math.Abs(currentPosition.Y - lastDetection.Y) < radius)
|
||||||
{
|
{
|
||||||
switch (mainConfig.Data.MovementMethod)
|
switch (config.MovementMethod)
|
||||||
{
|
{
|
||||||
case MovementMethod.MouseEvent:
|
case MovementMethod.MouseEvent:
|
||||||
MouseEvent.ClickDown();
|
MouseEvent.ClickDown();
|
||||||
break;
|
break;
|
||||||
case MovementMethod.Makcu:
|
case MovementMethod.Makcu:
|
||||||
if (EnsureMakcuReady())
|
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||||
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
||||||
else
|
else
|
||||||
MouseEvent.ClickDown();
|
MouseEvent.ClickDown();
|
||||||
break;
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.ClickDown();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
MouseEvent.ClickDown();
|
MouseEvent.ClickDown();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
await Task.Delay(mainConfig.Data.TriggerDuration);
|
await Task.Delay(config.TriggerDuration);
|
||||||
switch (mainConfig.Data.MovementMethod)
|
switch (config.MovementMethod)
|
||||||
{
|
{
|
||||||
case MovementMethod.MouseEvent:
|
case MovementMethod.MouseEvent:
|
||||||
MouseEvent.ClickUp();
|
MouseEvent.ClickUp();
|
||||||
break;
|
break;
|
||||||
case MovementMethod.Makcu:
|
case MovementMethod.Makcu:
|
||||||
if (EnsureMakcuReady())
|
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||||
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
||||||
else
|
else
|
||||||
MouseEvent.ClickUp();
|
MouseEvent.ClickUp();
|
||||||
break;
|
break;
|
||||||
|
case MovementMethod.Arduino:
|
||||||
|
ArduinoMain.ClickUp();
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
MouseEvent.ClickUp();
|
MouseEvent.ClickUp();
|
||||||
break;
|
break;
|
||||||
@@ -164,18 +188,17 @@ namespace Spectrum.Input
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void SetLastDetection(Point point)
|
public static void SetLastDetection(Point point) { lastDetection = point; }
|
||||||
{
|
|
||||||
lastDetection = point;
|
public static void SetLastDetectionBox(Rectangle box) { lastDetectionBox = box; }
|
||||||
}
|
|
||||||
|
|
||||||
[DllImport("user32.dll")]
|
[DllImport("user32.dll")]
|
||||||
private static extern short GetAsyncKeyState(int vKey);
|
private static extern short GetAsyncKeyState(int vKey);
|
||||||
|
|
||||||
private static readonly Keys[] MouseKeys =
|
private static readonly Keys[] MouseKeys =
|
||||||
{
|
[
|
||||||
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
Keys.LButton, Keys.RButton, Keys.MButton, Keys.XButton1, Keys.XButton2
|
||||||
};
|
];
|
||||||
|
|
||||||
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
public static Task<Keys> ListenForNextKeyOrMouseAsync(CancellationToken? cancellationToken = null)
|
||||||
{
|
{
|
||||||
@@ -183,7 +206,7 @@ namespace Spectrum.Input
|
|||||||
|
|
||||||
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
||||||
bool subscribedToMakcu = false;
|
bool subscribedToMakcu = false;
|
||||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady())
|
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||||
{
|
{
|
||||||
makcuHandler = (btn, isPressed) =>
|
makcuHandler = (btn, isPressed) =>
|
||||||
{
|
{
|
||||||
@@ -310,6 +333,36 @@ namespace Spectrum.Input
|
|||||||
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
|
return (GetAsyncKeyState((int)key) & 0x8000) != 0; ;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, bool> _keybindToggleStates = new();
|
||||||
|
|
||||||
|
public static bool IsKeyOrMouseDown(Keybind keybind)
|
||||||
|
{
|
||||||
|
if (keybind.Type == KeybindType.Always)
|
||||||
|
return true;
|
||||||
|
|
||||||
|
bool isKeyDown = IsKeyOrMouseDown(keybind.Key);
|
||||||
|
|
||||||
|
if (keybind.Type == KeybindType.Hold)
|
||||||
|
return isKeyDown;
|
||||||
|
|
||||||
|
string toggleKey = keybind.Key.ToString();
|
||||||
|
|
||||||
|
if (!_keybindToggleStates.ContainsKey(toggleKey))
|
||||||
|
_keybindToggleStates[toggleKey] = false;
|
||||||
|
|
||||||
|
if (isKeyDown && !_keybindToggleStates.ContainsKey($"{toggleKey}_pressed"))
|
||||||
|
{
|
||||||
|
_keybindToggleStates[$"{toggleKey}_pressed"] = true;
|
||||||
|
_keybindToggleStates[toggleKey] = !_keybindToggleStates[toggleKey];
|
||||||
|
}
|
||||||
|
else if (!isKeyDown)
|
||||||
|
{
|
||||||
|
_keybindToggleStates.Remove($"{toggleKey}_pressed");
|
||||||
|
}
|
||||||
|
|
||||||
|
return _keybindToggleStates[toggleKey];
|
||||||
|
}
|
||||||
|
|
||||||
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
|
private static MakcuMouseButton? MapKeysToMakcuButton(Keys key)
|
||||||
{
|
{
|
||||||
return key switch
|
return key switch
|
||||||
|
|||||||
@@ -1,9 +1,47 @@
|
|||||||
|
namespace Spectrum.Input
|
||||||
namespace Spectrum.Input
|
|
||||||
{
|
{
|
||||||
public class MovementPaths
|
public class MovementPaths
|
||||||
{
|
{
|
||||||
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
private static double Clamp01(double t) => t < 0 ? 0 : (t > 1 ? 1 : t);
|
||||||
|
private static readonly int[] _permutation = GeneratePermutation();
|
||||||
|
private static readonly int[] _p;
|
||||||
|
private static double _perlinTime = 0.0;
|
||||||
|
|
||||||
|
private static Point _lastMove = new Point(0, 0);
|
||||||
|
private static double _windX = 0.0;
|
||||||
|
private static double _windY = 0.0;
|
||||||
|
private static double _velocityX = 0.0;
|
||||||
|
private static double _velocityY = 0.0;
|
||||||
|
|
||||||
|
static MovementPaths()
|
||||||
|
{
|
||||||
|
_p = new int[512];
|
||||||
|
for (int i = 0; i < 256; i++)
|
||||||
|
{
|
||||||
|
_p[256 + i] = _p[i] = _permutation[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static double Fade(double t) => t * t * t * (t * (t * 6 - 15) + 10);
|
||||||
|
private static double Lerp(double a, double b, double t) => a + t * (b - a);
|
||||||
|
private static double Grad(int hash, double x)
|
||||||
|
{
|
||||||
|
int h = hash & 15;
|
||||||
|
double grad = 1 + (h & 7);
|
||||||
|
if ((h & 8) != 0) grad = -grad;
|
||||||
|
return grad * x;
|
||||||
|
}
|
||||||
|
private static double Perlin1D(double x)
|
||||||
|
{
|
||||||
|
int X = (int)Math.Floor(x) & 255;
|
||||||
|
x -= Math.Floor(x);
|
||||||
|
double u = Fade(x);
|
||||||
|
int a = _p[X];
|
||||||
|
int b = _p[X + 1];
|
||||||
|
double res = Lerp(Grad(a, x), Grad(b, x - 1), u);
|
||||||
|
return res * 0.188;
|
||||||
|
}
|
||||||
|
|
||||||
public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
public static Point CubicBezier(Point start, Point end, Point control1, Point control2, double t)
|
||||||
{
|
{
|
||||||
t = Clamp01(t);
|
t = Clamp01(t);
|
||||||
@@ -79,6 +117,31 @@ namespace Spectrum.Input
|
|||||||
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
||||||
return new Point(newX, newY);
|
return new Point(newX, newY);
|
||||||
}
|
}
|
||||||
|
public static Point PerlinNoiseMovement(Point start, Point end, double t, double amplitudeFraction = 0.2, double frequency = 1.5)
|
||||||
|
{
|
||||||
|
t = Clamp01(t);
|
||||||
|
double dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double distance = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (distance == 0 || t == 0) return start;
|
||||||
|
|
||||||
|
double baseX = start.X + dx * t;
|
||||||
|
double baseY = start.Y + dy * t;
|
||||||
|
|
||||||
|
_perlinTime += t * 0.75;
|
||||||
|
double noise = Perlin1D(_perlinTime * frequency);
|
||||||
|
|
||||||
|
double nx = -dy / distance;
|
||||||
|
double ny = dx / distance;
|
||||||
|
|
||||||
|
double offsetMag = amplitudeFraction * distance * t;
|
||||||
|
double ox = nx * noise * offsetMag;
|
||||||
|
double oy = ny * noise * offsetMag;
|
||||||
|
|
||||||
|
int finalX = (int)Math.Round(baseX + ox);
|
||||||
|
int finalY = (int)Math.Round(baseY + oy);
|
||||||
|
return new Point(finalX, finalY);
|
||||||
|
}
|
||||||
public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor)
|
public static double EmaSmoothing(double previousValue, double currentValue, double smoothingFactor)
|
||||||
{
|
{
|
||||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||||
@@ -92,5 +155,99 @@ namespace Spectrum.Input
|
|||||||
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
||||||
return new Point(x, y);
|
return new Point(x, y);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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 dx = end.X - start.X;
|
||||||
|
double dy = end.Y - start.Y;
|
||||||
|
double d = Math.Sqrt(dx * dx + dy * dy);
|
||||||
|
if (d <= 0) return start;
|
||||||
|
double inv = 1.0 / d;
|
||||||
|
double dirX = dx * inv;
|
||||||
|
double dirY = dy * inv;
|
||||||
|
|
||||||
|
if (insideBoundingBox)
|
||||||
|
{
|
||||||
|
double s = Math.Min(d * 0.35, maxStep * sensitivity * 0.6);
|
||||||
|
_perlinTime += 0.03;
|
||||||
|
double n = Math.Sin(_perlinTime * 1.1) * 0.3 + Math.Cos(_perlinTime * 0.9) * 0.2;
|
||||||
|
int x = (int)Math.Round(start.X + dirX * s + n);
|
||||||
|
int y = (int)Math.Round(start.Y + dirY * s + n * 0.7);
|
||||||
|
_windX *= 0.15;
|
||||||
|
_windY *= 0.15;
|
||||||
|
_velocityX *= 0.3;
|
||||||
|
_velocityY *= 0.3;
|
||||||
|
return _lastMove = new Point(x, y);
|
||||||
|
}
|
||||||
|
|
||||||
|
double distScale = Math.Min(d / 100.0, 3.0);
|
||||||
|
double sens = Math.Max(0.1, sensitivity);
|
||||||
|
double dyn = maxStep * sens * (1.0 + distScale);
|
||||||
|
double g = gravity * (1.0 + distScale * 0.3) * sens * (enableOvershoot ? 1.15 : 1.0);
|
||||||
|
double prox = insideBoundingBox ? 0.0 : 1.0;
|
||||||
|
double w = wind * Math.Pow(prox, 4.0) * (enableOvershoot ? 1.2 : 1.0);
|
||||||
|
|
||||||
|
if (insideBoundingBox)
|
||||||
|
{
|
||||||
|
double damp = 0.25;
|
||||||
|
_velocityX *= damp;
|
||||||
|
_velocityY *= damp;
|
||||||
|
double wd = Math.Pow(damp, 4.0);
|
||||||
|
_windX *= wd;
|
||||||
|
_windY *= wd;
|
||||||
|
}
|
||||||
|
|
||||||
|
_windX = _windX / Math.Sqrt(3) + (Random.Shared.NextDouble() * 2 - 1) * w;
|
||||||
|
_windY = _windY / Math.Sqrt(3) + (Random.Shared.NextDouble() * 2 - 1) * w;
|
||||||
|
|
||||||
|
_velocityX += _windX + g * dirX;
|
||||||
|
_velocityY += _windY + g * dirY;
|
||||||
|
|
||||||
|
double vm = Math.Sqrt(_velocityX * _velocityX + _velocityY * _velocityY);
|
||||||
|
if (vm > dyn)
|
||||||
|
{
|
||||||
|
double r = dyn / vm;
|
||||||
|
_velocityX *= r;
|
||||||
|
_velocityY *= r;
|
||||||
|
vm = dyn;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!enableOvershoot && insideBoundingBox)
|
||||||
|
{
|
||||||
|
double limit = d * 0.4;
|
||||||
|
if (vm > limit && vm > 0)
|
||||||
|
{
|
||||||
|
double r = limit / vm;
|
||||||
|
_velocityX *= r;
|
||||||
|
_velocityY *= r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int nx = (int)Math.Round(start.X + _velocityX);
|
||||||
|
int ny = (int)Math.Round(start.Y + _velocityY);
|
||||||
|
return _lastMove = new Point(nx, ny);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void ResetWindMouse()
|
||||||
|
{
|
||||||
|
_windX = 0.0;
|
||||||
|
_windY = 0.0;
|
||||||
|
_velocityX = 0.0;
|
||||||
|
_velocityY = 0.0;
|
||||||
|
_lastMove = new Point(0, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static int[] GeneratePermutation()
|
||||||
|
{
|
||||||
|
int[] perm = new int[256];
|
||||||
|
for (int i = 0; i < 256; i++) perm[i] = i;
|
||||||
|
for (int i = 255; i > 0; i--)
|
||||||
|
{
|
||||||
|
int j = Random.Shared.Next(i + 1);
|
||||||
|
(perm[i], perm[j]) = (perm[j], perm[i]);
|
||||||
|
}
|
||||||
|
return perm;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+32
-10
@@ -6,7 +6,9 @@ namespace Spectrum
|
|||||||
{
|
{
|
||||||
public class LogManager
|
public class LogManager
|
||||||
{
|
{
|
||||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
private static List<LogEntry> _logEntries = new List<LogEntry>();
|
||||||
|
private static readonly object _logLock = new object();
|
||||||
|
private static ConfigManager<ConfigData>? mainConfig;
|
||||||
public enum LogLevel
|
public enum LogLevel
|
||||||
{
|
{
|
||||||
Debug,
|
Debug,
|
||||||
@@ -31,19 +33,40 @@ namespace Spectrum
|
|||||||
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
private static List<LogEntry> _logEntries = new List<LogEntry>();
|
|
||||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||||
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;
|
||||||
if (mainConfig == null)
|
if (mainConfig == null)
|
||||||
mainConfig = Program.mainConfig;
|
{
|
||||||
if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached))
|
try { mainConfig = Program.mainConfig; } catch { }
|
||||||
return;
|
}
|
||||||
|
|
||||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
bool debugEnabled = Debugger.IsAttached;
|
||||||
Debug.WriteLine(logMessage);
|
try
|
||||||
_logEntries.Add(new LogEntry(level, message));
|
{
|
||||||
|
debugEnabled = debugEnabled || (mainConfig?.Data?.DebugMode ?? false);
|
||||||
|
}
|
||||||
|
catch { }
|
||||||
|
if (level == LogLevel.Debug && !debugEnabled)
|
||||||
|
return;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||||
|
Debug.WriteLine(logMessage);
|
||||||
|
lock (_logLock)
|
||||||
|
{
|
||||||
|
if (_logEntries == null)
|
||||||
|
{
|
||||||
|
_logEntries = new List<LogEntry>();
|
||||||
|
}
|
||||||
|
_logEntries.Add(new LogEntry(level, message));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
Debug.WriteLine($"[LogManager ERROR] Failed to append log entry: {ex.Message}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
public static void SaveLog(string filePath)
|
public static void SaveLog(string filePath)
|
||||||
{
|
{
|
||||||
@@ -65,7 +88,6 @@ namespace Spectrum
|
|||||||
public static void ClearLog()
|
public static void ClearLog()
|
||||||
{
|
{
|
||||||
_logEntries.Clear();
|
_logEntries.Clear();
|
||||||
Log("Log cleared.", LogLevel.Info);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public static void OpenLogFolder()
|
public static void OpenLogFolder()
|
||||||
@@ -73,7 +95,7 @@ namespace Spectrum
|
|||||||
Process.Start(new ProcessStartInfo
|
Process.Start(new ProcessStartInfo
|
||||||
{
|
{
|
||||||
FileName = "explorer.exe",
|
FileName = "explorer.exe",
|
||||||
Arguments = Directory.GetCurrentDirectory(),
|
Arguments = Path.Combine(Directory.GetCurrentDirectory(), "bin", "logs"),
|
||||||
UseShellExecute = true
|
UseShellExecute = true
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
+5
-11
@@ -9,9 +9,8 @@ namespace Spectrum
|
|||||||
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 ConfigManager<ConfigData>("bin\\configs\\config.json");
|
||||||
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
|
public static ConfigManager<ColorData> colorConfig = new ConfigManager<ColorData>("bin\\configs\\colors.json");
|
||||||
public static long iterationCount = 0;
|
|
||||||
public static long totalTime = 0;
|
|
||||||
private static DetectionManager? detectionManager;
|
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();
|
||||||
|
|
||||||
|
|
||||||
@@ -29,7 +28,6 @@ namespace Spectrum
|
|||||||
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
mainConfig.Data.CaptureMethod = CaptureMethod.GDI;
|
||||||
}
|
}
|
||||||
renderer.Run();
|
renderer.Run();
|
||||||
LogManager.Log("Renderer started successfully.", LogManager.LogLevel.Info);
|
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@@ -38,17 +36,13 @@ 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"];
|
||||||
foreach (var dir in dirs)
|
foreach (var dir in dirs)
|
||||||
{
|
{
|
||||||
if (!Directory.Exists(dir))
|
if (!Directory.Exists(dir))
|
||||||
{
|
|
||||||
Directory.CreateDirectory(dir);
|
Directory.CreateDirectory(dir);
|
||||||
LogManager.Log($"Created directory: {dir}", LogManager.LogLevel.Info);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
|
||||||
mainConfig.LoadConfig();
|
mainConfig.LoadConfig();
|
||||||
mainConfig.StartFileWatcher();
|
mainConfig.StartFileWatcher();
|
||||||
|
|
||||||
@@ -59,11 +53,11 @@ namespace Spectrum
|
|||||||
|
|
||||||
if (colorConfig.Data.Colors.Count == 0)
|
if (colorConfig.Data.Colors.Count == 0)
|
||||||
{
|
{
|
||||||
colorConfig.Data.Colors.Add(new ColorInfo("Arsenal [Magenta]", new Scalar(150, 255, 229), new Scalar(150, 255, 229)));
|
colorConfig.Data.Colors.Add(new ColorInfo("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.Data.Colors.Add(new ColorInfo("Combat Surf [Red]", new Scalar(0, 255, 255), new Scalar(0, 255, 255)));
|
||||||
colorConfig.SaveConfig();
|
colorConfig.SaveConfig();
|
||||||
colorConfig.LoadConfig(true);
|
colorConfig.LoadConfig();
|
||||||
mainConfig.LoadConfig(true);
|
mainConfig.LoadConfig();
|
||||||
}
|
}
|
||||||
|
|
||||||
Thread.Sleep(1000);
|
Thread.Sleep(1000);
|
||||||
|
|||||||
@@ -0,0 +1,520 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using OpenCvSharp;
|
||||||
|
using SixLabors.ImageSharp;
|
||||||
|
using SixLabors.ImageSharp.PixelFormats;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
partial class Renderer
|
||||||
|
{
|
||||||
|
private bool _showHSVRangeWindow = false;
|
||||||
|
private Mat? _originalImage = null;
|
||||||
|
private Mat? _maskedImage = null;
|
||||||
|
private Image<Rgba32>? _originalImageSharp = null;
|
||||||
|
private Image<Rgba32>? _maskedImageSharp = null;
|
||||||
|
private IntPtr _originalTextureId = IntPtr.Zero;
|
||||||
|
private IntPtr _maskedTextureId = IntPtr.Zero;
|
||||||
|
private Scalar _lowerHSV = new Scalar(0, 0, 0);
|
||||||
|
private Scalar _upperHSV = new Scalar(179, 255, 255);
|
||||||
|
private string _loadedImagePath = "";
|
||||||
|
private bool _needsTextureUpdate = false;
|
||||||
|
private string _colorName = "";
|
||||||
|
|
||||||
|
private int _maskDisplayMode = 0;
|
||||||
|
private Vector3 _maskTintColor = new Vector3(1.0f, 1.0f, 1.0f);
|
||||||
|
private float _maskOpacity = 1.0f;
|
||||||
|
private Vector3 _backgroundColor = new Vector3(0.0f, 0.0f, 0.0f);
|
||||||
|
private bool _showOnlyMaskedRegion = true;
|
||||||
|
|
||||||
|
void RenderHSVRangeWindow()
|
||||||
|
{
|
||||||
|
if (!_showHSVRangeWindow)
|
||||||
|
return;
|
||||||
|
|
||||||
|
ImGui.SetNextWindowSize(new Vector2(900, 700), ImGuiCond.FirstUseEver);
|
||||||
|
ImGui.Begin("HSV Range Selector", ImGuiWindowFlags.NoCollapse | ImGuiWindowFlags.NoTitleBar);
|
||||||
|
|
||||||
|
ImGui.Text("HSV Range Selector");
|
||||||
|
ImGui.SameLine();
|
||||||
|
float currentWidth = ImGui.GetWindowWidth();
|
||||||
|
ImGui.SetCursorPosX(currentWidth - 30);
|
||||||
|
if (ImGui.Button("X##HSVClose", new Vector2(22, 22)))
|
||||||
|
{
|
||||||
|
_showHSVRangeWindow = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ImGui.Button("Load Image"))
|
||||||
|
{
|
||||||
|
OpenImageFileDialog();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!string.IsNullOrEmpty(_loadedImagePath))
|
||||||
|
{
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.TextDisabled($"Loaded: {Path.GetFileName(_loadedImagePath)}");
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
if (_originalImage != null && !_originalImage.Empty())
|
||||||
|
{
|
||||||
|
float availWidth = ImGui.GetContentRegionAvail().X;
|
||||||
|
float availHeight = ImGui.GetContentRegionAvail().Y;
|
||||||
|
|
||||||
|
float controlsHeight = 500;
|
||||||
|
float maxImageHeight = Math.Max(100, availHeight - controlsHeight);
|
||||||
|
|
||||||
|
float imageDisplayWidth = (availWidth - 20) / 2;
|
||||||
|
float aspectRatio = (float)_originalImage.Height / _originalImage.Width;
|
||||||
|
float imageDisplayHeight = Math.Min(imageDisplayWidth * aspectRatio, maxImageHeight);
|
||||||
|
imageDisplayWidth = imageDisplayHeight / aspectRatio;
|
||||||
|
|
||||||
|
if (_needsTextureUpdate)
|
||||||
|
{
|
||||||
|
UpdateTextures();
|
||||||
|
_needsTextureUpdate = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.BeginGroup();
|
||||||
|
ImGui.Text("Original Image");
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
ImGui.Image(_originalTextureId, new Vector2(imageDisplayWidth, imageDisplayHeight));
|
||||||
|
}
|
||||||
|
ImGui.EndGroup();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
|
||||||
|
ImGui.BeginGroup();
|
||||||
|
ImGui.Text("Masked Image");
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
ImGui.Image(_maskedTextureId, new Vector2(imageDisplayWidth, imageDisplayHeight));
|
||||||
|
}
|
||||||
|
ImGui.EndGroup();
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
if (ImGui.CollapsingHeader("Visual Settings", ImGuiTreeNodeFlags.DefaultOpen))
|
||||||
|
{
|
||||||
|
bool visualChanged = false;
|
||||||
|
|
||||||
|
ImGui.Text("Display Mode");
|
||||||
|
if (ImGui.RadioButton("Masked Result", ref _maskDisplayMode, 0))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.SameLine();
|
||||||
|
if (ImGui.RadioButton("Mask Only", ref _maskDisplayMode, 1))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.SameLine();
|
||||||
|
if (ImGui.RadioButton("Overlay", ref _maskDisplayMode, 2))
|
||||||
|
visualChanged = true;
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 1 || _maskDisplayMode == 2)
|
||||||
|
{
|
||||||
|
if (ImGui.ColorEdit3("Mask Tint", ref _maskTintColor))
|
||||||
|
visualChanged = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 2)
|
||||||
|
{
|
||||||
|
if (ImGui.SliderFloat("Mask Opacity", ref _maskOpacity, 0.0f, 1.0f, "%.2f"))
|
||||||
|
visualChanged = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskDisplayMode == 0)
|
||||||
|
if (ImGui.Checkbox("Show Only Masked Region", ref _showOnlyMaskedRegion))
|
||||||
|
visualChanged = true;
|
||||||
|
|
||||||
|
if (!_showOnlyMaskedRegion && _maskDisplayMode == 0)
|
||||||
|
{
|
||||||
|
ImGui.Indent();
|
||||||
|
if (ImGui.ColorEdit3("Background Color", ref _backgroundColor))
|
||||||
|
visualChanged = true;
|
||||||
|
ImGui.Unindent();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (visualChanged)
|
||||||
|
{
|
||||||
|
UpdateMask();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
|
||||||
|
bool changed = false;
|
||||||
|
|
||||||
|
ImGui.Text("Lower HSV Bound");
|
||||||
|
|
||||||
|
int lowerH = (int)_lowerHSV.Val0;
|
||||||
|
int lowerS = (int)_lowerHSV.Val1;
|
||||||
|
int lowerV = (int)_lowerHSV.Val2;
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
if (ImGui.SliderInt("##LowerH", ref lowerH, 0, 179, "H: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##LowerS", ref lowerS, 0, 255, "S: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##LowerV", ref lowerV, 0, 255, "V: %d"))
|
||||||
|
changed = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.Text("Upper HSV Bound");
|
||||||
|
|
||||||
|
int upperH = (int)_upperHSV.Val0;
|
||||||
|
int upperS = (int)_upperHSV.Val1;
|
||||||
|
int upperV = (int)_upperHSV.Val2;
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
if (ImGui.SliderInt("##UpperH", ref upperH, 0, 179, "H: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##UpperS", ref upperS, 0, 255, "S: %d"))
|
||||||
|
changed = true;
|
||||||
|
if (ImGui.SliderInt("##UpperV", ref upperV, 0, 255, "V: %d"))
|
||||||
|
changed = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
if (changed)
|
||||||
|
{
|
||||||
|
_lowerHSV = new Scalar(
|
||||||
|
Math.Clamp(lowerH, 0, 179),
|
||||||
|
Math.Clamp(lowerS, 0, 255),
|
||||||
|
Math.Clamp(lowerV, 0, 255)
|
||||||
|
);
|
||||||
|
|
||||||
|
_upperHSV = new Scalar(
|
||||||
|
Math.Clamp(upperH, 0, 179),
|
||||||
|
Math.Clamp(upperS, 0, 255),
|
||||||
|
Math.Clamp(upperV, 0, 255)
|
||||||
|
);
|
||||||
|
|
||||||
|
UpdateMask();
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Separator();
|
||||||
|
ImGui.Spacing();
|
||||||
|
ImGui.Text("Save as New Color");
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
ImGui.InputText("##ColorName", ref _colorName, 256);
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
ImGui.Spacing();
|
||||||
|
|
||||||
|
if (ImGui.Button("Create Color", new Vector2(-1, 0)))
|
||||||
|
{
|
||||||
|
if (!string.IsNullOrWhiteSpace(_colorName))
|
||||||
|
{
|
||||||
|
var existingColor = Program.colorConfig.Data.Colors.Find(c => c.Name == _colorName);
|
||||||
|
if (existingColor != null)
|
||||||
|
{
|
||||||
|
existingColor.Lower = _lowerHSV;
|
||||||
|
existingColor.Upper = _upperHSV;
|
||||||
|
LogManager.Log($"Updated existing color: {_colorName}", LogManager.LogLevel.Info);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
Program.colorConfig.Data.Colors.Add(new ColorInfo(_colorName, _upperHSV, _lowerHSV));
|
||||||
|
}
|
||||||
|
Program.colorConfig.SaveConfig();
|
||||||
|
_colorName = "";
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
LogManager.Log("Please enter a color name", LogManager.LogLevel.Warning);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.End();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void OpenImageFileDialog()
|
||||||
|
{
|
||||||
|
Thread thread = new Thread(() =>
|
||||||
|
{
|
||||||
|
using (OpenFileDialog openFileDialog = new OpenFileDialog())
|
||||||
|
{
|
||||||
|
openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png|All Files|*.*";
|
||||||
|
openFileDialog.Title = "Select an Image";
|
||||||
|
openFileDialog.Multiselect = false;
|
||||||
|
|
||||||
|
var windowWrapper = new WindowWrapper(window.Handle);
|
||||||
|
if (openFileDialog.ShowDialog(windowWrapper) == DialogResult.OK)
|
||||||
|
{
|
||||||
|
LoadImage(openFileDialog.FileName);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
thread.SetApartmentState(ApartmentState.STA);
|
||||||
|
thread.Start();
|
||||||
|
}
|
||||||
|
|
||||||
|
private class WindowWrapper : IWin32Window
|
||||||
|
{
|
||||||
|
private readonly IntPtr _handle;
|
||||||
|
|
||||||
|
public WindowWrapper(IntPtr handle)
|
||||||
|
{
|
||||||
|
_handle = handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public IntPtr Handle => _handle;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void LoadImage(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
DisposeImageResources();
|
||||||
|
|
||||||
|
_originalImage = Cv2.ImRead(path, ImreadModes.Color);
|
||||||
|
|
||||||
|
if (_originalImage == null || _originalImage.Empty())
|
||||||
|
{
|
||||||
|
LogManager.Log($"Failed to load image: {path}");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
_loadedImagePath = path;
|
||||||
|
UpdateMask();
|
||||||
|
_needsTextureUpdate = true;
|
||||||
|
|
||||||
|
LogManager.Log($"Loaded image: {path} ({_originalImage.Width}x{_originalImage.Height})", LogManager.LogLevel.Debug);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error loading image: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateMask()
|
||||||
|
{
|
||||||
|
if (_originalImage == null || _originalImage.Empty())
|
||||||
|
return;
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
using (Mat hsvImage = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.CvtColor(_originalImage, hsvImage, ColorConversionCodes.BGR2HSV);
|
||||||
|
|
||||||
|
using (Mat mask = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.InRange(hsvImage, _lowerHSV, _upperHSV, mask);
|
||||||
|
|
||||||
|
_maskedImage?.Dispose();
|
||||||
|
_maskedImage = new Mat();
|
||||||
|
|
||||||
|
switch (_maskDisplayMode)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
if (_showOnlyMaskedRegion)
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, _maskedImage, mask);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
using (Mat background = new Mat(_originalImage.Size(), _originalImage.Type(),
|
||||||
|
new Scalar(_backgroundColor.Z * 255, _backgroundColor.Y * 255, _backgroundColor.X * 255)))
|
||||||
|
{
|
||||||
|
using (Mat maskedForeground = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedForeground, mask);
|
||||||
|
|
||||||
|
using (Mat invertedMask = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.BitwiseNot(mask, invertedMask);
|
||||||
|
using (Mat maskedBackground = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(background, background, maskedBackground, invertedMask);
|
||||||
|
Cv2.Add(maskedForeground, maskedBackground, _maskedImage);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 1:
|
||||||
|
using (Mat coloredMask = new Mat(_originalImage.Size(), _originalImage.Type()))
|
||||||
|
{
|
||||||
|
Cv2.CvtColor(mask, coloredMask, ColorConversionCodes.GRAY2BGR);
|
||||||
|
|
||||||
|
using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3,
|
||||||
|
new Scalar(_maskTintColor.Z, _maskTintColor.Y, _maskTintColor.X)))
|
||||||
|
{
|
||||||
|
using (Mat coloredMaskFloat = new Mat())
|
||||||
|
using (Mat tinted = new Mat())
|
||||||
|
{
|
||||||
|
coloredMask.ConvertTo(coloredMaskFloat, MatType.CV_32FC3, 1.0 / 255.0);
|
||||||
|
Cv2.Multiply(coloredMaskFloat, tintMat, tinted);
|
||||||
|
tinted.ConvertTo(_maskedImage, _originalImage.Type(), 255.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
|
||||||
|
case 2:
|
||||||
|
using (Mat maskedResult = new Mat())
|
||||||
|
{
|
||||||
|
Cv2.BitwiseAnd(_originalImage, _originalImage, maskedResult, mask);
|
||||||
|
|
||||||
|
using (Mat maskColored = new Mat(_originalImage.Size(), _originalImage.Type()))
|
||||||
|
{
|
||||||
|
Cv2.CvtColor(mask, maskColored, ColorConversionCodes.GRAY2BGR);
|
||||||
|
|
||||||
|
using (Mat tintMat = new Mat(_originalImage.Size(), MatType.CV_32FC3,
|
||||||
|
new Scalar(_maskTintColor.Z * _maskOpacity, _maskTintColor.Y * _maskOpacity, _maskTintColor.X * _maskOpacity)))
|
||||||
|
{
|
||||||
|
using (Mat maskColoredFloat = new Mat())
|
||||||
|
using (Mat tinted = new Mat())
|
||||||
|
using (Mat tintedByte = new Mat())
|
||||||
|
{
|
||||||
|
maskColored.ConvertTo(maskColoredFloat, MatType.CV_32FC3, 1.0 / 255.0);
|
||||||
|
Cv2.Multiply(maskColoredFloat, tintMat, tinted);
|
||||||
|
tinted.ConvertTo(tintedByte, _originalImage.Type(), 255.0);
|
||||||
|
|
||||||
|
using (Mat originalFloat = new Mat())
|
||||||
|
using (Mat tintedFloat = new Mat())
|
||||||
|
using (Mat blended = new Mat())
|
||||||
|
{
|
||||||
|
_originalImage.ConvertTo(originalFloat, MatType.CV_32FC3);
|
||||||
|
tintedByte.ConvertTo(tintedFloat, MatType.CV_32FC3);
|
||||||
|
Cv2.AddWeighted(originalFloat, 1.0 - _maskOpacity, tintedFloat, _maskOpacity, 0, blended);
|
||||||
|
blended.ConvertTo(_maskedImage, _originalImage.Type());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_needsTextureUpdate = true;
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating mask: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private void UpdateTextures()
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (_originalImage != null && !_originalImage.Empty())
|
||||||
|
{
|
||||||
|
_originalImageSharp?.Dispose();
|
||||||
|
_originalImageSharp = MatToImageSharp(_originalImage);
|
||||||
|
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
RemoveImage("hsv_original");
|
||||||
|
|
||||||
|
AddOrGetImagePointer("hsv_original", _originalImageSharp, false, out _originalTextureId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskedImage != null && !_maskedImage.Empty())
|
||||||
|
{
|
||||||
|
_maskedImageSharp?.Dispose();
|
||||||
|
_maskedImageSharp = MatToImageSharp(_maskedImage);
|
||||||
|
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
RemoveImage("hsv_masked");
|
||||||
|
|
||||||
|
AddOrGetImagePointer("hsv_masked", _maskedImageSharp, false, out _maskedTextureId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
LogManager.Log($"Error updating textures: {ex.Message}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private Image<Rgba32> MatToImageSharp(Mat mat)
|
||||||
|
{
|
||||||
|
Mat rgbaMat = new Mat();
|
||||||
|
Cv2.CvtColor(mat, rgbaMat, ColorConversionCodes.BGR2RGBA);
|
||||||
|
|
||||||
|
int width = rgbaMat.Width;
|
||||||
|
int height = rgbaMat.Height;
|
||||||
|
|
||||||
|
var config = new SixLabors.ImageSharp.Configuration();
|
||||||
|
config.PreferContiguousImageBuffers = true;
|
||||||
|
var image = new Image<Rgba32>(config, width, height);
|
||||||
|
|
||||||
|
if (image.DangerousTryGetSinglePixelMemory(out Memory<Rgba32> memory))
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* matData = (byte*)rgbaMat.Data;
|
||||||
|
var span = memory.Span;
|
||||||
|
|
||||||
|
fixed (Rgba32* destPtr = &span[0])
|
||||||
|
{
|
||||||
|
byte* dest = (byte*)destPtr;
|
||||||
|
int totalBytes = width * height * 4;
|
||||||
|
Buffer.MemoryCopy(matData, dest, totalBytes, totalBytes);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
unsafe
|
||||||
|
{
|
||||||
|
byte* matData = (byte*)rgbaMat.Data;
|
||||||
|
|
||||||
|
for (int y = 0; y < height; y++)
|
||||||
|
{
|
||||||
|
for (int x = 0; x < width; x++)
|
||||||
|
{
|
||||||
|
int idx = (y * width + x) * 4;
|
||||||
|
image[x, y] = new Rgba32(
|
||||||
|
matData[idx + 0],
|
||||||
|
matData[idx + 1],
|
||||||
|
matData[idx + 2],
|
||||||
|
matData[idx + 3]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rgbaMat.Dispose();
|
||||||
|
return image;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void DisposeImageResources()
|
||||||
|
{
|
||||||
|
_originalImage?.Dispose();
|
||||||
|
_originalImage = null;
|
||||||
|
|
||||||
|
_maskedImage?.Dispose();
|
||||||
|
_maskedImage = null;
|
||||||
|
|
||||||
|
_originalImageSharp?.Dispose();
|
||||||
|
_originalImageSharp = null;
|
||||||
|
|
||||||
|
_maskedImageSharp?.Dispose();
|
||||||
|
_maskedImageSharp = null;
|
||||||
|
|
||||||
|
if (_originalTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
RemoveImage("hsv_original");
|
||||||
|
_originalTextureId = IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_maskedTextureId != IntPtr.Zero)
|
||||||
|
{
|
||||||
|
RemoveImage("hsv_masked");
|
||||||
|
_maskedTextureId = IntPtr.Zero;
|
||||||
|
}
|
||||||
|
|
||||||
|
_loadedImagePath = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,549 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using OpenCvSharp;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using System.Globalization;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
public static class ImGuiExtensions
|
||||||
|
{
|
||||||
|
private static readonly Dictionary<string, string> _sliderEditBuffers = new();
|
||||||
|
public static bool ColorEditHSV3(string label, ref Scalar hsv)
|
||||||
|
{
|
||||||
|
ImGui.PushID(label);
|
||||||
|
|
||||||
|
int h = (int)Math.Clamp(Math.Round(hsv.Val0), 0, 179);
|
||||||
|
int s = (int)Math.Clamp(Math.Round(hsv.Val1), 0, 255);
|
||||||
|
int v = (int)Math.Clamp(Math.Round(hsv.Val2), 0, 255);
|
||||||
|
|
||||||
|
bool changed = false;
|
||||||
|
bool inputChanged = false;
|
||||||
|
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
|
||||||
|
var style = ImGui.GetStyle();
|
||||||
|
float avail = ImGui.GetContentRegionAvail().X;
|
||||||
|
float previewWidth = 21.0f;
|
||||||
|
float totalSpacing = style.ItemSpacing.X * 3;
|
||||||
|
float partWidth = Math.Max(24.0f, (avail - totalSpacing - previewWidth) / 3.0f);
|
||||||
|
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}H", ref h, 0, 179))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}S", ref s, 0, 255))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
ImGui.PushItemWidth(partWidth);
|
||||||
|
if (ImGui.InputInt($"##{label}V", ref v, 0, 255))
|
||||||
|
inputChanged = true;
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
|
||||||
|
if (inputChanged)
|
||||||
|
{
|
||||||
|
hsv = new Scalar(h, s, v);
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
Vector3 rgbColor = OpenCvHsvToRgb(hsv);
|
||||||
|
|
||||||
|
ImGui.SameLine();
|
||||||
|
Vector2 btnSize = new Vector2(previewWidth, previewWidth);
|
||||||
|
Vector4 previewCol4 = new Vector4(rgbColor.X, rgbColor.Y, rgbColor.Z, 1.0f);
|
||||||
|
string previewBtnId = $"##ColorPreview_{label}";
|
||||||
|
if (ImGui.ColorButton(previewBtnId, previewCol4, ImGuiColorEditFlags.NoInputs, btnSize))
|
||||||
|
{
|
||||||
|
ImGui.OpenPopup($"##ColorPicker_{label}");
|
||||||
|
}
|
||||||
|
if (ImGui.BeginPopup($"##ColorPicker_{label}"))
|
||||||
|
{
|
||||||
|
Vector3 picker = rgbColor;
|
||||||
|
if (ImGui.ColorPicker3($"##ColorPickerPicker_{label}", ref picker))
|
||||||
|
{
|
||||||
|
rgbColor = picker;
|
||||||
|
Scalar newHsv = RgbToOpenCvHsv(rgbColor);
|
||||||
|
hsv = newHsv;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.PopID();
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Vector3 OpenCvHsvToRgb(Scalar hsv)
|
||||||
|
{
|
||||||
|
double h = Math.Clamp(hsv.Val0, 0.0, 179.0);
|
||||||
|
double s = Math.Clamp(hsv.Val1, 0.0, 255.0);
|
||||||
|
double v = Math.Clamp(hsv.Val2, 0.0, 255.0);
|
||||||
|
|
||||||
|
double hueDeg = (h / 179.0) * 360.0;
|
||||||
|
if (hueDeg >= 360.0)
|
||||||
|
hueDeg -= 360.0;
|
||||||
|
|
||||||
|
double saturation = s / 255.0;
|
||||||
|
double value = v / 255.0;
|
||||||
|
|
||||||
|
if (saturation <= double.Epsilon)
|
||||||
|
{
|
||||||
|
return new Vector3((float)value, (float)value, (float)value);
|
||||||
|
}
|
||||||
|
|
||||||
|
double c = value * saturation;
|
||||||
|
double huePrime = hueDeg / 60.0;
|
||||||
|
double x = c * (1 - Math.Abs(huePrime % 2 - 1));
|
||||||
|
double m = value - c;
|
||||||
|
|
||||||
|
double r1 = 0, g1 = 0, b1 = 0;
|
||||||
|
|
||||||
|
int region = (int)Math.Floor(huePrime);
|
||||||
|
if (region >= 6)
|
||||||
|
region = 0;
|
||||||
|
|
||||||
|
switch (region)
|
||||||
|
{
|
||||||
|
case 0:
|
||||||
|
r1 = c;
|
||||||
|
g1 = x;
|
||||||
|
b1 = 0;
|
||||||
|
break;
|
||||||
|
case 1:
|
||||||
|
r1 = x;
|
||||||
|
g1 = c;
|
||||||
|
b1 = 0;
|
||||||
|
break;
|
||||||
|
case 2:
|
||||||
|
r1 = 0;
|
||||||
|
g1 = c;
|
||||||
|
b1 = x;
|
||||||
|
break;
|
||||||
|
case 3:
|
||||||
|
r1 = 0;
|
||||||
|
g1 = x;
|
||||||
|
b1 = c;
|
||||||
|
break;
|
||||||
|
case 4:
|
||||||
|
r1 = x;
|
||||||
|
g1 = 0;
|
||||||
|
b1 = c;
|
||||||
|
break;
|
||||||
|
case 5:
|
||||||
|
default:
|
||||||
|
r1 = c;
|
||||||
|
g1 = 0;
|
||||||
|
b1 = x;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
double r = r1 + m;
|
||||||
|
double g = g1 + m;
|
||||||
|
double b = b1 + m;
|
||||||
|
|
||||||
|
return new Vector3(
|
||||||
|
(float)Math.Clamp(r, 0.0, 1.0),
|
||||||
|
(float)Math.Clamp(g, 0.0, 1.0),
|
||||||
|
(float)Math.Clamp(b, 0.0, 1.0)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static Scalar RgbToOpenCvHsv(Vector3 rgb)
|
||||||
|
{
|
||||||
|
double r = Math.Clamp(rgb.X, 0f, 1f);
|
||||||
|
double g = Math.Clamp(rgb.Y, 0f, 1f);
|
||||||
|
double b = Math.Clamp(rgb.Z, 0f, 1f);
|
||||||
|
|
||||||
|
double max = Math.Max(r, Math.Max(g, b));
|
||||||
|
double min = Math.Min(r, Math.Min(g, b));
|
||||||
|
double delta = max - min;
|
||||||
|
|
||||||
|
double hueDeg;
|
||||||
|
if (delta <= double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 0;
|
||||||
|
}
|
||||||
|
else if (Math.Abs(max - r) < double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((g - b) / delta) % 6.0);
|
||||||
|
}
|
||||||
|
else if (Math.Abs(max - g) < double.Epsilon)
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((b - r) / delta) + 2.0);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
hueDeg = 60.0 * (((r - g) / delta) + 4.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hueDeg < 0)
|
||||||
|
hueDeg += 360.0;
|
||||||
|
|
||||||
|
double saturation = max <= double.Epsilon ? 0.0 : (delta / max);
|
||||||
|
double value = max;
|
||||||
|
|
||||||
|
int h = (int)Math.Round((hueDeg / 360.0) * 179.0);
|
||||||
|
int s = (int)Math.Round(saturation * 255.0);
|
||||||
|
int v = (int)Math.Round(value * 255.0);
|
||||||
|
|
||||||
|
h = Math.Clamp(h, 0, 179);
|
||||||
|
s = Math.Clamp(s, 0, 255);
|
||||||
|
v = Math.Clamp(v, 0, 255);
|
||||||
|
|
||||||
|
return new Scalar(h, s, v);
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool SliderFill(string label, ref float value, float min, float max, string format = "%.2f", bool enforceRange = true)
|
||||||
|
{
|
||||||
|
bool changed = false;
|
||||||
|
|
||||||
|
string FormatValue(float v)
|
||||||
|
{
|
||||||
|
if (string.IsNullOrEmpty(format))
|
||||||
|
return v.ToString(CultureInfo.InvariantCulture);
|
||||||
|
|
||||||
|
bool percent = format.Contains("%%");
|
||||||
|
string core = format.Replace("%%", "");
|
||||||
|
|
||||||
|
string result;
|
||||||
|
if (core.Contains("%d"))
|
||||||
|
{
|
||||||
|
result = ((int)Math.Round(v)).ToString(CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int pos = core.IndexOf("%.");
|
||||||
|
if (pos >= 0)
|
||||||
|
{
|
||||||
|
int fPos = core.IndexOf('f', pos + 2);
|
||||||
|
if (fPos > pos)
|
||||||
|
{
|
||||||
|
string digits = core.Substring(pos + 2, fPos - (pos + 2));
|
||||||
|
if (int.TryParse(digits, out int prec))
|
||||||
|
result = v.ToString("F" + prec, CultureInfo.InvariantCulture);
|
||||||
|
else
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else if (core.Contains("%f"))
|
||||||
|
{
|
||||||
|
result = v.ToString("F2", CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
result = v.ToString(core, CultureInfo.InvariantCulture);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (percent) result += "%";
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
string valueStr = FormatValue(value);
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(valueStr).X + 12);
|
||||||
|
ImGui.TextUnformatted(valueStr);
|
||||||
|
|
||||||
|
float sliderWidth = ImGui.GetContentRegionAvail().X;
|
||||||
|
float sliderHeight = ImGui.GetFrameHeight();
|
||||||
|
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, Vector2.Zero);
|
||||||
|
ImGui.InvisibleButton("##" + label, new Vector2(sliderWidth, sliderHeight));
|
||||||
|
bool active = ImGui.IsItemActive();
|
||||||
|
bool activated = ImGui.IsItemActivated();
|
||||||
|
var io = ImGui.GetIO();
|
||||||
|
|
||||||
|
if (activated && (io.KeyCtrl))
|
||||||
|
{
|
||||||
|
string popupId = $"##SliderFillEditPopup_{label}";
|
||||||
|
string seed = value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
if (!_sliderEditBuffers.ContainsKey(label))
|
||||||
|
_sliderEditBuffers[label] = seed;
|
||||||
|
ImGui.OpenPopup(popupId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (active && !io.KeyCtrl)
|
||||||
|
{
|
||||||
|
float mouseDelta = ImGui.GetIO().MousePos.X - ImGui.GetItemRectMin().X;
|
||||||
|
float newValue = min + (mouseDelta / sliderWidth) * (max - min);
|
||||||
|
newValue = Math.Clamp(newValue, min, max);
|
||||||
|
if (format.Contains("%d"))
|
||||||
|
{
|
||||||
|
newValue = (int)Math.Round(newValue);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
int pos = format.IndexOf("%.");
|
||||||
|
if (pos >= 0)
|
||||||
|
{
|
||||||
|
int fPos = format.IndexOf('f', pos + 2);
|
||||||
|
if (fPos > pos)
|
||||||
|
{
|
||||||
|
string digits = format.Substring(pos + 2, fPos - (pos + 2));
|
||||||
|
if (int.TryParse(digits, out int prec))
|
||||||
|
newValue = (float)Math.Round(newValue, prec);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Math.Abs(newValue - value) > float.Epsilon)
|
||||||
|
{
|
||||||
|
value = newValue;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
string popupIdOuter = $"##SliderFillEditPopup_{label}";
|
||||||
|
if (ImGui.BeginPopup(popupIdOuter))
|
||||||
|
{
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
ImGui.Separator();
|
||||||
|
ImGui.PushItemWidth(-1);
|
||||||
|
string buffer = value.ToString(CultureInfo.InvariantCulture);
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.FramePadding, new Vector2(6, 4));
|
||||||
|
var inputFlags = ImGuiInputTextFlags.EnterReturnsTrue | ImGuiInputTextFlags.AutoSelectAll | ImGuiInputTextFlags.CharsDecimal | ImGuiInputTextFlags.CharsNoBlank;
|
||||||
|
if (ImGui.InputText($"##SliderFillEdit_{label}", ref buffer, 32, inputFlags))
|
||||||
|
{
|
||||||
|
string parseStr = buffer.Trim();
|
||||||
|
if (parseStr.EndsWith("%")) parseStr = parseStr.TrimEnd('%');
|
||||||
|
if (float.TryParse(parseStr, NumberStyles.Float, CultureInfo.InvariantCulture, out float typed))
|
||||||
|
{
|
||||||
|
float clamped;
|
||||||
|
if (enforceRange)
|
||||||
|
clamped = Math.Clamp(typed, min, max);
|
||||||
|
else
|
||||||
|
clamped = typed;
|
||||||
|
if (Math.Abs(clamped - value) > float.Epsilon)
|
||||||
|
{
|
||||||
|
value = clamped;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
ImGui.CloseCurrentPopup();
|
||||||
|
}
|
||||||
|
ImGui.PopStyleVar();
|
||||||
|
|
||||||
|
_sliderEditBuffers[label] = buffer;
|
||||||
|
if (ImGui.IsKeyPressed(ImGuiKey.Escape))
|
||||||
|
{
|
||||||
|
ImGui.CloseCurrentPopup();
|
||||||
|
}
|
||||||
|
ImGui.PopItemWidth();
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
Vector2 p0 = ImGui.GetItemRectMin();
|
||||||
|
Vector2 p1 = ImGui.GetItemRectMax();
|
||||||
|
|
||||||
|
drawList.AddRectFilled(p0, p1, ImGui.GetColorU32(ImGuiCol.FrameBg), 4f);
|
||||||
|
|
||||||
|
float fillWidth = ((value - min) / (max - min)) * (p1.X - p0.X);
|
||||||
|
fillWidth = Math.Clamp(fillWidth, 0f, p1.X - p0.X);
|
||||||
|
drawList.AddRectFilled(p0, new Vector2(p0.X + fillWidth, p1.Y), ImGui.GetColorU32(ImGuiCol.SliderGrabActive), 4f);
|
||||||
|
|
||||||
|
ImGui.PopStyleVar();
|
||||||
|
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool SliderFill(string label, ref int value, int min, int max)
|
||||||
|
{
|
||||||
|
float temp = value;
|
||||||
|
bool changed = SliderFill(label, ref temp, min, max, "");
|
||||||
|
if (changed)
|
||||||
|
value = (int)Math.Round(temp);
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
private class PaneGroupState
|
||||||
|
{
|
||||||
|
public string Id = "";
|
||||||
|
public int Count;
|
||||||
|
public float Spacing;
|
||||||
|
public int Index;
|
||||||
|
public float Width;
|
||||||
|
public Vector2? Padding;
|
||||||
|
public ImGuiChildFlags ChildFlags;
|
||||||
|
public ImGuiWindowFlags WindowFlags;
|
||||||
|
public float Height;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Stack<PaneGroupState> _paneGroups = new();
|
||||||
|
private static readonly Stack<bool> _paneInnerStack = new();
|
||||||
|
|
||||||
|
public static void BeginPaneGroup(string id, int count, float spacing = 12f,
|
||||||
|
Vector2? padding = null,
|
||||||
|
ImGuiChildFlags childFlags = ImGuiChildFlags.None,
|
||||||
|
ImGuiWindowFlags windowFlags = ImGuiWindowFlags.None,
|
||||||
|
float height = 0f)
|
||||||
|
{
|
||||||
|
if (count < 1) count = 1;
|
||||||
|
var avail = ImGui.GetContentRegionAvail();
|
||||||
|
float width = (avail.X - spacing * (count - 1)) / count;
|
||||||
|
_paneGroups.Push(new PaneGroupState
|
||||||
|
{
|
||||||
|
Id = id,
|
||||||
|
Count = count,
|
||||||
|
Spacing = spacing,
|
||||||
|
Index = 0,
|
||||||
|
Width = width,
|
||||||
|
Padding = padding,
|
||||||
|
ChildFlags = childFlags,
|
||||||
|
WindowFlags = windowFlags,
|
||||||
|
Height = height <= 0 ? avail.Y : height
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public static bool BeginPane(string localId, bool showHeader = true)
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Peek();
|
||||||
|
if (g.Index > 0)
|
||||||
|
ImGui.SameLine(0, g.Spacing);
|
||||||
|
|
||||||
|
string outerId = $"{g.Id}_{g.Index}_{localId}_OUTER";
|
||||||
|
bool outerOpen = ImGui.BeginChild(outerId, new Vector2(g.Width, g.Height), ImGuiChildFlags.None);
|
||||||
|
if (!outerOpen)
|
||||||
|
{
|
||||||
|
ImGui.EndChild();
|
||||||
|
_paneInnerStack.Push(false);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
var style = ImGui.GetStyle();
|
||||||
|
float padX = (g.Padding?.X ?? style.WindowPadding.X);
|
||||||
|
float padY = (g.Padding?.Y ?? style.WindowPadding.Y);
|
||||||
|
|
||||||
|
float headerHeight = 0f;
|
||||||
|
if (showHeader)
|
||||||
|
{
|
||||||
|
string headerText = localId;
|
||||||
|
float textHeight = ImGui.GetTextLineHeight();
|
||||||
|
headerHeight = textHeight + style.FramePadding.Y * 2f;
|
||||||
|
|
||||||
|
Vector2 headerMin = ImGui.GetCursorScreenPos();
|
||||||
|
|
||||||
|
Vector2 headerMax = new Vector2(headerMin.X + g.Width, headerMin.Y + headerHeight);
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
uint bgCol = ImGui.GetColorU32(ImGuiCol.FrameBg);
|
||||||
|
uint borderCol = ImGui.GetColorU32(ImGuiCol.Border);
|
||||||
|
drawList.AddRectFilled(headerMin, headerMax, bgCol, style.ChildRounding);
|
||||||
|
drawList.AddLine(new Vector2(headerMin.X, headerMax.Y - 1), new Vector2(headerMax.X, headerMax.Y - 1), borderCol);
|
||||||
|
drawList.AddRect(headerMin, headerMax, borderCol, style.ChildRounding);
|
||||||
|
|
||||||
|
ImGui.SetCursorPos(new Vector2(padX, style.FramePadding.Y));
|
||||||
|
ImGui.TextUnformatted(headerText);
|
||||||
|
}
|
||||||
|
|
||||||
|
float innerHeight = g.Height - headerHeight;
|
||||||
|
if (innerHeight < 0) innerHeight = 0;
|
||||||
|
ImGui.SetCursorPos(new Vector2(0, headerHeight));
|
||||||
|
|
||||||
|
bool pushedPad = false;
|
||||||
|
if (g.Padding.HasValue)
|
||||||
|
{
|
||||||
|
ImGui.PushStyleVar(ImGuiStyleVar.WindowPadding, g.Padding.Value);
|
||||||
|
pushedPad = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool innerOpen = ImGui.BeginChild($"{outerId}_INNER", new Vector2(0, innerHeight), ImGuiChildFlags.AlwaysUseWindowPadding);
|
||||||
|
_paneInnerStack.Push(pushedPad);
|
||||||
|
return innerOpen;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EndPane()
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Peek();
|
||||||
|
bool hadPad = _paneInnerStack.Pop();
|
||||||
|
ImGui.EndChild(); // inner
|
||||||
|
if (hadPad) ImGui.PopStyleVar();
|
||||||
|
ImGui.EndChild(); // outer
|
||||||
|
g.Index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static void EndPaneGroup()
|
||||||
|
{
|
||||||
|
var g = _paneGroups.Pop();
|
||||||
|
g.Index = g.Count;
|
||||||
|
}
|
||||||
|
|
||||||
|
private static readonly Dictionary<string, bool> _keybindListening = [];
|
||||||
|
private static readonly Dictionary<string, Keys> _keybindPending = [];
|
||||||
|
private static readonly Dictionary<string, Task?> _keybindTasks = [];
|
||||||
|
|
||||||
|
public static bool KeybindInput(string label, ref Keybind keybind, bool inline = false)
|
||||||
|
{
|
||||||
|
bool changed = false;
|
||||||
|
ImGui.PushID(label);
|
||||||
|
|
||||||
|
if (!inline)
|
||||||
|
ImGui.TextUnformatted(label);
|
||||||
|
|
||||||
|
string buttonText = _keybindListening.GetValueOrDefault(label)
|
||||||
|
? "Listening..."
|
||||||
|
: keybind.Key.ToString();
|
||||||
|
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(buttonText).X);
|
||||||
|
|
||||||
|
if (!_keybindListening.GetValueOrDefault(label, false))
|
||||||
|
{
|
||||||
|
if (ImGui.Button($"{buttonText}###{label}_Button"))
|
||||||
|
{
|
||||||
|
_keybindListening[label] = true;
|
||||||
|
_keybindPending[label] = Keys.None;
|
||||||
|
_keybindTasks[label] = Task.Run(async () =>
|
||||||
|
{
|
||||||
|
var key = await InputManager.ListenForNextKeyOrMouseAsync();
|
||||||
|
_keybindPending[label] = key;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ImGui.BeginPopupContextItem($"###{label}_Context"))
|
||||||
|
{
|
||||||
|
bool isHold = keybind.Type == KeybindType.Hold;
|
||||||
|
if (ImGui.MenuItem("Hold", null, isHold))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Hold;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isToggle = keybind.Type == KeybindType.Toggle;
|
||||||
|
if (ImGui.MenuItem("Toggle", null, isToggle))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Toggle;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool isAlways = keybind.Type == KeybindType.Always;
|
||||||
|
if (ImGui.MenuItem("Always", null, isAlways))
|
||||||
|
{
|
||||||
|
keybind.Type = KeybindType.Always;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.EndPopup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
ImGui.Button($"{buttonText}###{label}_Listening");
|
||||||
|
if (_keybindPending.GetValueOrDefault(label, Keys.None) != Keys.None)
|
||||||
|
{
|
||||||
|
keybind.Key = _keybindPending[label];
|
||||||
|
_keybindPending[label] = Keys.None;
|
||||||
|
_keybindListening[label] = false;
|
||||||
|
changed = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.PopID();
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
using ImGuiNET;
|
||||||
|
using Spectrum.Input;
|
||||||
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace Spectrum
|
||||||
|
{
|
||||||
|
partial class Renderer
|
||||||
|
{
|
||||||
|
private bool _showMovementPreview = false;
|
||||||
|
private Point _previewStartPoint = new(100, 100);
|
||||||
|
private Point _previewEndPoint = new(400, 300);
|
||||||
|
private List<(Point point, double speed)> _previewPath = [];
|
||||||
|
private int UpdatePreviewInterval = 10; // ms
|
||||||
|
private DateTime _lastPreviewUpdate = DateTime.MinValue;
|
||||||
|
private bool _isDragging = false;
|
||||||
|
private bool _isMovingStart = false;
|
||||||
|
|
||||||
|
private void RenderMovementPreview()
|
||||||
|
{
|
||||||
|
if (!_showMovementPreview)
|
||||||
|
return;
|
||||||
|
|
||||||
|
var config = mainConfig.Data;
|
||||||
|
|
||||||
|
ImGui.SetNextWindowSize(new Vector2(500, 500), ImGuiCond.Always);
|
||||||
|
ImGui.SetNextWindowPos(new Vector2(screenSize.width / 2 - 300, screenSize.height / 2 - 250), ImGuiCond.FirstUseEver);
|
||||||
|
|
||||||
|
if (!ImGui.Begin("Movement Path Preview", ref _showMovementPreview, ImGuiWindowFlags.NoResize | ImGuiWindowFlags.NoDocking | ImGuiWindowFlags.NoTitleBar))
|
||||||
|
{
|
||||||
|
ImGui.End();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.TextUnformatted("Movement Path Preview");
|
||||||
|
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 14);
|
||||||
|
if (ImGui.Button("X", new Vector2(22, 22)))
|
||||||
|
{
|
||||||
|
_showMovementPreview = false;
|
||||||
|
ImGui.End();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var boundingBox = new Rectangle(_previewEndPoint.X - 20, _previewEndPoint.Y - 40, 40, 80);
|
||||||
|
|
||||||
|
if ((DateTime.Now - _lastPreviewUpdate).TotalMilliseconds > UpdatePreviewInterval)
|
||||||
|
{
|
||||||
|
_lastPreviewUpdate = DateTime.Now;
|
||||||
|
_previewPath.Clear();
|
||||||
|
|
||||||
|
MovementPaths.ResetWindMouse();
|
||||||
|
double progress = 0.0;
|
||||||
|
double increment = config.Sensitivity * 0.02;
|
||||||
|
Point current = _previewStartPoint;
|
||||||
|
int steps = 0;
|
||||||
|
int maxSteps = 10000;
|
||||||
|
|
||||||
|
while (true)
|
||||||
|
{
|
||||||
|
double distance = Math.Sqrt(Math.Pow(_previewEndPoint.X - current.X, 2) + Math.Pow(_previewEndPoint.Y - current.Y, 2));
|
||||||
|
if (steps++ >= maxSteps)
|
||||||
|
break;
|
||||||
|
bool isInBox = boundingBox.Contains(current);
|
||||||
|
Point nextPoint = config.AimMovementType switch
|
||||||
|
{
|
||||||
|
MovementType.Linear => MovementPaths.LinearInterpolation(current, _previewEndPoint, progress),
|
||||||
|
MovementType.CubicBezier => MovementPaths.CubicBezierCurvedMovement(current, _previewEndPoint, progress),
|
||||||
|
MovementType.Adaptive => MovementPaths.AdaptiveMovement(current, _previewEndPoint, progress),
|
||||||
|
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(current, _previewEndPoint, progress),
|
||||||
|
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(current, _previewEndPoint, progress),
|
||||||
|
MovementType.WindMouse => MovementPaths.WindMouse(current, _previewEndPoint,
|
||||||
|
config.WindMouseGravity,
|
||||||
|
config.WindMouseWind,
|
||||||
|
config.WindMouseMaxStep,
|
||||||
|
config.Sensitivity,
|
||||||
|
config.WindMouseOvershoot,
|
||||||
|
isInBox),
|
||||||
|
_ => MovementPaths.LinearInterpolation(current, _previewEndPoint, progress),
|
||||||
|
};
|
||||||
|
if (config.EmaSmoothening)
|
||||||
|
nextPoint = MovementPaths.EmaSmoothing(current, nextPoint, config.EmaSmootheningFactor);
|
||||||
|
|
||||||
|
double speed = Math.Sqrt(Math.Pow(nextPoint.X - current.X, 2) + Math.Pow(nextPoint.Y - current.Y, 2));
|
||||||
|
_previewPath.Add((nextPoint, speed));
|
||||||
|
current = nextPoint;
|
||||||
|
progress += increment;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var drawList = ImGui.GetWindowDrawList();
|
||||||
|
Vector2 canvasPos = ImGui.GetCursorScreenPos();
|
||||||
|
canvasPos.Y += 5;
|
||||||
|
Vector2 canvasSize = ImGui.GetContentRegionAvail();
|
||||||
|
Vector2 size = new Vector2(canvasSize.X, canvasSize.Y - 60);
|
||||||
|
drawList.AddRectFilled(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.12f, 0.12f, 0.14f, 1.0f)), 3f);
|
||||||
|
drawList.AddRect(canvasPos, size + canvasPos, ImGui.GetColorU32(new Vector4(0.17f, 0.17f, 0.20f, 1.0f)), 3f);
|
||||||
|
drawList.AddRect(
|
||||||
|
new Vector2(boundingBox.X + canvasPos.X, boundingBox.Top + canvasPos.Y),
|
||||||
|
new Vector2(boundingBox.X + boundingBox.Width + canvasPos.X, boundingBox.Y + boundingBox.Height + canvasPos.Y),
|
||||||
|
ImGui.GetColorU32(new Vector4(0, 0, 1, 1)), 0.0f, ImDrawFlags.None, 2.0f);
|
||||||
|
|
||||||
|
if (_previewPath.Count > 1)
|
||||||
|
{
|
||||||
|
double maxSpeed = _previewPath.Max(p => p.speed);
|
||||||
|
for (int i = 1; i < _previewPath.Count; i++)
|
||||||
|
{
|
||||||
|
var (prevPoint, _) = _previewPath[i - 1];
|
||||||
|
var (currPoint, speed) = _previewPath[i];
|
||||||
|
Vector2 p1 = new Vector2(canvasPos.X + prevPoint.X, canvasPos.Y + prevPoint.Y);
|
||||||
|
Vector2 p2 = new Vector2(canvasPos.X + currPoint.X, canvasPos.Y + currPoint.Y);
|
||||||
|
Vector4 color = speed < maxSpeed / 2 ?
|
||||||
|
Vector4.Lerp(new Vector4(0, 1, 0, 1), new Vector4(1, 1, 0, 1), (float)(speed / (maxSpeed / 2))) :
|
||||||
|
Vector4.Lerp(new Vector4(1, 1, 0, 1), new Vector4(1, 0, 0, 1), (float)((speed - (maxSpeed / 2)) / (maxSpeed / 2)));
|
||||||
|
drawList.AddLine(p1, p2, ImGui.GetColorU32(color), 2.0f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewStartPoint.X, canvasPos.Y + _previewStartPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(0, 1, 0, 1)));
|
||||||
|
drawList.AddCircleFilled(new Vector2(canvasPos.X + _previewEndPoint.X, canvasPos.Y + _previewEndPoint.Y), 5.0f, ImGui.GetColorU32(new Vector4(1, 0, 0, 1)));
|
||||||
|
|
||||||
|
ImGui.InvisibleButton("canvas", size);
|
||||||
|
var io = ImGui.GetIO();
|
||||||
|
var mousePos = io.MousePos;
|
||||||
|
bool isMouseInCanvas = mousePos.X >= canvasPos.X && mousePos.X <= canvasPos.X + size.X &&
|
||||||
|
mousePos.Y >= canvasPos.Y && mousePos.Y <= canvasPos.Y + size.Y;
|
||||||
|
|
||||||
|
bool isMouseDown = ImGui.IsMouseDown(ImGuiMouseButton.Left);
|
||||||
|
bool isMouseClicked = ImGui.IsMouseClicked(ImGuiMouseButton.Left);
|
||||||
|
bool isMouseReleased = ImGui.IsMouseReleased(ImGuiMouseButton.Left);
|
||||||
|
|
||||||
|
if (!_isDragging && isMouseInCanvas && isMouseClicked)
|
||||||
|
{
|
||||||
|
Vector2 localMousePos = mousePos - canvasPos;
|
||||||
|
float distToStart = Vector2.Distance(localMousePos, new Vector2(_previewStartPoint.X, _previewStartPoint.Y));
|
||||||
|
float distToEnd = Vector2.Distance(localMousePos, new Vector2(_previewEndPoint.X, _previewEndPoint.Y));
|
||||||
|
if (distToStart < 10.0f)
|
||||||
|
{
|
||||||
|
_isMovingStart = true;
|
||||||
|
_isDragging = true;
|
||||||
|
}
|
||||||
|
else if (distToEnd < 10.0f)
|
||||||
|
{
|
||||||
|
_isMovingStart = false;
|
||||||
|
_isDragging = true;
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_isDragging = false;
|
||||||
|
_isMovingStart = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isDragging && isMouseDown)
|
||||||
|
{
|
||||||
|
Vector2 localMousePos = mousePos - canvasPos;
|
||||||
|
if (localMousePos.X < 0) localMousePos.X = 0;
|
||||||
|
if (localMousePos.Y < 0) localMousePos.Y = 0;
|
||||||
|
if (localMousePos.X > size.X) localMousePos.X = size.X;
|
||||||
|
if (localMousePos.Y > size.Y) localMousePos.Y = size.Y;
|
||||||
|
if (_isMovingStart)
|
||||||
|
{
|
||||||
|
_previewStartPoint = new Point((int)localMousePos.X, (int)localMousePos.Y);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_previewEndPoint = new Point((int)localMousePos.X, (int)localMousePos.Y);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_isDragging && isMouseReleased)
|
||||||
|
{
|
||||||
|
_isDragging = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
ImGui.Dummy(new(ImGui.GetContentRegionAvail().X, 10));
|
||||||
|
int interval = UpdatePreviewInterval;
|
||||||
|
if (ImGuiExtensions.SliderFill("Update Interval (ms)", ref interval, 1, 100))
|
||||||
|
UpdatePreviewInterval = interval;
|
||||||
|
|
||||||
|
ImGui.End();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+444
-564
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user