Files
Spectrum/Spectrum/Detection/DetectionManager.cs
T
whoswhip e08e971bf9 old changes
all of these changes were done MONTHS ago, but i'll try to list them out:
- simplified input library switching & implementation
- implemented makcu binary, which is their new communication, have NOT tested
- renamed existing makcu implementation to makcuLegacy since they've changed their communication format
- overall simplification of code
- formatted code via csharpier
- minimal optimizations
2026-08-30 10:32:56 -04:00

396 lines
18 KiB
C#

using OpenCvSharp;
using Spectrum.Input;
using Spectrum.Utilities;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.Numerics;
namespace Spectrum.Detection
{
class DetectionManager
{
private readonly Stopwatch stopwatch = new();
private Rectangle bounds = new(0, 0, 0, 0);
private readonly Rectangle monitorBounds = Program.MonitorBounds;
private readonly ConfigManager<ConfigData> mainConfig = Program.mainConfig;
private readonly Renderer? renderer;
private readonly Thread? _detectionThread;
private DateTime lastMenuToggle = DateTime.MinValue;
private readonly CaptureManager _captureManager;
private Mat? hsvBuffer;
private Mat? maskBuffer;
private Mat? bgrBuffer;
private OpenCvSharp.Size bufferSize;
private OpenCvSharp.Size bgrBufferSize;
private static void AddTiming(string name, long ticks) => Program.Timings.Add(name, ticks);
public DetectionManager(Renderer renderer)
{
this.renderer = renderer;
_captureManager = Program.SharedCaptureManager;
_detectionThread = new Thread(DetectionLoop)
{
IsBackground = true,
Name = "Spectrum Detection Thread",
Priority = ThreadPriority.AboveNormal
};
_detectionThread.Start();
}
private void DetectionLoop()
{
while (true)
{
var config = mainConfig.Data;
try
{
if ((InputManager.IsKeyOrMouseDown(config.Keybind) || InputManager.IsKeyOrMouseDown(config.TriggerKeybind)) && (!config.ShowMenu || config.DebugMode))
{
if (config.DebugMode)
stopwatch.Restart();
var t0 = Stopwatch.GetTimestamp();
renderer?.ClearDetectionDrawCommands();
if (!config.ClosestToMouse)
{
bounds = new Rectangle(
monitorBounds.X + (monitorBounds.Width - config.ImageWidth) / 2,
monitorBounds.Y + (monitorBounds.Height - config.ImageHeight) / 2,
config.ImageWidth,
config.ImageHeight
);
}
else
{
var tCursor = Stopwatch.GetTimestamp();
_ = InputManager.GetCursorPos(out System.Drawing.Point mousePos);
AddTiming("Get Cursor Pos", Stopwatch.GetTimestamp() - tCursor);
bounds = new Rectangle(
mousePos.X - (config.ImageWidth / 2),
mousePos.Y - (config.ImageHeight / 2),
config.ImageWidth,
config.ImageHeight
);
}
bounds = Rectangle.Intersect(bounds, monitorBounds);
if (bounds.Width <= 0 || bounds.Height <= 0)
{
renderer?.CommitDetectionDrawCommands();
Thread.Sleep(2);
continue;
}
Bitmap? screenshot = null;
var tCapture = Stopwatch.GetTimestamp();
if (config.CaptureMethod == CaptureMethod.DirectX && _captureManager.IsDirectXAvailable)
{
var dxBounds = new Rectangle(
bounds.X - monitorBounds.X,
bounds.Y - monitorBounds.Y,
bounds.Width,
bounds.Height
);
screenshot = _captureManager.CaptureScreenshotDirectX(dxBounds);
}
else
{
if (_captureManager.IsInitialized)
_captureManager.Dispose();
screenshot = CaptureManager.CaptureScreenshotGdi(bounds);
}
AddTiming("Screen Capture", Stopwatch.GetTimestamp() - tCapture);
if (screenshot == null)
continue;
var tMat = Stopwatch.GetTimestamp();
Mat mat = ConvertBitmapToMat(screenshot);
screenshot.Dispose();
AddTiming("Bitmap to Mat", Stopwatch.GetTimestamp() - tMat);
EnsureBuffers(mat.Size());
var tConvert = Stopwatch.GetTimestamp();
Cv2.CvtColor(mat, hsvBuffer!, ColorConversionCodes.BGR2HSV);
AddTiming("Color Conversion", Stopwatch.GetTimestamp() - tConvert);
var tRange = Stopwatch.GetTimestamp();
Cv2.InRange(hsvBuffer!, config.LowerHSV, config.UpperHSV, maskBuffer!);
AddTiming("Range Check", Stopwatch.GetTimestamp() - tRange);
var tDilate = Stopwatch.GetTimestamp();
Cv2.Dilate(maskBuffer!, maskBuffer!, null, iterations: 2);
AddTiming("Dilation", Stopwatch.GetTimestamp() - tDilate);
var tContours = Stopwatch.GetTimestamp();
Cv2.FindContours(maskBuffer!, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
AddTiming("Find Contours", Stopwatch.GetTimestamp() - tContours);
var tFilter = Stopwatch.GetTimestamp();
var filteredContours = contours.Where(c => Cv2.ContourArea(c) >= config.MinAreaPx).ToList();
AddTiming("Filter Contours", Stopwatch.GetTimestamp() - tFilter);
var tMerge = Stopwatch.GetTimestamp();
var processedContours = MergeOverlappingContours(filteredContours);
AddTiming("Merge Contours", Stopwatch.GetTimestamp() - tMerge);
if (processedContours.Count > 0)
{
double refX = bounds.X + bounds.Width * 0.5;
double refY = bounds.Y + bounds.Height * 0.5;
double minDistSquared = double.MaxValue;
Rect bestRect = default;
bool shouldDrawDetections = config.DrawDetections && renderer != null;
var tProcess = Stopwatch.GetTimestamp();
foreach (var contour in processedContours)
{
var rect = Cv2.BoundingRect(contour);
var m = Cv2.Moments(contour);
if (m.M00 == 0)
continue;
double centerX = m.M10 / m.M00;
double centerY = m.M01 / m.M00;
double absCenterX = centerX + bounds.X;
double absCenterY = centerY + bounds.Y;
double dx = absCenterX - refX;
double dy = absCenterY - refY;
double distSquared = dx * dx + dy * dy;
if (distSquared < minDistSquared)
{
minDistSquared = distSquared;
bestRect = rect;
}
if (shouldDrawDetections)
renderer!.AddRect(rect, config.DetectionColor, 1.0f, bounds);
}
AddTiming("Process Contours", Stopwatch.GetTimestamp() - tProcess);
if (bestRect != default)
{
if (shouldDrawDetections && config.HighlightTarget)
renderer!.AddRect(bestRect, config.TargetColor, 1.0f, bounds);
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 targetY = groupY + bounds.Y;
if (config.DrawAimPoint)
{
if (config.AimPointType == AimpointType.Crosshair)
{
renderer!.AddLine(new Vector2(targetX - 10, targetY), new Vector2(targetX + 10, targetY), config.AimPointColor, 2);
renderer!.AddLine(new Vector2(targetX, targetY - 10), new Vector2(targetX, targetY + 10), config.AimPointColor, 2);
renderer!.AddCircle(new Vector2(targetX, targetY), 5, config.AimPointColor, 20);
}
else if (config.AimPointType == AimpointType.Dot)
{
renderer!.AddCircleFilled(new Vector2(targetX, targetY), 5, config.AimPointColor, 20);
}
else if (config.AimPointType == AimpointType.Circle)
{
renderer!.AddCircle(new Vector2(targetX, targetY), 10, config.AimPointColor, 20);
}
}
if (config.AutoLabel)
{
AutoLabeling.AddToQueue(mat, bounds, processedContours);
AutoLabeling.AddBackgroundImage(mat, true);
}
if (!config.AutoLabel && config.CollectData)
{
AutoLabeling.AddBackgroundImage(mat, false);
}
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 (config.EnableAim && InputManager.IsKeyOrMouseDown(config.Keybind))
{
var tMove = Stopwatch.GetTimestamp();
InputManager.MoveMouse();
AddTiming("Mouse Movement", Stopwatch.GetTimestamp() - tMove);
}
if (config.TriggerBot && config.TriggerKeybind.Key != Keys.None && InputManager.IsKeyOrMouseDown(config.TriggerKeybind))
{
var _ = InputManager.ClickMouse();
}
if (renderer != null && config.DrawTriggerFov && config.TriggerBot && !config.TriggerInBoundsOnly)
{
renderer.AddCircle(new System.Numerics.Vector2(targetX, targetY), config.TriggerFov, config.TriggerRadiusColor, 100);
}
}
}
else if (config.CollectData)
{
AutoLabeling.AddBackgroundImage(mat, false);
MovementPaths.ResetWindMouse();
}
renderer?.CommitDetectionDrawCommands();
if (!AutoLabeling.Started && (config.CollectData || config.AutoLabel))
AutoLabeling.StartLabeling();
else if (AutoLabeling.Started && !config.CollectData && !config.AutoLabel)
AutoLabeling.StopLabeling();
if (config.DebugMode)
{
stopwatch.Stop();
AddTiming("Frame", stopwatch.ElapsedTicks);
}
if (Program.Timings.GetCount(["Frame"]) >= 10000)
{
LogManager.Log("---- Timing Summary ----", LogManager.LogLevel.Info);
foreach (var timing in Program.Timings.GetSnapshot())
{
LogManager.Log($"{timing.Name}: Avg = {TimingStats.FormatDuration(timing.AverageTicks)} over {timing.Count} samples", LogManager.LogLevel.Info);
}
var frameTimings = Program.Timings.GetSnapshot(["Frame"]);
LogManager.Log($"Total Overall: Avg = {TimingStats.FormatDuration(frameTimings[0].AverageTicks)} over {frameTimings[0].Count} samples", LogManager.LogLevel.Info);
LogManager.Log("------------------------", LogManager.LogLevel.Info);
Program.Timings.Clear();
}
}
else
{
renderer?.ClearDetectionDrawCommands();
renderer?.CommitDetectionDrawCommands();
MovementPaths.ResetWindMouse();
}
if (InputManager.IsKeyOrMouseDown(config.MenuKey))
{
var now = DateTime.Now;
if ((now - lastMenuToggle).TotalMilliseconds > 175)
{
config.ShowMenu = !config.ShowMenu;
lastMenuToggle = now;
}
}
if (config.AntiCapture && !Win32.IsWindowHidden)
Win32.EnableAntiCapture(renderer!.window.Handle);
else if (!config.AntiCapture && Win32.IsWindowHidden)
Win32.DisableAntiCapture(renderer!.window.Handle);
}
catch (Exception ex)
{
LogManager.Log($"DetectionLoop error: {ex.GetType().Name}: {ex.Message}", LogManager.LogLevel.Error);
}
}
}
static List<OpenCvSharp.Point[]> MergeOverlappingContours(List<OpenCvSharp.Point[]> contours)
{
if (contours.Count <= 1)
return contours;
var items = contours.Select(c => (Rect: Cv2.BoundingRect(c), Points: c.ToList())).ToList();
bool merged;
do
{
merged = false;
for (int i = 0; i < items.Count; i++)
{
for (int j = i + 1; j < items.Count; j++)
{
if (items[i].Rect.IntersectsWith(items[j].Rect))
{
var r1 = items[i].Rect;
var r2 = items[j].Rect;
var combinedRect = new Rect(
Math.Min(r1.X, r2.X),
Math.Min(r1.Y, r2.Y),
Math.Max(r1.Right, r2.Right) - Math.Min(r1.X, r2.X),
Math.Max(r1.Bottom, r2.Bottom) - Math.Min(r1.Y, r2.Y)
);
items[i].Points.AddRange(items[j].Points);
items[i] = (combinedRect, items[i].Points);
items.RemoveAt(j);
merged = true;
break;
}
}
if (merged) break;
}
} while (merged);
return items.Select(x => Cv2.ConvexHull(x.Points)).ToList();
}
private void EnsureBuffers(OpenCvSharp.Size size)
{
if (size == bufferSize && hsvBuffer != null && maskBuffer != null)
return;
hsvBuffer?.Dispose();
maskBuffer?.Dispose();
hsvBuffer = new Mat(size, MatType.CV_8UC3);
maskBuffer = new Mat(size, MatType.CV_8UC1);
bufferSize = size;
}
private Mat ConvertBitmapToMat(Bitmap bitmap)
{
var size = new OpenCvSharp.Size(bitmap.Width, bitmap.Height);
if (bgrBuffer == null || size != bgrBufferSize)
{
bgrBuffer?.Dispose();
bgrBuffer = new Mat(size, MatType.CV_8UC4);
bgrBufferSize = size;
}
var rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
var bmpData = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
try
{
unsafe
{
long bytesToCopy = (long)bmpData.Stride * bitmap.Height;
Buffer.MemoryCopy((void*)bmpData.Scan0, (void*)bgrBuffer.DataPointer, bytesToCopy, bytesToCopy);
}
}
finally
{
bitmap.UnlockBits(bmpData);
}
return bgrBuffer;
}
}
}