Compare commits

...
Author SHA1 Message Date
huiyadanli c8fba493c1 Update version to 0.61.0 2026-05-23 19:49:45 +00:00
躁动的氨气andClaude Opus 4.7 96f523d4b8 fix: 修复复制配置组问题与加载器依赖解析问题 (#3139)
Co-authored-by: Claude Opus 4.7 <[email protected]>
2026-05-24 03:47:02 +08:00
huiyadanli f8e231c235 Update version to 0.60.3-alpha.2 2026-05-21 17:47:22 +00:00
辉鸭蛋 58bceffe0e 6.6角色 2026-05-22 01:18:40 +08:00
郝凯阳andhaokaiyang 4c6232fdb3 auto tcg: update character card config to v6.6 (#3132)
Co-authored-by: haokaiyang <[email protected]>
2026-05-21 14:31:16 +08:00
Jamis 1eb483b639 Update tp.json with new version and domains (#3128) 2026-05-20 23:29:32 +08:00
huiyadanli 796bda0af3 Update version to 0.60.3-alpha.1 2026-05-20 03:17:16 +00:00
辉鸭蛋 6d8bbc18fc Update BetterGI.Assets.Model package version 2026-05-20 11:13:39 +08:00
cookie981 753c595625 fix:一键宏停止时立即松开所有按键 (#3126) 2026-05-17 23:10:24 +08:00
DarkFlameMaster 88bd60ab93 feat(BvLocator): 使重试回调支持异步方法,添加设置超时和重试间隔的方法 (#3117)
* feat(BvLocator): 使重试回调支持异步方法

* feat(BvLocator): 支持自定义超时和重试间隔

新增WithTimeout和WithRetryInterval链式调用方法

* 可能是bug?

* fix
2026-05-12 22:03:35 +08:00
DarkFlameMaster 36669b89ef feat: 增加 HTML 遮罩窗口点击穿透模式切换功能 (#3100)
* 增加html遮罩点击穿透模式的切换

* fix:修两个小问题

* 切换穿透状态时自动切换焦点

* feat:停止脚本自动关闭html遮罩,并修复衍生问题
2026-05-12 01:43:34 +08:00
ema 70b3f6dd99 修复出错啦窗口显示版本号错误问题 (#3116) 2026-05-12 01:43:03 +08:00
DarkFlameMaster 6996356251 feat(脚本引擎): 提供对 战斗策略 目录的访问 (#3111)
* feat(脚本引擎): 提供对 战斗策略 目录的访问

* 移除目录不存在时创建的逻辑

* feat: 新增CreateDirectory方法用于创建指定路径的目录
2026-05-11 10:27:28 +08:00
躁动的氨气 359bdb899e feat: 单轮旋转直接取最近目标 (#3114) 2026-05-11 10:12:01 +08:00
泠色 ec39fc980e 想打完每日再亲自过一下剧情。。。。 (#3115) 2026-05-11 10:11:40 +08:00
火山andcoderabbitai[bot] 8d502d76c1 [优化] 重构万叶战后长E拾取逻辑:提取公共输入时序、增强防卡键保护及OCR释放校验 (#3108)
* 修改万叶的模拟战技与普攻输入操作

将高层的技能释放 / 普通攻击函数调用,替换为明确的模拟输入时序流程,以提升运行稳定性。
改动内容:
AutoFightTask(自动战斗任务)
元素战技采用鼠标 / 按键按下 + 松开时序模拟(长按后松开);将原有三次普通攻击调用,改为6 次鼠标左键按下 / 松开循环,并优化了间隔延时。
AutoLeyLineOutcropTask(自动地脉之花任务)
对万叶长按元素战技(长 E)做同款重构:模拟按键按下 / 松开动作,新增对元素战技冷却区域的视觉 / OCR 识别校验以确认技能已释放;截取冷却区域数据并调用技能后置回调函数,同时沿用 6 次普攻循环;补充了所需的资源引用命名空间。
PickUpCollectHandler(拾取收集处理器)
将长 E 预设等待时长从 1.0 秒 调整为 0.8 秒。
改动说明
本次优化调校了各操作时序,并新增视觉校验机制,减少拾取、技能连招过程中技能 / 普攻输入失效、漏触发的问题。

* Update BetterGenshinImpact/GameTask/AutoFight/AutoFightTask.cs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update BetterGenshinImpact/GameTask/AutoLeyLineOutcrop/AutoLeyLineOutcropTask.cs

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* 重构万叶战后长E拾取逻辑:提取公共输入时序、增强防卡键保护及OCR释放校验

- 提取公共输入时序方法 ( TaskControl.cs )
- 新增 SimulateHoldActionAsync 、 SimulateHoldElementalSkillAsync :封装了包含前摇处理、精准延时按压和后摇缓冲的长按逻辑。
- 新增 SimulateMouseLeftClickLoopAsync :封装了左键连续点击循环。
- 核心安全提升 :在上述所有涉及 KeyDown/LeftButtonDown 的方法中,全面引入了双层 try/finally 块,确保在任何异常或手动停止任务的情况下,必然触发 KeyUp/LeftButtonUp 。
- 重构自动战斗拾取 ( AutoFightTask.cs )
- 移除 picker.UseSkill(true) ,接入新的公共方法,将长 E 持续时间精准设定为 800ms 。
- 重构地脉拾取并增加状态双重校验 ( AutoLeyLineOutcropTask.cs )
- 接入公共方法,将长 E 持续时间设定为 1000ms 。
- 新增校验拦截 :在松开 E 键后,截取当前画面,通过 HSV过滤 + PaddleOCR 读取技能 CD 数字,结合 Bv.IsSkillReady 进行双重验证。若未读取到 CD 且图标依然高亮(技能未成功释放),则提前 return 跳过后续左键下落攻击动作,并 阻断 AfterUseSkill 的调用,避免污染 CD 池。

* Update TaskControl.cs

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-05-09 10:23:31 +08:00
huiyadanli 3519008bd2 Update version to 0.60.2-alpha.4 2026-05-07 17:19:34 +00:00
辉鸭蛋 649bc0fc66 修复Q技能分类的问题 2026-05-08 01:15:32 +08:00
DarkFlameMaster 4fbc74e7e0 feat(BvLocator): 为 JavaScript 添加动态参数重载方法 (#3106) 2026-05-07 14:30:51 +08:00
辉鸭蛋 847e4076d2 提交一些项目规则 2026-05-06 01:46:52 +08:00
辉鸭蛋 951a890ded 又修复了一个陈年老bug #3099 2026-05-06 01:02:08 +08:00
辉鸭蛋 ea13091320 fixed #3099 2026-05-06 00:47:12 +08:00
躁动的氨气 2e57a3aae9 feat: 莉奈娅挖矿配置优化 (#3102) 2026-05-06 00:41:09 +08:00
火山andcoderabbitai[bot] ff4ff78349 重置鼠标按键,发送 3 次普攻指令,确保枫原万叶下落拾取动作完整执行 (#3101)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-05-05 15:59:20 +08:00
辉鸭蛋 71ace72d9c Merge remote-tracking branch 'origin/main' 2026-05-05 15:54:34 +08:00
辉鸭蛋 e54e5e7af7 fix: update BetterGI.Assets.Map package version to 1.0.19 2026-05-05 15:54:27 +08:00
辉鸭蛋 17af6e01f8 自动战斗Q技能加入CD判断 2026-05-05 00:01:56 +08:00
辉鸭蛋 5e98ff724f 改名 2026-05-04 21:06:48 +08:00
辉鸭蛋 e2f84f7edd JS获取当前在小地图上的位置坐标 新增 matchingMethod 的传入 2026-05-04 20:47:49 +08:00
辉鸭蛋 de75d02104 fix: 修复禁用HDR时错误删除注册表项的问题
将删除注册表值改为修改值为0,避免HDR设置被完全移除导致游戏可能重新启用HDR
2026-05-03 16:40:03 +08:00
37 changed files with 1164 additions and 141 deletions

No files matched your search

-4
View File
@@ -31,10 +31,6 @@ github_actions_cache/
# Rider
.idea
.claude
CLAUDE.md
AGENTS.md
__pycache__/
+8 -2
View File
@@ -14,7 +14,8 @@
- 请尽量使用 Behaviors 库来实现交互,避免不符合 MVVM 规范的交互事件触发方式。
### 其他框架使用要求
请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
1. 请优先使用 Newtonsoft.Json 作为json序列化工具,但是如果这个模型已经被System.Text.Json序列化过了,那么就直接使用System.Text.Json反序列化。
2. 所有简单的对话框弹出需求优先使用 ThemedMessageBox 弹出。而不是 WPF 自带的 MessageBox。
## MVVM 架构规则
@@ -77,4 +78,9 @@
services.AddSingleton<IExampleService, ExampleService>();
```
最后,程序能够编译就认为成功,无需实际运行程序。
最后,程序能够编译就认为成功,无需实际运行程序。
编译指令参考,如果出现程序占用场景,直接放弃编译验证即可
```
dotnet build BetterGenshinImpact.sln -c Debug
```
+86
View File
@@ -0,0 +1,86 @@
本项目使用了 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.3</Version>
<Version>0.61.0</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -43,8 +43,8 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.22" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.23" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.15" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
@@ -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.0" />
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<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.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="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="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
+91 -14
View File
@@ -21,10 +21,12 @@ 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 Action<List<Region>>? RetryAction { get; set; }
public Func<List<Region>, Task>? RetryAction { get; set; }
public static int DefaultTimeout { get; set; } = 10000;
@@ -98,17 +100,21 @@ public class BvLocator
public async Task<List<Region>> WaitFor(int? timeout = null)
{
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
List<Region> results = [];
var retryRes = await NewRetry.WaitForAction(() =>
var retryRes = await NewRetry.WaitForAction(async () =>
{
results = FindAll();
var b = results.Count > 0;
RetryAction?.Invoke(results);
if (!b && RetryAction != null)
{
await RetryAction(results);
}
return b;
}, _cancellationToken, retryCount, DefaultRetryInterval);
}, _cancellationToken, retryCount, actualRetryInterval);
if (retryRes)
{
@@ -150,20 +156,21 @@ public class BvLocator
public async Task WaitForDisappear(int? timeout = null)
{
var actualTimeout = timeout ?? DefaultTimeout;
var retryCount = actualTimeout / DefaultRetryInterval;
var actualTimeout = timeout ?? _timeout ?? DefaultTimeout;
var actualRetryInterval = _retryInterval ?? DefaultRetryInterval;
var retryCount = Math.Max(1, actualTimeout / actualRetryInterval);
var retryRes = await NewRetry.WaitForAction(() =>
var retryRes = await NewRetry.WaitForAction(async () =>
{
var results = FindAll();
var b = results.Count == 0;
if (!b)
if (!b && RetryAction != null)
{
RetryAction?.Invoke(results);
await RetryAction(results);
}
return b;
}, _cancellationToken, retryCount, DefaultRetryInterval);
}, _cancellationToken, retryCount, actualRetryInterval);
if (!retryRes)
{
@@ -205,7 +212,77 @@ public class BvLocator
public BvLocator WithRetryAction(Action<List<Region>>? action)
{
RetryAction = action;
if (action == null)
{
RetryAction = null;
}
else
{
RetryAction = (results) =>
{
action(results);
return Task.CompletedTask;
};
}
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,6 +55,12 @@ 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");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -144,4 +150,4 @@ public class BgiOnnxModel
RegisteredModels.Add(model);
return model;
}
}
}
@@ -88,6 +88,7 @@ public class AutoPathingScript
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
@@ -216,6 +216,11 @@ public class Genshin
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
public Point2f? GetPositionFromMapWithMatchingMethod(string matchingMethod)
{
return GetPositionFromMapWithMatchingMethod(nameof(MapTypes.Teyvat), matchingMethod);
}
public float GetCameraOrientation()
{
@@ -230,14 +235,18 @@ 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,6 +145,35 @@ 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,6 +15,7 @@ public class LimitedFile(string rootPath)
{
/// <summary>
/// 读取指定文件夹内所有文件和文件夹的路径(非递归方式)。
/// 目录不存在时返回空数组
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
@@ -23,19 +24,19 @@ public class LimitedFile(string rootPath)
try
{
// 对传入的文件夹路径进行标准化
string normalizedFolderPath = NormalizePath(folderPath);
string fullPath = NormalizePath(folderPath);
// 确保目录存在
if (!Directory.Exists(normalizedFolderPath))
if (!Directory.Exists(fullPath))
{
Directory.CreateDirectory(normalizedFolderPath);
TaskControl.Logger.LogError("ReadPathSync 目录不存在: {Path}", fullPath);
return Array.Empty<string>();
}
// 获取指定文件夹下的所有文件(非递归)
string[] files = Directory.GetFiles(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
string[] files = Directory.GetFiles(fullPath, "*", SearchOption.TopDirectoryOnly);
// 获取指定文件夹下的所有子文件夹(非递归)
string[] directories = Directory.GetDirectories(normalizedFolderPath, "*", SearchOption.TopDirectoryOnly);
string[] directories = Directory.GetDirectories(fullPath, "*", SearchOption.TopDirectoryOnly);
// 合并文件和文件夹路径
string[] combined = files.Concat(directories).ToArray();
@@ -45,12 +46,33 @@ 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>
@@ -0,0 +1,43 @@
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,6 +77,7 @@ 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#的类型
@@ -95,7 +96,7 @@ public class EngineExtend
// 导入 JavaScript 模块
// https://microsoft.github.io/ClearScript/2023/01/24/module-interop.html
// https://github.com/microsoft/ClearScript/blob/master/ClearScriptTest/V8ModuleTest.cs
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.EnableFileLoading | DocumentAccessFlags.AllowCategoryMismatch;
engine.DocumentSettings.AccessFlags = DocumentAccessFlags.AllowCategoryMismatch;
if (searchPaths != null)
{
var normalizedPaths = new List<string>();
@@ -9,7 +9,7 @@ using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DocumentLoader
public class PackageDocumentLoader : DefaultDocumentLoader
{
private readonly string _scriptRootPath;
@@ -22,21 +22,42 @@ namespace BetterGenshinImpact.Core.Script
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
// ResolvePhysicalPath 可能因 sourceInfo 为空而失败,直接从脚本根目录兜底
if (targetPath == null || !File.Exists(targetPath))
{
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
var stripped = Regex.Replace(specifier, @"^(?:\.\.?/)+", "");
if (!Path.IsPathRooted(stripped))
{
var fullPath = Path.GetFullPath(Path.Combine(_scriptRootPath, stripped));
if (fullPath.StartsWith(_scriptRootPath, StringComparison.OrdinalIgnoreCase)
&& File.Exists(fullPath))
{
targetPath = fullPath;
}
}
}
if (targetPath == null || !File.Exists(targetPath))
{
throw new FileNotFoundException($"无法解析模块导入路径: '{specifier}'", specifier);
}
// 处理 JS 文件的重写
if (Path.GetExtension(targetPath).ToLower() == ".js")
{
var uri = new Uri(targetPath);
// 检查缓存
var cached = GetCachedDocument(uri);
if (cached != null) return cached;
string content = await File.ReadAllTextAsync(targetPath);
string processedCode = RewriteScriptCode(content, targetPath);
var documentInfo = new DocumentInfo(new Uri(targetPath)) { Category = ModuleCategory.Standard };
return new StringDocument(documentInfo, processedCode);
var documentInfo = new DocumentInfo(uri) { Category = ModuleCategory.Standard };
return CacheDocument(new StringDocument(documentInfo, processedCode), false);
}
return await Default.LoadDocumentAsync(settings, sourceInfo, specifier, category, contextCallback);
throw new FileNotFoundException($"不支持的模块导入类型: '{specifier}' (仅支持 .js 文件)", specifier);
}
/// <summary>
@@ -54,11 +75,9 @@ namespace BetterGenshinImpact.Core.Script
{
string importPart = match.Groups[1].Value.Trim();
string quote = match.Groups[2].Value;
string rawPath = match.Groups[3].Value;
string path = rawPath.Replace("../../../packages", "packages");
string path = match.Groups[3].Value.Replace("../../../packages", "packages");
string? resourceFullPath = ResolvePathInternal(null, currentFilePath, path);
if (resourceFullPath != null && File.Exists(resourceFullPath))
{
string normalizedPath = Path.GetRelativePath(_scriptRootPath, resourceFullPath).Replace("\\", "/");
@@ -88,7 +107,24 @@ namespace BetterGenshinImpact.Core.Script
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier)
{
return ResolvePathInternal(settings.SearchPath, sourceInfo?.Name, specifier);
string? referrer = null;
if (sourceInfo.HasValue)
{
var sourceUri = sourceInfo.Value.Uri;
if (sourceUri != null && sourceUri.IsAbsoluteUri && sourceUri.IsFile)
{
referrer = sourceUri.LocalPath;
}
else if (!string.IsNullOrEmpty(sourceInfo.Value.Name))
{
if (Uri.TryCreate(sourceInfo.Value.Name, UriKind.Absolute, out var nameUri) && nameUri.IsFile)
{
referrer = nameUri.LocalPath;
}
}
}
return ResolvePathInternal(settings.SearchPath, referrer, specifier);
}
private string? ResolvePathInternal(string? searchPath, string? referrer, string specifier)
@@ -98,6 +134,12 @@ namespace BetterGenshinImpact.Core.Script
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
var packagesMatch = Regex.Match(specifier, @"^(?:\.\.\/)+(packages/.*)$");
if (packagesMatch.Success)
{
return ProbeFile(Path.Combine(_scriptRootPath, packagesMatch.Groups[1].Value));
}
if (specifier.StartsWith("."))
{
if (!string.IsNullOrEmpty(referrer))
@@ -128,8 +170,9 @@ namespace BetterGenshinImpact.Core.Script
{
try
{
if (File.Exists(path)) return path;
if (File.Exists(path + ".js")) return path + ".js";
var normalized = Path.GetFullPath(path);
if (File.Exists(normalized)) return normalized;
if (File.Exists(normalized + ".js")) return normalized + ".js";
}
catch { }
return null;
@@ -28,6 +28,9 @@ public class Simulation
SendInput.Keyboard.KeyUp(key);
}
}
SendInput.Mouse.LeftButtonUp();
SendInput.Mouse.RightButtonUp();
SendInput.Mouse.MiddleButtonUp();
}
public static bool IsKeyDown(User32.VK key)
@@ -22,6 +22,7 @@ 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;
@@ -78,6 +79,8 @@ 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
@@ -2075,5 +2075,41 @@
"nameEn": "Linnea",
"skillCD": 18,
"weapon": "10"
},
{
"alias": [
"洛恩",
"Lohen"
],
"burstCD": 15,
"id": "10000129",
"name": "洛恩",
"nameEn": "Lohen",
"skillCD": 18,
"weapon": "10"
},
{
"alias": [
"尼可",
"Nicole"
],
"burstCD": 15,
"id": "10000131",
"name": "尼可",
"nameEn": "Nicole",
"skillCD": 16,
"weapon": "10"
},
{
"alias": [
"布伦妮",
"Prune"
],
"burstCD": 18,
"id": "10000132",
"name": "布伦妮",
"nameEn": "Prune",
"skillCD": 15,
"weapon": "10"
}
]
@@ -13,7 +13,7 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
[Serializable]
public partial class AutoFightConfig : ObservableObject
{
[ObservableProperty] private string _strategyName = "";
[ObservableProperty] private string _strategyName = "根据队伍自动选择";
/// <summary>
/// 英文逗号分割 强制指定队伍角色
@@ -680,11 +680,21 @@ public class AutoFightTask : ISoloTask
await Delay(200, ct);
if (picker.TrySwitch(10))
{
// 等待元素战技 CD 就绪
await picker.WaitSkillCd(ct);
picker.UseSkill(true);
await Delay(50, ct);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
// 调用统一的辅助方法,模拟万叶长按 E 的输入序列:
// 包含释放鼠标左键前摇防卡键 -> E 键 KeyDown -> 延时 800ms -> E 键 KeyUp -> 延时 50ms
await SimulateHoldElementalSkillAsync(800, ct);
// 调用统一的辅助方法,模拟 6 次鼠标左键连续点击:
// 配合万叶长 E 的滞空特性执行下落攻击,内部包含 try/finally 以保证取消任务时安全释放左键
await SimulateMouseLeftClickLoopAsync(6, ct);
// 等待下落攻击和聚怪拾取动作彻底结束
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,6 +24,11 @@ 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;
@@ -99,7 +104,10 @@ 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)
{
@@ -591,6 +599,14 @@ 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 })
@@ -598,6 +614,7 @@ public class Avatar
return;
}
// Logger.LogInformation("释放Q");
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
Sleep(200, Ct);
@@ -610,9 +627,47 @@ 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
@@ -1098,4 +1153,4 @@ public class Avatar
return null;
}
}
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
public enum BurstReadyState
{
Ready,
Cooldown,
Unknown
}
@@ -1,4 +1,5 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.Model;
@@ -74,6 +75,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
else
{
_cts.Cancel();
Simulation.ReleaseAllKey();
}
}
}
@@ -89,6 +91,7 @@ public class OneKeyFightTask : Singleton<OneKeyFightTask>
if (IsHoldOnMode())
{
_cts?.Cancel();
Simulation.ReleaseAllKey();
}
}
@@ -179,9 +182,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);
@@ -717,7 +717,7 @@
"nameEn": "wriothesley",
"type": "character",
"name": "莱欧斯利",
"hp": 10,
"hp": 11,
"energy": 3,
"element": "冰元素",
"weapon": "法器",
@@ -4670,6 +4670,83 @@
}
]
},
{
"id": 1418,
"nameEn": "flins",
"type": "character",
"name": "菲林斯",
"hp": 10,
"energy": 4,
"element": "雷元素",
"weapon": "长柄武器",
"skills": [
{
"nameEn": "pocztowy_demonspear",
"name": "扈圣魔枪",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "ancient_rite_arcane_light",
"name": "古律·孤灯遗秘",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 2
}
]
},
{
"nameEn": "ancient_ritual_cometh_the_night",
"name": "旧仪·夜客致访",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 4
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 4
}
]
},
{
"nameEn": "moonsign_benediction_old_world_secrets",
"name": "月兆祝赐·旧世潜藏",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1501,
"nameEn": "sucrose",
@@ -5296,7 +5373,7 @@
"nameEn": "xianyun",
"type": "character",
"name": "闲云",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "风元素",
"weapon": "法器",
@@ -7224,6 +7301,83 @@
}
]
},
{
"id": 1711,
"nameEn": "lauma",
"type": "character",
"name": "菈乌玛",
"hp": 11,
"energy": 2,
"element": "草元素",
"weapon": "法器",
"skills": [
{
"nameEn": "peregrination_of_linnunrata",
"name": "林麓旅踏",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "runo_dawnless_rest_of_karsikko",
"name": "圣言述咏·终宵永眠",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
}
]
},
{
"nameEn": "runo_all_hearts_become_the_beating_moon",
"name": "圣言述咏·众心为月",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "moonsign_benediction_natures_chorus",
"name": "月兆祝赐·千籁恩宠",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 2101,
"nameEn": "fatui_cryo_cicin_mage",
@@ -9515,6 +9669,75 @@
}
]
},
{
"id": 2605,
"nameEn": "experimental_field_generator",
"type": "character",
"name": "实验性场力发生装置",
"hp": 11,
"energy": 2,
"element": "岩元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "gravity_application_crush",
"name": "重力应用程式·砸击",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "gravity_application_point_null",
"name": "重力应用程式·点状抵消",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
}
]
},
{
"nameEn": "gravity_application_field_reduction",
"name": "重力应用程式·削减场域",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
}
]
},
{
"id": 2701,
"nameEn": "jadeplume_terrorshroom",
@@ -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,6 +11,7 @@ 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;
@@ -1081,11 +1082,34 @@ public class AutoLeyLineOutcropTask : ISoloTask
_logger.LogInformation("战后聚集拾取:万叶已切换,等待元素战技CD");
await kazuha.WaitSkillCd(_ct);
kazuha.UseSkill(true);
await Delay(50, _ct);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
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);
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 != null && config is PathingPartyConfig patyConfig && patyConfig.AutoFightEnabled)
if (config is PathingPartyConfig { Enabled: true, AutoFightEnabled: true } partyConfig)
{
//替换配置为地图追踪
taskParams = GetFightAutoFightParam(patyConfig.AutoFightConfig);
taskParams = GetFightAutoFightParam(partyConfig.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))
if ("根据队伍自动选择".Equals(config.StrategyName) || string.IsNullOrEmpty(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 (1, 5);
if (string.IsNullOrEmpty(actionParams)) return (LinneaMiningTask.DefaultMineCount, LinneaMiningTask.DefaultScanRounds);
var parts = actionParams.Split(',');
var mineCount = -1;
@@ -72,8 +72,8 @@ public class LinneaMiningHandler : IActionHandler
}
}
if (mineCount == -1) mineCount = 1;
if (scanRounds == -1) scanRounds = 5;
if (mineCount == -1) mineCount = LinneaMiningTask.DefaultMineCount;
if (scanRounds == -1) scanRounds = LinneaMiningTask.DefaultScanRounds;
if (scanRounds < mineCount) scanRounds = mineCount;
return (mineCount, scanRounds);
@@ -25,8 +25,8 @@ public class PickUpCollectHandler : IActionHandler
/// </summary>
public static readonly string[] PickUpActions =
[
"枫原万叶-长E keydown(E),wait(0.7),keyup(E),attack(0.2),wait(0.5)",
"枫原万叶-短E e,attack(0.15)",
"枫原万叶-长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 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)," +
@@ -1,6 +1,6 @@
{
"language": "CHS",
"version": "56882a11588d5e79a1b6b51739f9fb27e9952fd7",
"version": "cffc7f010f1a4bf4a0bdfb0865d0737d4aec6b7a",
"data": [
{
"sceneId": 3,
@@ -14224,6 +14224,29 @@
9669.12
]
},
{
"id": 2003,
"type": "BlessDomain",
"name": "山风的荆冕",
"country": "蒙德",
"areas": [
"风息山"
],
"position": [
3266.666,
290.28,
47.39246
],
"tranPosition": [
3258.3,
289.17,
47.8
],
"rewards": [
"天之美赐",
"影中沉凝的幻灭"
]
},
{
"id": 2009,
"type": "TeleportWaypoint",
@@ -14318,6 +14341,31 @@
347.94803,
-217.91002
]
},
{
"id": 2053,
"type": "TrounceDomain",
"name": "万有涅槃缚境",
"country": "须弥",
"areas": [
"护世森",
"茸蕈窟"
],
"position": [
221.1095,
270.9658,
2915.052
],
"tranPosition": [
217.3052,
268.16556,
2917.7302
],
"rewards": [
"亵渎的新芽",
"扭曲的枯枝",
"赝作的树脂"
]
}
]
},
@@ -16234,4 +16282,4 @@
]
}
]
}
}
@@ -8,6 +8,7 @@ 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;
@@ -15,6 +16,7 @@ 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;
@@ -30,8 +32,8 @@ public class LinneaMiningTask
private const double BaseClusterDistance = 400;
// 聚类面积基准值(1920宽度下的标准矿石面积)
private const double BaseClusterArea = 1800;
// 对准判定阈值(基于宽度缩放)
private const double BaseArrivalThreshold = 50;
// 对准判定:使用目标矿物框四周扩张像素(基于宽度缩放)
private const double BaseAlignmentExpansion = 3;
// 屏幕边缘忽略区域宽度(基于宽度缩放)
private const double BaseEdgeIgnore = 200;
// 瞄准模式X轴灵敏度补偿系数
@@ -46,8 +48,10 @@ public class LinneaMiningTask
private const int LeftTurnStep = -250;
// 内层最大检测次数
private const int MaxInnerRetry = 7;
// 默认射箭次数
public const int DefaultMineCount = 1;
// 默认大循环次数
private const int DefaultScanRounds = 5;
public const int DefaultScanRounds = 1;
// 元素视野刷新间隔
private const int ElementSightRefreshMs = 3000;
@@ -58,22 +62,24 @@ 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 = 1)
public LinneaMiningTask(int scanRounds = DefaultScanRounds, int mineCount = DefaultMineCount)
{
_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)
@@ -83,7 +89,7 @@ public class LinneaMiningTask
{
// Logger.LogInformation("开始寻矿");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
aimingModeEntered = true;
await Delay(400, ct);
@@ -139,7 +145,7 @@ public class LinneaMiningTask
await Delay(800, ct);
}
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
aimingModeEntered = false;
}
catch (OperationCanceledException)
@@ -154,7 +160,7 @@ public class LinneaMiningTask
{
if (aimingModeEntered)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_R);
Simulation.SendInput.Keyboard.KeyPress(GIActions.SwitchAimingMode.ToActionKey().ToVK());
}
Simulation.SendInput.Mouse.MiddleButtonUp();
@@ -184,18 +190,16 @@ 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) <= dynamicThreshold / 2 && Math.Abs(offsetY) <= dynamicThreshold / 2;
var isAligned = Math.Abs(offsetX) <= (cluster.TargetWidth + AlignmentExpansion * 2) / 2
&& Math.Abs(offsetY) <= (cluster.TargetHeight + AlignmentExpansion * 2) / 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);
}
@@ -288,20 +292,17 @@ public class LinneaMiningTask
var clusters = ClusterMinerals(oreBoxes);
// 画聚类中心标记框
var refArea = BaseClusterArea * _widthScale * _widthScale;
var clusterDrawList = new List<RectDrawable>();
foreach (var cluster in clusters)
// 画聚类目标矿物框
var expansion = (int)AlignmentExpansion;
var clusterDrawList = clusters.Select(c =>
{
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})",
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})",
new Pen(Color.DodgerBlue, 2)
));
}
);
}).ToList();
VisionContext.Instance().DrawContent.PutOrRemoveRectList("MiningCluster", clusterDrawList);
// 忽略屏幕边缘聚类,仅当中间区域存在聚类时生效
@@ -360,7 +361,7 @@ public class LinneaMiningTask
}
}
clusters.Add(new MineralCluster(rect, AreaRatioThreshold));
clusters.Add(new MineralCluster(rect, AreaRatioThreshold, _preferRight));
}
return clusters;
@@ -377,15 +378,19 @@ 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)
public MineralCluster(Rect firstRect, double areaRatioThreshold = 5, bool preferRight = true)
{
AreaRatioThreshold = areaRatioThreshold;
PreferRight = preferRight;
Rects.Add(firstRect);
RecalculateCenter();
}
private readonly double AreaRatioThreshold;
private readonly bool PreferRight;
public bool TryAddRect(Rect rect)
{
@@ -402,16 +407,28 @@ public class MineralCluster
CenterX = Rects.Average(r => r.X + r.Width / 2.0);
CenterY = Rects.Average(r => r.Y + r.Height / 2.0);
// 按距离质心排序,取最近2个中靠左的
var candidates = Rects
var sorted = 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)))
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))
.OrderBy(t => t.dist)
.Take(2)
.OrderBy(t => t.cx)
.First();
.ToList();
TargetX = candidates.cx;
TargetY = candidates.cy;
(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;
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -89,6 +89,28 @@ 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,6 +9,7 @@ using Fischless.GameCapture;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using Vanara.PInvoke;
using BetterGenshinImpact.Core.Simulator.Extensions;
namespace BetterGenshinImpact.GameTask.Common;
@@ -184,6 +185,90 @@ 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();
@@ -225,4 +310,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 deletedPaths = new List<string>();
var updatedPaths = new List<string>();
foreach (var parentKeyPath in HdrRegistryParentKeyPaths)
{
try
@@ -41,21 +41,34 @@ public static class GenshinHdrRegistryHelper
continue;
}
if (key.GetValue(HdrRegistryEntryName) == null)
var value = key.GetValue(HdrRegistryEntryName);
if (value == null)
{
continue;
}
key.DeleteValue(HdrRegistryEntryName, throwOnMissingValue: false);
deletedPaths.Add($@"HKEY_CURRENT_USER\{parentKeyPath}\{HdrRegistryEntryName}");
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}");
}
catch
{
// 忽略删除失败,避免影响启动流程
// 忽略写入失败,避免影响启动流程
}
}
deletedFullKeyPaths = deletedPaths.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
deletedFullKeyPaths = updatedPaths.Distinct(StringComparer.OrdinalIgnoreCase).ToArray();
return deletedFullKeyPaths.Count > 0;
}
}
@@ -190,6 +190,7 @@ public class TaskRunner
TaskTriggerDispatcher.Instance().SetTriggers(GameTaskManager.LoadInitialTriggers());
VisionContext.Instance().DrawContent.ClearAll();
HtmlMaskWindow.CloseAll();
}
}
+5 -3
View File
@@ -9,7 +9,9 @@
WindowStartupLocation="Manual"
ShowInTaskbar="False"
Topmost="True">
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
<Border x:Name="ClickThroughBorder" Background="Transparent">
<Grid>
<wv2:WebView2 x:Name="WebView" DefaultBackgroundColor="Transparent"/>
</Grid>
</Border>
</Window>
+148 -13
View File
@@ -17,7 +17,7 @@ using Microsoft.Web.WebView2.Core;
namespace BetterGenshinImpact.View;
/// <summary>
/// HTML遮罩窗口 - 仅用于显示,不可交互(点击穿透)
/// HTML遮罩窗口
/// </summary>
public partial class HtmlMaskWindow : Window
{
@@ -29,12 +29,21 @@ 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");
@@ -42,6 +51,7 @@ public partial class HtmlMaskWindow : Window
_webView2DataPath = Path.Combine(workDir, "WebView2Data");
_pageUrl = url;
InitializeComponent();
ClickThroughBorder.Background = _backgroundBrush;
Loaded += OnLoaded;
InitializeAsync(url);
}
@@ -156,6 +166,47 @@ 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>
@@ -164,13 +215,24 @@ public partial class HtmlMaskWindow : Window
if (!_windows.TryGetValue(windowId, out var window)) return;
window.Dispatcher.BeginInvoke(() =>
{
// 页面还没加载完,消息留在队列中由 NavigationCompleted 统一推送
if (!window._navigationCompleted) return;
if (window.WebView.CoreWebView2 == null) return;
HtmlMask.FlushPendingMessages(windowId, json =>
try
{
window.WebView.CoreWebView2.PostWebMessageAsString(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遮罩窗口消息推送异常");
}
});
}
@@ -178,7 +240,7 @@ public partial class HtmlMaskWindow : Window
private void OnLoaded(object sender, RoutedEventArgs e)
{
SetClickThrough();
SetClickThrough(true);
UpdatePosition();
}
@@ -387,14 +449,87 @@ public partial class HtmlMaskWindow : Window
}
/// <summary>
/// 设置点击穿透
/// 设置点击穿透模式
/// </summary>
private void SetClickThrough()
/// <param name="enabled">true=点击穿透,false=可交互</param>
private void SetClickThrough(bool enabled)
{
var hwnd = new WindowInteropHelper(this).Handle;
var style = (int)GetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE);
User32.SetWindowLong(hwnd, WindowLongFlags.GWL_EXSTYLE,
(IntPtr)(style | (int)User32.WindowStylesEx.WS_EX_TRANSPARENT));
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));
}
/// <summary>
@@ -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,6 +650,9 @@ 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(); });
@@ -820,4 +823,4 @@ public partial class OneDragonFlowViewModel : ViewModel
Toast.Error("重命名配置时失败");
}
}
}
}
@@ -640,6 +640,18 @@ public partial class ScriptControlViewModel : ViewModel
if (newScriptGroup != null)
{
newScriptGroup.Name = str;
ScriptGroup.ResetGroupInfo(newScriptGroup);
foreach (var project in newScriptGroup.Projects)
{
try
{
project.BuildScriptProjectRelation();
}
catch
{
// ignored
}
}
ScriptGroups.Add(newScriptGroup);
}
@@ -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.0" />
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
</ItemGroup>
</Project>