mirror of
https://github.com/whoswhip/Spectrum.git
synced 2026-12-06 01:28:42 +00:00
feat:
- triggerbot radius - perlin noise movement path - arduino mouse movement - HSV color picker - detection configs panel fix: - arsenal [magenta] color range - renderer available check when drawing detects and fov - extra makcu checks chore: - remove debug print in auto labeling - simplify variable initializations and other things
This commit is contained in:
+13
-16
@@ -1,7 +1,6 @@
|
||||
using Newtonsoft.Json;
|
||||
using OpenCvSharp;
|
||||
using System.Numerics;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
using LogLevel = Spectrum.LogManager.LogLevel;
|
||||
|
||||
namespace Spectrum
|
||||
@@ -94,12 +93,14 @@ namespace Spectrum
|
||||
Linear,
|
||||
CubicBezier,
|
||||
QuadraticBezier,
|
||||
Adaptive
|
||||
Adaptive,
|
||||
PerlinNoise
|
||||
}
|
||||
public enum MovementMethod
|
||||
{
|
||||
MouseEvent,
|
||||
Makcu
|
||||
Makcu,
|
||||
Arduino
|
||||
}
|
||||
public enum FovType
|
||||
{
|
||||
@@ -140,6 +141,8 @@ namespace Spectrum
|
||||
public int TriggerDelay { get; set; } = 50; // milliseconds
|
||||
public int TriggerRadius { get; set; } = 15; // pixels
|
||||
public int TriggerDuration { get; set; } = 100; // milliseconds
|
||||
public bool DrawTriggerRadius { get; set; } = false;
|
||||
public Vector4 TriggerRadiusColor { get; set; } = new Vector4(1.0f, 0.0f, 0.0f, 1.0f);
|
||||
|
||||
// Display settings
|
||||
public bool DrawDetections { get; set; } = true;
|
||||
@@ -156,8 +159,8 @@ namespace Spectrum
|
||||
public int BackgroundImageInterval { get; set; } = 10;
|
||||
|
||||
// Color settings
|
||||
public Scalar UpperHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 229);
|
||||
public Scalar UpperHSV { get; set; } = new Scalar(179, 255, 255);
|
||||
public Scalar LowerHSV { get; set; } = new Scalar(150, 255, 255);
|
||||
public string SelectedColor { get; set; } = "Arsenal [Magenta]";
|
||||
|
||||
// Misc
|
||||
@@ -165,19 +168,13 @@ namespace Spectrum
|
||||
}
|
||||
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 Scalar Upper { get; set; }
|
||||
public Scalar Lower { get; set; }
|
||||
public ColorInfo(string name, Scalar upper, Scalar lower)
|
||||
{
|
||||
Name = name;
|
||||
Upper = upper;
|
||||
Lower = lower;
|
||||
}
|
||||
public string Name { get; set; } = name;
|
||||
public Scalar Upper { get; set; } = upper;
|
||||
public Scalar Lower { get; set; } = lower;
|
||||
}
|
||||
}
|
||||
@@ -114,8 +114,6 @@ namespace Spectrum.Detection
|
||||
|
||||
public static void AddToQueue(Mat mat, Rectangle bounds, OpenCvSharp.Point[][] filteredContours)
|
||||
{
|
||||
|
||||
LogManager.Log($"Adding {filteredContours.Length} contours to labeling queue.", LogLevel.Debug);
|
||||
if (!mainConfig.Data.AutoLabel || filteredContours.Length == 0)
|
||||
return;
|
||||
|
||||
|
||||
@@ -110,16 +110,20 @@ namespace Spectrum.Detection
|
||||
bestMaxY = maxY;
|
||||
}
|
||||
|
||||
if (renderer != null && mainConfig.Data.DrawDetections)
|
||||
if (renderer != null)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
minX + bounds.X,
|
||||
minY + bounds.Y,
|
||||
(maxX - minX + 1),
|
||||
(maxY - minY + 1)
|
||||
);
|
||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||
if (mainConfig.Data.DrawDetections)
|
||||
{
|
||||
var _rect = new Rectangle(
|
||||
minX + bounds.X,
|
||||
minY + bounds.Y,
|
||||
(maxX - minX + 1),
|
||||
(maxY - minY + 1)
|
||||
);
|
||||
renderer.AddRect(_rect, mainConfig.Data.DetectionColor, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
if (closestContour != null)
|
||||
@@ -149,6 +153,10 @@ namespace Spectrum.Detection
|
||||
{
|
||||
var _ = InputManager.ClickMouse();
|
||||
}
|
||||
if (renderer != null && mainConfig.Data.DrawTriggerRadius)
|
||||
{
|
||||
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), mainConfig.Data.TriggerRadius, new System.Numerics.Vector4(1.0f, 0.0f, 0.0f, 1.0f), 100);
|
||||
}
|
||||
}
|
||||
if (mainConfig.Data.DebugMode)
|
||||
{
|
||||
|
||||
@@ -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,60 @@
|
||||
#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 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
|
||||
{
|
||||
public static MakcuMouse MakcuInstance { get; private set; }
|
||||
public static MakcuMouse? MakcuInstance { get; private set; }
|
||||
|
||||
private static bool _isMakcuLoaded = false;
|
||||
|
||||
@@ -45,7 +45,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
return false;
|
||||
}
|
||||
|
||||
string version = MakcuInstance.GetKmVersion();
|
||||
string? version = MakcuInstance.GetKmVersion();
|
||||
|
||||
_isMakcuLoaded = true;
|
||||
|
||||
@@ -53,7 +53,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
catch
|
||||
{
|
||||
_isMakcuLoaded = false;
|
||||
if (MakcuInstance != null && MakcuInstance.IsInitializedAndConnected)
|
||||
@@ -69,10 +69,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
public static void Unload()
|
||||
{
|
||||
UnsubscribeFromButtonEvents();
|
||||
if (MakcuInstance != null)
|
||||
{
|
||||
MakcuInstance.Close();
|
||||
}
|
||||
MakcuInstance?.Close();
|
||||
_isMakcuLoaded = false;
|
||||
LogManager.Log("MakcuMain: Makcu device unloaded/closed.", LogLevel.Debug);
|
||||
}
|
||||
|
||||
@@ -14,23 +14,23 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
|
||||
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 _sendInitCommands;
|
||||
|
||||
private readonly object _serialLock = new object();
|
||||
private readonly object _serialLock = new();
|
||||
private bool _isInitializedAndConnected = false;
|
||||
private Thread _listenerThread;
|
||||
private ManualResetEventSlim _stopListenerEvent = new ManualResetEventSlim(false);
|
||||
private Thread? _listenerThread;
|
||||
private ManualResetEventSlim _stopListenerEvent = new(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 bool IsInitializedAndConnected => _isInitializedAndConnected && _serialPort != null && _serialPort.IsOpen;
|
||||
|
||||
@@ -65,13 +65,13 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
catch (Exception ex)
|
||||
{
|
||||
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().");
|
||||
return null;
|
||||
return "";
|
||||
}
|
||||
|
||||
Log($"Available COM ports: {string.Join(", ", availablePorts)}. Testing each one...");
|
||||
@@ -79,7 +79,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
foreach (string portName in availablePorts)
|
||||
{
|
||||
Log($"Testing port: {portName}");
|
||||
SerialPort testPort = null;
|
||||
SerialPort? testPort = null;
|
||||
try
|
||||
{
|
||||
|
||||
@@ -121,7 +121,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
|
||||
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}'");
|
||||
testPort.Close();
|
||||
@@ -157,7 +157,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
}
|
||||
|
||||
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;
|
||||
if (!_isInitializedAndConnected || _serialPort == null || !_serialPort.IsOpen)
|
||||
@@ -286,7 +286,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
if (expectResponse)
|
||||
{
|
||||
var stopwatch = Stopwatch.StartNew();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
StringBuilder sb = new();
|
||||
string commandTrimmed = command.Trim();
|
||||
bool firstLineIsEcho = true;
|
||||
|
||||
@@ -307,7 +307,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{
|
||||
if (sb.Length > 0) continue;
|
||||
}
|
||||
if (sb.Length > 0) sb.Append("\n");
|
||||
if (sb.Length > 0) sb.Append('\n');
|
||||
sb.Append(line);
|
||||
}
|
||||
if (_serialPort.BytesToRead == 0 && sb.Length > 0)
|
||||
@@ -367,7 +367,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
{3, MakcuMouseButton.Mouse4}, {4, MakcuMouseButton.Mouse5}
|
||||
};
|
||||
|
||||
byte[] packetHeader = { 0x6B, 0x6D, 0x2E };
|
||||
byte[] packetHeader = [0x6B, 0x6D, 0x2E];
|
||||
int currentHeaderIndex = 0;
|
||||
|
||||
while (!_stopListenerEvent.IsSet)
|
||||
@@ -428,7 +428,7 @@ namespace Spectrum.Input.InputLibraries.Makcu
|
||||
if (debug)
|
||||
{
|
||||
var pressedButtons = _buttonStates.Where(kvp => kvp.Value).Select(kvp => kvp.Key.ToString()).ToArray();
|
||||
Log($"Listener: Button states updated. Mask: 0x{currentMask:X2} -> {(pressedButtons.Any() ? string.Join(", ", pressedButtons) : "None")}");
|
||||
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 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)
|
||||
{
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using Spectrum.Input.InputLibraries.Arduino;
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using MouseEvent = Spectrum.Input.InputLibraries.MouseEvent.MouseMain;
|
||||
@@ -7,9 +8,6 @@ namespace Spectrum.Input
|
||||
{
|
||||
public static class InputManager
|
||||
{
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool GetCursorPos(out Point lpPoint);
|
||||
private static ConfigManager<ConfigData> mainConfig = Program.mainConfig;
|
||||
@@ -67,6 +65,7 @@ namespace Spectrum.Input
|
||||
MovementType.Linear => MovementPaths.LinearInterpolation(start, end, effSensitivity),
|
||||
MovementType.Adaptive => MovementPaths.AdaptiveMovement(start, end, effSensitivity),
|
||||
MovementType.QuadraticBezier => MovementPaths.CurvedMovement(start, end, effSensitivity),
|
||||
MovementType.PerlinNoise => MovementPaths.PerlinNoiseMovement(start, end, effSensitivity),
|
||||
_ => end
|
||||
};
|
||||
|
||||
@@ -90,11 +89,14 @@ namespace Spectrum.Input
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||
MakcuMain.MakcuInstance.Move(deltaX, deltaY);
|
||||
else
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.Move(deltaX, deltaY);
|
||||
break;
|
||||
default:
|
||||
MouseEvent.Move(deltaX, deltaY);
|
||||
break;
|
||||
@@ -132,11 +134,14 @@ namespace Spectrum.Input
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||
MakcuMain.MakcuInstance.Press(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.ClickDown();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickDown();
|
||||
break;
|
||||
@@ -148,11 +153,14 @@ namespace Spectrum.Input
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
case MovementMethod.Makcu:
|
||||
if (EnsureMakcuReady())
|
||||
if (EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||
MakcuMain.MakcuInstance.Release(MakcuMouseButton.Left);
|
||||
else
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
case MovementMethod.Arduino:
|
||||
ArduinoMain.ClickUp();
|
||||
break;
|
||||
default:
|
||||
MouseEvent.ClickUp();
|
||||
break;
|
||||
@@ -183,7 +191,7 @@ namespace Spectrum.Input
|
||||
|
||||
Action<MakcuMouseButton, bool>? makcuHandler = null;
|
||||
bool subscribedToMakcu = false;
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady())
|
||||
if (mainConfig.Data.MovementMethod == MovementMethod.Makcu && EnsureMakcuReady() && MakcuMain.MakcuInstance != null)
|
||||
{
|
||||
makcuHandler = (btn, isPressed) =>
|
||||
{
|
||||
|
||||
@@ -4,6 +4,39 @@ namespace Spectrum.Input
|
||||
public class MovementPaths
|
||||
{
|
||||
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;
|
||||
|
||||
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)
|
||||
{
|
||||
t = Clamp01(t);
|
||||
@@ -79,6 +112,31 @@ namespace Spectrum.Input
|
||||
int newY = (int)Math.Round(start.Y + directionY * stepSize);
|
||||
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)
|
||||
{
|
||||
smoothingFactor = Math.Max(0, Math.Min(1, smoothingFactor));
|
||||
@@ -92,5 +150,21 @@ namespace Spectrum.Input
|
||||
int y = (int)Math.Round(EmaSmoothing(previous.Y, current.Y, smoothingFactor));
|
||||
return new Point(x, y);
|
||||
}
|
||||
|
||||
|
||||
private static int[] GeneratePermutation()
|
||||
{
|
||||
int[] perm = new int[256];
|
||||
for (int i = 0; i < 256; i++) perm[i] = i;
|
||||
string user = Environment.UserName;
|
||||
int seed = Environment.TickCount + user.GetHashCode();
|
||||
Random rand = new(seed);
|
||||
for (int i = 255; i > 0; i--)
|
||||
{
|
||||
int j = rand.Next(i + 1);
|
||||
(perm[i], perm[j]) = (perm[j], perm[i]);
|
||||
}
|
||||
return perm;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+32
-9
@@ -6,7 +6,9 @@ namespace Spectrum
|
||||
{
|
||||
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
|
||||
{
|
||||
Debug,
|
||||
@@ -31,19 +33,40 @@ namespace Spectrum
|
||||
return $"[{Timestamp:yyyy-MM-dd HH:mm:ss}] [{Level}] {Message}";
|
||||
}
|
||||
}
|
||||
private static List<LogEntry> _logEntries = new List<LogEntry>();
|
||||
public static IReadOnlyList<LogEntry> LogEntries => _logEntries.AsReadOnly();
|
||||
public static void Log(string message, LogLevel level = LogLevel.Info)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message)) return;
|
||||
if (mainConfig == null)
|
||||
mainConfig = Program.mainConfig;
|
||||
if (level == LogLevel.Debug && (!mainConfig.Data.DebugMode && !Debugger.IsAttached))
|
||||
return;
|
||||
{
|
||||
try { mainConfig = Program.mainConfig; } catch { }
|
||||
}
|
||||
|
||||
string logMessage = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
|
||||
Debug.WriteLine(logMessage);
|
||||
_logEntries.Add(new LogEntry(level, message));
|
||||
bool debugEnabled = Debugger.IsAttached;
|
||||
try
|
||||
{
|
||||
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)
|
||||
{
|
||||
@@ -73,7 +96,7 @@ namespace Spectrum
|
||||
Process.Start(new ProcessStartInfo
|
||||
{
|
||||
FileName = "explorer.exe",
|
||||
Arguments = Directory.GetCurrentDirectory(),
|
||||
Arguments = Path.Combine(Directory.GetCurrentDirectory(), "bin", "logs"),
|
||||
UseShellExecute = true
|
||||
});
|
||||
}
|
||||
|
||||
+2
-3
@@ -38,7 +38,7 @@ namespace Spectrum
|
||||
});
|
||||
renderThread.Start();
|
||||
|
||||
string[] dirs = { "bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs" };
|
||||
string[] dirs = ["bin", "bin/dataset", "bin/dataset/images", "bin/dataset/labels", "bin/logs", "bin/configs"];
|
||||
foreach (var dir in dirs)
|
||||
{
|
||||
if (!Directory.Exists(dir))
|
||||
@@ -48,7 +48,6 @@ namespace Spectrum
|
||||
}
|
||||
}
|
||||
|
||||
var screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
mainConfig.LoadConfig();
|
||||
mainConfig.StartFileWatcher();
|
||||
|
||||
@@ -59,7 +58,7 @@ namespace Spectrum
|
||||
|
||||
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.SaveConfig();
|
||||
colorConfig.LoadConfig(true);
|
||||
|
||||
+329
-84
@@ -1,17 +1,18 @@
|
||||
using ClickableTransparentOverlay;
|
||||
using ImGuiNET;
|
||||
using OpenCvSharp;
|
||||
using Spectrum.Detection;
|
||||
using Spectrum.Input;
|
||||
using Spectrum.Input.InputLibraries.Arduino;
|
||||
using Spectrum.Input.InputLibraries.Makcu;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Diagnostics;
|
||||
using System.Numerics;
|
||||
using System.Globalization;
|
||||
using Spectrum.Detection;
|
||||
using System.Numerics;
|
||||
|
||||
namespace Spectrum
|
||||
{
|
||||
class Renderer : Overlay
|
||||
partial class Renderer : Overlay
|
||||
{
|
||||
static (int width, int height) screenSize = SystemHelper.GetPrimaryScreenSize();
|
||||
private List<Action<ImDrawListPtr>> drawCommands = new List<Action<ImDrawListPtr>>();
|
||||
@@ -28,6 +29,7 @@ namespace Spectrum
|
||||
private ConfigManager<ColorData> colorConfig = Program.colorConfig;
|
||||
private string ColorName = "New Color";
|
||||
private static bool scrollToBottom = true;
|
||||
private ColorInfo? selectedColor = null;
|
||||
|
||||
public Renderer(CaptureManager captureManager) : base("Spectrum", screenSize.width, screenSize.width)
|
||||
{
|
||||
@@ -77,9 +79,9 @@ namespace Spectrum
|
||||
}
|
||||
|
||||
ImGui.SameLine();
|
||||
ImGui.Text("Enable Aiming");
|
||||
ImGui.TextUnformatted("Enable Aiming");
|
||||
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.Keybind.ToString()).X);
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Aiming") ? "Listening..." : mainConfig.Data.Keybind.ToString()).X);
|
||||
if (!_waitingForKeybind.GetValueOrDefault("Aiming", false))
|
||||
{
|
||||
if (ImGui.Button($"{mainConfig.Data.Keybind.ToString()}###AimKeybind"))
|
||||
@@ -105,7 +107,7 @@ namespace Spectrum
|
||||
}
|
||||
|
||||
bool closestToMouse = mainConfig.Data.ClosestToMouse;
|
||||
if (ImGui.Checkbox("Closest to Mouse", ref closestToMouse))
|
||||
if (ImGui.Checkbox(" Closest to Mouse", ref closestToMouse))
|
||||
{
|
||||
mainConfig.Data.ClosestToMouse = closestToMouse;
|
||||
}
|
||||
@@ -139,7 +141,8 @@ namespace Spectrum
|
||||
foreach (MovementType type in Enum.GetValues(typeof(MovementType)))
|
||||
{
|
||||
bool isSelected = (type == AimPath);
|
||||
if (ImGui.Selectable(type.ToString(), isSelected))
|
||||
string displayName = string.Concat(type.ToString().Select((x, i) => i > 0 && char.IsUpper(x) ? " " + x : x.ToString())); // just adds a space before capitals except for the first
|
||||
if (ImGui.Selectable(displayName, isSelected))
|
||||
{
|
||||
mainConfig.Data.AimMovementType = type;
|
||||
}
|
||||
@@ -224,14 +227,14 @@ namespace Spectrum
|
||||
if (ImGuiExtensions.BeginPane("Triggerbot"))
|
||||
{
|
||||
bool triggerBot = mainConfig.Data.TriggerBot;
|
||||
if (ImGui.Checkbox("Enabled", ref triggerBot))
|
||||
if (ImGui.Checkbox(" Enabled", ref triggerBot))
|
||||
{
|
||||
mainConfig.Data.TriggerBot = triggerBot;
|
||||
}
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(mainConfig.Data.TriggerKey.ToString()).X);
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - ImGui.CalcTextSize(_waitingForKeybind.GetValueOrDefault("Trigger Key") ? "Listening..." : mainConfig.Data.TriggerKey.ToString()).X);
|
||||
if (!_waitingForKeybind.GetValueOrDefault("Trigger Key", false))
|
||||
{
|
||||
if (ImGui.Button($"{mainConfig.Data.TriggerKey.ToString()}###TriggerKeybind"))
|
||||
if (ImGui.Button($"{mainConfig.Data.TriggerKey}###TriggerKeybind"))
|
||||
{
|
||||
_waitingForKeybind["Trigger Key"] = true;
|
||||
_pendingKeybind["Trigger Key"] = Keys.None;
|
||||
@@ -242,7 +245,7 @@ namespace Spectrum
|
||||
});
|
||||
}
|
||||
}
|
||||
else if (triggerBot)
|
||||
else
|
||||
{
|
||||
ImGui.Button("Listening... ###TriggerListening");
|
||||
if (_pendingKeybind.GetValueOrDefault("Trigger Key", Keys.None) != Keys.None)
|
||||
@@ -272,6 +275,21 @@ namespace Spectrum
|
||||
{
|
||||
mainConfig.Data.TriggerDuration = triggerDuration;
|
||||
}
|
||||
|
||||
bool DrawTriggerRadius = mainConfig.Data.DrawTriggerRadius;
|
||||
if (ImGui.Checkbox("##Draw Trigger Radius", ref DrawTriggerRadius))
|
||||
{
|
||||
mainConfig.Data.DrawTriggerRadius = DrawTriggerRadius;
|
||||
}
|
||||
ImGui.SameLine();
|
||||
ImGui.TextUnformatted("Draw Trigger Radius");
|
||||
ImGui.SameLine(ImGui.GetContentRegionAvail().X - 12);
|
||||
Vector4 RadiusColor = mainConfig.Data.TriggerRadiusColor;
|
||||
if (ImGui.ColorEdit4("Trigger Color", ref RadiusColor, ImGuiColorEditFlags.NoInputs | ImGuiColorEditFlags.NoLabel))
|
||||
{
|
||||
mainConfig.Data.DetectionColor = RadiusColor;
|
||||
}
|
||||
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
@@ -283,12 +301,14 @@ namespace Spectrum
|
||||
|
||||
if (ImGui.BeginTabItem("Detection"))
|
||||
{
|
||||
ImGuiExtensions.BeginPaneGroup("Detection Panes", 1, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
ImGuiExtensions.BeginPaneGroup("Detection Panes", 2, 12f, new Vector2(12, 10), ImGuiChildFlags.AlwaysUseWindowPadding, ImGuiWindowFlags.None, 0f);
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Detection Settings"))
|
||||
{
|
||||
ImGui.TextUnformatted("Image Width");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
int ImageWidth = mainConfig.Data.ImageWidth;
|
||||
if (ImGui.InputInt("Image Width", ref ImageWidth, 1, screenSize.width))
|
||||
if (ImGui.InputInt("##Image Width", ref ImageWidth, 1, screenSize.width))
|
||||
{
|
||||
if (ImageWidth < 1)
|
||||
ImageWidth = 1;
|
||||
@@ -297,8 +317,10 @@ namespace Spectrum
|
||||
mainConfig.Data.ImageWidth = ImageWidth;
|
||||
}
|
||||
|
||||
ImGui.TextUnformatted("Image Height");
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
int ImageHeight = mainConfig.Data.ImageHeight;
|
||||
if (ImGui.InputInt("Image Height", ref ImageHeight, 1, screenSize.height))
|
||||
if (ImGui.InputInt("##Image Height", ref ImageHeight, 1, screenSize.height))
|
||||
{
|
||||
if (ImageHeight < 1)
|
||||
ImageHeight = 1;
|
||||
@@ -307,79 +329,96 @@ namespace Spectrum
|
||||
mainConfig.Data.ImageHeight = ImageHeight;
|
||||
}
|
||||
|
||||
Scalar UpperHSV = mainConfig.Data.UpperHSV;
|
||||
Vector3 UpperHSVVec3 = new Vector3((float)UpperHSV.Val0, (float)UpperHSV.Val1, (float)UpperHSV.Val2);
|
||||
if (ImGui.InputFloat3("Upper HSV", ref UpperHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal))
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
Scalar upperHSV = mainConfig.Data.UpperHSV;
|
||||
if (ImGuiExtensions.ColorEditHSV3("Upper HSV", ref upperHSV))
|
||||
{
|
||||
mainConfig.Data.UpperHSV = new Scalar(UpperHSVVec3.X, UpperHSVVec3.Y, UpperHSVVec3.Z);
|
||||
mainConfig.Data.UpperHSV = upperHSV;
|
||||
}
|
||||
Scalar lowerHSV = mainConfig.Data.LowerHSV;
|
||||
if (ImGuiExtensions.ColorEditHSV3("Lower HSV", ref lowerHSV))
|
||||
{
|
||||
mainConfig.Data.LowerHSV = lowerHSV;
|
||||
}
|
||||
|
||||
|
||||
Scalar LowerHSV = mainConfig.Data.LowerHSV;
|
||||
Vector3 LowerHSVVec3 = new Vector3((float)LowerHSV.Val0, (float)LowerHSV.Val1, (float)LowerHSV.Val2);
|
||||
if (ImGui.InputFloat3("Lower HSV", ref LowerHSVVec3, "%.0f", ImGuiInputTextFlags.CharsDecimal))
|
||||
{
|
||||
mainConfig.Data.LowerHSV = new Scalar(LowerHSVVec3.X, LowerHSVVec3.Y, LowerHSVVec3.Z);
|
||||
}
|
||||
|
||||
List<ColorInfo> colors = colorConfig.Data.Colors;
|
||||
if (colors.Count != 0)
|
||||
{
|
||||
if (ImGui.BeginCombo("Colors", mainConfig.Data.SelectedColor))
|
||||
{
|
||||
foreach (ColorInfo color in colors)
|
||||
{
|
||||
bool isSelected = (color.Name == mainConfig.Data.SelectedColor);
|
||||
if (ImGui.Selectable(color.Name, isSelected))
|
||||
{
|
||||
mainConfig.Data.SelectedColor = color.Name;
|
||||
mainConfig.Data.UpperHSV = color.Upper;
|
||||
mainConfig.Data.LowerHSV = color.Lower;
|
||||
ColorName = color.Name;
|
||||
}
|
||||
if (isSelected)
|
||||
{
|
||||
ImGui.SetItemDefaultFocus();
|
||||
}
|
||||
}
|
||||
ImGui.EndCombo();
|
||||
}
|
||||
}
|
||||
|
||||
ImGui.InputText("##ColorNameInput", ref ColorName, 32);
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Delete Color"))
|
||||
{
|
||||
if (colors.Any(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
colors.RemoveAll(c => c.Name.Equals(mainConfig.Data.SelectedColor, StringComparison.OrdinalIgnoreCase));
|
||||
colorConfig.SaveConfig();
|
||||
mainConfig.Data.SelectedColor = "Arsenal [Magenta]";
|
||||
mainConfig.Data.UpperHSV = new Scalar(150, 255, 229);
|
||||
mainConfig.Data.LowerHSV = new Scalar(150, 255, 229);
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"Color '{mainConfig.Data.SelectedColor}' does not exist.", LogManager.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Save Color"))
|
||||
{
|
||||
var color = new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV);
|
||||
if (!string.IsNullOrEmpty(ColorName))
|
||||
{
|
||||
colors.Add(color);
|
||||
colorConfig.SaveConfig();
|
||||
mainConfig.Data.SelectedColor = ColorName;
|
||||
}
|
||||
else
|
||||
{
|
||||
LogManager.Log($"Colorname is empty.", LogManager.LogLevel.Warning);
|
||||
}
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
|
||||
if (ImGuiExtensions.BeginPane("Detection Configs"))
|
||||
{
|
||||
List<ColorInfo> colors = colorConfig.Data.Colors;
|
||||
ImGui.PushStyleColor(ImGuiCol.ChildBg, new Vector4(0.110f, 0.110f, 0.125f, 1.000f));
|
||||
ImGui.BeginChild("##DetectionConfigsChild", new Vector2(0, ImGui.GetContentRegionAvail().Y / 2), ImGuiChildFlags.None);
|
||||
ImGui.Dummy(new Vector2(0, 4));
|
||||
foreach (var color in colors)
|
||||
{
|
||||
if (ImGui.Selectable(" " + color.Name, selectedColor == color))
|
||||
{
|
||||
selectedColor = color;
|
||||
ColorName = color.Name;
|
||||
mainConfig.Data.SelectedColor = selectedColor.Name;
|
||||
}
|
||||
}
|
||||
ImGui.EndChild();
|
||||
ImGui.PopStyleColor();
|
||||
|
||||
ImGui.SetNextItemWidth(-1);
|
||||
ImGui.InputTextWithHint("##ColorName", "Color Name", ref ColorName, 100);
|
||||
|
||||
Vector2 size = new Vector2((ImGui.GetContentRegionAvail().X / 3) - 5.7f, 22);
|
||||
if (ImGui.Button("Load Color", size))
|
||||
{
|
||||
if (selectedColor != null)
|
||||
{
|
||||
mainConfig.Data.SelectedColor = selectedColor.Name;
|
||||
mainConfig.Data.UpperHSV = selectedColor.Upper;
|
||||
mainConfig.Data.LowerHSV = selectedColor.Lower;
|
||||
ColorName = selectedColor.Name;
|
||||
}
|
||||
}
|
||||
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Save Color", size))
|
||||
{
|
||||
if (colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase)) is ColorInfo existingColor)
|
||||
{
|
||||
existingColor.Upper = mainConfig.Data.UpperHSV;
|
||||
existingColor.Lower = mainConfig.Data.LowerHSV;
|
||||
selectedColor = existingColor;
|
||||
}
|
||||
else
|
||||
{
|
||||
colors.Add(new ColorInfo(ColorName, mainConfig.Data.UpperHSV, mainConfig.Data.LowerHSV));
|
||||
colorConfig.SaveConfig();
|
||||
selectedColor = colors.Find(c => c.Name.Equals(ColorName, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
}
|
||||
ImGui.SameLine();
|
||||
if (ImGui.Button("Delete Color", size))
|
||||
{
|
||||
if (selectedColor != null)
|
||||
{
|
||||
int currentIndex = colors.IndexOf(selectedColor);
|
||||
colors.RemoveAll(c => c.Name.Equals(selectedColor.Name, StringComparison.OrdinalIgnoreCase));
|
||||
colorConfig.SaveConfig();
|
||||
if (colors.Count > 0)
|
||||
{
|
||||
int nextIndex = Math.Max(0, currentIndex - 1);
|
||||
selectedColor = colors[currentIndex - 1];
|
||||
mainConfig.Data.SelectedColor = selectedColor.Name;
|
||||
mainConfig.Data.UpperHSV = selectedColor.Upper;
|
||||
mainConfig.Data.LowerHSV = selectedColor.Lower;
|
||||
ColorName = selectedColor.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
selectedColor = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
ImGuiExtensions.EndPane();
|
||||
}
|
||||
|
||||
|
||||
ImGui.EndTabItem();
|
||||
}
|
||||
@@ -405,6 +444,7 @@ namespace Spectrum
|
||||
{
|
||||
case MovementMethod.Makcu:
|
||||
{
|
||||
ArduinoMain.Close();
|
||||
var ok = MakcuMain.Load().GetAwaiter().GetResult();
|
||||
if (!ok)
|
||||
{
|
||||
@@ -414,7 +454,20 @@ namespace Spectrum
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MovementMethod.Arduino:
|
||||
{
|
||||
MakcuMain.Unload();
|
||||
var ok = ArduinoMain.Load();
|
||||
if (!ok)
|
||||
{
|
||||
LogManager.Log("Arduino failed to initialize. Falling back to MouseEvent.", LogManager.LogLevel.Warning);
|
||||
mainConfig.Data.MovementMethod = MovementMethod.MouseEvent;
|
||||
ArduinoMain.Close();
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
ArduinoMain.Close();
|
||||
MakcuMain.Unload();
|
||||
break;
|
||||
}
|
||||
@@ -564,7 +617,8 @@ namespace Spectrum
|
||||
float scrollMaxY = ImGui.GetScrollMaxY();
|
||||
bool isAtBottom = (scrollY >= scrollMaxY - 1.0f);
|
||||
|
||||
var _LogEntries = LogManager.LogEntries.ToArray();
|
||||
var _LogEntries = LogManager.LogEntries;
|
||||
_LogEntries = [.. _LogEntries];
|
||||
foreach (var log in _LogEntries)
|
||||
{
|
||||
ImGui.Text(log.ToString());
|
||||
@@ -610,6 +664,7 @@ namespace Spectrum
|
||||
ImGui.End();
|
||||
}
|
||||
|
||||
|
||||
protected void RenderOverlay()
|
||||
{
|
||||
ImGui.SetNextWindowSize(new Vector2(screenSize.width, screenSize.height), ImGuiCond.Always);
|
||||
@@ -786,6 +841,196 @@ 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 changed = false;
|
||||
|
||||
Reference in New Issue
Block a user