Compare commits

..
Author SHA1 Message Date
辉鸭蛋 00f680f4ec 修改屏幕缩放问题 2026-05-03 13:01:40 +08:00
39 changed files with 178 additions and 912 deletions

No files matched your search

+4
View File
@@ -31,6 +31,10 @@ github_actions_cache/
# Rider
.idea
.claude
CLAUDE.md
AGENTS.md
__pycache__/
+2 -8
View File
@@ -14,8 +14,7 @@
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
## MVVM 架构规则
@@ -78,9 +77,4 @@
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
最后,程序能够编译就认为成功,无需实际运行程序。
-86
View File
@@ -1,86 +0,0 @@
本项目使用了 WPF-UI、 CommunityToolkit.Mvvm、Microsoft.Xaml.Behaviors.Wpf 来实现 MVVM 架构。在编写代码的时候请注意:
### 主要依赖框架
#### UI 框架
- **WPF-UI (4.0.2)** - 现代化 WPF UI 框架
- **gong-wpf-dragdrop(3.2.1)** - 拖拽框架
#### MVVM 框架
- **CommunityToolkit.Mvvm (8.2.2)** - 微软官方 MVVM 工具包
- 所有 ViewModel 必须继承自 `ObservableObject`
- 使用 `[ObservableProperty]` 特性自动生成属性
- 使用 `[RelayCommand]` 特性自动生成命令
- **Microsoft.Xaml.Behaviors.Wpf(1.1.122)** - WPF 行为扩展库
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
### 基础架构
### ViewModel 编写规范
1. **继承规则**
```csharp
public partial class ExampleViewModel : ViewModel
{
[ObservableProperty]
private string _title = "";
[RelayCommand]
private void DoSomething()
{
// 实现逻辑
}
}
```
2. **属性命名**
- 私有字段使用下划线前缀: `_fieldName`
- 公共属性使用 PascalCase: `PropertyName`
- 使用 `[ObservableProperty]` 自动生成属性
3. **命令实现**
- 使用 `[RelayCommand]` 特性
- 异步命令使用 `[RelayCommand]` + `async Task`
### View 编写规范
1. **代码后置**
```csharp
public partial class ExamplePage : UserControl
{
public ExampleViewModel ViewModel { get; }
public ExamplePage(ExampleViewModel viewModel)
{
ViewModel = viewModel;
DataContext = this;
InitializeComponent();
}
}
```
2. **XAML 绑定**
- 使用 `{Binding}` 语法绑定 ViewModel 属性
- 命令绑定: `Command="{Binding ExampleCommand}"`
- 避免在 XAML 中编写复杂逻辑
### 依赖注入规范
1. **服务注册**
```csharp
// 在 App.xaml.cs 中注册
services.AddView<ExamplePage, ExampleViewModel>();
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.60.2-alpha.4</Version>
<Version>0.60.2-alpha.3</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -43,7 +43,7 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.22" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.15" />
@@ -85,17 +85,17 @@
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<!-- <PackageReference Include="supabase-csharp" Version="0.16.2" />-->
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
<PackageReference Include="Vanara.PInvoke.NtDll" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.SHCore" Version="4.1.3" />
<PackageReference Include="Vanara.PInvoke.User32" Version="4.1.3" />
<PackageReference Include="XamlAnimatedGif" Version="2.3.1" />
<PackageReference Include="WPF-UI" Version="4.3.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.3.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.3.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.3.0.0" />
<PackageReference Include="WPF-UI" Version="4.2.0" />
<PackageReference Include="WPF-UI.DependencyInjection" Version="4.2.0" />
<PackageReference Include="WPF-UI.Tray" Version="4.2.0" />
<PackageReference Include="WPF-UI.Violeta" Version="4.2.0.10" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
+14 -91
View File
@@ -21,12 +21,10 @@ public class BvLocator
{
private static readonly ILogger Logger = App.GetLogger<BvLocator>();
private readonly CancellationToken _cancellationToken;
private int? _timeout;
private int? _retryInterval;
public RecognitionObject RecognitionObject { get; }
public Func<List<Region>, Task>? RetryAction { get; set; }
public Action<List<Region>>? RetryAction { get; set; }
public static int DefaultTimeout { get; set; } = 10000;
@@ -100,21 +98,17 @@ public class BvLocator
public async Task<List<Region>> WaitFor(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
List<Region> results = [];
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
results = FindAll();
var b = results.Count > 0;
if (!b && RetryAction != null)
{
await RetryAction(results);
}
RetryAction?.Invoke(results);
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (retryRes)
{
@@ -156,21 +150,20 @@ public class BvLocator
public async Task WaitForDisappear(int? timeout = null)
{
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var retryRes = await NewRetry.WaitForAction(async () =>
var retryRes = await NewRetry.WaitForAction(() =>
{
var results = FindAll();
var b = results.Count == 0;
if (!b && RetryAction != null)
if (!b)
{
await RetryAction(results);
RetryAction?.Invoke(results);
}
return b;
}, _cancellationToken, retryCount, actualRetryInterval);
}, _cancellationToken, retryCount, DefaultRetryInterval);
if (!retryRes)
{
@@ -212,77 +205,7 @@ public class BvLocator
public BvLocator WithRetryAction(Action<List<Region>>? action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = (results) =>
{
action(results);
return Task.CompletedTask;
};
}
RetryAction = action;
return this;
}
/// <summary>
/// 设置超时时间(毫秒)
/// </summary>
/// <param name="timeout">超时时间(毫秒)</param>
/// <returns></returns>
public BvLocator WithTimeout(int timeout)
{
if (timeout <= 0)
{
throw new ArgumentOutOfRangeException(nameof(timeout), "timeout 必须大于 0");
}
_timeout = timeout;
return this;
}
/// <summary>
/// 设置重试间隔(毫秒)
/// </summary>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns></returns>
public BvLocator WithRetryInterval(int retryInterval)
{
if (retryInterval <= 0)
{
throw new ArgumentOutOfRangeException(nameof(retryInterval), "retryInterval 必须大于 0");
}
_retryInterval = retryInterval;
return this;
}
/// <summary>
/// 为 JavaScript 提供的动态参数重载
/// 解决 ClearScript 无法将 JS 函数隐式转换为 Action 委托的问题
/// 支持同步和异步 JS 函数
/// </summary>
/// <param name="action">JS 回调函数</param>
/// <returns></returns>
public BvLocator WithRetryAction(dynamic action)
{
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = async (results) =>
{
var taskResult = action(results);
// 如果 JS 返回的是 Promise/Task,等待其完成
if (taskResult is Task task)
{
await task;
}
};
}
return this;
}
}
}
@@ -55,15 +55,6 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel BgiAvatarSide =
Register("BgiAvatarSide", @"Assets\Model\Common\avatar_side_classify_sim.onnx");
/// <summary>
/// Q技能冷却分类模型
/// </summary>
public static readonly BgiOnnxModel BgiQClassify =
Register("BgiQClassify", @"Assets\Model\Common\q_classify_sim.onnx");
public static readonly BgiOnnxModel BgiPickClassify =
Register("BgiPickClassify", @"Assets\Model\Common\pick.onnx");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -153,4 +144,4 @@ public class BgiOnnxModel
RegisteredModels.Add(model);
return model;
}
}
}
@@ -88,7 +88,6 @@ public class AutoPathingScript
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
@@ -216,11 +216,6 @@ public class Genshin
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
public Point2f? GetPositionFromMapWithMatchingMethod(string matchingMethod)
{
return GetPositionFromMapWithMatchingMethod(nameof(MapTypes.Teyvat), matchingMethod);
}
public float GetCameraOrientation()
{
@@ -235,18 +230,14 @@ public class Genshin
/// <param name="cacheTimeMs">缓存时间,单位毫秒,默认900ms</param>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f? GetPositionFromMap(string mapName, int cacheTimeMs = 900)
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return GetPositionFromMapWithMatchingMethod(mapName,matchingMethod, cacheTimeMs);
}
public Point2f? GetPositionFromMapWithMatchingMethod(string mapName, string matchingMethod, int cacheTimeMs = 900)
{
var imageRegion = CaptureToRectArea();
if (!Bv.IsInMainUi(imageRegion))
{
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
}
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
return MapManager.GetMap(mapName, matchingMethod)
.ConvertImageCoordinatesToGenshinMapCoordinates(LazyNavigationInstance.Value
.GetPositionStableByCache(imageRegion, mapName, matchingMethod, cacheTimeMs));
@@ -145,35 +145,6 @@ public class HtmlMask : IDisposable
/// </summary>
public bool Exists(string id) => HtmlMaskWindow.Exists(id);
/// <summary>
/// 设置窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThrough(string windowId, bool enabled)
{
HtmlMaskWindow.SetClickThrough(windowId, enabled);
}
/// <summary>
/// 获取窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>true=点击穿透,false=可交互</returns>
public bool GetClickThrough(string windowId)
{
return HtmlMaskWindow.GetClickThrough(windowId);
}
/// <summary>
/// 切换窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public void ToggleClickThrough(string windowId)
{
HtmlMaskWindow.ToggleClickThrough(windowId);
}
#endregion
#region 消息通信
@@ -15,7 +15,6 @@ public class LimitedFile(string rootPath)
{
/// <summary>
/// 读取指定文件夹内所有文件和文件夹的路径(非递归方式)。
/// 目录不存在时返回空数组
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
@@ -24,19 +23,19 @@ public class LimitedFile(string rootPath)
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
string normalizedFolderPath = NormalizePath(folderPath);
if (!Directory.Exists(fullPath))
// 确保目录存在
if (!Directory.Exists(normalizedFolderPath))
{
TaskControl.Logger.LogError("ReadPathSync 目录不存在: {Path}", fullPath);
return Array.Empty<string>();
Directory.CreateDirectory(normalizedFolderPath);
}
// 获取指定文件夹下的所有文件(非递归)
string[] files = Directory.GetFiles(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 获取指定文件夹下的所有子文件夹(非递归)
string[] directories = Directory.GetDirectories(fullPath, "*", SearchOption.TopDirectoryOnly);
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
// 合并文件和文件夹路径
string[] combined = files.Concat(directories).ToArray();
@@ -46,33 +45,12 @@ public class LimitedFile(string rootPath)
}
catch (Exception ex)
{
// 记录异常并返回空数组
TaskControl.Logger.LogError("ReadPathSync 异常: {Message}", ex.Message);
return Array.Empty<string>();
}
}
/// <summary>
/// 创建指定路径的目录,如果已存在则跳过
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>是否创建成功或目录已存在</returns>
public bool CreateDirectory(string folderPath)
{
try
{
// 对传入的文件夹路径进行标准化
string fullPath = NormalizePath(folderPath);
// 如果目录不存在,自动创建
if (!Directory.Exists(fullPath)){Directory.CreateDirectory(fullPath);}
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("CreateDir 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定路径是否为文件夹。
/// </summary>
@@ -1,43 +0,0 @@
using System;
using System.Linq;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// 战斗策略文件访问类
/// 提供JS脚本环境访问 User\AutoFight 目录下战斗策略文件的方法
/// </summary>
public class StrategyFile
{
private readonly LimitedFile _strategyFile = new(Global.Absolute(@"User\AutoFight"));
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => _strategyFile.IsFolder(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => _strategyFile.IsFile(subPath);
/// <summary>
/// 判断 User\AutoFight 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => _strategyFile.IsExists(subPath);
/// <summary>
/// 读取 User\AutoFight 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoFight 的子目录路径,默认为根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => _strategyFile.ReadPathSync(subPath);
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Collections.Generic;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
@@ -77,7 +77,6 @@ public class EngineExtend
engine.AddHostType("AutoFightParam", typeof(AutoFightParam));
engine.AddHostType("AutoLeyLineOutcropParam", typeof(AutoLeyLineOutcropParam));
engine.AddHostType("AutoStygianOnslaughtParam", typeof(AutoStygianOnslaughtParam));
engine.AddHostObject("strategyFile", new StrategyFile());
//鼠标回调
engine.AddHostType("KeyMouseHook", typeof(KeyMouseHook));
// 添加C#的类型
@@ -28,9 +28,6 @@ public class Simulation
SendInput.Keyboard.KeyUp(key);
}
}
SendInput.Mouse.LeftButtonUp();
SendInput.Mouse.RightButtonUp();
SendInput.Mouse.MiddleButtonUp();
}
public static bool IsKeyDown(User32.VK key)
@@ -22,7 +22,6 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
public Rect ERect;
public Rect ECooldownRect;
public Rect QRect;
public Rect QRectForClassify;
public Rect ZCooldownRect;
public Rect EndTipsUpperRect; // 挑战达成提示
public Rect EndTipsRect;
@@ -79,8 +78,6 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
(int)(41 * AssetScale), (int)(18 * AssetScale));
QRect = new Rect(CaptureRect.Width - (int)(157 * AssetScale), CaptureRect.Height - (int)(165 * AssetScale),
(int)(110 * AssetScale), (int)(110 * AssetScale));
QRectForClassify = new Rect(CaptureRect.Width - (int)(172 * AssetScale), CaptureRect.Height - (int)(166 * AssetScale),
(int)(137 * AssetScale), (int)(137 * AssetScale));
ZCooldownRect = new Rect(CaptureRect.Width - (int)(130 * AssetScale), (int)(814 * AssetScale),
(int)(60 * AssetScale), (int)(24 * AssetScale));
// 小道具位置 1920-133,800,60,50
@@ -13,7 +13,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
[Serializable]
public partial class AutoFightConfig : ObservableObject
{
[ObservableProperty] private string _strategyName = "根据队伍自动选择";
[ObservableProperty] private string _strategyName = "";
/// <summary>
/// 英文逗号分割 强制指定队伍角色
@@ -680,21 +680,11 @@ public class AutoFightTask : ISoloTask
await Delay(200, ct);
if (picker.TrySwitch(10))
{
// 等待元素战技 CD 就绪
await picker.WaitSkillCd(ct);
// 调用统一的辅助方法,模拟万叶长按 E 的输入序列:
// 包含释放鼠标左键前摇防卡键 -> E 键 KeyDown -> 延时 800ms -> E 键 KeyUp -> 延时 50ms
await SimulateHoldElementalSkillAsync(800, ct);
// 调用统一的辅助方法,模拟 6 次鼠标左键连续点击:
// 配合万叶长 E 的滞空特性执行下落攻击,内部包含 try/finally 以保证取消任务时安全释放左键
await SimulateMouseLeftClickLoopAsync(6, ct);
// 等待下落攻击和聚怪拾取动作彻底结束
picker.UseSkill(true);
await Delay(50, ct);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1500, ct);
// 截图并更新技能最新冷却时间
picker.AfterUseSkill();
}
}
else
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Simulator;
@@ -24,11 +24,6 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Common;
using Compunet.YoloSharp;
using Compunet.YoloSharp.Data;
using Microsoft.Extensions.DependencyInjection;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -104,10 +99,7 @@ public class Avatar
};
private static readonly Random UnstuckRandom = new();
private static readonly Lazy<BgiYoloPredictor> QBurstClassifierLazy = new(() =>
App.ServiceProvider.GetRequiredService<BgiOnnxFactory>().CreateYoloPredictor(BgiOnnxModel.BgiQClassify));
public Avatar(CombatScenes combatScenes, string name, int index, Rect nameRect, double manualSkillCd = -1)
{
@@ -599,14 +591,6 @@ public class Avatar
/// </summary>
public void UseBurst()
{
// CD 中立即返回,其余场景尝试释放
using var region1 = CaptureToRectArea();
if (IsBurstReadyByClassify(region1) != BurstReadyState.Ready)
{
// Logger.LogInformation("Q在CD,跳过");
return;
}
for (var i = 0; i < 10; i++)
{
if (Ct is { IsCancellationRequested: true })
@@ -614,7 +598,6 @@ public class Avatar
return;
}
// Logger.LogInformation("释放Q");
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
Sleep(200, Ct);
@@ -627,47 +610,9 @@ public class Avatar
Sleep(1500, Ct);
return;
}
else
{
// 找到编号块判断是否进入了CD,四星角色没有大招动画
if (IsBurstReadyByClassify(region) != BurstReadyState.Ready)
{
// Logger.LogInformation("释放Q后检查到CD");
Sleep(1500, Ct);
return;
}
}
}
}
private static BurstReadyState IsBurstReadyByClassify(ImageRegion imageRegion)
{
using var qRa = imageRegion.DeriveCrop(AutoFightAssets.Instance.QRectForClassify);
var result = QBurstClassifierLazy.Value.Predictor.Classify(qRa.CacheImage);
var topClass = result.GetTopClass();
var topClassName = topClass.Name.Name;
// Logger.LogInformation("Q技能冷却分类:{ClassName},置信度:{Confidence:F2}", topClassName, topClass.Confidence);
// 置信度不足时,直接返回未知,避免误判导致漏放/乱放
if (topClass.Confidence <= 0.7)
{
// Logger.LogInformation("Q技能冷却分类置信度不足:{Confidence:F2},类别:{ClassName}", topClass.Confidence, topClassName);
return BurstReadyState.Unknown;
}
if (topClassName.Contains("cd 1", StringComparison.OrdinalIgnoreCase))
{
return BurstReadyState.Cooldown;
}
if (topClassName.Contains("energy 1 cd 0", StringComparison.OrdinalIgnoreCase))
{
return BurstReadyState.Ready;
}
return BurstReadyState.Unknown;
}
// /// <summary>
// /// 元素爆发是否正在CD中
// /// 右下 157x165
@@ -1153,4 +1098,4 @@ public class Avatar
return null;
}
}
}
@@ -1,9 +0,0 @@
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
public enum BurstReadyState
{
Ready,
Cooldown,
Unknown
}
@@ -1,5 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.Model;
@@ -75,7 +74,6 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
else
{
_cts.Cancel();
Simulation.ReleaseAllKey();
}
}
}
@@ -91,7 +89,6 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
if (IsHoldOnMode())
{
_cts?.Cancel();
Simulation.ReleaseAllKey();
}
}
@@ -182,9 +179,9 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
// 通用化战斗策略
foreach (var command in combatCommands)
{
if (ct.IsCancellationRequested) break;
if (command.ActivatingRound != null && command.ActivatingRound.Count > 0 && !command.ActivatingRound.Contains(round))
{
// 跳过强制首轮指令
continue;
}
command.Execute(activeAvatar);
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Config;
@@ -11,7 +11,6 @@ using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoPick.Assets;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
@@ -1082,34 +1081,11 @@ public class AutoLeyLineOutcropTask : ISoloTask
_logger.LogInformation("战后聚集拾取:万叶已切换,等待元素战技CD");
await kazuha.WaitSkillCd(_ct);
await SimulateHoldElementalSkillAsync(1000, _ct);
await Delay(200, _ct);
// 获取游戏画面,进行 OCR 及视觉状态双重验证,以确认长E技能是否真正释放成功
using (var region = CaptureToRectArea())
{
// 裁剪技能 CD 区域并做 HSV 颜色过滤,分离出白色的 CD 数字
using var eRa = region.DeriveCrop(AutoFightAssets.Instance.ECooldownRect);
using var eRaWhite = OpenCvCommonHelper.InRangeHsv(eRa.SrcMat, new Scalar(0, 0, 235), new Scalar(0, 25, 255));
var text = OcrFactory.Paddle.OcrWithoutDetector(eRaWhite);
// 如果成功读到了大于 0 的 CD 数值,说明技能已释放
var hasOcrCd = double.TryParse(text, out var ocrCd) && ocrCd > 0;
// 视觉上判断当前技能图标是否高亮就绪,如果不亮(false)也说明技能释放进入了冷却
var isVisualReady = Bv.IsSkillReady(region, kazuha.Index, false);
// 当 OCR 没读出 CD(可能网络卡顿技能没放出来),并且视觉上技能图标依然亮着就绪时,判断为释放失败
if (!hasOcrCd && isVisualReady)
{
_logger.LogWarning("战后聚集拾取:万叶长E释放确认失败(OCR:{Text}),跳过后续拾取动作", text);
return;
}
// 更新技能冷却记录,防止干扰后续冷却判断
kazuha.AfterUseSkill(region);
}
await SimulateMouseLeftClickLoopAsync(6, _ct);
kazuha.UseSkill(true);
await Delay(50, _ct);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1500, _ct);
kazuha.AfterUseSkill();
_logger.LogInformation("战后聚集拾取:万叶长E动作完成,等待拾取动作结束");
await Delay(KazuhaPickupPostSkillWaitMs, _ct);
_logger.LogInformation("战后聚集拾取:万叶长E聚集动作执行完成");
@@ -28,11 +28,11 @@ internal class AutoFightHandler : IActionHandler
TaskControl.Logger.LogInformation("执行 {Text}", "自动战斗");
// 爷们要战斗
AutoFightParam taskParams = null;
if (config is PathingPartyConfig { Enabled: true, AutoFightEnabled: true } partyConfig)
if (config != null && config is PathingPartyConfig patyConfig && patyConfig.AutoFightEnabled)
{
//替换配置为地图追踪
taskParams = GetFightAutoFightParam(partyConfig.AutoFightConfig);
taskParams = GetFightAutoFightParam(patyConfig.AutoFightConfig);
}
else
{
@@ -80,7 +80,7 @@ internal class AutoFightHandler : IActionHandler
private string GetFightStrategy(AutoFightConfig config)
{
var path = Global.Absolute(@"User\AutoFight\" + config.StrategyName + ".txt");
if ("根据队伍自动选择".Equals(config.StrategyName) || string.IsNullOrEmpty(config.StrategyName))
if ("根据队伍自动选择".Equals(config.StrategyName))
{
path = Global.Absolute(@"User\AutoFight\");
}
@@ -44,7 +44,7 @@ public class LinneaMiningHandler : IActionHandler
private static (int mineCount, int scanRounds) ParseParams(string? actionParams)
{
if (string.IsNullOrEmpty(actionParams)) return (LinneaMiningTask.DefaultMineCount, LinneaMiningTask.DefaultScanRounds);
if (string.IsNullOrEmpty(actionParams)) return (1, 5);
var parts = actionParams.Split(',');
var mineCount = -1;
@@ -72,8 +72,8 @@ public class LinneaMiningHandler : IActionHandler
}
}
if (mineCount == -1) mineCount = LinneaMiningTask.DefaultMineCount;
if (scanRounds == -1) scanRounds = LinneaMiningTask.DefaultScanRounds;
if (mineCount == -1) mineCount = 1;
if (scanRounds == -1) scanRounds = 5;
if (scanRounds < mineCount) scanRounds = mineCount;
return (mineCount, scanRounds);
@@ -25,8 +25,8 @@ public class PickUpCollectHandler : IActionHandler
/// </summary>
public static readonly string[] PickUpActions =
[
"枫原万叶-长E attack(0.08),keydown(E),wait(0.8),keyup(E),attack(0.5)",
"枫原万叶-短E attack(0.08),keydown(E),wait(0.47),keyup(E),attack(0.5)",
"枫原万叶-长E keydown(E),wait(0.7),keyup(E),attack(0.2),wait(0.5)",
"枫原万叶-短E e,attack(0.15)",
"琴-短E wait(0.1),keydown(E),wait(0.4),moveby(1000,0),wait(0.2),moveby(1000,0),wait(0.2),moveby(1000,0),wait(0.2),moveby(1000,-3500),wait(1.8),keyup(E),wait(0.3),click(middle)",
"琴-长E wait(0.1),click(middle),keydown(E),click(middle),wait(0.4),moveby(500,0),wait(0.1),moveby(500,0),wait(0.1)," +
"moveby(500,0),wait(0.1),moveby(500,0),wait(0.1),moveby(500,0),wait(0.1),moveby(500,0),wait(0.1),moveby(500,0),wait(0.1)," +
@@ -37,14 +37,6 @@ namespace BetterGenshinImpact.GameTask.AutoPick
[ObservableProperty]
private string _ocrEngine = PickOcrEngineEnum.Paddle.ToString();
/// <summary>
/// 拾取内容识别方式
/// - Ocr
/// - Model
/// </summary>
[ObservableProperty]
private string _itemRecognitionMode = PickItemRecognitionModeEnum.Ocr.ToString();
/// <summary>
/// 急速模式
/// 无视文字识别结果,直接拾取
@@ -1,6 +1,5 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
@@ -9,8 +8,6 @@ using BetterGenshinImpact.GameTask.AutoPick.Assets;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.View.Windows;
using Compunet.YoloSharp.Data;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
@@ -22,7 +19,6 @@ using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading;
using BetterGenshinImpact.GameTask.Model.Area;
using Compunet.YoloSharp;
namespace BetterGenshinImpact.GameTask.AutoPick;
@@ -161,12 +157,6 @@ public partial class AutoPickTrigger : ITaskTrigger
/// </summary>
private int _prevClickFrameIndex = -1;
private static readonly Lazy<BgiYoloPredictor> PickClassifierLazy = new(() =>
App.ServiceProvider.GetRequiredService<BgiOnnxFactory>().CreateYoloPredictor(BgiOnnxModel.BgiPickClassify));
private bool _loggedPickModelMissing;
//private int _fastModePickCount = 0;
public void OnCapture(CaptureContent content)
@@ -281,16 +271,53 @@ public partial class AutoPickTrigger : ITaskTrigger
return;
}
var text = RecognizePickItem(content, foundRectArea, textRect, config);
string text;
if (config.OcrEngine == nameof(PickOcrEngineEnum.Yap))
{
var textMat = new Mat(content.CaptureRectArea.CacheGreyMat, textRect);
text = TextInferenceFactory.Pick.Value.Inference(textMat);
}
else
{
using var textMat = new Mat(content.CaptureRectArea.SrcMat, textRect);
var boundingRect = TextRectExtractor.GetTextBoundingRect(textMat);
// var boundingRect = new Rect(); // 不使用自己写的文字区域提取
// 如果找到有效区域
if (boundingRect.X < 20 && boundingRect.Width > 5 && boundingRect.Height > 5)
{
// 截取只包含文字的区域
using var textOnlyMat = new Mat(textMat, new Rect(0, 0,
boundingRect.Right + 5 < textMat.Width ? boundingRect.Right + 5 : textMat.Width, textMat.Height));
text = OcrFactory.Paddle.OcrWithoutDetector(textOnlyMat);
speedTimer.Record("识别");
// if (RuntimeHelper.IsDebug)
// {
// // 如果不等于正确文字,则保存图片
// if (text != "烹饪")
// {
// var path = Global.Absolute("log/pick");
// Directory.CreateDirectory(path);
// var str = $"{DateTime.Now:yyyyMMddHHmmssfff}";
// // textMat.SaveImage(Path.Combine(path, $"pick_ocr_ori_{str}.png"));
// // 画上 boundingRect
// Cv2.Rectangle(textMat, boundingRect, new Scalar(0, 0, 255), 1);
// textMat.SaveImage(Path.Combine(path, $"pick_ocr_rect_{str}.png"));
// bin.SaveImage(Path.Combine(path, $"bin_{str}.png"));
// }
// }
}
else
{
Debug.WriteLine("-- 无法识别到有效文字区域,尝试直接OCR DET");
text = OcrFactory.Paddle.Ocr(textMat);
}
}
speedTimer.Record("文字识别");
if (!string.IsNullOrEmpty(text))
{
// 处理OCR识别结果,清理无效字符并确保引号配对
if (config.ItemRecognitionMode != nameof(PickItemRecognitionModeEnum.Classify))
{
text = ProcessOcrText(text);
}
text = ProcessOcrText(text);
if (DoNotPick(text))
{
@@ -343,64 +370,6 @@ public partial class AutoPickTrigger : ITaskTrigger
speedTimer.DebugPrint();
}
private string RecognizePickItem(CaptureContent content, Region foundRectArea, Rect textRect, AutoPickConfig config)
{
if (config.ItemRecognitionMode == nameof(PickItemRecognitionModeEnum.Classify))
{
return RecognizePickItemByClassify(content.CaptureRectArea, foundRectArea);
}
else
{
return RecognizePickItemByOcr(content, textRect, config);
}
}
private string RecognizePickItemByOcr(CaptureContent content, Rect textRect, AutoPickConfig config)
{
if (config.OcrEngine == nameof(PickOcrEngineEnum.Yap))
{
using var greyTextMat = new Mat(content.CaptureRectArea.CacheGreyMat, textRect);
return TextInferenceFactory.Pick.Value.Inference(greyTextMat);
}
else
{
using var textMat = new Mat(content.CaptureRectArea.SrcMat, textRect);
var boundingRect = TextRectExtractor.GetTextBoundingRect(textMat);
// var boundingRect = new Rect(); // 不使用自己写的文字区域提取
// 如果找到有效区域
if (boundingRect.X < 20 && boundingRect.Width > 5 && boundingRect.Height > 5)
{
// 截取只包含文字的区域
using var textOnlyMat = new Mat(textMat, new Rect(0, 0,
boundingRect.Right + 5 < textMat.Width ? boundingRect.Right + 5 : textMat.Width, textMat.Height));
return OcrFactory.Paddle.OcrWithoutDetector(textOnlyMat);
}
Debug.WriteLine("-- 无法识别到有效文字区域,尝试直接OCR DET");
return OcrFactory.Paddle.Ocr(textMat);
}
}
private string RecognizePickItemByClassify(ImageRegion captureRectArea, Region foundRectArea)
{
using var itemRegion = captureRectArea.DeriveCrop(GetPickModelRect(foundRectArea));
var result = PickClassifierLazy.Value.Predictor.Classify(itemRegion.CacheImage);
var topClass = result.GetTopClass();
// Debug.WriteLine($"AutoPickTrigger: 拾取,{topClass.Name.Name} {topClass.Confidence:F2}");
if (topClass.Confidence <= 0.75)
{
return string.Empty;
}
// itemRegion.SrcMat.SaveImage(Global.Absolute("log\\pick.png"));
return topClass.Name.Name;
}
private static Rect GetPickModelRect(Region foundRectArea)
{
return new Rect(foundRectArea.Right + 20, foundRectArea.Y - 16, 64, 64);
}
private bool DoNotPick(string text)
{
// 唯一一个动态拾取项,特殊处理,不拾取
@@ -436,7 +405,7 @@ public partial class AutoPickTrigger : ITaskTrigger
{
return true;
}
if (text.Contains("月谕圣牌"))
{
return true;
@@ -1,7 +0,0 @@
namespace BetterGenshinImpact.GameTask.AutoPick;
public enum PickItemRecognitionModeEnum
{
Ocr,
Classify
}
@@ -8,7 +8,6 @@ using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.View.Drawable;
using Compunet.YoloSharp;
using Microsoft.Extensions.DependencyInjection;
@@ -16,7 +15,6 @@ using Microsoft.Extensions.Logging;
using BetterGenshinImpact.GameTask.Model.Area;
using OpenCvSharp;
using Vanara.PInvoke;
using static BetterGenshinImpact.Core.Simulator.Extensions.SimulateKeyHelper;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.Common.Job;
@@ -32,8 +30,8 @@ public class LinneaMiningTask
private const double BaseClusterDistance = 400;
// 聚类面积基准值(1920宽度下的标准矿石面积)
private const double BaseClusterArea = 1800;
// 对准判定:使用目标矿物框四周扩张像素(基于宽度缩放)
private const double BaseAlignmentExpansion = 3;
// 对准判定阈值(基于宽度缩放)
private const double BaseArrivalThreshold = 50;
// 屏幕边缘忽略区域宽度(基于宽度缩放)
private const double BaseEdgeIgnore = 200;
// 瞄准模式X轴灵敏度补偿系数
@@ -48,10 +46,8 @@ public class LinneaMiningTask
private const int LeftTurnStep = -250;
// 内层最大检测次数
private const int MaxInnerRetry = 7;
// 默认射箭次数
public const int DefaultMineCount = 1;
// 默认大循环次数
public const int DefaultScanRounds = 1;
private const int DefaultScanRounds = 5;
// 元素视野刷新间隔
private const int ElementSightRefreshMs = 3000;
@@ -62,24 +58,22 @@ public class LinneaMiningTask
private readonly double _widthScale = TaskContext.Instance().SystemInfo.CaptureAreaRect.Width / 1920.0;
private readonly double _heightScale = TaskContext.Instance().SystemInfo.CaptureAreaRect.Height / 1080.0;
private readonly double ClusterDistanceThreshold;
private readonly double ArrivalThreshold;
private readonly double EdgeIgnore;
private readonly double AlignmentExpansion;
private readonly int _scanRounds;
private readonly int _mineCount;
private readonly bool _preferRight;
private int _debugIndex;
public LinneaMiningTask(int scanRounds = DefaultScanRounds, int mineCount = DefaultMineCount)
public LinneaMiningTask(int scanRounds = DefaultScanRounds, int mineCount = 1)
{
_scanRounds = scanRounds;
_mineCount = mineCount;
_preferRight = scanRounds > 1;
_predictor = App.ServiceProvider.GetRequiredService<BgiOnnxFactory>()
.CreateYoloPredictor(BgiOnnxModel.BgiMine);
ClusterDistanceThreshold = BaseClusterDistance * _widthScale;
ArrivalThreshold = BaseArrivalThreshold * _widthScale;
EdgeIgnore = BaseEdgeIgnore * _widthScale;
AlignmentExpansion = BaseAlignmentExpansion * _widthScale;
}
public async Task Start(CancellationToken ct)
@@ -89,7 +83,7 @@ public class LinneaMiningTask
{
// Logger.LogInformation("开始寻矿");
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
aimingModeEntered = true;
await Delay(400, ct);
@@ -145,7 +139,7 @@ public class LinneaMiningTask
await Delay(800, ct);
}
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
aimingModeEntered = false;
}
catch (OperationCanceledException)
@@ -160,7 +154,7 @@ public class LinneaMiningTask
{
if (aimingModeEntered)
{
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
}
Simulation.SendInput.Mouse.MiddleButtonUp();
@@ -190,16 +184,18 @@ public class LinneaMiningTask
var offsetX = cluster.TargetX - centerX;
var offsetY = cluster.TargetY - centerY;
var avgArea = cluster.Rects.Average(r => (double)r.Width * r.Height);
var refArea = BaseClusterArea * _widthScale * _widthScale;
var dynamicThreshold = ArrivalThreshold * Math.Max(1.0, Math.Sqrt(avgArea / refArea));
var isLast = retry == MaxInnerRetry - 1;
var isAligned = Math.Abs(offsetX) <= (cluster.TargetWidth + AlignmentExpansion * 2) / 2
&& Math.Abs(offsetY) <= (cluster.TargetHeight + AlignmentExpansion * 2) / 2;
var isAligned = Math.Abs(offsetX) <= dynamicThreshold / 2 && Math.Abs(offsetY) <= dynamicThreshold / 2;
// 前面所有循环都检测成功时,以不计入总次数的方式兜底射击一次
if (isAligned || (isLast && hadResult))
{
Simulation.SendInput.Mouse.MiddleButtonUp();
await Delay(300, ct);
Logger.LogInformation("开始挖矿");
// Logger.LogInformation("开始挖矿");
await Mine(ct, totalDy < 0);
return (true, isAligned, 0, 0);
}
@@ -292,17 +288,20 @@ public class LinneaMiningTask
var clusters = ClusterMinerals(oreBoxes);
// 画聚类目标矿物框
var expansion = (int)AlignmentExpansion;
var clusterDrawList = clusters.Select(c =>
// 画聚类中心标记框
var refArea = BaseClusterArea * _widthScale * _widthScale;
var clusterDrawList = new List<RectDrawable>();
foreach (var cluster in clusters)
{
var mark = new Rect((int)(c.TargetX - c.TargetWidth / 2) - expansion, (int)(c.TargetY - c.TargetHeight / 2) - expansion,
(int)c.TargetWidth + expansion * 2, (int)c.TargetHeight + expansion * 2);
return ra.ToRectDrawable(mark,
$"({(int)c.TargetX},{(int)c.TargetY})",
var avgArea = cluster.Rects.Average(r => (double)r.Width * r.Height);
var markerSize = ArrivalThreshold * Math.Max(1.0, Math.Sqrt(avgArea / refArea));
var half = (int)markerSize / 2;
var mark = new Rect((int)cluster.TargetX - half, (int)cluster.TargetY - half, (int)markerSize, (int)markerSize);
clusterDrawList.Add(ra.ToRectDrawable(mark,
$"({(int)cluster.TargetX},{(int)cluster.TargetY})",
new Pen(Color.DodgerBlue, 2)
);
}).ToList();
));
}
VisionContext.Instance().DrawContent.PutOrRemoveRectList("MiningCluster", clusterDrawList);
// 忽略屏幕边缘聚类,仅当中间区域存在聚类时生效
@@ -361,7 +360,7 @@ public class LinneaMiningTask
}
}
clusters.Add(new MineralCluster(rect, AreaRatioThreshold, _preferRight));
clusters.Add(new MineralCluster(rect, AreaRatioThreshold));
}
return clusters;
@@ -378,19 +377,15 @@ public class MineralCluster
public double CenterY { get; private set; }
public double TargetX { get; private set; }
public double TargetY { get; private set; }
public double TargetWidth { get; private set; }
public double TargetHeight { get; private set; }
public MineralCluster(Rect firstRect, double areaRatioThreshold = 5, bool preferRight = true)
public MineralCluster(Rect firstRect, double areaRatioThreshold = 5)
{
AreaRatioThreshold = areaRatioThreshold;
PreferRight = preferRight;
Rects.Add(firstRect);
RecalculateCenter();
}
private readonly double AreaRatioThreshold;
private readonly bool PreferRight;
public bool TryAddRect(Rect rect)
{
@@ -407,28 +402,16 @@ public class MineralCluster
CenterX = Rects.Average(r => r.X + r.Width / 2.0);
CenterY = Rects.Average(r => r.Y + r.Height / 2.0);
var sorted = Rects
// 按距离质心排序,取最近2个中靠左的
var candidates = Rects
.Select(r => (cx: r.X + r.Width / 2.0, cy: r.Y + r.Height / 2.0,
dist: Math.Pow(r.X + r.Width / 2.0 - CenterX, 2) + Math.Pow(r.Y + r.Height / 2.0 - CenterY, 2),
w: (double)r.Width, h: (double)r.Height))
dist: Math.Pow(r.X + r.Width / 2.0 - CenterX, 2) + Math.Pow(r.Y + r.Height / 2.0 - CenterY, 2)))
.OrderBy(t => t.dist)
.ToList();
.Take(2)
.OrderBy(t => t.cx)
.First();
(double cx, double cy, double dist, double w, double h) target;
if (PreferRight && sorted.Count >= 2)
{
// 多轮旋转时:取最近2个中靠右的,对冲左转偏移
target = sorted.Take(2).OrderByDescending(t => t.cx).First();
}
else
{
// 单轮时:直接选最近的
target = sorted.First();
}
TargetX = target.cx;
TargetY = target.cy;
TargetWidth = target.w;
TargetHeight = target.h;
TargetX = candidates.cx;
TargetY = candidates.cy;
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -89,28 +89,6 @@ public static class NewRetry
return false;
}
/// <summary>
/// 重试执行异步 action,直到返回 true 或达到最大重试次数。
/// </summary>
/// <param name="action">判断条件(异步)</param>
/// <param name="ct">取消令牌</param>
/// <param name="retryTimes">最大重试次数</param>
/// <param name="delayMs">每次重试间隔(毫秒)</param>
/// <returns>是否成功</returns>
public static async Task<bool> WaitForAction(Func<Task<bool>> action, CancellationToken ct, int retryTimes = 10, int delayMs = 1000)
{
for (var i = 0; i < retryTimes; i++)
{
await TaskControl.Delay(delayMs, ct);
if (await action())
{
return true;
}
}
return false;
}
/// <summary>
/// 重试直到某个元素出现,可执行键盘或鼠标操作。
/// </summary>
@@ -1,4 +1,4 @@
using System;
using System;
using System.Drawing;
using System.Threading;
using System.Threading.Tasks;
@@ -9,7 +9,6 @@ using Fischless.GameCapture;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using Vanara.PInvoke;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.Common;
@@ -185,90 +184,6 @@ public class TaskControl
}
}
/// <summary>
/// 模拟长按指定动作。使用 try/finally 块确保在任务被取消或发生异常时,按键也能安全释放,防止卡键。
/// </summary>
/// <param name="action">需要模拟的游戏动作(如元素战技、普通攻击等)</param>
/// <param name="holdMs">长按持续的时间(毫秒)</param>
/// <param name="ct">用于监控任务取消的取消令牌</param>
public static async Task SimulateHoldActionAsync(GIActions action, int holdMs, CancellationToken ct)
{
try
{
Simulation.SendInput.SimulateAction(action, KeyType.KeyDown);
await Delay(holdMs, ct);
}
finally
{
Simulation.SendInput.SimulateAction(action, KeyType.KeyUp);
}
}
/// <summary>
/// 模拟长按元素战技(如万叶长E)。包含释放前摇、长按以及释放后的缓冲延时。
/// </summary>
/// <param name="holdMs">元素战技按住的时间(毫秒)</param>
/// <param name="ct">用于监控任务取消的取消令牌</param>
/// <param name="releaseLeftMouseBefore">是否在按下元素战技前先松开鼠标左键,避免输入冲突,默认 true</param>
/// <param name="releaseLeftMouseDelayMs">松开鼠标左键后的缓冲时间(毫秒),默认 10ms</param>
/// <param name="postKeyUpDelayMs">元素战技释放后的缓冲时间(毫秒),默认 50ms</param>
public static async Task SimulateHoldElementalSkillAsync(
int holdMs,
CancellationToken ct,
bool releaseLeftMouseBefore = true,
int releaseLeftMouseDelayMs = 10,
int postKeyUpDelayMs = 50)
{
if (releaseLeftMouseBefore)
{
Simulation.SendInput.Mouse.LeftButtonUp();
await Delay(releaseLeftMouseDelayMs, ct);
}
await SimulateHoldActionAsync(GIActions.ElementalSkill, holdMs, ct);
await Delay(postKeyUpDelayMs, ct);
}
/// <summary>
/// 模拟鼠标左键连续点击循环(如万叶长E后的下落攻击)。双层 try/finally 设计以确保无论在循环的哪个阶段发生取消或异常,鼠标左键都会被强制释放。
/// </summary>
/// <param name="repeatCount">需要循环点击的次数</param>
/// <param name="ct">用于监控任务取消的取消令牌</param>
/// <param name="preUpDelayMs">每次点击前,预先抬起左键后的缓冲延时(毫秒),默认 10ms</param>
/// <param name="downHoldMs">鼠标左键按下的保持时间(毫秒),默认 35ms</param>
/// <param name="postUpDelayMs">每次点击完成后的等待时间(毫秒),默认 50ms</param>
public static async Task SimulateMouseLeftClickLoopAsync(
int repeatCount,
CancellationToken ct,
int preUpDelayMs = 10,
int downHoldMs = 35,
int postUpDelayMs = 50)
{
try
{
for (var i = 0; i < repeatCount; i++)
{
Simulation.SendInput.Mouse.LeftButtonUp();
await Delay(preUpDelayMs, ct);
Simulation.SendInput.Mouse.LeftButtonDown();
try
{
await Delay(downHoldMs, ct);
}
finally
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
await Delay(postUpDelayMs, ct);
}
}
finally
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
}
public static Mat CaptureGameImage(IGameCapture? gameCapture)
{
var image = gameCapture?.Capture();
@@ -310,4 +225,4 @@ public class TaskControl
var content = new CaptureContent(image, 0, 0);
return content.CaptureRectArea;
}
}
}
@@ -30,7 +30,7 @@ public static class GenshinHdrRegistryHelper
public static bool TryDisableHdr(out IReadOnlyList<string> deletedFullKeyPaths)
{
var updatedPaths = new List<string>();
var deletedPaths = new List<string>();
foreach (var parentKeyPath in HdrRegistryParentKeyPaths)
{
try
@@ -41,34 +41,21 @@ public static class GenshinHdrRegistryHelper
continue;
}
var value = key.GetValue(HdrRegistryEntryName);
if (value == null)
if (key.GetValue(HdrRegistryEntryName) == null)
{
continue;
}
var isHdrEnabled = value switch
{
int intValue => intValue == 1,
long longValue => longValue == 1L,
_ => false
};
if (!isHdrEnabled)
{
continue;
}
key.SetValue(HdrRegistryEntryName, 0, RegistryValueKind.DWord);
updatedPaths.Add($@"HKEY_CURRENT_USER\{parentKeyPath}\{HdrRegistryEntryName}");
key.DeleteValue(HdrRegistryEntryName, throwOnMissingValue: false);
deletedPaths.Add($@"HKEY_CURRENT_USER\{parentKeyPath}\{HdrRegistryEntryName}");
}
catch
{
// 忽略写入失败,避免影响启动流程
// 忽略删除失败,避免影响启动流程
}
}
deletedFullKeyPaths = updatedPaths.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
deletedFullKeyPaths = deletedPaths.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
return deletedFullKeyPaths.Count > 0;
}
}
@@ -63,15 +63,15 @@ public class GameCaptureRegion(Mat mat, int initX, int initY, Region? owner = nu
/// <returns></returns>
public ImageRegion DeriveTo1080P()
{
if (Width <= 1920)
if (Width <= 1920 || Height <= 1080)
{
return this;
}
var scale = Width / 1920d;
var scale = SystemInfo.MinZoomOut1080PRatio(Width, Height);
var newMat = new Mat();
Cv2.Resize(SrcMat, newMat, new Size(1920, Height / scale));
Cv2.Resize(SrcMat, newMat, new Size(Width / scale, Height / scale));
Dispose();
return new ImageRegion(newMat, 0, 0, this, new ScaleConverter(scale));
// return new ImageRegion(newMat, 0, 0, this, new TranslationConverter(0, 0));
@@ -81,12 +81,12 @@ namespace BetterGenshinImpact.GameTask.Model
}
// 0.28 改动,素材缩放比例不可以超过 1,也就是图像识别时分辨率大于 1920x1080 的情况下直接进行缩放
if (GameScreenSize.Width < 1920)
if (GameScreenSize.Width < 1920 || GameScreenSize.Height < 1080)
{
ZoomOutMax1080PRatio = GameScreenSize.Width / 1920d;
ZoomOutMax1080PRatio = MinZoomOut1080PRatio(GameScreenSize.Width, GameScreenSize.Height);
AssetScale = ZoomOutMax1080PRatio;
}
ScaleTo1080PRatio = GameScreenSize.Width / 1920d; // 1080P 为标准
ScaleTo1080PRatio = MinZoomOut1080PRatio(GameScreenSize.Width, GameScreenSize.Height); // 1080P 为标准
CaptureAreaRect = SystemControl.GetCaptureRect(hWnd);
if (CaptureAreaRect.Width > 1920)
@@ -99,5 +99,10 @@ namespace BetterGenshinImpact.GameTask.Model
ScaleMax1080PCaptureRect = new Rect(CaptureAreaRect.X, CaptureAreaRect.Y, CaptureAreaRect.Width, CaptureAreaRect.Height);
}
}
public static double MinZoomOut1080PRatio(double width, double height)
{
return Math.Min(width / 1920d, height / 1080d);
}
}
}
@@ -190,7 +190,6 @@ public class TaskRunner
TaskTriggerDispatcher.Instance().SetTriggers(GameTaskManager.LoadInitialTriggers());
VisionContext.Instance().DrawContent.ClearAll();
HtmlMaskWindow.CloseAll();
}
}
+3 -5
View File
@@ -9,9 +9,7 @@
WindowStartupLocation="Manual"
ShowInTaskbar="False"
Topmost="True">
<Border x:Name="ClickThroughBorder" Background="Transparent">
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
</Border>
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
</Window>
+13 -148
View File
@@ -17,7 +17,7 @@ using Microsoft.Web.WebView2.Core;
namespace BetterGenshinImpact.View;
/// <summary>
/// HTML遮罩窗口
/// HTML遮罩窗口 - 仅用于显示,不可交互(点击穿透)
/// </summary>
public partial class HtmlMaskWindow : Window
{
@@ -29,21 +29,12 @@ public partial class HtmlMaskWindow : Window
private readonly string _webView2DataPath;
private readonly string _pageUrl;
private bool _navigationCompleted;
private bool _styleCaptured;
private int _originalStyle;
private volatile bool _isClickThrough = true;
private readonly System.Windows.Media.SolidColorBrush _backgroundBrush = new();
/// <summary>
/// 窗口唯一标识
/// </summary>
public string MaskId => _id;
/// <summary>
/// 当前是否处于点击穿透模式
/// </summary>
public bool IsClickThrough => _isClickThrough;
private HtmlMaskWindow(string url, string? id, string workDir)
{
_id = id ?? Guid.NewGuid().ToString("N");
@@ -51,7 +42,6 @@ public partial class HtmlMaskWindow : Window
_webView2DataPath = Path.Combine(workDir, "WebView2Data");
_pageUrl = url;
InitializeComponent();
ClickThroughBorder.Background = _backgroundBrush;
Loaded += OnLoaded;
InitializeAsync(url);
}
@@ -166,47 +156,6 @@ public partial class HtmlMaskWindow : Window
return _windows.ContainsKey(id);
}
/// <summary>
/// 获取窗口实例,不存在则抛出异常
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>窗口实例</returns>
private static HtmlMaskWindow GetWindowOrThrow(string windowId)
{
if (_windows.TryGetValue(windowId, out var window))
return window;
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
}
/// <summary>
/// 设置指定窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public static void SetClickThrough(string windowId, bool enabled)
{
GetWindowOrThrow(windowId).SetClickThroughMode(enabled);
}
/// <summary>
/// 获取指定窗口的点击穿透状态
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <returns>点击穿透状态</returns>
public static bool GetClickThrough(string windowId)
{
return GetWindowOrThrow(windowId).IsClickThrough;
}
/// <summary>
/// 原子切换指定窗口的点击穿透模式
/// </summary>
/// <param name="windowId">窗口ID</param>
public static void ToggleClickThrough(string windowId)
{
GetWindowOrThrow(windowId).ToggleClickThroughCore();
}
/// <summary>
/// 通知窗口刷新待推送的消息
/// </summary>
@@ -215,24 +164,13 @@ public partial class HtmlMaskWindow : Window
if (!_windows.TryGetValue(windowId, out var window)) return;
window.Dispatcher.BeginInvoke(() =>
{
try
// 页面还没加载完,消息留在队列中由 NavigationCompleted 统一推送
if (!window._navigationCompleted) return;
if (window.WebView.CoreWebView2 == null) return;
HtmlMask.FlushPendingMessages(windowId, json =>
{
// 页面还没加载完,消息留在队列中由 NavigationCompleted 统一推送
if (!window._navigationCompleted) return;
if (window.WebView.CoreWebView2 == null) return;
HtmlMask.FlushPendingMessages(windowId, json =>
{
window.WebView.CoreWebView2.PostWebMessageAsString(json);
});
}
catch (ObjectDisposedException)
{
// WebView 已被释放,忽略此消息推送
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩窗口消息推送异常");
}
window.WebView.CoreWebView2.PostWebMessageAsString(json);
});
});
}
@@ -240,7 +178,7 @@ public partial class HtmlMaskWindow : Window
private void OnLoaded(object sender, RoutedEventArgs e)
{
SetClickThrough(true);
SetClickThrough();
UpdatePosition();
}
@@ -449,87 +387,14 @@ public partial class HtmlMaskWindow : Window
}
/// <summary>
/// 设置点击穿透模式
/// 设置点击穿透
/// </summary>
/// <param name="enabled">true=点击穿透,false=可交互</param>
private void SetClickThrough(bool enabled)
private void SetClickThrough()
{
var hwnd = new WindowInteropHelper(this).Handle;
if (hwnd == IntPtr.Zero) return;
if (!_styleCaptured)
{
_originalStyle = (int)GetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE);
_styleCaptured = true;
}
int newStyle = enabled
? (_originalStyle | (int)User32.WindowStylesEx.WS_EX_TRANSPARENT | (int)User32.WindowStylesEx.WS_EX_LAYERED)
: _originalStyle;
User32.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE, (IntPtr)newStyle);
_isClickThrough = enabled;
SetBackgroundOpacity(!enabled);
if (!enabled)
{
// 禁用穿透:激活遮罩窗口,确保获得键盘和鼠标焦点
try
{
User32.SetForegroundWindow(hwnd);
User32.BringWindowToTop(hwnd);
Dispatcher.Invoke(() => Activate());
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩窗口激活失败");
}
}
else
{
// 开启穿透:将焦点还给游戏窗口
try
{
var gameHandle = TaskContext.Instance().GameHandle;
if (gameHandle != IntPtr.Zero)
{
SystemControl.FocusWindow(gameHandle);
}
}
catch (Exception ex)
{
TaskControl.Logger.LogDebug(ex, "HTML遮罩恢复游戏焦点失败");
}
}
}
/// <summary>
/// 设置背景透明度
/// </summary>
/// <param name="isInteractive">是否处于交互模式</param>
private void SetBackgroundOpacity(bool isInteractive)
{
_backgroundBrush.Color = isInteractive
? System.Windows.Media.Color.FromArgb(1, 0, 0, 0)
: System.Windows.Media.Color.FromArgb(0, 0, 0, 0);
}
/// <summary>
/// 设置点击穿透模式
/// </summary>
/// <param name="enabled">true=点击穿透,false=可交互</param>
public void SetClickThroughMode(bool enabled)
{
Dispatcher.Invoke(() => SetClickThrough(enabled));
}
/// <summary>
/// 切换点击穿透模式
/// </summary>
private void ToggleClickThroughCore()
{
Dispatcher.Invoke(() => SetClickThrough(!_isClickThrough));
var style = (int)GetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE);
User32.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE,
(IntPtr)(style | (int)User32.WindowStylesEx.WS_EX_TRANSPARENT));
}
/// <summary>
@@ -80,33 +80,6 @@
Margin="0,0,8,0"
IsChecked="{Binding Config.AutoPickConfig.FastModeEnabled, 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="识别方式"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="OCR 通过文字识别拾取内容;Classify 使用物品分类模型识别"
TextWrapping="Wrap" />
<ComboBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Width="100"
Margin="0,0,8,0"
ItemsSource="{Binding PickItemRecognitionModeNames}"
SelectedItem="{Binding Config.AutoPickConfig.ItemRecognitionMode, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -229,7 +229,7 @@ public partial class OneDragonFlowViewModel : ViewModel
[ObservableProperty] private List<string> _domainNameList = ["", ..MapLazyAssets.Instance.DomainNameList];
[ObservableProperty] private List<string> _completionActionList = ["无", "关闭游戏", "关闭软件", "关闭游戏和软件", "关机"];
[ObservableProperty] private List<string> _completionActionList = ["无", "关闭游戏", "关闭游戏和软件", "关机"];
[ObservableProperty] private List<string> _sundayEverySelectedValueList = ["","1", "2", "3"];
@@ -650,9 +650,6 @@ public partial class OneDragonFlowViewModel : ViewModel
case "关闭游戏":
SystemControl.CloseGame();
break;
case "关闭软件":
Application.Current.Dispatcher.Invoke(() => { Application.Current.Shutdown(); });
break;
case "关闭游戏和软件":
SystemControl.CloseGame();
Application.Current.Dispatcher.Invoke(() => { Application.Current.Shutdown(); });
@@ -823,4 +820,4 @@ public partial class OneDragonFlowViewModel : ViewModel
Toast.Error("重命名配置时失败");
}
}
}
}
@@ -30,8 +30,6 @@ public partial class TriggerSettingsPageViewModel : ViewModel
[ObservableProperty] private string[] _selectChatOptionTypeNames = [SelectChatOptionTypes.UseMouse, SelectChatOptionTypes.UseInteractionKey];
[ObservableProperty] private string[] _pickItemRecognitionModeNames = [PickItemRecognitionModeEnum.Ocr.ToString(), PickItemRecognitionModeEnum.Classify.ToString()];
[ObservableProperty] private string[] _pickOcrEngineNames = [PickOcrEngineEnum.Paddle.ToString(), PickOcrEngineEnum.Yap.ToString()];
[ObservableProperty] private List<string> _pickButtonNames;
@@ -22,7 +22,7 @@
<PackageReference Include="Vanara.Windows.Extensions" Version="4.1.3" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
</ItemGroup>
</Project>