Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b276509109 | ||
|
|
91963a2507 | ||
|
|
bc5ae1177c | ||
|
|
177c0f9aa7 | ||
|
|
4ba2c8d7ed | ||
|
|
b2d8e8a512 | ||
|
|
b72024de04 | ||
|
|
399441b9e8 | ||
|
|
0f2b1a5fe7 | ||
|
|
9af7575d2b | ||
|
|
db06c771cd | ||
|
|
b146743c57 | ||
|
|
b0ec7eadd6 | ||
|
|
8951cc1adc | ||
|
|
c5e34a3d39 | ||
|
|
06364325b0 | ||
|
|
ffd7cfabbc | ||
|
|
057efe78a9 | ||
|
|
0fb59b19ef | ||
|
|
ca3deb42cc | ||
|
|
f23975f04c | ||
|
|
2662e7e01e | ||
|
|
cbaf1f6c36 |
No files matched your search
@@ -10,7 +10,7 @@
|
||||
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
|
||||
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<AssemblyVersion>0.44.0</AssemblyVersion>
|
||||
<AssemblyVersion>0.44.3</AssemblyVersion>
|
||||
<Platforms>x64</Platforms>
|
||||
<DebugType>embedded</DebugType>
|
||||
</PropertyGroup>
|
||||
@@ -56,16 +56,16 @@
|
||||
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
|
||||
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
|
||||
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.10.0.20240616" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.10.0.20240616" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.10.0.20240616" />
|
||||
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.122" />
|
||||
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
|
||||
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
|
||||
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
|
||||
<PackageReference Include="PresentMonFps" Version="2.0.5" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.5.1" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0" />
|
||||
<PackageReference Include="Sdcb.PaddleInference.runtime.win64.openblas" Version="2.6.1" />
|
||||
<PackageReference Include="Sdcb.PaddleOCR" Version="2.7.0.3" />
|
||||
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
|
||||
<PackageReference Include="Serilog.Extensions.Logging" Version="8.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
|
||||
|
||||
@@ -366,7 +366,7 @@ public static class KeyIdConverter
|
||||
KeyId.ScrollLock => "Scroll Lock",
|
||||
KeyId.LeftShift => "Left Shift",
|
||||
KeyId.RightShift => "Right Shift",
|
||||
KeyId.LeftCtrl => "Left Crtl",
|
||||
KeyId.LeftCtrl => "Left Ctrl",
|
||||
KeyId.RightCtrl => "Right Ctrl",
|
||||
KeyId.LeftAlt => "Left Alt",
|
||||
KeyId.RightAlt => "Right Alt",
|
||||
|
||||
@@ -119,7 +119,7 @@ public partial class PathingConditionConfig : ObservableObject
|
||||
{
|
||||
if (avatarCondition.Result == "循环短E" || avatarCondition.Result == "循环长E")
|
||||
{
|
||||
foreach (var avatar in combatScenes.Avatars)
|
||||
foreach (var avatar in combatScenes.GetAvatars())
|
||||
{
|
||||
if (avatarCondition is { Object: not null } && avatarCondition.Object.Contains(avatar.Name))
|
||||
{
|
||||
@@ -127,12 +127,12 @@ public partial class PathingConditionConfig : ObservableObject
|
||||
if (avatarCondition.Result == "循环长E")
|
||||
{
|
||||
partyConfig.GuardianElementalSkillLongPress = true;
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.SkillHoldCd.ToString(CultureInfo.CurrentCulture);
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.CombatAvatar.SkillHoldCd.ToString(CultureInfo.CurrentCulture);
|
||||
}
|
||||
else
|
||||
{
|
||||
partyConfig.GuardianElementalSkillLongPress = false;
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.SkillCd.ToString(CultureInfo.CurrentCulture);
|
||||
partyConfig.GuardianElementalSkillSecondInterval = avatar.CombatAvatar.SkillCd.ToString(CultureInfo.CurrentCulture);
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -149,9 +149,9 @@ public partial class PathingConditionConfig : ObservableObject
|
||||
{
|
||||
if (avatarCondition.Result == "作为主要行走角色")
|
||||
{
|
||||
foreach (var avatar in combatScenes.Avatars)
|
||||
foreach (var avatar in combatScenes.GetAvatars())
|
||||
{
|
||||
if (avatarCondition is { Object: not null } && avatarCondition.Object.Contains(avatar.Name))
|
||||
if (avatarCondition is not null && avatarCondition.Object.Contains(avatar.Name))
|
||||
{
|
||||
partyConfig.MainAvatarIndex = avatar.Index.ToString();
|
||||
break;
|
||||
|
||||
@@ -6,6 +6,7 @@ using Sdcb.PaddleOCR.Models;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using static Vanara.PInvoke.Gdi32;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OCR;
|
||||
|
||||
@@ -68,6 +69,16 @@ public class PaddleOcrService : IOcrService
|
||||
}
|
||||
|
||||
public PaddleOcrResult OcrResult(Mat mat)
|
||||
{
|
||||
if (mat.Channels() == 4)
|
||||
{
|
||||
using var mat3 = mat.CvtColor(ColorConversionCodes.BGRA2BGR);
|
||||
return _OcrResult(mat3);
|
||||
}
|
||||
return _OcrResult(mat);
|
||||
}
|
||||
|
||||
private PaddleOcrResult _OcrResult(Mat mat)
|
||||
{
|
||||
lock (locker)
|
||||
{
|
||||
|
||||
@@ -61,14 +61,14 @@ public static class CommonExtension
|
||||
|
||||
public static Point GetCenterPoint(this Rect rectangle)
|
||||
{
|
||||
if (rectangle == Rect.Empty) throw new ArgumentException("rectangle is empty");
|
||||
if (rectangle == default) throw new ArgumentException("rectangle is empty");
|
||||
|
||||
return new Point(rectangle.X + rectangle.Width / 2, rectangle.Y + rectangle.Height / 2);
|
||||
}
|
||||
|
||||
public static Rect Multiply(this Rect rect, double assetScale)
|
||||
{
|
||||
if (rect == Rect.Empty) throw new ArgumentException("rect is empty");
|
||||
if (rect == default) throw new ArgumentException("rect is empty");
|
||||
|
||||
return new Rect((int)(rect.X * assetScale), (int)(rect.Y * assetScale), (int)(rect.Width * assetScale), (int)(rect.Height * assetScale));
|
||||
}
|
||||
|
||||
@@ -334,7 +334,7 @@ public class FeatureMatcher
|
||||
var corners = MatchCorners(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
|
||||
if (corners.Length == 0)
|
||||
{
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
return Cv2.BoundingRect(corners);
|
||||
}
|
||||
@@ -483,7 +483,7 @@ public class FeatureMatcher
|
||||
var corners = KnnMatchCorners(_trainKeyPoints, _trainDescriptors, queryMat, queryMatMask);
|
||||
if (corners.Length == 0)
|
||||
{
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
return Cv2.BoundingRect(corners);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using OpenCvSharp;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
|
||||
@@ -7,7 +10,6 @@ public class OpenCvCommonHelper
|
||||
{
|
||||
/// <summary>
|
||||
/// 计算灰度图中某个颜色的像素个数
|
||||
/// 快速遍历方法来自于: https://blog.csdn.net/TyroneKing/article/details/129108838
|
||||
/// </summary>
|
||||
/// <param name="mat"></param>
|
||||
/// <param name="color"></param>
|
||||
@@ -15,57 +17,65 @@ public class OpenCvCommonHelper
|
||||
public static int CountGrayMatColor(Mat mat, byte color)
|
||||
{
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
var channels = mat.Channels();
|
||||
var nRows = mat.Rows;
|
||||
var nCols = mat.Cols * channels;
|
||||
if (mat.IsContinuous())
|
||||
return SplitChannal(mat, m => CountGrayMatColorC1(m, color)).Sum();
|
||||
}
|
||||
|
||||
private static IEnumerable<T> SplitChannal<T>(Mat mat, Func<Mat, T> func)
|
||||
{
|
||||
if (mat.Empty()) return [];
|
||||
if (mat.Channels() == 1)
|
||||
{
|
||||
nCols *= nRows;
|
||||
nRows = 1;
|
||||
return [func.Invoke(mat)];
|
||||
}
|
||||
|
||||
var sum = 0;
|
||||
unsafe
|
||||
Mat[]? channels = null;
|
||||
try
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
var p = mat.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
for (var j = 0; j < nCols; j++)
|
||||
if (b[j] == color)
|
||||
sum++;
|
||||
}
|
||||
channels = mat.Split();
|
||||
return channels.AsParallel().Select(func);
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 释放所有分离出的通道内存
|
||||
if (channels is not null)
|
||||
foreach (var ch in channels)
|
||||
ch.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
/// <summary>
|
||||
/// 仅限单通道,统计等于color的颜色
|
||||
/// </summary>
|
||||
/// <param name="mat">矩阵</param>
|
||||
/// <param name="color">值</param>
|
||||
/// <returns></returns>
|
||||
public static int CountGrayMatColorC1(Mat mat, byte color)
|
||||
{
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
Debug.Assert(mat.Channels() == 1);
|
||||
using var dst = new Mat();
|
||||
Cv2.Compare(mat, color, dst, CmpType.EQ);
|
||||
return Cv2.CountNonZero(dst);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅限单通道,统计颜色在lowColor和highColor中范围
|
||||
/// </summary>
|
||||
/// <param name="mat">矩阵</param>
|
||||
/// <param name="lowColor">低</param>
|
||||
/// <param name="highColor">高</param>
|
||||
/// <returns></returns>
|
||||
public static int CountGrayMatColorC1(Mat mat, byte lowColor, byte highColor)
|
||||
{
|
||||
using var mask = new Mat();
|
||||
// 使用InRange直接生成二值掩膜
|
||||
Cv2.InRange(mat, new Scalar(lowColor), new Scalar(highColor), mask);
|
||||
return Cv2.CountNonZero(mask);
|
||||
}
|
||||
|
||||
public static int CountGrayMatColor(Mat mat, byte lowColor, byte highColor)
|
||||
{
|
||||
Debug.Assert(mat.Depth() == MatType.CV_8U);
|
||||
var channels = mat.Channels();
|
||||
var nRows = mat.Rows;
|
||||
var nCols = mat.Cols * channels;
|
||||
if (mat.IsContinuous())
|
||||
{
|
||||
nCols *= nRows;
|
||||
nRows = 1;
|
||||
}
|
||||
|
||||
var sum = 0;
|
||||
unsafe
|
||||
{
|
||||
for (var i = 0; i < nRows; i++)
|
||||
{
|
||||
var p = mat.Ptr(i);
|
||||
var b = (byte*)p.ToPointer();
|
||||
for (var j = 0; j < nCols; j++)
|
||||
if (b[j] >= lowColor && b[j] <= highColor)
|
||||
sum++;
|
||||
}
|
||||
}
|
||||
|
||||
return sum;
|
||||
return SplitChannal(mat, m => CountGrayMatColorC1(m, lowColor, highColor)).Sum();
|
||||
}
|
||||
|
||||
public static Mat Threshold(Mat src, Scalar low, Scalar high)
|
||||
@@ -75,7 +85,7 @@ public class OpenCvCommonHelper
|
||||
|
||||
Cv2.CvtColor(src, rgbMat, ColorConversionCodes.BGR2RGB);
|
||||
Cv2.InRange(rgbMat, low, high, mask);
|
||||
Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化
|
||||
// Cv2.Threshold(mask, mask, 0, 255, ThresholdTypes.Binary); //二值化 //不需要
|
||||
return mask.Clone();
|
||||
}
|
||||
|
||||
@@ -104,6 +114,6 @@ public class OpenCvCommonHelper
|
||||
{
|
||||
var mask = new Mat();
|
||||
Cv2.InRange(src, s, s, mask);
|
||||
return 255 - mask;
|
||||
return ~ mask;
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,11 @@ using Vanara.PInvoke;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.ViewModel.Pages;
|
||||
using System;
|
||||
|
||||
using BetterGenshinImpact.GameTask.AutoPathing;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using OpenCvSharp;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using BetterGenshinImpact.GameTask.Common.Map;
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public class Genshin
|
||||
@@ -69,6 +73,87 @@ public class Genshin
|
||||
await Tp(dx, dy, force);
|
||||
}
|
||||
|
||||
|
||||
#region 大地图操作
|
||||
/// <summary>
|
||||
/// 移动大地图到指定坐标
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 与内置传送功能不同,此方法不会多次重试。
|
||||
/// 为避免初次中心点识别失败,建议先使用 SetBigMapZoomLevel 设置合适的大地图缩放等级。
|
||||
/// </remarks>
|
||||
/// <param name="x">目标X坐标</param>
|
||||
/// <param name="y">目标Y坐标</param>
|
||||
/// <param name="forceCountry">强制指定移动大地图时先切换的国家,默认为null</param>
|
||||
public async Task MoveMapTo(int x, int y, string? forceCountry = null)
|
||||
{
|
||||
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
|
||||
await tpTask.CheckInBigMapUi();
|
||||
await tpTask.SwitchRecentlyCountryMap(x, y, forceCountry);
|
||||
await tpTask.MoveMapTo(x, y);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前大地图缩放等级
|
||||
/// </summary>
|
||||
/// <returns>当前大地图缩放等级,范围1.0-6.0</returns>
|
||||
public double GetBigMapZoomLevel()
|
||||
{
|
||||
TpTask tpTask = new(CancellationContext.Instance.Cts.Token);
|
||||
return tpTask.GetBigMapZoomLevel(CaptureToRectArea());
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将大地图缩放等级设置为指定值
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 缩放等级说明:
|
||||
/// - 数值范围:1.0(最大地图) 到 6.0(最小地图)
|
||||
/// - 缩放效果:数值越大,地图显示范围越广,细节越少
|
||||
/// - 缩放位置:1.0 对应缩放条最上方,6.0 对应缩放条最下方
|
||||
/// - 推荐范围:建议在 2.0 到 5.0 之间调整,过大或过小可能影响操作
|
||||
/// </remarks>
|
||||
/// <param name="zoomLevel">目标缩放等级,范围 1.0-6.0</param>
|
||||
public async Task SetBigMapZoomLevel(double zoomLevel)
|
||||
{
|
||||
TpTask tpTask = new(CancellationContext.Instance.Cts.Token);
|
||||
double currentZoomLevel = GetBigMapZoomLevel();
|
||||
await tpTask.AdjustMapZoomLevel(currentZoomLevel, zoomLevel);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 传送到用户指定的七天神像
|
||||
/// </summary>
|
||||
public async Task TpToStatueOfTheSeven()
|
||||
{
|
||||
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
|
||||
await tpTask.TpToStatueOfTheSeven();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前在大地图上的位置坐标
|
||||
/// </summary>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromBigMap()
|
||||
{
|
||||
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
|
||||
return tpTask.GetPositionFromBigMap();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前在小地图上的位置坐标
|
||||
/// </summary>
|
||||
/// <returns>包含X和Y坐标的Point2f结构体</returns>
|
||||
public Point2f GetPositionFromMap(){
|
||||
var imageRegion = CaptureToRectArea();
|
||||
if (!Bv.IsInMainUi(imageRegion))
|
||||
{
|
||||
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
|
||||
}
|
||||
return MapCoordinate.Main2048ToGame(Navigation.GetPositionStable(imageRegion));
|
||||
}
|
||||
|
||||
#endregion 大地图操作
|
||||
/// <summary>
|
||||
/// 切换队伍
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using BetterGenshinImpact.Service.Notification.Model.Enum;
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Script.Dependence;
|
||||
|
||||
public class Notification
|
||||
{
|
||||
private readonly AllConfig _config = TaskContext.Instance().Config;
|
||||
private readonly ILogger<Notification> _logger = App.GetLogger<Notification>();
|
||||
private readonly TimeSpan _timeWindow = TimeSpan.FromMinutes(1);
|
||||
private readonly int _maxNotifications = 5;
|
||||
private readonly Queue<DateTime> _callRecords = new();
|
||||
|
||||
private static readonly string[] _forbiddenPatterns =
|
||||
[
|
||||
"<script>", "http://", "https://"
|
||||
];
|
||||
|
||||
private bool CheckNotificationPermission()
|
||||
{
|
||||
try
|
||||
{
|
||||
var currentProject = TaskContext.Instance().CurrentScriptProject;
|
||||
return _config.NotificationConfig.JsNotificationEnabled &&
|
||||
(currentProject?.AllowJsNotification ?? true);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ValidateContent(string message) // 不允许发送超过 500 字符的消息
|
||||
{
|
||||
if (message.Length > 500) return false;
|
||||
|
||||
return !_forbiddenPatterns
|
||||
.Any(p => message.IndexOf(p, StringComparison.OrdinalIgnoreCase) >= 0);
|
||||
}
|
||||
|
||||
private bool CheckRateLimit() // 不允许频繁发送消息
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
while (_callRecords.TryPeek(out var time) && now - time > _timeWindow)
|
||||
{
|
||||
_callRecords.Dequeue();
|
||||
}
|
||||
|
||||
if (_callRecords.Count >= _maxNotifications)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
_callRecords.Enqueue(now);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送成功通知
|
||||
/// </summary>
|
||||
/// <param name="message">通知消息</param>
|
||||
public void Send(string message)
|
||||
{
|
||||
if (!CheckNotificationPermission())
|
||||
{
|
||||
_logger.LogWarning("JS 通知关闭,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
if (!CheckRateLimit())
|
||||
{
|
||||
_logger.LogWarning("通知频率超限,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
if (!ValidateContent(message))
|
||||
{
|
||||
_logger.LogWarning("通知内容违规,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
Notify.Event(NotificationEvent.JsCustom).Send(message);
|
||||
_logger.LogInformation("通知发送成功:" + message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送错误通知
|
||||
/// </summary>
|
||||
/// <param name="message">通知消息</param>
|
||||
public void Error(string message)
|
||||
{
|
||||
if (!CheckNotificationPermission())
|
||||
{
|
||||
_logger.LogWarning("JS 通知关闭,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
if (!CheckRateLimit())
|
||||
{
|
||||
_logger.LogWarning("通知频率超限,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ValidateContent(message))
|
||||
{
|
||||
_logger.LogWarning("通知内容违规,消息被拦截: " + message);
|
||||
return;
|
||||
}
|
||||
Notify.Event(NotificationEvent.JsError).Error(message);
|
||||
_logger.LogInformation("错误通知发送成功:" + message);
|
||||
}
|
||||
}
|
||||
@@ -28,6 +28,7 @@ public class EngineExtend
|
||||
engine.AddHostObject("genshin", new Dependence.Genshin());
|
||||
engine.AddHostObject("log", new Log());
|
||||
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
|
||||
engine.AddHostObject("notification", new Notification());
|
||||
|
||||
// 任务调度器
|
||||
engine.AddHostObject("dispatcher", new Dispatcher(config));
|
||||
@@ -42,6 +43,7 @@ public class EngineExtend
|
||||
|
||||
// 识图模块相关
|
||||
engine.AddHostType("Mat", typeof(Mat));
|
||||
engine.AddHostType("Point2f", typeof(Point2f)); // 添加Point2f类型暴露
|
||||
engine.AddHostType("RecognitionObject", typeof(RecognitionObject));
|
||||
engine.AddHostType("DesktopRegion", typeof(DesktopRegion));
|
||||
engine.AddHostType("GameCaptureRegion", typeof(GameCaptureRegion));
|
||||
|
||||
@@ -9,6 +9,7 @@ using BetterGenshinImpact.ViewModel.Pages;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Dynamic;
|
||||
using System.IO;
|
||||
using System.Text.Json.Serialization;
|
||||
@@ -77,6 +78,9 @@ public partial class ScriptGroupProject : ObservableObject
|
||||
[JsonIgnore]
|
||||
[ObservableProperty]
|
||||
public bool? _nextFlag = false;
|
||||
|
||||
[ObservableProperty]
|
||||
private bool? _allowJsNotification = true;
|
||||
|
||||
public ScriptGroupProject()
|
||||
{
|
||||
|
||||
@@ -75,7 +75,8 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
|
||||
|
||||
IStringLocalizer<AutoDomainTask> stringLocalizer = App.GetService<IStringLocalizer<AutoDomainTask>>() ?? throw new NullReferenceException();
|
||||
IStringLocalizer<AutoDomainTask> stringLocalizer =
|
||||
App.GetService<IStringLocalizer<AutoDomainTask>>() ?? throw new NullReferenceException();
|
||||
CultureInfo cultureInfo = new CultureInfo(TaskContext.Instance().Config.OtherConfig.GameCultureInfoName);
|
||||
this.challengeCompletedLocalizedString = stringLocalizer.WithCultureGet(cultureInfo, "挑战达成");
|
||||
this.autoLeavingLocalizedString = stringLocalizer.WithCultureGet(cultureInfo, "自动退出");
|
||||
@@ -210,13 +211,15 @@ public class AutoDomainTask : ISoloTask
|
||||
var gameScreenSize = SystemControl.GetGameScreenRect(TaskContext.Instance().GameHandle);
|
||||
if (gameScreenSize.Width * 9 != gameScreenSize.Height * 16)
|
||||
{
|
||||
Logger.LogError("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
Logger.LogError("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏无法正常使用自动秘境功能 !",
|
||||
gameScreenSize.Width, gameScreenSize.Height);
|
||||
throw new Exception("游戏窗口分辨率不是 16:9");
|
||||
}
|
||||
|
||||
if (gameScreenSize.Width < 1920 || gameScreenSize.Height < 1080)
|
||||
{
|
||||
Logger.LogWarning("游戏窗口分辨率小于 1920x1080 !当前分辨率为 {Width}x{Height} , 小于 1920x1080 的分辨率的游戏可能无法正常使用自动秘境功能 !", gameScreenSize.Width, gameScreenSize.Height);
|
||||
Logger.LogWarning("游戏窗口分辨率小于 1920x1080 !当前分辨率为 {Width}x{Height} , 小于 1920x1080 的分辨率的游戏可能无法正常使用自动秘境功能 !",
|
||||
gameScreenSize.Width, gameScreenSize.Height);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -328,7 +331,7 @@ public class AutoDomainTask : ISoloTask
|
||||
await Delay(800, _ct);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// 点击单人挑战
|
||||
int retryTimes = 0;
|
||||
while (retryTimes < 20)
|
||||
@@ -343,14 +346,18 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
await Delay(1500, _ct);
|
||||
}
|
||||
|
||||
|
||||
// 判断弹框
|
||||
await Delay(600, _ct);
|
||||
using var confirmRectArea2 = CaptureToRectArea().Find(ElementAssets.Instance.BtnBlackConfirm);
|
||||
if (!confirmRectArea2.IsEmpty())
|
||||
var ra = CaptureToRectArea();
|
||||
using var confirmRectArea2 = ra.Find(RecognitionObject.Ocr(ra.Width * 0.263, ra.Height * 0.32,
|
||||
ra.Width - ra.Width * 0.263 * 2, ra.Height - ra.Height * 0.32 - ra.Height * 0.353));
|
||||
if (confirmRectArea2.IsExist() && confirmRectArea2.Text.Contains("是否仍要挑战该秘境"))
|
||||
{
|
||||
throw new Exception("收取完成秘境的奖励需要20点原粹树脂,当前树脂不足,自动秘境停止运行");
|
||||
Logger.LogWarning("自动秘境:检测到树脂不足提示:{Text}", confirmRectArea2.Text);
|
||||
throw new Exception("当前树脂不足,自动秘境停止运行。");
|
||||
}
|
||||
|
||||
|
||||
// 点击进入
|
||||
retryTimes = 0;
|
||||
while (retryTimes < 20)
|
||||
@@ -362,6 +369,7 @@ public class AutoDomainTask : ISoloTask
|
||||
confirmRectArea.Click();
|
||||
break;
|
||||
}
|
||||
|
||||
await Delay(1200, _ct);
|
||||
}
|
||||
|
||||
@@ -387,7 +395,9 @@ public class AutoDomainTask : ISoloTask
|
||||
// }
|
||||
|
||||
var ocrList = ra.FindMulti(RecognitionObject.Ocr(0, ra.Height * 0.2, ra.Width, ra.Height * 0.6));
|
||||
var done = ocrList.FirstOrDefault(t => Regex.IsMatch(t.Text, this.leyLineDisorderLocalizedString) || Regex.IsMatch(t.Text, this.clickanywheretocloseLocalizedString));
|
||||
var done = ocrList.FirstOrDefault(t =>
|
||||
Regex.IsMatch(t.Text, this.leyLineDisorderLocalizedString) ||
|
||||
Regex.IsMatch(t.Text, this.clickanywheretocloseLocalizedString));
|
||||
if (done != null)
|
||||
{
|
||||
await Delay(1000, _ct);
|
||||
@@ -404,7 +414,7 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
private List<CombatCommand> FindCombatScriptAndSwitchAvatar(CombatScenes combatScenes)
|
||||
{
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.GetAvatars());
|
||||
var avatar = combatScenes.SelectAvatar(combatCommands[0].Name);
|
||||
avatar?.SwitchWithoutCts();
|
||||
Sleep(200);
|
||||
@@ -447,9 +457,9 @@ public class AutoDomainTask : ISoloTask
|
||||
Simulation.SendInput.Keyboard.KeyPress(AutoPickAssets.Instance.PickVk);
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
// 超时直接放弃整个秘境
|
||||
if (DateTime.Now - startTime> TimeSpan.FromSeconds(60))
|
||||
if (DateTime.Now - startTime > TimeSpan.FromSeconds(60))
|
||||
{
|
||||
Logger.LogWarning("自动秘境:{Text}", "前往目标位置处超时,如果选择了秘境名称,将在传送后重试秘境!");
|
||||
Avatar.TpForRecover(_ct, new RetryException("前往目标位置处超时,先传送到七天神像,然后重试秘境"));
|
||||
@@ -662,7 +672,7 @@ public class AutoDomainTask : ISoloTask
|
||||
while (!_ct.IsCancellationRequested)
|
||||
{
|
||||
var treeRect = DetectTree(CaptureToRectArea());
|
||||
if (treeRect != Rect.Empty)
|
||||
if (treeRect != default)
|
||||
{
|
||||
var treeMiddleX = treeRect.X + treeRect.Width / 2;
|
||||
if (treeRect.X + treeRect.Width < middleX && !_config.ShortMovement)
|
||||
@@ -828,7 +838,7 @@ public class AutoDomainTask : ISoloTask
|
||||
return new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height);
|
||||
}
|
||||
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
|
||||
private Task LockCameraToEastTask(CancellationTokenSource cts, Task moveAvatarTask)
|
||||
@@ -943,7 +953,8 @@ public class AutoDomainTask : ISoloTask
|
||||
using var ra = CaptureToRectArea();
|
||||
|
||||
// OCR识别是否有跳过
|
||||
var ocrList = ra.FindMulti(RecognitionObject.Ocr(captureArea.Width - 230 * assetScale, 0, 230 * assetScale - 5, 80 * assetScale));
|
||||
var ocrList = ra.FindMulti(RecognitionObject.Ocr(captureArea.Width - 230 * assetScale, 0,
|
||||
230 * assetScale - 5, 80 * assetScale));
|
||||
var skipTextRa = ocrList.FirstOrDefault(t => Regex.IsMatch(t.Text, this.skipLocalizedString));
|
||||
if (skipTextRa != null)
|
||||
{
|
||||
@@ -1012,7 +1023,8 @@ public class AutoDomainTask : ISoloTask
|
||||
if (!condensedResinCountRa.IsEmpty())
|
||||
{
|
||||
// 图像右侧就是浓缩树脂数量
|
||||
var countArea = ra.DeriveCrop(condensedResinCountRa.X + condensedResinCountRa.Width, condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height);
|
||||
var countArea = ra.DeriveCrop(condensedResinCountRa.X + condensedResinCountRa.Width,
|
||||
condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height);
|
||||
// Cv2.ImWrite($"log/resin_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")}.png", countArea.SrcGreyMat);
|
||||
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
|
||||
condensedResinCount = StringUtils.TryParseInt(count);
|
||||
@@ -1023,12 +1035,14 @@ public class AutoDomainTask : ISoloTask
|
||||
if (!fragileResinCountRa.IsEmpty())
|
||||
{
|
||||
// 图像右侧就是脆弱树脂数量
|
||||
var countArea = ra.DeriveCrop(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y, (int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height);
|
||||
var countArea = ra.DeriveCrop(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y,
|
||||
(int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height);
|
||||
var count = OcrFactory.Paddle.Ocr(countArea.SrcGreyMat);
|
||||
fragileResinCount = StringUtils.TryParseInt(count);
|
||||
}
|
||||
|
||||
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 脆弱树脂 {FragileResinCount}", condensedResinCount, fragileResinCount);
|
||||
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 脆弱树脂 {FragileResinCount}", condensedResinCount,
|
||||
fragileResinCount);
|
||||
return (condensedResinCount, fragileResinCount);
|
||||
}
|
||||
|
||||
|
||||
@@ -7,21 +7,17 @@ using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Diagnostics;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Assets;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.GameTask.Common.Job;
|
||||
using OpenCvSharp;
|
||||
using Vanara;
|
||||
using Vanara.PInvoke;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Vanara;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight;
|
||||
|
||||
@@ -56,9 +52,12 @@ public class AutoFightTask : ISoloTask
|
||||
FastCheckEnabled = finishDetectConfig.FastCheckEnabled;
|
||||
ParseCheckTimeString(finishDetectConfig.FastCheckParams, out CheckTime, CheckNames);
|
||||
ParseFastCheckEndDelayString(finishDetectConfig.CheckEndDelay, out DelayTime, DelayTimes);
|
||||
BattleEndProgressBarColor = ParseStringToTuple(finishDetectConfig.BattleEndProgressBarColor, (95, 235, 255));
|
||||
BattleEndProgressBarColorTolerance = ParseSingleOrCommaSeparated(finishDetectConfig.BattleEndProgressBarColorTolerance, (6, 6, 6));
|
||||
DetectDelayTime = (int)((double.TryParse(finishDetectConfig.BeforeDetectDelay, out var result) ? result : 0.45) * 1000);
|
||||
BattleEndProgressBarColor =
|
||||
ParseStringToTuple(finishDetectConfig.BattleEndProgressBarColor, (95, 235, 255));
|
||||
BattleEndProgressBarColorTolerance =
|
||||
ParseSingleOrCommaSeparated(finishDetectConfig.BattleEndProgressBarColorTolerance, (6, 6, 6));
|
||||
DetectDelayTime =
|
||||
(int)((double.TryParse(finishDetectConfig.BeforeDetectDelay, out var result) ? result : 0.45) * 1000);
|
||||
}
|
||||
|
||||
public (int, int, int) BattleEndProgressBarColor { get; }
|
||||
@@ -85,7 +84,8 @@ public class AutoFightTask : ISoloTask
|
||||
var trimmedSegment = segment.Trim();
|
||||
|
||||
// 如果是纯数字部分
|
||||
if (double.TryParse(trimmedSegment, NumberStyles.Float, CultureInfo.InvariantCulture, out double number))
|
||||
if (double.TryParse(trimmedSegment, NumberStyles.Float, CultureInfo.InvariantCulture,
|
||||
out double number))
|
||||
{
|
||||
checkTime = number; // 更新 CheckTime
|
||||
}
|
||||
@@ -120,7 +120,8 @@ public class AutoFightTask : ISoloTask
|
||||
// 如果是纯数字部分
|
||||
if (parts.Length == 1)
|
||||
{
|
||||
if (double.TryParse(parts[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double number))
|
||||
if (double.TryParse(parts[0].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture,
|
||||
out double number))
|
||||
{
|
||||
delayTime = (int)(number * 1000); // 更新 delayTime
|
||||
}
|
||||
@@ -129,7 +130,8 @@ public class AutoFightTask : ISoloTask
|
||||
else if (parts.Length == 2)
|
||||
{
|
||||
string name = parts[0].Trim();
|
||||
if (double.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out double value))
|
||||
if (double.TryParse(parts[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture,
|
||||
out double value))
|
||||
{
|
||||
nameDelayMap[name] = (int)(value * 1000); // 更新字典,取最后一个值
|
||||
}
|
||||
@@ -204,8 +206,37 @@ public class AutoFightTask : ISoloTask
|
||||
throw new Exception("识别队伍角色失败");
|
||||
}
|
||||
|
||||
var actionSchedulerByCd = ParseStringToDictionary(_taskParam.ActionSchedulerByCd);
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
|
||||
|
||||
// var actionSchedulerByCd = ParseStringToDictionary(_taskParam.ActionSchedulerByCd);
|
||||
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.GetAvatars());
|
||||
// 命令用到的角色 筛选交集
|
||||
var commandAvatars = combatCommands.Select(c => c.Name).Distinct()
|
||||
.Select(n => combatScenes.SelectAvatar(n))
|
||||
.WhereNotNull().ToImmutableDictionary(avatar => avatar.Name);
|
||||
// 过滤不可执行的脚本,Task里并不支持"当前角色"。
|
||||
combatCommands = combatCommands
|
||||
.Where(c =>commandAvatars.ContainsKey(c.Name))
|
||||
.ToList();
|
||||
if (commandAvatars.IsEmpty)
|
||||
{
|
||||
throw new Exception("没有可用战斗脚本");
|
||||
}
|
||||
// 可以跳过的角色名
|
||||
List<string> canBeSkippedAvatarNames = [];
|
||||
// 通过环境更新角色的cd并看看那些角色启用了跳过
|
||||
foreach (var avatar in commandAvatars)
|
||||
{
|
||||
var mCd = Avatar.ParseActionSchedulerByCd(_taskParam.ActionSchedulerByCd, avatar.Key);
|
||||
if (mCd is not null)
|
||||
{
|
||||
avatar.Value.ManualSkillCd = (double)mCd;
|
||||
canBeSkippedAvatarNames.Add(avatar.Key);
|
||||
}
|
||||
else
|
||||
{
|
||||
avatar.Value.ManualSkillCd = -1;
|
||||
}
|
||||
}
|
||||
|
||||
// 新的取消token
|
||||
var cts2 = new CancellationTokenSource();
|
||||
@@ -225,7 +256,7 @@ public class AutoFightTask : ISoloTask
|
||||
// }
|
||||
var fightEndFlag = false;
|
||||
string lastFightName = "";
|
||||
string skipFightName = "";
|
||||
|
||||
//统计切换人打架次数
|
||||
var countFight = 0;
|
||||
// 战斗操作
|
||||
@@ -235,10 +266,57 @@ public class AutoFightTask : ISoloTask
|
||||
{
|
||||
while (!cts2.Token.IsCancellationRequested)
|
||||
{
|
||||
if (commandAvatars.Count == canBeSkippedAvatarNames.Count)
|
||||
{
|
||||
// 所有战斗角色都可以被取消
|
||||
var minCoolDown = commandAvatars.Select(a => a.Value.GetSkillCdSeconds()).Min();
|
||||
if (minCoolDown > 0)
|
||||
{
|
||||
Logger.LogInformation("队伍中所有角色的技能都在冷却中,等待{MinCoolDown}秒后继续。", Math.Round(minCoolDown, 2));
|
||||
await Delay((int)Math.Ceiling(minCoolDown * 1000), ct);
|
||||
}
|
||||
}
|
||||
var skipFightName = "";
|
||||
// 通用化战斗策略
|
||||
for (var i = 0; i < combatCommands.Count; i++)
|
||||
{
|
||||
var command = combatCommands[i];
|
||||
//如果上个执行者和这次是一个角色,且中间没有跳过,继续执行不判断cd
|
||||
if (lastFightName != command.Name || skipFightName != "")
|
||||
{
|
||||
var avatar = combatScenes.SelectAvatar(command.Name);
|
||||
if (avatar is null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var cd = avatar.GetSkillCdSeconds();
|
||||
if (cd > 0)
|
||||
{
|
||||
if (skipFightName != command.Name && canBeSkippedAvatarNames.Contains(command.Name))
|
||||
{
|
||||
var manualSkillCd = avatar.ManualSkillCd;
|
||||
if (manualSkillCd > 0)
|
||||
{
|
||||
Logger.LogInformation("{commandName}cd冷却为{skillCd}秒,剩余{Cd}秒,跳过此次行动",
|
||||
command.Name,
|
||||
manualSkillCd, Math.Round(cd, 2));
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("{CommandName}cd冷却剩余{Cd}秒,跳过此次行动", command.Name,
|
||||
Math.Round(cd, 2));
|
||||
}
|
||||
}
|
||||
|
||||
// 避免重复log提示
|
||||
skipFightName = command.Name;
|
||||
continue;
|
||||
}
|
||||
skipFightName = "";
|
||||
}
|
||||
|
||||
|
||||
if (timeoutStopwatch.Elapsed > fightTimeout)
|
||||
{
|
||||
Logger.LogInformation("战斗超时结束");
|
||||
@@ -246,34 +324,6 @@ public class AutoFightTask : ISoloTask
|
||||
break;
|
||||
}
|
||||
|
||||
//根据元素技能冷却事件优化出招流程,只有当人物切换后才会触发检查
|
||||
double skillCd;
|
||||
if (lastFightName != command.Name && actionSchedulerByCd.TryGetValue(command.Name, out skillCd))
|
||||
{
|
||||
var avatar = combatScenes.SelectAvatar(command.Name);
|
||||
if (avatar == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (skillCd < 0)
|
||||
{
|
||||
skillCd = FindMax([avatar.SkillCd, avatar.SkillHoldCd]);
|
||||
}
|
||||
var dif = (DateTime.UtcNow - avatar.LastSkillTime);
|
||||
//当技能未冷却时,跳过此次出招
|
||||
if ((DateTime.UtcNow - avatar.LastSkillTime).TotalSeconds < skillCd)
|
||||
{
|
||||
if (skipFightName != command.Name)
|
||||
{
|
||||
Logger.LogInformation($"{command.Name}cd冷却为{skillCd}秒,剩余{skillCd - dif.TotalSeconds}秒,跳过此次行动");
|
||||
}
|
||||
skipFightName = command.Name;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
command.Execute(combatScenes);
|
||||
//统计战斗人次
|
||||
if (i == combatCommands.Count - 1 || command.Name != combatCommands[i + 1].Name)
|
||||
@@ -287,8 +337,10 @@ public class AutoFightTask : ISoloTask
|
||||
//处于最后一个位置,或者当前执行人和下一个人名字不一样的情况,满足一定条件(开启快速检查,并且检查时间大于0或人名存在配置)检查战斗
|
||||
if (i == combatCommands.Count - 1
|
||||
|| (
|
||||
_finishDetectConfig.FastCheckEnabled && command.Name != combatCommands[i + 1].Name &&
|
||||
((_finishDetectConfig.CheckTime > 0 && checkFightFinishStopwatch.Elapsed > checkFightFinishTime)
|
||||
_finishDetectConfig.FastCheckEnabled &&
|
||||
command.Name != combatCommands[i + 1].Name &&
|
||||
((_finishDetectConfig.CheckTime > 0 &&
|
||||
checkFightFinishStopwatch.Elapsed > checkFightFinishTime)
|
||||
|| _finishDetectConfig.CheckNames.Contains(command.Name))
|
||||
))
|
||||
{
|
||||
@@ -373,7 +425,7 @@ public class AutoFightTask : ISoloTask
|
||||
if (_taskParam.KazuhaPickupEnabled)
|
||||
{
|
||||
// 队伍中存在万叶的时候使用一次长E
|
||||
var kazuha = combatScenes.Avatars.FirstOrDefault(a => a.Name == "枫原万叶");
|
||||
var kazuha = combatScenes.SelectAvatar("枫原万叶");
|
||||
if (kazuha != null)
|
||||
{
|
||||
var time = DateTime.UtcNow - kazuha.LastSkillTime;
|
||||
@@ -384,13 +436,7 @@ public class AutoFightTask : ISoloTask
|
||||
await Delay(300, ct);
|
||||
if (kazuha.TrySwitch())
|
||||
{
|
||||
time = DateTime.UtcNow - kazuha.LastSkillTime;
|
||||
if (time.TotalMilliseconds > 0 && time.TotalSeconds <= kazuha.SkillHoldCd)
|
||||
{
|
||||
Logger.LogInformation("枫原万叶长E技能可能处于冷却中,等待 {Time} s", time.TotalSeconds);
|
||||
await Delay((int)Math.Ceiling(time.TotalMilliseconds), ct);
|
||||
}
|
||||
|
||||
await kazuha.WaitSkillCd(ct);
|
||||
kazuha.UseSkill(true);
|
||||
await Task.Delay(100);
|
||||
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
|
||||
@@ -467,7 +513,10 @@ public class AutoFightTask : ISoloTask
|
||||
var b3 = ra.SrcMat.At<Vec3b>(50, 790); //进度条颜色
|
||||
var whiteTile = ra.SrcMat.At<Vec3b>(50, 768); //白块
|
||||
Simulation.SendInput.SimulateAction(GIActions.Drop);
|
||||
if (IsWhite(whiteTile.Item2, whiteTile.Item1, whiteTile.Item0) && IsYellow(b3.Item2, b3.Item1, b3.Item0) /* AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance)*/)
|
||||
if (IsWhite(whiteTile.Item2, whiteTile.Item1, whiteTile.Item0) &&
|
||||
IsYellow(b3.Item2, b3.Item1,
|
||||
b3.Item0) /* AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance)*/
|
||||
)
|
||||
{
|
||||
Logger.LogInformation("识别到战斗结束");
|
||||
return true;
|
||||
@@ -504,6 +553,7 @@ public class AutoFightTask : ISoloTask
|
||||
(g >= 240 && g <= 255) &&
|
||||
(b >= 240 && b <= 255);
|
||||
}
|
||||
|
||||
static double FindMax(double[] numbers)
|
||||
{
|
||||
if (numbers == null || numbers.Length == 0)
|
||||
@@ -520,6 +570,8 @@ public class AutoFightTask : ISoloTask
|
||||
|
||||
return max;
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
private static Dictionary<string, double> ParseStringToDictionary(string input, double defaultValue = -1)
|
||||
{
|
||||
var dictionary = new Dictionary<string, double>();
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OCR;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
@@ -9,9 +8,9 @@ using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.AutoTrackPath;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
@@ -28,46 +27,36 @@ namespace BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
/// </summary>
|
||||
public class Avatar
|
||||
{
|
||||
/// <summary>
|
||||
/// 配置文件中的角色信息
|
||||
/// </summary>
|
||||
public readonly CombatAvatar CombatAvatar;
|
||||
|
||||
/// <summary>
|
||||
/// 角色名称 中文
|
||||
/// </summary>
|
||||
public string Name { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 角色名称 英文
|
||||
/// </summary>
|
||||
public string? NameEn { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 队伍内序号
|
||||
/// </summary>
|
||||
public int Index { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 武器类型
|
||||
/// 最近一次OCR识别出的CD到期时间
|
||||
/// </summary>
|
||||
public string Weapon { get; set; }
|
||||
private DateTime OcrSkillCd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 元素战技CD
|
||||
/// 手动配置的技能CD,有它就不使用OCR,小于0为自动
|
||||
/// </summary>
|
||||
public double SkillCd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 长按元素战技CD
|
||||
/// </summary>
|
||||
public double SkillHoldCd { get; set; }
|
||||
public double ManualSkillCd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次使用元素战技的时间
|
||||
/// </summary>
|
||||
public DateTime LastSkillTime { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 元素爆发CD
|
||||
/// </summary>
|
||||
public double BurstCd { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 元素爆发是否就绪
|
||||
/// </summary>
|
||||
@@ -93,22 +82,20 @@ public class Avatar
|
||||
/// </summary>
|
||||
public CombatScenes CombatScenes { get; set; }
|
||||
|
||||
public static string? LastActiveAvatar { get; internal set; } = null;
|
||||
|
||||
public Avatar(CombatScenes combatScenes, string name, int index, Rect nameRect)
|
||||
|
||||
public Avatar(CombatScenes combatScenes, string name, int index, Rect nameRect, double manualSkillCd = -1)
|
||||
{
|
||||
CombatScenes = combatScenes;
|
||||
Name = name;
|
||||
Index = index;
|
||||
NameRect = nameRect;
|
||||
|
||||
var ca = DefaultAutoFightConfig.CombatAvatarMap[name];
|
||||
NameEn = ca.NameEn;
|
||||
Weapon = ca.Weapon;
|
||||
SkillCd = ca.SkillCd;
|
||||
SkillHoldCd = ca.SkillHoldCd;
|
||||
BurstCd = ca.BurstCd;
|
||||
CombatAvatar = DefaultAutoFightConfig.CombatAvatarMap[name];
|
||||
ManualSkillCd = manualSkillCd;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 是否存在角色被击败
|
||||
/// 通过判断确认按钮
|
||||
@@ -159,7 +146,7 @@ public class Avatar
|
||||
var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
|
||||
{
|
||||
return;
|
||||
@@ -211,11 +198,12 @@ public class Avatar
|
||||
var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == CombatScenes.ExpectedTeamAvatarNum - 1)
|
||||
{
|
||||
if (needLog && i > 0)
|
||||
{
|
||||
LastActiveAvatar = Name;
|
||||
Logger.LogInformation("成功切换角色:{Name}", Name);
|
||||
}
|
||||
|
||||
@@ -261,7 +249,7 @@ public class Avatar
|
||||
var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (IsActive(region) && notActiveCount == 3)
|
||||
{
|
||||
return;
|
||||
@@ -299,7 +287,7 @@ public class Avatar
|
||||
/// <returns></returns>
|
||||
public bool IsActive(ImageRegion region)
|
||||
{
|
||||
if (IndexRect == Rect.Empty)
|
||||
if (IndexRect == default)
|
||||
{
|
||||
throw new Exception("IndexRect为空");
|
||||
}
|
||||
@@ -328,7 +316,7 @@ public class Avatar
|
||||
public bool IsActiveNoIndexRect(ImageRegion region)
|
||||
{
|
||||
// 通过寻找右侧人物编号来判断是否出战
|
||||
if (IndexRect == Rect.Empty)
|
||||
if (IndexRect == default)
|
||||
{
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
// 剪裁出队伍区域
|
||||
@@ -344,7 +332,9 @@ public class Avatar
|
||||
ContourApproximationModes.ApproxSimple);
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var boxes = contours.Select(Cv2.BoundingRect).Where(w => w.Width >= 20 * assetScale && w.Height >= 18 * assetScale).OrderByDescending(w => w.Width).ToList();
|
||||
var boxes = contours.Select(Cv2.BoundingRect)
|
||||
.Where(w => w.Width >= 20 * assetScale && w.Height >= 18 * assetScale)
|
||||
.OrderByDescending(w => w.Width).ToList();
|
||||
if (boxes.Count is not 0)
|
||||
{
|
||||
IndexRect = boxes.First();
|
||||
@@ -357,7 +347,8 @@ public class Avatar
|
||||
// 剪裁出IndexRect区域
|
||||
var teamRa = region.DeriveCrop(AutoFightAssets.Instance.TeamRect);
|
||||
var blockX = NameRect.X + NameRect.Width * 2 - 10;
|
||||
var indexBlock = teamRa.DeriveCrop(new Rect(blockX + IndexRect.X, NameRect.Y + IndexRect.Y, IndexRect.Width, IndexRect.Height));
|
||||
var indexBlock = teamRa.DeriveCrop(new Rect(blockX + IndexRect.X, NameRect.Y + IndexRect.Y, IndexRect.Width,
|
||||
IndexRect.Height));
|
||||
// Cv2.ImWrite($"indexBlock_{Name}.png", indexBlock.SrcMat);
|
||||
var count = OpenCvCommonHelper.CountGrayMatColor(indexBlock.SrcGreyMat, 255);
|
||||
if (count * 1.0 / (IndexRect.Width * IndexRect.Height) > 0.5)
|
||||
@@ -429,37 +420,59 @@ public class Avatar
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyPress);
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
|
||||
}
|
||||
|
||||
Sleep(200, Ct);
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
var cd = GetSkillCurrentCd(region);
|
||||
ThrowWhenDefeated(region, Ct); // 检测是不是要跑神像
|
||||
var cd = AfterUseSkill(region);
|
||||
if (cd > 0)
|
||||
{
|
||||
Logger.LogInformation(hold ? "{Name} 长按元素战技,cd:{Cd}" : "{Name} 点按元素战技,cd:{Cd}", Name, cd);
|
||||
// todo 把cd加入执行队列
|
||||
LastSkillTime = DateTime.UtcNow;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用完元素战技的回调,注意,不会在这里检测是不是需要跑七天神像 <br/>
|
||||
/// UseSkill 方法内会调用,如果没有使用UseSkill但是释放了技能之后记得调用一下这个方法
|
||||
/// </summary>
|
||||
/// <returns>当前技能CD</returns>
|
||||
public double AfterUseSkill(ImageRegion? givenRegion = null)
|
||||
{
|
||||
LastSkillTime = DateTime.UtcNow;
|
||||
if (ManualSkillCd > 0)
|
||||
{
|
||||
return GetSkillCdSeconds();
|
||||
}
|
||||
|
||||
var region = givenRegion ?? CaptureToRectArea();
|
||||
return GetSkillCurrentCd(region);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 元素战技是否正在CD中
|
||||
/// 右下 267x132
|
||||
/// 77x77
|
||||
/// </summary>
|
||||
public double GetSkillCurrentCd(ImageRegion imageRegion)
|
||||
private double GetSkillCurrentCd(ImageRegion imageRegion)
|
||||
{
|
||||
var eRa = imageRegion.DeriveCrop(AutoFightAssets.Instance.ECooldownRect);
|
||||
var eRaWhite = OpenCvCommonHelper.InRangeHsv(eRa.SrcMat, new Scalar(0, 0, 235), new Scalar(0, 25, 255));
|
||||
var text = OcrFactory.Paddle.OcrWithoutDetector(eRaWhite);
|
||||
return StringUtils.TryParseDouble(text);
|
||||
var cd = StringUtils.TryParseDouble(text);
|
||||
if (cd > 0 && cd <= CombatAvatar.SkillCd)
|
||||
{
|
||||
OcrSkillCd = DateTime.UtcNow.AddSeconds(cd);
|
||||
}
|
||||
|
||||
return cd;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 使用元素爆发 Q
|
||||
/// Q释放等待 2s 超时认为没有Q技能
|
||||
@@ -479,7 +492,7 @@ public class Avatar
|
||||
|
||||
var region = CaptureToRectArea();
|
||||
ThrowWhenDefeated(region, Ct);
|
||||
var notActiveCount = CombatScenes.Avatars.Count(avatar => !avatar.IsActive(region));
|
||||
var notActiveCount = CombatScenes.GetAvatars().Count(avatar => !avatar.IsActive(region));
|
||||
if (notActiveCount == 0)
|
||||
{
|
||||
// isBurstReleased = true;
|
||||
@@ -588,6 +601,84 @@ public class Avatar
|
||||
Sleep(ms); // 由于存在宏操作,等待不应被cts取消
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// 根据cd推算E技能是否好了
|
||||
/// </summary>
|
||||
/// <param name="skillCd">强制指定技能CD</param>
|
||||
/// <param name="printLog">log是否输出</param>
|
||||
/// <returns>是否好了</returns>
|
||||
public bool IsSkillReady(bool printLog = false)
|
||||
{
|
||||
var cd = GetSkillCdSeconds();
|
||||
if (cd > 0)
|
||||
{
|
||||
if (printLog)
|
||||
{
|
||||
Logger.LogInformation("{Name}的E技能未准备好,CD还有{Seconds}秒", Name, Math.Round(cd, 2));
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算上一次使用技能到现在还剩下多长时间的cd
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public double GetSkillCdSeconds()
|
||||
{
|
||||
switch (ManualSkillCd)
|
||||
{
|
||||
case < 0:
|
||||
{
|
||||
var now = DateTime.UtcNow;
|
||||
// 若未经过OCR的技能释放,上次时间加上最长的技能时间
|
||||
var maxCd = Math.Max(CombatAvatar.SkillHoldCd, CombatAvatar.SkillCd);
|
||||
var target =
|
||||
LastSkillTime >= OcrSkillCd
|
||||
? LastSkillTime.AddSeconds(Math.Max(CombatAvatar.SkillHoldCd, CombatAvatar.SkillCd))
|
||||
: OcrSkillCd;
|
||||
var result = now > target ? 0d : (target - now).TotalSeconds;
|
||||
if (!(result > maxCd)) return result;
|
||||
Logger.LogWarning("{Name}的当前技能CD大于其最大技能CD{MaxCd}。如果你没有调整系统时间的话,这是一个bug。", Name, maxCd);
|
||||
return maxCd;
|
||||
}
|
||||
case > 0:
|
||||
{
|
||||
// 用户设置,所以直接通过上次释放技能的时间计算
|
||||
var dif = DateTime.UtcNow - LastSkillTime;
|
||||
if (ManualSkillCd > dif.TotalSeconds)
|
||||
{
|
||||
return ManualSkillCd - dif.TotalSeconds;
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 等待技能CD
|
||||
/// </summary>
|
||||
/// <param name="ct">CancellationToken</param>
|
||||
public async Task WaitSkillCd(CancellationToken ct = default)
|
||||
{
|
||||
// 获取CD时间
|
||||
if (IsSkillReady())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var s = GetSkillCdSeconds() + 0.2;
|
||||
Logger.LogInformation("{Name}的E技能CD未结束,等待{Seconds}秒", Name, Math.Round(s, 2));
|
||||
await Delay((int)Math.Ceiling(s * 1000), ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 跳跃
|
||||
/// </summary>
|
||||
@@ -637,7 +728,7 @@ public class Avatar
|
||||
}
|
||||
|
||||
// 恰在蓄力时快速转动会把视角趋向于水平,所以在回正的时候不做额外Y轴移动
|
||||
double rate = cnt % 10 < 5 ? 0 : 4.5;//每500ms做一轮上下移动。
|
||||
double rate = cnt % 10 < 5 ? 0 : 4.5; //每500ms做一轮上下移动。
|
||||
cnt++;
|
||||
Simulation.SendInput.Mouse.MoveMouseBy((int)(500 * dpi), (int)(rate * 100 * dpi));
|
||||
ms -= 50;
|
||||
@@ -787,4 +878,59 @@ public class Avatar
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从配置字符串中查找角色cd
|
||||
/// 仅有角色名时返回 -1 ,没找到角色返回null
|
||||
/// </summary>
|
||||
/// <param name="input">序列</param>
|
||||
/// <param name="avatarName">角色名</param>
|
||||
/// <returns></returns>
|
||||
public static double? ParseActionSchedulerByCd(string input, string avatarName)
|
||||
{
|
||||
if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(avatarName))
|
||||
return null;
|
||||
|
||||
var searchIndex = input.Length - 1;
|
||||
|
||||
while (true)
|
||||
{
|
||||
// 逆向查找角色名最后一次出现的位置
|
||||
var foundIndex = input.LastIndexOf(avatarName, searchIndex, StringComparison.Ordinal);
|
||||
if (foundIndex == -1) return null;
|
||||
|
||||
// 验证前向边界(分号或字符串起点)
|
||||
var startValid = foundIndex == 0 ||
|
||||
input[foundIndex - 1] == ';';
|
||||
|
||||
// 验证后向边界(逗号或分号/字符串终点)
|
||||
var endValid = foundIndex + avatarName.Length == input.Length ||
|
||||
input[foundIndex + avatarName.Length] == ',' ||
|
||||
input[foundIndex + avatarName.Length] == ';';
|
||||
|
||||
if (startValid && endValid)
|
||||
{
|
||||
var valueStart = foundIndex + avatarName.Length;
|
||||
// 处理逗号后的数值部分
|
||||
if (valueStart >= input.Length || input[valueStart] != ',') return -1;
|
||||
var valueEnd = input.IndexOf(';', valueStart);
|
||||
if (valueEnd == -1) valueEnd = input.Length;
|
||||
|
||||
if (double.TryParse(input.AsSpan(valueStart + 1, valueEnd - valueStart - 1),
|
||||
out var result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
// 存在角色名但没有数值的情况
|
||||
return -1;
|
||||
}
|
||||
|
||||
// 更新搜索范围继续查找
|
||||
searchIndex = foundIndex - 1;
|
||||
if (searchIndex < 0) break;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ using OpenCvSharp.Extensions;
|
||||
using Sdcb.PaddleOCR;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Drawing.Imaging;
|
||||
@@ -32,11 +33,10 @@ public class CombatScenes : IDisposable
|
||||
/// <summary>
|
||||
/// 当前配队
|
||||
/// </summary>
|
||||
public Avatar[] Avatars { get; set; } = [];
|
||||
private Avatar[] Avatars { set; get; } = [];
|
||||
|
||||
public Dictionary<string, Avatar> AvatarMap { get; set; } = [];
|
||||
public int AvatarCount => Avatars.Length;
|
||||
|
||||
public int AvatarCount { get; set; }
|
||||
|
||||
private readonly YoloV8Predictor _predictor =
|
||||
YoloV8Builder.CreateDefaultBuilder()
|
||||
@@ -46,6 +46,16 @@ public class CombatScenes : IDisposable
|
||||
|
||||
public int ExpectedTeamAvatarNum { get; private set; } = 4;
|
||||
|
||||
/// <summary>
|
||||
/// 获取一个只读的Avatars
|
||||
/// </summary>
|
||||
/// <returns>Avatars</returns>
|
||||
public ReadOnlyCollection<Avatar> GetAvatars()
|
||||
{
|
||||
return Avatars.AsReadOnly();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 通过YOLO分类器识别队伍内角色
|
||||
/// </summary>
|
||||
@@ -124,7 +134,6 @@ public class CombatScenes : IDisposable
|
||||
|
||||
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", displayNames));
|
||||
Avatars = BuildAvatars([.. names], null, avatarIndexRectList);
|
||||
AvatarMap = Avatars.ToDictionary(x => x.Name);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -169,7 +178,8 @@ public class CombatScenes : IDisposable
|
||||
if (result.TopClass.Confidence < 0.51)
|
||||
{
|
||||
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
|
||||
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
throw new Exception(
|
||||
$"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
}
|
||||
}
|
||||
else
|
||||
@@ -177,7 +187,8 @@ public class CombatScenes : IDisposable
|
||||
if (result.TopClass.Confidence < 0.7)
|
||||
{
|
||||
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
|
||||
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
throw new Exception(
|
||||
$"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,7 +212,6 @@ public class CombatScenes : IDisposable
|
||||
Logger.LogInformation("强制指定队伍角色:{Text}", string.Join(",", names));
|
||||
TaskContext.Instance().Config.AutoFightConfig.TeamNames = string.Join(",", names);
|
||||
Avatars = BuildAvatars([.. names]);
|
||||
AvatarMap = Avatars.ToDictionary(x => x.Name);
|
||||
}
|
||||
|
||||
public bool CheckTeamInitialized()
|
||||
@@ -214,8 +224,11 @@ public class CombatScenes : IDisposable
|
||||
return true;
|
||||
}
|
||||
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null, List<Rect>? avatarIndexRectList = null)
|
||||
|
||||
private Avatar[] BuildAvatars(List<string> names, List<Rect>? nameRects = null,
|
||||
List<Rect>? avatarIndexRectList = null)
|
||||
{
|
||||
var cdConfig = TaskContext.Instance().Config.AutoFightConfig.ActionSchedulerByCd;
|
||||
if (avatarIndexRectList == null && ExpectedTeamAvatarNum == 4)
|
||||
{
|
||||
avatarIndexRectList = AutoFightAssets.Instance.AvatarIndexRectList;
|
||||
@@ -226,12 +239,14 @@ public class CombatScenes : IDisposable
|
||||
throw new Exception("联机状态下,此方法必须传入队伍角色编号位置信息");
|
||||
}
|
||||
|
||||
AvatarCount = names.Count;
|
||||
var avatars = new Avatar[AvatarCount];
|
||||
for (var i = 0; i < AvatarCount; i++)
|
||||
var namesCount = names.Count;
|
||||
var avatars = new Avatar[namesCount];
|
||||
for (var i = 0; i < namesCount; i++)
|
||||
{
|
||||
var nameRect = nameRects?[i] ?? Rect.Empty;
|
||||
avatars[i] = new Avatar(this, names[i], i + 1, nameRect)
|
||||
var nameRect = nameRects?[i] ?? default;
|
||||
// 根据手动写的出招表来优化CD
|
||||
var cd = Avatar.ParseActionSchedulerByCd(names[i], cdConfig);
|
||||
avatars[i] = new Avatar(this, names[i], i + 1, nameRect, cd ?? -1)
|
||||
{
|
||||
IndexRect = avatarIndexRectList[i]
|
||||
};
|
||||
@@ -252,7 +267,7 @@ public class CombatScenes : IDisposable
|
||||
{
|
||||
// 释放所有按键
|
||||
Simulation.ReleaseAllKey();
|
||||
|
||||
|
||||
var mwk = SelectAvatar("玛薇卡");
|
||||
if (mwk != null)
|
||||
{
|
||||
@@ -268,9 +283,61 @@ public class CombatScenes : IDisposable
|
||||
|
||||
public Avatar? SelectAvatar(string name)
|
||||
{
|
||||
return AvatarMap.GetValueOrDefault(name);
|
||||
return Avatars.FirstOrDefault(avatar => avatar.Name.Equals(name));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用编号切换角色
|
||||
/// </summary>
|
||||
/// <param name="avatarIndex">从1开始</param>
|
||||
/// <returns></returns>
|
||||
public Avatar? SelectAvatar(int avatarIndex)
|
||||
{
|
||||
if (avatarIndex < 1 || avatarIndex >= AvatarCount)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Avatars[avatarIndex - 1];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前出战角色名
|
||||
/// </summary>
|
||||
/// <param name="force"></param>
|
||||
/// <param name="region"></param>
|
||||
/// <param name="ct"></param>
|
||||
/// <returns></returns>
|
||||
public string? CurrentAvatar(bool force = false, ImageRegion? region = null,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
if (!force && Avatar.LastActiveAvatar is not null)
|
||||
{
|
||||
return Avatar.LastActiveAvatar;
|
||||
}
|
||||
|
||||
var imageRegion = region ?? CaptureToRectArea();
|
||||
string? avatarName = null;
|
||||
|
||||
var notActiveCount = 0;
|
||||
foreach (var avatar in GetAvatars())
|
||||
{
|
||||
if (avatar.IsActive(imageRegion))
|
||||
{
|
||||
avatarName = avatar.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
notActiveCount++;
|
||||
}
|
||||
}
|
||||
|
||||
if (notActiveCount != ExpectedTeamAvatarNum - 1) return avatarName;
|
||||
Avatar.LastActiveAvatar = avatarName;
|
||||
return Avatar.LastActiveAvatar;
|
||||
}
|
||||
|
||||
|
||||
#region OCR识别队伍(已弃用)
|
||||
|
||||
/// <summary>
|
||||
@@ -290,7 +357,8 @@ public class CombatScenes : IDisposable
|
||||
// 剪裁出队伍区域
|
||||
var teamRa = content.CaptureRectArea.DeriveCrop(AutoFightAssets.Instance.TeamRectNoIndex);
|
||||
// 过滤出白色
|
||||
var hsvFilterMat = OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
|
||||
var hsvFilterMat =
|
||||
OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
|
||||
|
||||
// 识别队伍内角色
|
||||
var result = OcrFactory.Paddle.OcrResult(hsvFilterMat);
|
||||
@@ -348,7 +416,8 @@ public class CombatScenes : IDisposable
|
||||
}
|
||||
|
||||
var rect = item.Rect.BoundingRect();
|
||||
if (rect.Y > wanderer.Y && wanderer.Y + wanderer.Height > rect.Y + rect.Height && !names.Contains("流浪者"))
|
||||
if (rect.Y > wanderer.Y && wanderer.Y + wanderer.Height > rect.Y + rect.Height &&
|
||||
!names.Contains("流浪者"))
|
||||
{
|
||||
names.Add("流浪者");
|
||||
nameRects.Add(item.Rect.BoundingRect());
|
||||
@@ -364,7 +433,6 @@ public class CombatScenes : IDisposable
|
||||
|
||||
Logger.LogInformation("识别到的队伍角色:{Text}", string.Join(",", names));
|
||||
Avatars = BuildAvatars(names, nameRects);
|
||||
AvatarMap = Avatars.ToDictionary(x => x.Name);
|
||||
}
|
||||
|
||||
[Obsolete]
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
|
||||
using BetterGenshinImpact.Model;
|
||||
using BetterGenshinImpact.Service;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
@@ -40,8 +38,10 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isKeyDown = true;
|
||||
if (activeMacroPriority != TaskContext.Instance().Config.MacroConfig.CombatMacroPriority || IsAvatarMacrosEdited())
|
||||
if (activeMacroPriority != TaskContext.Instance().Config.MacroConfig.CombatMacroPriority ||
|
||||
IsAvatarMacrosEdited())
|
||||
{
|
||||
activeMacroPriority = TaskContext.Instance().Config.MacroConfig.CombatMacroPriority;
|
||||
_avatarMacros = LoadAvatarMacros();
|
||||
@@ -146,8 +146,22 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
_currentCombatScenes = combatScenes;
|
||||
}
|
||||
|
||||
// 找到出战角色
|
||||
var activeAvatar = _currentCombatScenes.Avatars.First(avatar => avatar.IsActive(imageRegion));
|
||||
// var activeAvatar = _currentCombatScenes.GetAvatars().First(avatar => avatar.IsActive(imageRegion));
|
||||
var avatarName = _currentCombatScenes.CurrentAvatar(true, imageRegion, ct);
|
||||
if (avatarName is null)
|
||||
{
|
||||
Logger.LogError("无法识别出战角色");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
var activeAvatar = _currentCombatScenes.SelectAvatar(avatarName);
|
||||
if (activeAvatar is null)
|
||||
{
|
||||
Logger.LogError("获取出战角色{Name}失败", avatarName);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
if (_avatarMacros != null && _avatarMacros.TryGetValue(activeAvatar.Name, out var combatCommands))
|
||||
{
|
||||
@@ -167,6 +181,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
command.Execute(activeAvatar);
|
||||
}
|
||||
}
|
||||
|
||||
Logger.LogInformation("→ {Name}停止宏", activeAvatar.Name);
|
||||
});
|
||||
}
|
||||
@@ -187,6 +202,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
var result = new Dictionary<string, List<CombatCommand>>();
|
||||
foreach (var avatarMacro in avatarMacros)
|
||||
{
|
||||
@@ -196,6 +212,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
result.Add(avatarMacro.Name, commands);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -221,4 +238,4 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
|
||||
{
|
||||
return TaskContext.Instance().Config.MacroConfig.CombatMacroHotkeyMode == TickMode;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -28,14 +28,13 @@ public class CombatCommand
|
||||
|
||||
var parameters = command.Substring(startIndex + 1, endIndex - startIndex - 1);
|
||||
Args = [..parameters.Split(',', StringSplitOptions.TrimEntries)];
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
Method = Method.GetEnumByCode(command);
|
||||
Args = [];
|
||||
}
|
||||
|
||||
|
||||
// 校验参数
|
||||
if (Method == Method.Walk)
|
||||
{
|
||||
@@ -71,7 +70,12 @@ public class CombatCommand
|
||||
if (Name == CombatScriptParser.CurrentAvatarName)
|
||||
{
|
||||
// 如果是当前角色,不进行角色切换
|
||||
avatar = combatScenes.Avatars[0]; // 随便取一个角色
|
||||
var avatarName = combatScenes.CurrentAvatar();
|
||||
avatar = avatarName is not null ? combatScenes.SelectAvatar(avatarName) : combatScenes.SelectAvatar(1);
|
||||
if (avatar == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -81,6 +85,7 @@ public class CombatCommand
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 非宏类脚本,等待切换角色成功
|
||||
if (Method != Method.Wait
|
||||
&& Method != Method.MouseDown
|
||||
@@ -94,7 +99,7 @@ public class CombatCommand
|
||||
avatar.Switch();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Execute(avatar);
|
||||
}
|
||||
|
||||
@@ -103,6 +108,22 @@ public class CombatCommand
|
||||
if (Method == Method.Skill)
|
||||
{
|
||||
var hold = Args != null && Args.Contains("hold");
|
||||
var wait = Args != null && Args.Contains("wait");
|
||||
var fast = Args != null && Args.Contains("fast");
|
||||
if (fast)
|
||||
{
|
||||
// 快速跳过e
|
||||
if (!avatar.IsSkillReady(true))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
else if (wait)
|
||||
{
|
||||
// 等待e结束,同步等待
|
||||
avatar.WaitSkillCd().Wait();
|
||||
}
|
||||
|
||||
avatar.UseSkill(hold);
|
||||
}
|
||||
else if (Method == Method.Burst)
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
@@ -14,7 +15,7 @@ public class CombatScriptBag(List<CombatScript> combatScripts)
|
||||
{
|
||||
}
|
||||
|
||||
public List<CombatCommand> FindCombatScript(Avatar[] avatars)
|
||||
public List<CombatCommand> FindCombatScript(ReadOnlyCollection<Avatar> avatars)
|
||||
{
|
||||
foreach (var combatScript in CombatScripts)
|
||||
{
|
||||
@@ -26,11 +27,9 @@ public class CombatScriptBag(List<CombatScript> combatScripts)
|
||||
matchCount++;
|
||||
}
|
||||
|
||||
if (matchCount == avatars.Length)
|
||||
{
|
||||
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
|
||||
return combatScript.CombatCommands;
|
||||
}
|
||||
if (matchCount != avatars.Count) continue;
|
||||
Logger.LogInformation("匹配到战斗脚本:{Name}", combatScript.Name);
|
||||
return combatScript.CombatCommands;
|
||||
}
|
||||
|
||||
combatScript.MatchCount = matchCount;
|
||||
|
||||
@@ -99,7 +99,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
Debug.WriteLine(e);
|
||||
}
|
||||
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,7 +63,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
var result = blackboard.Predictor.Detect(memoryStream);
|
||||
Debug.WriteLine($"YOLOv8识别: {result.Speed}");
|
||||
var fishpond = new Fishpond(result, ignoreObtained: true);
|
||||
if (fishpond.FishpondRect == Rect.Empty)
|
||||
if (fishpond.FishpondRect == default)
|
||||
{
|
||||
return BehaviourStatus.Running;
|
||||
}
|
||||
@@ -313,7 +313,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
var fishpond = new Fishpond(result, includeTarget: timeProvider.GetLocalNow() <= ignoreObtainedEndTime);
|
||||
blackboard.fishpond = fishpond;
|
||||
Random _rd = new();
|
||||
if (fishpond.TargetRect == null || fishpond.TargetRect == Rect.Empty)
|
||||
if (fishpond.TargetRect == null || fishpond.TargetRect == default)
|
||||
{
|
||||
if (!foundTarget)
|
||||
{
|
||||
@@ -713,7 +713,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
//VisionContext.Instance().DrawContent.PutRect("liftingWordsAreaRect", liftingWordsAreaRect.ToRectDrawable(new Pen(Color.Cyan, 2)));
|
||||
using var wordCaptureMat = new Mat(imageRegion.SrcMat, liftingWordsAreaRect);
|
||||
var currentBiteWordsTips = AutoFishingImageRecognition.MatchFishBiteWords(wordCaptureMat, liftingWordsAreaRect);
|
||||
if (currentBiteWordsTips != Rect.Empty)
|
||||
if (currentBiteWordsTips != default)
|
||||
{
|
||||
// VisionContext.Instance().DrawContent.PutRect("FishBiteTips",
|
||||
// currentBiteWordsTips
|
||||
|
||||
@@ -52,7 +52,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
/// <summary>
|
||||
/// 拉条位置的识别框
|
||||
/// </summary>
|
||||
internal Rect fishBoxRect = Rect.Empty;
|
||||
internal Rect fishBoxRect;
|
||||
|
||||
/// <summary>
|
||||
/// 是否正在选鱼饵界面
|
||||
@@ -106,7 +106,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
|
||||
abort = false;
|
||||
throwRodNoTargetTimes = 0;
|
||||
throwRodNoBaitFishFailures = new List<string>();
|
||||
fishBoxRect = Rect.Empty;
|
||||
fishBoxRect = default;
|
||||
chooseBaitUIOpening = false;
|
||||
chooseBaitFailures = new List<string>();
|
||||
pitchReset = true;
|
||||
|
||||
@@ -115,7 +115,7 @@ public class Fishpond
|
||||
{
|
||||
if (Fishes.Count == 0)
|
||||
{
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
|
||||
var left = int.MaxValue;
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.VisualBasic.Logging;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
@@ -29,9 +27,9 @@ public class CombatScriptHandler : IActionHandler
|
||||
|
||||
|
||||
// 提前校验是否存在策略要求的角色
|
||||
if (!combatScript.AvatarNames.Contains("当前角色"))
|
||||
if (!combatScript.AvatarNames.Contains(CombatScriptParser.CurrentAvatarName))
|
||||
{
|
||||
bool hasAvatar = combatScenes.Avatars.Any(avatar => combatScript.AvatarNames.Contains(avatar.Name));
|
||||
bool hasAvatar = combatScenes.GetAvatars().Any(avatar => combatScript.AvatarNames.Contains(avatar.Name));
|
||||
if (!hasAvatar)
|
||||
{
|
||||
Logger.LogError("简易策略脚本要求的角色不存在!队伍中需要存在下面角色中的一个或多个:{AvatarNames}", string.Join(", ", combatScript.AvatarNames));
|
||||
|
||||
@@ -3,8 +3,6 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -29,7 +27,7 @@ public class ElementalCollectHandler(ElementalType elementalType) : IActionHandl
|
||||
// 筛选出对应元素的角色列表
|
||||
var elementalCollectAvatars = ElementalCollectAvatarConfigs.Lists.Where(x => x.ElementalType == elementalType).ToList();
|
||||
// 循环遍历角色列表
|
||||
foreach (var combatScenesAvatar in combatScenes.Avatars)
|
||||
foreach (var combatScenesAvatar in combatScenes.GetAvatars())
|
||||
{
|
||||
// 判断是否为对应元素的角色
|
||||
var elementalCollectAvatar = elementalCollectAvatars.FirstOrDefault(x => x.Name == combatScenesAvatar.Name);
|
||||
@@ -47,18 +45,9 @@ public class ElementalCollectHandler(ElementalType elementalType) : IActionHandl
|
||||
}
|
||||
else if (elementalCollectAvatar.ElementalSkill)
|
||||
{
|
||||
// 获取CD时间
|
||||
var cdTime = combatScenesAvatar.SkillCd * 1000;
|
||||
var cdRemain = (DateTime.UtcNow - elementalCollectAvatar.LastUseSkillTime).TotalMilliseconds;
|
||||
if (cdRemain < cdTime)
|
||||
{
|
||||
var ms = (int)Math.Ceiling(cdTime - cdRemain) + 100;
|
||||
Logger.LogInformation("{Name}的E技能CD未结束,等待{Milliseconds}ms", combatScenesAvatar.Name, ms);
|
||||
await Delay(ms, ct);
|
||||
}
|
||||
|
||||
await combatScenesAvatar.WaitSkillCd(ct);
|
||||
combatScenesAvatar.UseSkill();
|
||||
elementalCollectAvatar.LastUseSkillTime = DateTime.UtcNow;
|
||||
}
|
||||
}
|
||||
else
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Model;
|
||||
using BetterGenshinImpact.GameTask.AutoFight.Script;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
@@ -20,9 +19,9 @@ public class MiningHandler : IActionHandler
|
||||
private readonly CombatScript _miningCombatScript = CombatScriptParser.ParseContext("""
|
||||
钟离 e(hold)
|
||||
雷泽 e(hold)
|
||||
坎蒂丝 e(hold)
|
||||
卡齐娜 e(hold),keydown(s),wait(0.4),keyup(s),attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2)
|
||||
凝光 attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2),attack(0.2)
|
||||
坎蒂丝 e(hold)
|
||||
凝光 a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2),a(0.2)
|
||||
""");
|
||||
|
||||
private readonly ScanPickTask _scanPickTask = new();
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Simulator;
|
||||
using BetterGenshinImpact.Core.Simulator.Extensions;
|
||||
using BetterGenshinImpact.GameTask.AutoPathing.Model;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Vanara.PInvoke;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
|
||||
@@ -31,7 +28,8 @@ public class NahidaCollectHandler : IActionHandler
|
||||
}
|
||||
|
||||
// 切人
|
||||
if (combatScenes.AvatarMap.TryGetValue("纳西妲", out var nahida))
|
||||
var nahida = combatScenes.SelectAvatar("纳西妲");
|
||||
if (nahida is not null)
|
||||
{
|
||||
nahida.TrySwitch();
|
||||
}
|
||||
@@ -41,11 +39,7 @@ public class NahidaCollectHandler : IActionHandler
|
||||
return;
|
||||
}
|
||||
|
||||
var cd = DateTime.Now - lastETime;
|
||||
if (cd < TimeSpan.FromSeconds(10))
|
||||
{
|
||||
await Delay((int)((6 - cd.TotalSeconds + 0.5) * 1000), ct);
|
||||
}
|
||||
await nahida.WaitSkillCd(ct);
|
||||
|
||||
var dpi = TaskContext.Instance().DpiScale;
|
||||
|
||||
@@ -57,36 +51,46 @@ public class NahidaCollectHandler : IActionHandler
|
||||
|
||||
// 按住E技能 无死角扫码
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
|
||||
await Delay(200, ct);
|
||||
|
||||
// 先地面来一圈
|
||||
for (int j = 0; j < 15; j++)
|
||||
try
|
||||
{
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, 500);
|
||||
await Delay(30, ct);
|
||||
}
|
||||
await Delay(200, ct);
|
||||
|
||||
// 然后抬斜向转圈
|
||||
while (!ct.IsCancellationRequested && i > 0)
|
||||
{
|
||||
i--;
|
||||
if (i == 40)
|
||||
// 先地面来一圈
|
||||
for (int j = 0; j < 15; j++)
|
||||
{
|
||||
y -= (int)(20 * dpi);
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, 500);
|
||||
await Delay(30, ct);
|
||||
}
|
||||
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
|
||||
await Delay(30, ct);
|
||||
// 然后抬斜向转圈
|
||||
while (!ct.IsCancellationRequested && i > 0)
|
||||
{
|
||||
i--;
|
||||
if (i == 40)
|
||||
{
|
||||
y -= (int)(20 * dpi);
|
||||
}
|
||||
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
|
||||
await Delay(30, ct);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// 就算被终止也要让按键弹回
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
|
||||
// 更新纳西妲CD
|
||||
if (!ct.IsCancellationRequested)
|
||||
{
|
||||
await Delay(200, ct);
|
||||
var cd = nahida.AfterUseSkill();
|
||||
Logger.LogInformation("{Nhd} 长按E转圈,cd:{Cd}", "纳西妲", Math.Round(cd, 2));
|
||||
}
|
||||
}
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
|
||||
|
||||
lastETime = DateTime.Now;
|
||||
|
||||
await Delay(1000, ct);
|
||||
|
||||
await Delay(800, ct);
|
||||
// 恢复视角
|
||||
Simulation.SendInput.Mouse.MiddleButtonClick();
|
||||
|
||||
await Delay(1000, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.Mvvm.Messaging.Messages;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing;
|
||||
|
||||
@@ -42,6 +43,39 @@ public class Navigation
|
||||
return p;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 稳定获取当前位置坐标,优先使用全地图匹配,适用于不需要高效率但需要高稳定性的场景
|
||||
/// </summary>
|
||||
/// <param name="imageRegion">图像区域</param>
|
||||
/// <param name="retryCount">匹配失败时的重试次数</param>
|
||||
/// <returns>当前位置坐标</returns>
|
||||
public static Point2f GetPositionStable(ImageRegion imageRegion, int retryCount = 3)
|
||||
{
|
||||
var greyMat = new Mat(imageRegion.SrcGreyMat, MapAssets.Instance.MimiMapRect);
|
||||
|
||||
// 先尝试使用局部匹配
|
||||
var p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
|
||||
|
||||
// 如果全地图匹配失败,再尝试局部匹配
|
||||
if (p == new Point2f())
|
||||
{
|
||||
p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
|
||||
|
||||
// 如果仍然失败,进行多次重试
|
||||
int attempts = 0;
|
||||
while (p == new Point2f() && attempts < retryCount)
|
||||
{
|
||||
// 重置位置记录,强制使用全地图匹配
|
||||
Reset();
|
||||
p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
|
||||
attempts++;
|
||||
}
|
||||
}
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(typeof(Navigation),
|
||||
"SendCurrentPosition", new object(), p));
|
||||
return p;
|
||||
}
|
||||
|
||||
public static int GetTargetOrientation(Waypoint waypoint, Point2f position)
|
||||
{
|
||||
double deltaX = waypoint.X - position.X;
|
||||
|
||||
@@ -455,7 +455,7 @@ public class PathExecutor
|
||||
{
|
||||
if (task.HasAction(action))
|
||||
{
|
||||
foreach (var avatar in combatScenes.Avatars)
|
||||
foreach (var avatar in combatScenes.GetAvatars())
|
||||
{
|
||||
if (ElementalCollectAvatarConfigs.Get(avatar.Name, el) != null)
|
||||
{
|
||||
@@ -504,7 +504,8 @@ public class PathExecutor
|
||||
/// </summary>
|
||||
private async Task<bool> TryPartyHealing()
|
||||
{
|
||||
foreach (var avatar in _combatScenes?.Avatars ?? [])
|
||||
if (_combatScenes is null) return false;
|
||||
foreach (var avatar in _combatScenes.GetAvatars())
|
||||
{
|
||||
if (avatar.Name == "白术")
|
||||
{
|
||||
@@ -629,6 +630,11 @@ public class PathExecutor
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
while (!ct.IsCancellationRequested)
|
||||
{
|
||||
if (!Simulation.IsKeyDown(GIActions.MoveForward.ToActionKey().ToVK()))
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
|
||||
}
|
||||
|
||||
num++;
|
||||
if ((DateTime.UtcNow - moveToStartTime).TotalSeconds > 240)
|
||||
{
|
||||
@@ -813,7 +819,7 @@ public class PathExecutor
|
||||
|
||||
// 切人
|
||||
Logger.LogInformation("切换盾、回血角色,使用元素战技");
|
||||
var avatar = await SwitchAvatar(PartyConfig.GuardianAvatarIndex);
|
||||
var avatar = await SwitchAvatar(PartyConfig.GuardianAvatarIndex,true);
|
||||
if (avatar == null)
|
||||
{
|
||||
return;
|
||||
@@ -827,19 +833,8 @@ public class PathExecutor
|
||||
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
|
||||
await Delay(200, ct);
|
||||
}
|
||||
|
||||
if (PartyConfig.GuardianElementalSkillLongPress)
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
|
||||
await Task.Delay(800); // 不能取消
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
|
||||
await Delay(700, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill);
|
||||
await Delay(300, ct);
|
||||
}
|
||||
|
||||
avatar.UseSkill(PartyConfig.GuardianElementalSkillLongPress);
|
||||
|
||||
// 钟离往身后放柱子 后继续走路
|
||||
if (avatar.Name == "钟离")
|
||||
@@ -935,28 +930,27 @@ public class PathExecutor
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<Avatar?> SwitchAvatar(string index)
|
||||
private async Task<Avatar?> SwitchAvatar(string index,bool needSkill = false)
|
||||
{
|
||||
if (string.IsNullOrEmpty(index))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var avatar = _combatScenes?.Avatars[int.Parse(index) - 1];
|
||||
if (avatar != null)
|
||||
var avatar = _combatScenes?.SelectAvatar(int.Parse(index));
|
||||
if (avatar == null) return null;
|
||||
if (needSkill && !avatar.IsSkillReady())
|
||||
{
|
||||
bool success = avatar.TrySwitch();
|
||||
if (success)
|
||||
{
|
||||
await Delay(100, ct);
|
||||
return avatar;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("尝试切换角色{Name}失败!", avatar.Name);
|
||||
}
|
||||
Logger.LogInformation("角色{Name}技能未冷却,跳过。", avatar.Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
var success = avatar.TrySwitch();
|
||||
if (success)
|
||||
{
|
||||
await Delay(100, ct);
|
||||
return avatar;
|
||||
}
|
||||
Logger.LogInformation("尝试切换角色{Name}失败!", avatar.Name);
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -993,8 +987,15 @@ public class PathExecutor
|
||||
var closeRa2 = imageRegion.Find(ElementAssets.Instance.PageCloseWhiteRo);
|
||||
if (cookRa.IsExist() || closeRa.IsExist() || closeRa2.IsExist())
|
||||
{
|
||||
// 排除大地图
|
||||
if (Bv.IsInBigMapUi(imageRegion))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
Logger.LogInformation("检测到其他界面,使用ESC关闭界面");
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
|
||||
await Delay(1000, ct); // 等待界面关闭
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ public class PathRecorder : Singleton<PathRecorder>
|
||||
TaskControl.Logger.LogInformation("开始路径点记录");
|
||||
var waypoint = new Waypoint();
|
||||
var screen = TaskControl.CaptureToRectArea();
|
||||
var position = Navigation.GetPosition(screen);
|
||||
var position = Navigation.GetPositionStable(screen);
|
||||
position = MapCoordinate.Main2048ToGame(position);
|
||||
waypoint.X = position.X;
|
||||
waypoint.Y = position.Y;
|
||||
@@ -61,7 +61,7 @@ public class PathRecorder : Singleton<PathRecorder>
|
||||
{
|
||||
Waypoint waypoint = new();
|
||||
var screen = TaskControl.CaptureToRectArea();
|
||||
var position = Navigation.GetPosition(screen);
|
||||
var position = Navigation.GetPositionStable(screen);
|
||||
position = MapCoordinate.Main2048ToGame(position);
|
||||
waypoint.X = position.X;
|
||||
waypoint.Y = position.Y;
|
||||
|
||||
@@ -36,7 +36,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
|
||||
/// <summary>
|
||||
/// 任务距离
|
||||
/// </summary>
|
||||
private Rect _missionDistanceRect = Rect.Empty;
|
||||
private Rect _missionDistanceRect = default;
|
||||
|
||||
private CancellationToken _ct;
|
||||
|
||||
@@ -131,7 +131,7 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
|
||||
var centerX = ra.Width / 2;
|
||||
var centerY = ra.Height / 2;
|
||||
var minDistance = double.MaxValue;
|
||||
var nearestRect = Rect.Empty;
|
||||
Rect nearestRect = default;
|
||||
foreach (var tpPoint in tpPointList)
|
||||
{
|
||||
var distanceTp = Math.Sqrt(Math.Pow(Math.Abs(tpPoint.X - centerX), 2) + Math.Pow(Math.Abs(tpPoint.Y - centerY), 2));
|
||||
|
||||
@@ -75,7 +75,7 @@ public class ExpeditionTask
|
||||
var result = CaptureAndOcr(content, new Rect(0, 0, captureRect.Width - (int)(480 * assetScale), captureRect.Height));
|
||||
var rect = result.FindRectByText("探险完成");
|
||||
// TODO i>1 的时候,可以通过关键词“探索派遣限制 4 / 5 ”判断是否已经派遣完成?
|
||||
if (rect != Rect.Empty)
|
||||
if (rect != default)
|
||||
{
|
||||
// 点击探险完成下方的人物头像
|
||||
content.CaptureRectArea.Derive(new Rect(rect.X, rect.Y + (int)(50 * assetScale), rect.Width, (int)(80 * assetScale))).Click();
|
||||
@@ -83,7 +83,7 @@ public class ExpeditionTask
|
||||
// 重新截图 找领取
|
||||
result = CaptureAndOcr(content);
|
||||
rect = result.FindRectByText("领取");
|
||||
if (rect != Rect.Empty)
|
||||
if (rect != default)
|
||||
{
|
||||
using var ra = content.CaptureRectArea.Derive(rect);
|
||||
ra.Click();
|
||||
@@ -96,7 +96,7 @@ public class ExpeditionTask
|
||||
// 选择角色
|
||||
result = CaptureAndOcr(content);
|
||||
rect = result.FindRectByText("选择角色");
|
||||
if (rect != Rect.Empty)
|
||||
if (rect != default)
|
||||
{
|
||||
content.CaptureRectArea.Derive(rect).Click();
|
||||
TaskControl.Sleep(400); // 等待动画
|
||||
|
||||
@@ -23,7 +23,7 @@ public class HangoutOption : IDisposable
|
||||
|
||||
// 选项文字所在区域初始化
|
||||
// 选项图标往上下区域扩展 2/3
|
||||
var r = Rect.Empty;
|
||||
Rect r = default;
|
||||
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
|
||||
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
|
||||
if (IconRect.Left > captureArea.Width / 2)
|
||||
@@ -44,10 +44,10 @@ public class HangoutOption : IDisposable
|
||||
if (r.Width < captureArea.Width / 8)
|
||||
{
|
||||
TaskControl.Logger.LogError("自动邀约:选项文字区域过小 {Rect}", TextRect);
|
||||
r = Rect.Empty;
|
||||
r = default;
|
||||
}
|
||||
|
||||
if (r != Rect.Empty)
|
||||
if (r != default)
|
||||
{
|
||||
if (iconRect.Prev is ImageRegion prev)
|
||||
{
|
||||
|
||||
@@ -330,7 +330,7 @@ public class TpTask(CancellationToken ct)
|
||||
return (clickX, clickY);
|
||||
}
|
||||
|
||||
private async Task CheckInBigMapUi()
|
||||
public async Task CheckInBigMapUi()
|
||||
{
|
||||
// 尝试打开地图失败后,先回到主界面后再次尝试打开地图
|
||||
if (!await TryToOpenBigMapUi())
|
||||
@@ -409,7 +409,7 @@ public class TpTask(CancellationToken ct)
|
||||
/// <param name="x">目标x坐标</param>
|
||||
/// <param name="y">目标y坐标</param>
|
||||
/// <param name="finalZoomLevel">到达目标点的最小缩放等级,只在 MapZoomEnabled 为 True 生效</param>
|
||||
private async Task MoveMapTo(double x, double y, double finalZoomLevel = 2)
|
||||
public async Task MoveMapTo(double x, double y, double finalZoomLevel = 2)
|
||||
{
|
||||
// 参数初始化
|
||||
double minZoomLevel = Math.Min(finalZoomLevel, _tpConfig.MinZoomLevel);
|
||||
@@ -565,11 +565,18 @@ public class TpTask(CancellationToken ct)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 调整地图的缩放级别(支持浮点数精度)。
|
||||
/// 将大地图缩放等级设置为指定值
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 缩放等级说明:
|
||||
/// - 数值范围:1.0(最大地图) 到 6.0(最小地图)
|
||||
/// - 缩放效果:数值越大,地图显示范围越广,细节越少
|
||||
/// - 缩放位置:1.0 对应缩放条最上方,6.0 对应缩放条最下方
|
||||
/// - 推荐范围:建议在 2.0 到 5.0 之间调整,过大或过小可能影响操作
|
||||
/// </remarks>
|
||||
/// <param name="zoomLevel">当前缩放等级:1.0-6.0,浮点数。</param>
|
||||
/// <param name="targetZoomLevel">目标缩放等级:1.0-6.0,浮点数。</param>
|
||||
private async Task AdjustMapZoomLevel(double zoomLevel, double targetZoomLevel)
|
||||
public async Task AdjustMapZoomLevel(double zoomLevel, double targetZoomLevel)
|
||||
{
|
||||
// Logger.LogInformation("调整地图缩放等级:{zoomLevel:0.000} -> {targetZoomLevel:0.000}", zoomLevel, targetZoomLevel);
|
||||
int initialY = (int)(_tpConfig.ZoomStartY + (_tpConfig.ZoomEndY - _tpConfig.ZoomStartY) * (zoomLevel - 1) / 5d);
|
||||
@@ -660,7 +667,7 @@ public class TpTask(CancellationToken ct)
|
||||
if (mapScaleButtonRa.IsExist())
|
||||
{
|
||||
rect = BigMap.Instance.GetBigMapRectByFeatureMatch(ra.SrcGreyMat);
|
||||
if (rect == Rect.Empty)
|
||||
if (rect == default)
|
||||
{
|
||||
// 滚轮调整后再次识别
|
||||
Simulation.SendInput.Mouse.VerticalScroll(2);
|
||||
@@ -674,7 +681,7 @@ public class TpTask(CancellationToken ct)
|
||||
}
|
||||
}, TimeSpan.FromMilliseconds(500), 5);
|
||||
|
||||
if (rect == Rect.Empty)
|
||||
if (rect == default)
|
||||
{
|
||||
throw new InvalidOperationException("多次重试后,识别大地图位置失败");
|
||||
}
|
||||
@@ -953,7 +960,7 @@ public class TpTask(CancellationToken ct)
|
||||
/// </summary>
|
||||
/// <param name="region"></param>
|
||||
/// <returns></returns>
|
||||
private double GetBigMapZoomLevel(ImageRegion region)
|
||||
public double GetBigMapZoomLevel(ImageRegion region)
|
||||
{
|
||||
var s = Bv.GetBigMapScale(region);
|
||||
// 1~6 的缩放等级
|
||||
|
||||
@@ -53,7 +53,7 @@ public class BigMap : Singleton<BigMap>
|
||||
catch
|
||||
{
|
||||
Debug.WriteLine("Feature Match Failed");
|
||||
return Rect.Empty;
|
||||
return default;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -103,8 +103,8 @@ public class CameraOrientationFromLimint
|
||||
|
||||
private void GeneratePoints()
|
||||
{
|
||||
Mat r = new Mat(1, rLength, MatType.CV_32F, LinearSpaced(tplInnRad, tplOutRad, rLength));
|
||||
Mat theta = new Mat(thetaLength, 1, MatType.CV_32F, LinearSpaced(0, 360, thetaLength, false));
|
||||
Mat r = Mat.FromPixelData(1, rLength, MatType.CV_32F, LinearSpaced(tplInnRad, tplOutRad, rLength));
|
||||
Mat theta =Mat.FromPixelData(thetaLength, 1, MatType.CV_32F, LinearSpaced(0, 360, thetaLength, false));
|
||||
Mat rMat = r.Repeat(thetaLength, 1);
|
||||
Mat thetaMat = theta.Repeat(1, rLength);
|
||||
rotationRemapDataX = new Mat();
|
||||
@@ -117,13 +117,13 @@ public class CameraOrientationFromLimint
|
||||
private void CreateAlphaMask()
|
||||
{
|
||||
var values = LinearSpaced(tplInnRad, tplOutRad, rLength);
|
||||
var alphaMask1Row = new Mat(1, rLength, MatType.CV_32F, values.Select(v =>
|
||||
var alphaMask1Row = Mat.FromPixelData(1, rLength, MatType.CV_32F, values.Select(v =>
|
||||
{
|
||||
var index = Array.BinarySearch(alphaParams1, v);
|
||||
return (float)(229 + (index < 0 ? ~index : index));
|
||||
}).ToArray());
|
||||
alphaMask1 = alphaMask1Row.Repeat(thetaLength, 1);
|
||||
var alphaMask2Row = new Mat(1, rLength, MatType.CV_32F, values.Select(v => (float)(111.7 + 1.836 * v)).ToArray());
|
||||
var alphaMask2Row = Mat.FromPixelData(1, rLength, MatType.CV_32F, values.Select(v => (float)(111.7 + 1.836 * v)).ToArray());
|
||||
alphaMask2 = alphaMask2Row.Repeat(thetaLength, 1);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ public class CharacterOrientation
|
||||
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var maxRect = Rect.Empty;
|
||||
Rect maxRect = default;
|
||||
var maxIndex = 0;
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
|
||||
@@ -71,7 +71,8 @@ public class ImageRegion : Region
|
||||
}
|
||||
}
|
||||
|
||||
public ImageRegion(Mat mat, int x, int y, Region? owner = null, INodeConverter? converter = null, DrawContent? drawContent = null) : base(x, y, mat.Width, mat.Height, owner, converter, drawContent)
|
||||
public ImageRegion(Mat mat, int x, int y, Region? owner = null, INodeConverter? converter = null,
|
||||
DrawContent? drawContent = null) : base(x, y, mat.Width, mat.Height, owner, converter, drawContent)
|
||||
{
|
||||
_srcMat = mat;
|
||||
}
|
||||
@@ -160,21 +161,27 @@ public class ImageRegion : Region
|
||||
throw new Exception($"[TemplateMatch]识别对象{ro.Name}的模板图片不能为null");
|
||||
}
|
||||
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
// TODO roi 是可以加缓存的
|
||||
if (!(0 <= ro.RegionOfInterest.X && 0 <= ro.RegionOfInterest.Width && ro.RegionOfInterest.X + ro.RegionOfInterest.Width <= roi.Cols
|
||||
&& 0 <= ro.RegionOfInterest.Y && 0 <= ro.RegionOfInterest.Height && ro.RegionOfInterest.Y + ro.RegionOfInterest.Height <= roi.Rows))
|
||||
if (!(0 <= ro.RegionOfInterest.X && 0 <= ro.RegionOfInterest.Width &&
|
||||
ro.RegionOfInterest.X + ro.RegionOfInterest.Width <= roi.Cols
|
||||
&& 0 <= ro.RegionOfInterest.Y && 0 <= ro.RegionOfInterest.Height &&
|
||||
ro.RegionOfInterest.Y + ro.RegionOfInterest.Height <= roi.Rows))
|
||||
{
|
||||
TaskControl.Logger.LogError("在图像{W1}x{H1}中查找模板,名称:{Name},ROI位置{X2}x{Y2},区域{H2}x{W2},边界溢出!", roi.Width, roi.Height, ro.Name, ro.RegionOfInterest.X, ro.RegionOfInterest.Y, ro.RegionOfInterest.Width, ro.RegionOfInterest.Height);
|
||||
TaskControl.Logger.LogError("在图像{W1}x{H1}中查找模板,名称:{Name},ROI位置{X2}x{Y2},区域{H2}x{W2},边界溢出!",
|
||||
roi.Width, roi.Height, ro.Name, ro.RegionOfInterest.X, ro.RegionOfInterest.Y,
|
||||
ro.RegionOfInterest.Width, ro.RegionOfInterest.Height);
|
||||
}
|
||||
|
||||
roi = new Mat(roi, ro.RegionOfInterest);
|
||||
}
|
||||
|
||||
var p = MatchTemplateHelper.MatchTemplate(roi, template, ro.TemplateMatchMode, ro.MaskMat, ro.Threshold);
|
||||
if (p != new Point())
|
||||
{
|
||||
var newRa = Derive(p.X + ro.RegionOfInterest.X, p.Y + ro.RegionOfInterest.Y, template.Width, template.Height);
|
||||
var newRa = Derive(p.X + ro.RegionOfInterest.X, p.Y + ro.RegionOfInterest.Y, template.Width,
|
||||
template.Height);
|
||||
if (ro.DrawOnWindow && !string.IsNullOrEmpty(ro.Name))
|
||||
{
|
||||
newRa.DrawSelf(ro.Name, ro.DrawOnWindowPen);
|
||||
@@ -202,7 +209,7 @@ public class ImageRegion : Region
|
||||
}
|
||||
|
||||
var roi = SrcGreyMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
}
|
||||
@@ -256,7 +263,9 @@ public class ImageRegion : Region
|
||||
if (ro.DrawOnWindow && !string.IsNullOrEmpty(ro.Name))
|
||||
{
|
||||
// 画出OCR识别到的区域
|
||||
var drawList = result.Regions.Select(item => this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name, ro.DrawOnWindowPen)).ToList();
|
||||
var drawList = result.Regions.Select(item =>
|
||||
this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name,
|
||||
ro.DrawOnWindowPen)).ToList();
|
||||
drawContent.PutOrRemoveRectList(ro.Name, drawList);
|
||||
}
|
||||
|
||||
@@ -274,27 +283,30 @@ public class ImageRegion : Region
|
||||
return new Region();
|
||||
}
|
||||
}
|
||||
else if (RecognitionTypes.Ocr.Equals(ro.RecognitionType) || RecognitionTypes.ColorRangeAndOcr.Equals(ro.RecognitionType))
|
||||
else if (RecognitionTypes.Ocr.Equals(ro.RecognitionType) ||
|
||||
RecognitionTypes.ColorRangeAndOcr.Equals(ro.RecognitionType))
|
||||
{
|
||||
Mat roi;
|
||||
if (RecognitionTypes.ColorRangeAndOcr.Equals(ro.RecognitionType))
|
||||
{
|
||||
roi = SrcMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
roi = new Mat(SrcMat, ro.RegionOfInterest);
|
||||
}
|
||||
|
||||
roi = roi.Clone();
|
||||
if (ro.ColorConversionCode != ColorConversionCodes.BGRA2BGR)
|
||||
{
|
||||
Cv2.CvtColor(roi, roi, ro.ColorConversionCode);
|
||||
}
|
||||
|
||||
Cv2.InRange(roi, ro.LowerColor, ro.UpperColor, roi);
|
||||
}
|
||||
else
|
||||
{
|
||||
roi = SrcGreyMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
}
|
||||
@@ -308,10 +320,13 @@ public class ImageRegion : Region
|
||||
if (ro.DrawOnWindow && !string.IsNullOrEmpty(ro.Name))
|
||||
{
|
||||
// 画出OCR识别到的区域
|
||||
var drawList = result.Regions.Select(item => this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name, ro.DrawOnWindowPen)).ToList();
|
||||
var drawList = result.Regions.Select(item =>
|
||||
this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name,
|
||||
ro.DrawOnWindowPen)).ToList();
|
||||
drawContent.PutOrRemoveRectList(ro.Name, drawList);
|
||||
}
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
var newRa = Derive(ro.RegionOfInterest);
|
||||
newRa.Text = text;
|
||||
@@ -354,7 +369,8 @@ public class ImageRegion : Region
|
||||
/// <param name="failAction">失败后做什么</param>
|
||||
/// <returns>无内嵌图片的 RectArea List</returns>
|
||||
/// <exception cref="Exception"></exception>
|
||||
public List<Region> FindMulti(RecognitionObject ro, Action<List<Region>>? successAction = null, Action? failAction = null)
|
||||
public List<Region> FindMulti(RecognitionObject ro, Action<List<Region>>? successAction = null,
|
||||
Action? failAction = null)
|
||||
{
|
||||
if (!HasImage())
|
||||
{
|
||||
@@ -387,19 +403,21 @@ public class ImageRegion : Region
|
||||
throw new Exception($"[TemplateMatch]识别对象{ro.Name}的模板图片不能为null");
|
||||
}
|
||||
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
roi = new Mat(roi, ro.RegionOfInterest);
|
||||
}
|
||||
|
||||
var rectList = MatchTemplateHelper.MatchOnePicForOnePic(roi, template, ro.TemplateMatchMode, ro.MaskMat, ro.Threshold);
|
||||
var rectList =
|
||||
MatchTemplateHelper.MatchOnePicForOnePic(roi, template, ro.TemplateMatchMode, ro.MaskMat, ro.Threshold);
|
||||
if (rectList.Count > 0)
|
||||
{
|
||||
var resRaList = rectList.Select(r => this.Derive(r + ro.RegionOfInterest.Location)).ToList();
|
||||
|
||||
if (ro.DrawOnWindow && !string.IsNullOrEmpty(ro.Name))
|
||||
{
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(ro.Name, resRaList.Select(ra => ra.SelfToRectDrawable(ro.Name)).ToList());
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(ro.Name,
|
||||
resRaList.Select(ra => ra.SelfToRectDrawable(ro.Name)).ToList());
|
||||
}
|
||||
|
||||
successAction?.Invoke(resRaList);
|
||||
@@ -419,7 +437,7 @@ public class ImageRegion : Region
|
||||
else if (RecognitionTypes.Ocr.Equals(ro.RecognitionType))
|
||||
{
|
||||
var roi = SrcGreyMat;
|
||||
if (ro.RegionOfInterest != Rect.Empty)
|
||||
if (ro.RegionOfInterest != default)
|
||||
{
|
||||
roi = new Mat(SrcGreyMat, ro.RegionOfInterest);
|
||||
}
|
||||
@@ -437,7 +455,9 @@ public class ImageRegion : Region
|
||||
if (ro.DrawOnWindow && !string.IsNullOrEmpty(ro.Name))
|
||||
{
|
||||
// 画出OCR识别到的区域
|
||||
var drawList = result.Regions.Select(item => this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name, ro.DrawOnWindowPen)).ToList();
|
||||
var drawList = result.Regions.Select(item =>
|
||||
this.ToRectDrawable(item.Rect.BoundingRect() + ro.RegionOfInterest.Location, ro.Name,
|
||||
ro.DrawOnWindowPen)).ToList();
|
||||
VisionContext.Instance().DrawContent.PutOrRemoveRectList(ro.Name, drawList);
|
||||
}
|
||||
|
||||
@@ -467,4 +487,4 @@ public class ImageRegion : Region
|
||||
_srcMat?.Dispose();
|
||||
_srcBitmap?.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,7 +157,7 @@ public class TestTrigger : ITaskTrigger
|
||||
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var maxRect = Rect.Empty;
|
||||
Rect maxRect = default;
|
||||
var maxIndex = 0;
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
|
||||
@@ -6,6 +6,7 @@ using BetterGenshinImpact.Helpers;
|
||||
using BetterGenshinImpact.Service;
|
||||
using System;
|
||||
using System.Threading;
|
||||
using BetterGenshinImpact.Core.Script.Group;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask
|
||||
{
|
||||
@@ -16,6 +17,7 @@ namespace BetterGenshinImpact.GameTask
|
||||
{
|
||||
private static TaskContext? _uniqueInstance;
|
||||
private static object? InstanceLocker;
|
||||
public ScriptGroupProject? CurrentScriptProject { get; set; }
|
||||
|
||||
#pragma warning disable CS8618 // 在退出构造函数时,不可为 null 的字段必须包含非 null 值。请考虑声明为可以为 null。
|
||||
|
||||
|
||||
@@ -19,6 +19,8 @@ public class NotificationEvent(string code, string msg)
|
||||
public static readonly NotificationEvent AlbumEnd = new("album.end", "自动音游专辑结束");
|
||||
public static readonly NotificationEvent AlbumError = new("album.error", "自动音游专辑错误");
|
||||
public static readonly NotificationEvent DailyReward = new("daily.reward", "检查每日奖励领取状态");
|
||||
public static readonly NotificationEvent JsCustom = new("js.custom", "JS自定义事件");
|
||||
public static readonly NotificationEvent JsError = new("js.error", "JS运行时错误");
|
||||
|
||||
public string Code { get; private set; } = code;
|
||||
public string Msg { get; private set; } = msg;
|
||||
|
||||
@@ -9,6 +9,10 @@ namespace BetterGenshinImpact.Service.Notification;
|
||||
[Serializable]
|
||||
public partial class NotificationConfig : ObservableObject
|
||||
{
|
||||
/// <summary>
|
||||
/// 是否允许 js 发送通知
|
||||
/// </summary>
|
||||
[ObservableProperty] private bool _jsNotificationEnabled = false;
|
||||
/// <summary>
|
||||
/// 传"none"时,点击推送不会弹窗
|
||||
/// </summary>
|
||||
|
||||
@@ -202,6 +202,7 @@ public partial class ScriptService : IScriptService
|
||||
target.RunNum = source.RunNum;
|
||||
target.JsScriptSettingsObject = source.JsScriptSettingsObject;
|
||||
target.GroupInfo = source.GroupInfo;
|
||||
target.AllowJsNotification = source.AllowJsNotification;
|
||||
}
|
||||
|
||||
// private List<ScriptProject> ExtractJsProjects(List<ScriptGroupProject> list)
|
||||
@@ -220,6 +221,7 @@ public partial class ScriptService : IScriptService
|
||||
|
||||
private async Task ExecuteProject(ScriptGroupProject project)
|
||||
{
|
||||
TaskContext.Instance().CurrentScriptProject = project;
|
||||
if (project.Type == "Javascript")
|
||||
{
|
||||
if (project.Project == null)
|
||||
|
||||
@@ -4886,5 +4886,6 @@
|
||||
"马察特利",
|
||||
"阿乌伊娅",
|
||||
"特帕切",
|
||||
"莉莉尤"
|
||||
"莉莉尤",
|
||||
"呼唤猫猫"
|
||||
]
|
||||
@@ -77,6 +77,31 @@
|
||||
Margin="0,0,36,0"
|
||||
IsChecked="{Binding Config.NotificationConfig.IncludeScreenShot, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
<ui:TextBlock Grid.Row="0"
|
||||
Grid.Column="0"
|
||||
FontTypography="Body"
|
||||
Text="是否允许 JS 通知"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:TextBlock Grid.Row="1"
|
||||
Grid.Column="0"
|
||||
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
|
||||
Text="开启时允许 JS 脚本发送通知"
|
||||
TextWrapping="Wrap" />
|
||||
<ui:ToggleSwitch Grid.Row="0"
|
||||
Grid.RowSpan="2"
|
||||
Grid.Column="1"
|
||||
Margin="0,0,36,0"
|
||||
IsChecked="{Binding Config.NotificationConfig.JsNotificationEnabled, Mode=TwoWay}" />
|
||||
</Grid>
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:local="clr-namespace:BetterGenshinImpact.Core.Script.Group"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:editable="clr-namespace:BetterGenshinImpact.ViewModel.Windows.Editable"
|
||||
xmlns:sys="clr-namespace:System;assembly=System.Runtime"
|
||||
Width="200"
|
||||
Height="300"
|
||||
d:DesignHeight="200"
|
||||
@@ -16,6 +18,7 @@
|
||||
<ObjectDataProvider x:Key="ScheduleDescriptionsProvider"
|
||||
MethodName="GetScheduleDescriptions"
|
||||
ObjectType="{x:Type local:ScriptGroupProjectExtensions}" />
|
||||
<BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
|
||||
</UserControl.Resources>
|
||||
<Grid>
|
||||
<StackPanel>
|
||||
@@ -35,6 +38,18 @@
|
||||
ItemsSource="{Binding Source={StaticResource StatusDescriptionsProvider}}"
|
||||
SelectedValue="{Binding Status, Mode=TwoWay}"
|
||||
SelectedValuePath="Key" />
|
||||
<TextBlock Margin="0,10,0,5" Text="JS 通知权限"
|
||||
Visibility="{Binding IsJsScript, Converter={StaticResource BoolToVisConverter}}"/>
|
||||
<ComboBox Margin="0,0,0,10"
|
||||
ItemsSource="{Binding JsNotificationOptions}"
|
||||
DisplayMemberPath="Value"
|
||||
SelectedValuePath="Key"
|
||||
IsEnabled="{Binding GlobalJsNotificationEnabled}"
|
||||
ToolTip="{Binding JsNotificationToolTip}"
|
||||
SelectedValue="{Binding AllowJsNotification, Mode=TwoWay}"
|
||||
Visibility="{Binding IsJsScript, Converter={StaticResource BoolToVisConverter}}">
|
||||
</ComboBox>
|
||||
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -1,11 +1,14 @@
|
||||
using System.Windows.Controls;
|
||||
using BetterGenshinImpact.Core.Script.Group;
|
||||
using BetterGenshinImpact.ViewModel.Windows.Editable;
|
||||
|
||||
namespace BetterGenshinImpact.View.Windows.Editable;
|
||||
|
||||
public partial class ScriptGroupProjectEditor : UserControl
|
||||
{
|
||||
public ScriptGroupProjectEditor()
|
||||
public ScriptGroupProjectEditor(ScriptGroupProject project)
|
||||
{
|
||||
InitializeComponent();
|
||||
DataContext = new ScriptGroupProjectEditorViewModel(project);
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ using BetterGenshinImpact.View.Pages.View;
|
||||
using BetterGenshinImpact.View.Windows;
|
||||
using BetterGenshinImpact.View.Windows.Editable;
|
||||
using BetterGenshinImpact.ViewModel.Pages.View;
|
||||
using BetterGenshinImpact.ViewModel.Windows.Editable;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -921,12 +922,17 @@ public partial class ScriptControlViewModel : ViewModel
|
||||
item.NextFlag = true;
|
||||
}
|
||||
|
||||
public static void ShowEditWindow(object viewModel)
|
||||
public static void ShowEditWindow(ScriptGroupProject project)
|
||||
{
|
||||
var viewModel = new ScriptGroupProjectEditorViewModel(project);
|
||||
var editor = new ScriptGroupProjectEditor(project)
|
||||
{
|
||||
DataContext = viewModel
|
||||
};
|
||||
var uiMessageBox = new Wpf.Ui.Controls.MessageBox
|
||||
{
|
||||
Title = "修改通用设置",
|
||||
Content = new ScriptGroupProjectEditor { DataContext = viewModel },
|
||||
Content = editor,
|
||||
CloseButtonText = "关闭",
|
||||
Owner = Application.Current.MainWindow,
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner,
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Text.Json.Serialization;
|
||||
using BetterGenshinImpact.Core.Script.Group;
|
||||
using BetterGenshinImpact.GameTask;
|
||||
using BetterGenshinImpact.Service.Notification;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
|
||||
namespace BetterGenshinImpact.ViewModel.Windows.Editable;
|
||||
|
||||
public class ScriptGroupProjectEditorViewModel : ObservableObject
|
||||
{
|
||||
private readonly ScriptGroupProject _project;
|
||||
private readonly NotificationConfig _globalNotificationConfig;
|
||||
|
||||
public bool GlobalJsNotificationEnabled
|
||||
=> _globalNotificationConfig.JsNotificationEnabled;
|
||||
|
||||
public List<KeyValuePair<bool, string>> JsNotificationOptions { get; } = new()
|
||||
{
|
||||
new KeyValuePair<bool, string>(true, "启用"),
|
||||
new KeyValuePair<bool, string>(false, "禁用")
|
||||
};
|
||||
|
||||
public bool IsJsScript => _project.Type == "Javascript";
|
||||
public bool? AllowJsNotification
|
||||
{
|
||||
get => _project.AllowJsNotification;
|
||||
set
|
||||
{
|
||||
if (!GlobalJsNotificationEnabled) return;
|
||||
_project.AllowJsNotification = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
public string Status
|
||||
{
|
||||
get => _project.Status;
|
||||
set
|
||||
{
|
||||
if (_project.Status != value)
|
||||
{
|
||||
_project.Status = value;
|
||||
OnPropertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
public ScriptGroupProjectEditorViewModel(ScriptGroupProject project)
|
||||
{
|
||||
_project = project ?? throw new ArgumentNullException(nameof(project));
|
||||
_globalNotificationConfig = TaskContext.Instance().Config.NotificationConfig;
|
||||
// 监听全局配置变更
|
||||
_project.PropertyChanged += (s, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(ScriptGroupProject.AllowJsNotification))
|
||||
{
|
||||
OnPropertyChanged(nameof(AllowJsNotification));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,33 +1,103 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using OpenCvSharp;
|
||||
using Vanara.PInvoke;
|
||||
using static System.Console;
|
||||
|
||||
namespace Fischless.GameCapture.BitBlt;
|
||||
|
||||
public class BitBltCapture : IGameCapture
|
||||
{
|
||||
private nint _hWnd;
|
||||
|
||||
private static readonly object LockObject = new object();
|
||||
|
||||
|
||||
public CaptureModes Mode => CaptureModes.BitBlt;
|
||||
|
||||
public bool IsCapturing { get; private set; }
|
||||
private readonly Stopwatch _sizeCheckTimer = new();
|
||||
private readonly ReaderWriterLockSlim _lockSlim = new();
|
||||
private volatile nint _hWnd; // 需要加锁
|
||||
private BitBltSession? _session; // 需要加锁
|
||||
|
||||
private volatile bool _needResetSession;
|
||||
|
||||
public void Dispose() => Stop();
|
||||
|
||||
public void Start(nint hWnd, Dictionary<string, object>? settings = null)
|
||||
{
|
||||
_hWnd = hWnd;
|
||||
IsCapturing = true;
|
||||
if (settings != null && settings.TryGetValue("autoFixWin11BitBlt", out var value))
|
||||
if (settings == null || !settings.TryGetValue("autoFixWin11BitBlt", out var value)) return;
|
||||
if (value is true)
|
||||
{
|
||||
if (value is true)
|
||||
BitBltRegistryHelper.SetDirectXUserGlobalSettings();
|
||||
}
|
||||
|
||||
_lockSlim.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_hWnd = hWnd;
|
||||
if (_hWnd == IntPtr.Zero)
|
||||
{
|
||||
BitBltRegistryHelper.SetDirectXUserGlobalSettings();
|
||||
return;
|
||||
}
|
||||
|
||||
_session?.Dispose();
|
||||
_session = null;
|
||||
IsCapturing = true;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lockSlim.ExitWriteLock();
|
||||
}
|
||||
|
||||
CheckSession();
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 检查窗口大小,如果改变则更新截图尺寸。返回是否成功。
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private bool CheckSession()
|
||||
{
|
||||
if (!_lockSlim.TryEnterWriteLock(TimeSpan.FromSeconds(0.5)))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
if (_session is not null && (_session.IsInvalid() || _needResetSession)) // 窗口状态变化可能会导致会话失效
|
||||
{
|
||||
_session.Dispose();
|
||||
_session = null;
|
||||
}
|
||||
|
||||
if (!User32.GetClientRect(_hWnd, out var windowRect) || windowRect == default)
|
||||
{
|
||||
// Debug.Fail("Failed to get client rectangle");
|
||||
// 窗口获取不到或者最小化
|
||||
_session?.Dispose();
|
||||
_session = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
var width = windowRect.right - windowRect.left;
|
||||
var height = windowRect.bottom - windowRect.top;
|
||||
|
||||
_session ??= new BitBltSession(_hWnd, width, height);
|
||||
if (_session.Width == width && _session.Height == height)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// 窗口尺寸被改变,释放资源
|
||||
_session.Dispose();
|
||||
_session = new BitBltSession(_hWnd, width, height);
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Error.WriteLine("[BitBlt]Failed to create session:{0}", e);
|
||||
return false;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lockSlim.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,84 +108,89 @@ public class BitBltCapture : IGameCapture
|
||||
return null;
|
||||
}
|
||||
|
||||
// 加锁
|
||||
lock (LockObject)
|
||||
if (!_sizeCheckTimer.IsRunning)
|
||||
{
|
||||
User32.SafeReleaseHDC hdcSrc = User32.SafeReleaseHDC.Null;
|
||||
Gdi32.SafeHDC hdcDest = Gdi32.SafeHDC.Null;
|
||||
Gdi32.SafeHBITMAP hBitmap = Gdi32.SafeHBITMAP.Null;
|
||||
try
|
||||
_sizeCheckTimer.Start();
|
||||
}
|
||||
|
||||
if (_sizeCheckTimer.ElapsedMilliseconds > 1000)
|
||||
{
|
||||
_sizeCheckTimer.Reset();
|
||||
// 不会经常调整窗口尺寸的,所以隔一段时间检查一次就行
|
||||
if (!CheckSession())
|
||||
{
|
||||
User32.GetClientRect(_hWnd, out var windowRect);
|
||||
int x = 0, y = 0;
|
||||
var width = windowRect.right - windowRect.left;
|
||||
var height = windowRect.bottom - windowRect.top;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
hdcSrc = User32.GetDC(_hWnd == IntPtr.Zero ? User32.GetDesktopWindow() : _hWnd);
|
||||
hdcDest = Gdi32.CreateCompatibleDC(hdcSrc);
|
||||
|
||||
var bmi = new Gdi32.BITMAPINFO
|
||||
Mat? mat = null;
|
||||
try
|
||||
{
|
||||
_lockSlim.EnterReadLock();
|
||||
if (_session is null)
|
||||
{
|
||||
// 没有成功创建会话,直接返回空
|
||||
return null;
|
||||
}
|
||||
mat = _session.GetMat();
|
||||
|
||||
if (mat is not null) // 成功执行
|
||||
{
|
||||
if (!mat.Empty()) // 并且获取到了图
|
||||
{
|
||||
bmiHeader = new Gdi32.BITMAPINFOHEADER
|
||||
{
|
||||
biSize = (uint)Marshal.SizeOf<Gdi32.BITMAPINFOHEADER>(),
|
||||
biWidth = width,
|
||||
biHeight = -height, // Top-down image
|
||||
biPlanes = 1,
|
||||
biBitCount = 32,
|
||||
biCompression = 0, // BI_RGB
|
||||
biSizeImage = 0
|
||||
}
|
||||
};
|
||||
|
||||
nint bits = 0;
|
||||
hBitmap = Gdi32.CreateDIBSection(hdcDest, bmi, Gdi32.DIBColorMode.DIB_RGB_COLORS, out bits, IntPtr.Zero, 0);
|
||||
var oldBitmap = Gdi32.SelectObject(hdcDest, hBitmap);
|
||||
|
||||
Gdi32.StretchBlt(hdcDest, 0, 0, width, height, hdcSrc, x, y, width, height, Gdi32.RasterOperationMode.SRCCOPY);
|
||||
|
||||
var mat = new Mat(height, width, MatType.CV_8UC4, bits);
|
||||
Gdi32.SelectObject(hdcDest, oldBitmap);
|
||||
|
||||
if (!mat.Empty())
|
||||
{
|
||||
Mat bgrMat = new Mat();
|
||||
Cv2.CvtColor(mat, bgrMat, ColorConversionCodes.BGRA2BGR);
|
||||
return bgrMat;
|
||||
_needResetSession = false;
|
||||
return mat;
|
||||
}
|
||||
else
|
||||
else // 成功执行但是没有图,可能是截图过快导致的
|
||||
{
|
||||
return null;
|
||||
mat.Dispose();
|
||||
mat = null; // 防止二次释放
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.WriteLine(e);
|
||||
return null!;
|
||||
}
|
||||
finally
|
||||
{
|
||||
if (hBitmap != Gdi32.SafeHBITMAP.Null)
|
||||
{
|
||||
Gdi32.DeleteObject(hBitmap);
|
||||
}
|
||||
|
||||
if (hdcDest != Gdi32.SafeHDC.Null)
|
||||
{
|
||||
Gdi32.DeleteDC(hdcDest);
|
||||
}
|
||||
|
||||
if (_hWnd != IntPtr.Zero)
|
||||
{
|
||||
User32.ReleaseDC(_hWnd, hdcSrc);
|
||||
}
|
||||
// 无论没有图还是执行失败都会到这里
|
||||
if (_session is not null && !_session.IsInvalid())
|
||||
{
|
||||
// _session正确但是截图失败,如果持续出现这个问题需要重置会话
|
||||
_needResetSession = true;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
// 理论这里不应出现异常,除非窗口不存在了或者有什么bug
|
||||
// 出现异常的时候释放内存
|
||||
mat?.Dispose();
|
||||
// 如果持续出现异常则重置会话
|
||||
_needResetSession = true;
|
||||
Error.WriteLine("[BitBlt]Failed to capture image {0}", e);
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lockSlim.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
public void Stop()
|
||||
{
|
||||
_hWnd = IntPtr.Zero;
|
||||
_lockSlim.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_hWnd = IntPtr.Zero;
|
||||
_sizeCheckTimer.Stop();
|
||||
if (_session != null)
|
||||
{
|
||||
_session.Dispose();
|
||||
_session = null;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lockSlim.ExitWriteLock();
|
||||
}
|
||||
|
||||
IsCapturing = false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.InteropServices;
|
||||
using OpenCvSharp;
|
||||
using Vanara.PInvoke;
|
||||
|
||||
namespace Fischless.GameCapture.BitBlt;
|
||||
|
||||
public class BitBltSession : IDisposable
|
||||
{
|
||||
// 窗口句柄
|
||||
private readonly HWND _hWnd;
|
||||
|
||||
// 来源DC
|
||||
private User32.SafeReleaseHDC _hdcSrc;
|
||||
|
||||
// 缓冲区 CompatibleDC
|
||||
private Gdi32.SafeHDC _hdcDest;
|
||||
|
||||
// 位图句柄
|
||||
private Gdi32.SafeHBITMAP _hBitmap;
|
||||
|
||||
// 位图指针,这个指针会在位图释放时自动释放
|
||||
private IntPtr _bitsPtr;
|
||||
|
||||
// 旧位图,析构时一起释放掉
|
||||
private HGDIOBJ _oldBitmap;
|
||||
public int Width { get; }
|
||||
|
||||
public int Height { get; }
|
||||
|
||||
// 用于过滤alpha通道
|
||||
private static readonly Gdi32.BLENDFUNCTION BlendFunction = new()
|
||||
{
|
||||
BlendOp = 0, //Gdi32.BlendOperation.AC_SRC_OVER,
|
||||
BlendFlags = 0,
|
||||
SourceConstantAlpha = 255,
|
||||
AlphaFormat = 0,
|
||||
};
|
||||
|
||||
private readonly object _lockObject = new object();
|
||||
|
||||
|
||||
public BitBltSession(HWND hWnd, int w, int h)
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (hWnd.IsNull)
|
||||
{
|
||||
throw new Exception("hWnd is invalid");
|
||||
}
|
||||
|
||||
_hWnd = hWnd;
|
||||
if (w <= 0 || h <= 0)
|
||||
{
|
||||
throw new Exception("Invalid width or height");
|
||||
}
|
||||
|
||||
Width = w;
|
||||
Height = h;
|
||||
_hdcSrc = User32.GetDC(_hWnd);
|
||||
if (_hdcSrc.IsInvalid)
|
||||
{
|
||||
throw new Exception("Failed to get DC for {_hWnd}");
|
||||
}
|
||||
|
||||
_hdcDest = Gdi32.CreateCompatibleDC(_hdcSrc);
|
||||
if (_hdcSrc.IsInvalid)
|
||||
{
|
||||
Debug.Fail("Failed to create CompatibleDC");
|
||||
throw new Exception("Failed to create CompatibleDC for {_hWnd}");
|
||||
}
|
||||
|
||||
|
||||
var bmi = new Gdi32.BITMAPINFO
|
||||
{
|
||||
bmiHeader = new Gdi32.BITMAPINFOHEADER
|
||||
{
|
||||
biSize = (uint)Marshal.SizeOf<Gdi32.BITMAPINFOHEADER>(),
|
||||
biWidth = Width,
|
||||
biHeight = -Height, // Top-down image
|
||||
biPlanes = 1,
|
||||
biBitCount = 24,
|
||||
biCompression = 0, // BI_RGB
|
||||
biSizeImage = 0,
|
||||
}
|
||||
};
|
||||
_hBitmap = Gdi32.CreateDIBSection(_hdcDest, bmi, Gdi32.DIBColorMode.DIB_RGB_COLORS, out var bits,
|
||||
IntPtr.Zero);
|
||||
|
||||
if (_hBitmap.IsInvalid || bits == 0)
|
||||
{
|
||||
if (!_hBitmap.IsInvalid)
|
||||
{
|
||||
Gdi32.DeleteObject(_hBitmap);
|
||||
}
|
||||
|
||||
throw new Exception($"Failed to create dIB section for {_hWnd}");
|
||||
}
|
||||
|
||||
_bitsPtr = bits;
|
||||
_oldBitmap = Gdi32.SelectObject(_hdcDest, _hBitmap);
|
||||
if (_oldBitmap.IsNull)
|
||||
{
|
||||
throw new Exception("Failed to select object");
|
||||
}
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
ReleaseResources();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 调用GDI复制到缓冲区并返回新的mat
|
||||
/// </summary>
|
||||
/// <returns>MatType.CV_8UC3</returns>
|
||||
public Mat? GetMat()
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
// 直接返回转换后的位图
|
||||
return Gdi32.AlphaBlend(_hdcDest, 0, 0, Width, Height, _hdcSrc, 0, 0, Width, Height, BlendFunction)
|
||||
? Mat.FromPixelData(Height, Width, MatType.CV_8UC3, _bitsPtr, (Width * 3 + 3) & ~3)
|
||||
: null;
|
||||
|
||||
// 原始宏 ((((biWidth * biBitCount) + 31) & ~31) >> 3) => (biWidth * biBitCount + 3) & ~3) (在总位数是8的倍数时,两者等价)
|
||||
// 对齐 https://learn.microsoft.com/zh-cn/windows/win32/api/wingdi/ns-wingdi-bitmapinfoheader
|
||||
|
||||
// 适用于32位(RGBA)
|
||||
// return Gdi32.BitBlt(_hdcDest, 0, 0, Width, Height, _hdcSrc, 0, 0, Gdi32.RasterOperationMode.SRCCOPY ) ? Mat.FromPixelData(Height, Width, MatType.CV_8UC3, _bitsPtr) : null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 不是所有的失效情况都能被检测到
|
||||
///
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool IsInvalid()
|
||||
{
|
||||
return _hWnd.IsNull || _hdcSrc.IsInvalid || _hdcDest.IsInvalid || _hBitmap.IsInvalid || _bitsPtr == IntPtr.Zero;
|
||||
}
|
||||
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
lock (_lockObject)
|
||||
{
|
||||
ReleaseResources();
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 需加锁环境下访问,释放资源
|
||||
/// </summary>
|
||||
private void ReleaseResources()
|
||||
{
|
||||
if (!_oldBitmap.IsNull)
|
||||
{
|
||||
// 先选回资源再释放_hBitmap
|
||||
Gdi32.SelectObject(_hdcDest, _oldBitmap);
|
||||
_oldBitmap = Gdi32.SafeHBITMAP.Null;
|
||||
}
|
||||
|
||||
|
||||
if (!_hBitmap.IsNull)
|
||||
{
|
||||
Gdi32.DeleteObject(_hBitmap);
|
||||
_hBitmap = Gdi32.SafeHBITMAP.Null;
|
||||
}
|
||||
|
||||
|
||||
if (!_hdcDest.IsNull)
|
||||
{
|
||||
Gdi32.DeleteDC(_hdcDest);
|
||||
_hdcDest = Gdi32.SafeHDC.Null;
|
||||
}
|
||||
|
||||
if (_hdcSrc != IntPtr.Zero)
|
||||
{
|
||||
User32.ReleaseDC(_hWnd, _hdcSrc);
|
||||
_hdcSrc = User32.SafeReleaseHDC.Null;
|
||||
}
|
||||
|
||||
_bitsPtr = IntPtr.Zero;
|
||||
}
|
||||
}
|
||||
@@ -19,8 +19,8 @@
|
||||
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
|
||||
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.0.2" />
|
||||
<PackageReference Include="Vanara.Windows.Extensions" Version="4.0.2" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.8.0.20230708" />
|
||||
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.10.0.20240616" />
|
||||
<PackageReference Include="OpenCvSharp4.Windows" Version="4.10.0.20240616" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
@@ -40,9 +40,10 @@ public class GraphicsCapture : IGameCapture
|
||||
|
||||
// 用于获取帧数据的临时纹理和暂存资源
|
||||
private Texture2D? _stagingTexture;
|
||||
|
||||
|
||||
private long _lastFrameTime = 0;
|
||||
|
||||
private readonly Stopwatch _frameTimer = new Stopwatch();
|
||||
|
||||
public void Dispose() => Stop();
|
||||
|
||||
@@ -81,16 +82,19 @@ public class GraphicsCapture : IGameCapture
|
||||
_captureFramePool.FrameArrived += OnFrameArrived;
|
||||
|
||||
_captureSession = _captureFramePool.CreateCaptureSession(_captureItem);
|
||||
if (ApiInformation.IsPropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession", "IsCursorCaptureEnabled"))
|
||||
if (ApiInformation.IsPropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession",
|
||||
"IsCursorCaptureEnabled"))
|
||||
{
|
||||
_captureSession.IsCursorCaptureEnabled = false;
|
||||
}
|
||||
|
||||
if (ApiInformation.IsWriteablePropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession", "IsBorderRequired"))
|
||||
if (ApiInformation.IsWriteablePropertyPresent("Windows.Graphics.Capture.GraphicsCaptureSession",
|
||||
"IsBorderRequired"))
|
||||
{
|
||||
_captureSession.IsBorderRequired = false;
|
||||
}
|
||||
|
||||
_frameTimer.Start();
|
||||
_captureSession.StartCapture();
|
||||
IsCapturing = true;
|
||||
}
|
||||
@@ -110,7 +114,8 @@ public class GraphicsCapture : IGameCapture
|
||||
|
||||
|
||||
ResourceRegion region = new();
|
||||
DwmApi.DwmGetWindowAttribute<RECT>(hWnd, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_EXTENDED_FRAME_BOUNDS, out var windowRect);
|
||||
DwmApi.DwmGetWindowAttribute<RECT>(hWnd, DwmApi.DWMWINDOWATTRIBUTE.DWMWA_EXTENDED_FRAME_BOUNDS,
|
||||
out var windowRect);
|
||||
User32.GetClientRect(_hWnd, out var clientRect);
|
||||
//POINT point = default; // 这个点和 DwmGetWindowAttribute 结果差1
|
||||
//User32.ClientToScreen(hWnd, ref point);
|
||||
@@ -174,14 +179,13 @@ public class GraphicsCapture : IGameCapture
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// 限制最高处理帧率为66fps
|
||||
var now = Kernel32.GetTickCount();
|
||||
if (now - _lastFrameTime < 15)
|
||||
|
||||
// 限制最高处理帧率为62fps
|
||||
if (_frameTimer.ElapsedMilliseconds - _lastFrameTime < 16)
|
||||
{
|
||||
return;
|
||||
}
|
||||
_lastFrameTime = now;
|
||||
_lastFrameTime = _frameTimer.ElapsedMilliseconds;
|
||||
|
||||
var frameSize = _captureItem.Size;
|
||||
|
||||
@@ -227,7 +231,7 @@ public class GraphicsCapture : IGameCapture
|
||||
try
|
||||
{
|
||||
// 创建一个新的Mat
|
||||
var newFrame = new Mat(stagingTexture.Description.Height, stagingTexture.Description.Width,
|
||||
var newFrame = Mat.FromPixelData(stagingTexture.Description.Height, stagingTexture.Description.Width,
|
||||
_isHdrEnabled ? MatType.MakeType(7, 4) : MatType.CV_8UC4, dataBox.DataPointer);
|
||||
|
||||
// 如果是HDR,进行HDR到SDR的转换
|
||||
@@ -309,18 +313,18 @@ public class GraphicsCapture : IGameCapture
|
||||
IsCapturing = false;
|
||||
|
||||
// 释放最新帧
|
||||
// _frameAccessLock.EnterWriteLock();
|
||||
// try
|
||||
// {
|
||||
// _latestFrame?.Dispose();
|
||||
// _latestFrame = null;
|
||||
// }
|
||||
// finally
|
||||
// {
|
||||
// _frameAccessLock.ExitWriteLock();
|
||||
// }
|
||||
//
|
||||
// _frameAccessLock.Dispose();
|
||||
_frameAccessLock.EnterWriteLock();
|
||||
try
|
||||
{
|
||||
_latestFrame?.Dispose();
|
||||
_latestFrame = null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_frameAccessLock.ExitWriteLock();
|
||||
}
|
||||
|
||||
_frameAccessLock.Dispose();
|
||||
}
|
||||
|
||||
private void CaptureItemOnClosed(GraphicsCaptureItem sender, object args)
|
||||
|
||||
@@ -46,9 +46,11 @@ public static class Direct3D11Helper
|
||||
return CreateDevice(false);
|
||||
}
|
||||
|
||||
private static SharpDX.Direct3D11.Device? d3dDevice;
|
||||
|
||||
public static IDirect3DDevice CreateDevice(bool useWARP)
|
||||
{
|
||||
var d3dDevice = new SharpDX.Direct3D11.Device(
|
||||
d3dDevice ??= new SharpDX.Direct3D11.Device(
|
||||
useWARP ? SharpDX.Direct3D.DriverType.Software : SharpDX.Direct3D.DriverType.Hardware,
|
||||
SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport);
|
||||
var device = CreateDirect3DDeviceFromSharpDXDevice(d3dDevice);
|
||||
|
||||
@@ -90,7 +90,7 @@ public static class Texture2DExtensions
|
||||
MapMode.Read,
|
||||
SharpDX.Direct3D11.MapFlags.None);
|
||||
|
||||
var mat = new Mat(staging.Description.Height, staging.Description.Width, MatType.CV_8UC4, dataBox.DataPointer);
|
||||
var mat = Mat.FromPixelData(staging.Description.Height, staging.Description.Width, MatType.CV_8UC4, dataBox.DataPointer);
|
||||
return mat;
|
||||
}
|
||||
catch (Exception e)
|
||||
|
||||
@@ -130,4 +130,4 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
|
||||
|
||||
## 问题反馈
|
||||
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1029539994](https://qm.qq.com/q/vCOphnHFK2)
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1036100501](https://qm.qq.com/q/fvRNqEbFyo)
|
||||
@@ -19,12 +19,16 @@ public class AvatarClassifyGen
|
||||
// 读取基础图像
|
||||
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// 只用一个图像
|
||||
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Varesa.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Iansan.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"),
|
||||
"UI_AvatarIcon_Side_Varesa.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"),
|
||||
"UI_AvatarIcon_Side_Iansan.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
sideImageFiles.AddRange(sideImageFiles2);
|
||||
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_AmborCostumeWic.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"),
|
||||
"UI_AvatarIcon_Side_AmborCostumeWic.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
sideImageFiles.AddRange(sideImageFiles3);
|
||||
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Ambor.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"),
|
||||
"UI_AvatarIcon_Side_Ambor.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
sideImageFiles.AddRange(sideImageFiles4);
|
||||
// List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_XianglingCostumeWinter.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// sideImageFiles.AddRange(sideImageFiles5);
|
||||
@@ -72,11 +76,14 @@ public class AvatarClassifyGen
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
// 随机挑选一张背景图像
|
||||
string backgroundImageFile = Path.Combine(BackgroundDir, Directory.GetFiles(BackgroundDir, "*.png")[Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
|
||||
string backgroundImageFile = Path.Combine(BackgroundDir,
|
||||
Directory.GetFiles(BackgroundDir, "*.png")[
|
||||
Rd.Next(Directory.GetFiles(BackgroundDir, "*.png").Length)]);
|
||||
|
||||
// 从背景图像中随机取一块 128x128 的区域
|
||||
Mat backgroundImage = Cv2.ImRead(backgroundImageFile, ImreadModes.Color);
|
||||
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128), new Random().Next(backgroundImage.Height - 128), 128, 128);
|
||||
Rect backgroundRect = new Rect(Rd.Next(backgroundImage.Width - 128),
|
||||
new Random().Next(backgroundImage.Height - 128), 128, 128);
|
||||
Mat backgroundImageRegion = backgroundImage[backgroundRect];
|
||||
|
||||
// 随机平移、缩放保留区域
|
||||
@@ -93,9 +100,11 @@ public class AvatarClassifyGen
|
||||
// Cv2.ImShow("resizedSideImage", resizedSideImage);
|
||||
var resizedMaskImage = new Mat();
|
||||
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
|
||||
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
Cv2.Resize(~alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0,
|
||||
InterpolationFlags.Cubic);
|
||||
var resizedAlphaChannel = new Mat();
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0,
|
||||
InterpolationFlags.Cubic);
|
||||
|
||||
// Cv2.ImShow("resizedMaskImage", resizedMaskImage);
|
||||
// generatedImage[transformedRect] = resizedSideImage;
|
||||
@@ -112,7 +121,8 @@ public class AvatarClassifyGen
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}大于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX, (resizedSideImage.Height - 128) + offsetY, 128, 128);
|
||||
var roi = new Rect((resizedSideImage.Width - 128) / 2 + offsetX,
|
||||
(resizedSideImage.Height - 128) + offsetY, 128, 128);
|
||||
// result = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone, backgroundImageRegionClone, result, resizedMaskImage[roi]);
|
||||
result = Mul(backgroundImageRegionClone, resizedAlphaChannel[roi]);
|
||||
@@ -126,7 +136,8 @@ public class AvatarClassifyGen
|
||||
int offsetY = Rd.Next(-ySpace, 0);
|
||||
Debug.WriteLine($"{sideImageFileName} 缩放{scale}小于等于1 偏移 ({offsetX},{offsetY})");
|
||||
|
||||
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX, (128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
|
||||
var roi = new Rect((128 - resizedSideImage.Width) / 2 + offsetX,
|
||||
(128 - resizedSideImage.Height) + offsetY, resizedSideImage.Width, resizedSideImage.Height);
|
||||
var res = new Mat();
|
||||
// Cv2.BitwiseAnd(backgroundImageRegionClone[roi], backgroundImageRegionClone[roi], res, resizedMaskImage);
|
||||
res = Mul(backgroundImageRegionClone[roi], resizedAlphaChannel);
|
||||
@@ -146,11 +157,12 @@ public class AvatarClassifyGen
|
||||
var channels = background.Split();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
|
||||
Cv2.Multiply(channels[i], ~ alphaChannel, channels[i], 1 / 255.0);
|
||||
}
|
||||
|
||||
Mat result = new Mat();
|
||||
Cv2.Merge(channels[..3], result);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -100,7 +100,7 @@ public class AvatarClassifyTransparentGen
|
||||
// Cv2.ImShow("resizedSideImage", resizedSideImage);
|
||||
var resizedMaskImage = new Mat();
|
||||
// Cv2.Threshold(alphaChannel, alphaChannel, 200, 255, ThresholdTypes.Otsu);
|
||||
Cv2.Resize(255 - alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
Cv2.Resize(~ alphaChannel, resizedMaskImage, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
var resizedAlphaChannel = new Mat();
|
||||
Cv2.Resize(alphaChannel, resizedAlphaChannel, new Size(128 * scale, 128 * scale), 0, 0, InterpolationFlags.Cubic);
|
||||
|
||||
@@ -153,7 +153,7 @@ public class AvatarClassifyTransparentGen
|
||||
var channels = background.Split();
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
Cv2.Multiply(channels[i], 255 - alphaChannel, channels[i], 1 / 255.0);
|
||||
Cv2.Multiply(channels[i], ~ alphaChannel, channels[i], 1 / 255.0);
|
||||
}
|
||||
Mat result = new Mat();
|
||||
Cv2.Merge(channels[..3], result);
|
||||
|
||||
@@ -281,10 +281,10 @@ public class KeyPointMatchTest
|
||||
writer.Write(image.Rows);
|
||||
writer.Write(image.Cols);
|
||||
int depth = image.Depth();
|
||||
int type = image.Type();
|
||||
MatType type = image.Type();
|
||||
int channels = image.Channels();
|
||||
writer.Write(depth);
|
||||
writer.Write(type);
|
||||
writer.Write(type.Value);
|
||||
writer.Write(channels);
|
||||
int sizeInBytes = (int)image.Step() * image.Rows;
|
||||
writer.Write(sizeInBytes);
|
||||
|
||||
@@ -282,7 +282,7 @@ public class CharacterOrientationTest
|
||||
|
||||
if (contours.Length > 0)
|
||||
{
|
||||
var maxRect = Rect.Empty;
|
||||
Rect maxRect = default;
|
||||
var maxIndex = 0;
|
||||
for (int i = 0; i < contours.Length; i++)
|
||||
{
|
||||
|
||||
+10
-10
@@ -31,7 +31,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
FakeSystemInfo systemInfo = new FakeSystemInfo(new Vanara.PInvoke.RECT(0, 0, mat.Width, mat.Height), 1);
|
||||
var blackboard = new Blackboard(sleep: i => { })
|
||||
{
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList())
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList())
|
||||
};
|
||||
|
||||
//
|
||||
@@ -62,7 +62,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
FakeSystemInfo systemInfo = new FakeSystemInfo(new Vanara.PInvoke.RECT(0, 0, mat.Width, mat.Height), 1);
|
||||
var blackboard = new Blackboard(sleep: i => { })
|
||||
{
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList())
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList())
|
||||
};
|
||||
|
||||
DateTimeOffset dateTime = new DateTimeOffset(2025, 2, 26, 16, 13, 54, 285, TimeSpan.FromHours(8));
|
||||
@@ -116,7 +116,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
FakeSystemInfo systemInfo = new FakeSystemInfo(new Vanara.PInvoke.RECT(0, 0, mat.Width, mat.Height), 1);
|
||||
var blackboard = new Blackboard(sleep: i => { })
|
||||
{
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList())
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList())
|
||||
};
|
||||
|
||||
DateTimeOffset dateTime = new DateTimeOffset(2025, 2, 26, 16, 13, 54, 285, TimeSpan.FromHours(8));
|
||||
@@ -155,7 +155,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region medaka受到遮挡,第3次失败
|
||||
//
|
||||
fishNames = new string[] { "koi", "koi head", "sunfish" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(20));
|
||||
|
||||
@@ -173,7 +173,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region sunfish受到遮挡,medaka再次出现,第4次成功,并钓起medaka
|
||||
//
|
||||
fishNames = new string[] { "koi", "koi head", "medaka" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(30));
|
||||
|
||||
@@ -191,7 +191,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region sunfish再次出现,第5次失败
|
||||
//
|
||||
fishNames = new string[] { "koi", "koi head", "sunfish" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(40));
|
||||
|
||||
@@ -222,7 +222,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
IEnumerable<string> fishNames = new string[] { "koi", "koi head", "sunfish" };
|
||||
var blackboard = new Blackboard(sleep: i => { })
|
||||
{
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList())
|
||||
fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList())
|
||||
};
|
||||
|
||||
DateTimeOffset dateTime = new DateTimeOffset(2025, 2, 26, 16, 13, 54, 285, TimeSpan.FromHours(8));
|
||||
@@ -244,7 +244,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region koi受到遮挡,第2次失败
|
||||
//
|
||||
fishNames = new string[] { "sunfish" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(10));
|
||||
|
||||
@@ -263,7 +263,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region koi再次出现,第3次失败
|
||||
//
|
||||
fishNames = new string[] { "koi", "koi head", "sunfish" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(20));
|
||||
|
||||
@@ -281,7 +281,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
#region 第4次失败
|
||||
//
|
||||
fishNames = new string[] { "koi", "koi head", "sunfish" };
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, OpenCvSharp.Rect.Empty, 0)).ToList());
|
||||
blackboard.fishpond = new Fishpond(fishNames.Select(n => new OneFish(n, default, 0)).ToList());
|
||||
sut.Reset();
|
||||
fakeTimeProvider.SetUtcNow(dateTime.AddSeconds(40));
|
||||
|
||||
|
||||
+1
-1
@@ -135,7 +135,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
var actual = sut.currentFish;
|
||||
|
||||
//
|
||||
Assert.True(blackboard.fishpond.TargetRect != null && blackboard.fishpond.TargetRect.Value != OpenCvSharp.Rect.Empty);
|
||||
Assert.True(blackboard.fishpond.TargetRect != null && blackboard.fishpond.TargetRect.Value != default);
|
||||
Assert.Equal(3, blackboard.fishpond.Fishes.Count(f => f.FishType.Name == "pufferfish"));
|
||||
Assert.Equal(blackboard.fishpond.Fishes.OrderBy(f => f.Rect.X).First(), actual);
|
||||
|
||||
|
||||
Reference in new issue
Block a user