Compare commits

..
Author SHA1 Message Date
辉鸭蛋 b7aa7fc663 Merge branch 'main' into d-v3
# Conflicts:
#	AGENTS.md
#	BetterGenshinImpact/App.xaml.cs
2026-07-26 15:55:47 +08:00
辉鸭蛋 e08aaa8e0f UI: 处理 FooterMenuItems 的场景 2026-07-26 15:53:16 +08:00
辉鸭蛋 fb587f4bb7 UI: 菜单切换加入类似 WinUI3 的效果 2026-07-26 15:40:36 +08:00
辉鸭蛋 dc1070ad19 Feat/child session v2 (#3348) 2026-07-26 14:37:35 +08:00
ddaodan 5a38fc6aa4 修复:为遮罩指标栏添加独立快捷键 (#3346) 2026-07-26 04:14:48 +08:00
Tianxiang Shi 80a9c059bf fix: 使用 HLS 颜色空间识别传送候选文字 (#3345) 2026-07-26 04:10:39 +08:00
辉鸭蛋 9f80a18e7d feat(childsession): 添加系统组合键发送目标切换与操作通知
- 新增快捷键菜单选项,支持切换系统组合键发送到本机或桌面分身
- 新增顶部通知弹窗,替代原有的弹出式提示,优化用户体验
- 重构RDP会话的连接、重连与重试逻辑,添加超时处理机制
- 完善视图模型绑定与命令逻辑,同步界面与业务状态
2026-07-25 18:20:44 +08:00
辉鸭蛋 1bb8017e55 RDP失败的时候提示报错信息 2026-07-25 16:49:41 +08:00
huiyadanli fd8da28084 Update version to 0.62.2-alpha.1 2026-07-25 03:32:03 +00:00
辉鸭蛋 9099e17b5a 加入rawinput的监听,桌面分身中游戏支持鼠标相对移动 (#3341) 2026-07-25 09:01:59 +08:00
mno 6f0dbd9c3f fix:修复赶路角色接近节点多处问题:按键残留、角度阈值不生效、希诺下车检测不准 (#3336) 2026-07-24 21:35:16 +08:00
辉鸭蛋 d1eb06e411 新增桌面分身功能,解决游戏后台键鼠问题 (#3334) 2026-07-24 21:33:58 +08:00
辉鸭蛋 603d75f085 Add code review rules and output language guidelines
Added code review rules and output language guidelines.
2026-07-24 16:03:05 +08:00
mno 2a07ea7a5a 优化连续赶路模式下下车判定条件,添加节点角度作为参考 (#3328) 2026-07-24 01:58:14 +08:00
ShadowLemoon 780f566198 fix: 兼容没解锁n6的号 (#3331) 2026-07-23 16:47:44 +08:00
辉鸭蛋 76d11e16c9 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2026-07-23 00:51:23 +08:00
辉鸭蛋 d7e25d00cd build(依赖包): 更新MailKit和MimeKit至4.16.0 2026-07-23 00:51:14 +08:00
mnoand辉鸭蛋 c135f63730 feat: 新增遮罩窗口准星功能,支持十字/倒V字/圆点/中心点十字/自定义等多种样式 (#3320)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-23 00:49:16 +08:00
辉鸭蛋 df4a058715 添加开发文档 2026-07-23 00:08:41 +08:00
mno 1040e45da5 fix: 转圈异常时先松W再转向,否则按住W转向仍然可能触发转圈 (#3310) 2026-07-23 00:01:05 +08:00
bling-yshs bd0039f2fb fix: 修复进入游戏 choose_enter_game 按钮识别范围,避免误点击 (#3326) 2026-07-22 23:55:51 +08:00
Arkadegong ad5a5f8a1b feat: 排版修复、边距统一与滚动交互优化 (#3303) 2026-07-22 23:52:29 +08:00
Jamis 761d66b651 Add 隐居处 teleport point to tp.json (#3324) 2026-07-22 23:34:39 +08:00
辉鸭蛋 1678aada02 Merge remote-tracking branch 'origin/main' 2026-07-22 23:24:16 +08:00
辉鸭蛋 99e97d7180 秘境级联选择框支持清除选择 2026-07-22 23:23:47 +08:00
FishmanTheMurloc 40d424dc71 清理主项目的TorchSharp (#3322) 2026-07-22 23:09:58 +08:00
辉鸭蛋 0f951a4249 使用新的 md 渲染组件 2026-07-22 22:45:53 +08:00
DarkFlameMaster 0d9b024ec3 feat/refactor: 添加在大地图点击坐标的方法,获取小地图摄像机角度时不再为负数 (#3317) 2026-07-22 11:13:48 +08:00
mno 6d73496132 fix: 桑多涅体力识别替代序列冲刺管理,玛薇卡跳飞安全降落 (#3319) 2026-07-22 11:12:34 +08:00
DarkFlameMaster f63362299c fix:增加与鸭鸭战斗前等待时长避免过早战斗失败 (#3309) 2026-07-20 10:37:01 +08:00
辉鸭蛋 132f16cb12 feat(recognition): 删除识别对象的默认克隆操作,只在有必要时clone 2026-07-18 21:43:41 +08:00
mno 5437cb7116 feat: OCR兜底识别失败时填充未知角色并添加角色映射 (#3297) 2026-07-18 01:37:07 +08:00
mno c5f1890d97 feat: 动态追踪传奇血条(帧间连续性 y 96-200,5帧阈值) (#3299)
扩展传奇血条判定:y<96 直接判定;96-200 用帧间连续性动态追踪(连续5帧出现标记,允许1帧容错);≥200 直接普通。解决部分Boss血条不在标准y范围时的漏识别问题。
2026-07-17 10:26:22 +08:00
辉鸭蛋 14068e7279 Update BetterGI.Assets.Model package version 2026-07-16 10:40:47 +08:00
huiyadanli 7d7ebe1fc2 Update version to 0.62.1-alpha.3 2026-07-16 02:04:25 +00:00
mno 98e50ebf3c fix: 查找和关闭游戏进程时按SessionId过滤,避免多用户串扰 (#3298)
* fix: 查找和关闭游戏进程时按SessionId过滤,避免多用户串扰

* fix: 逐进程容错处理 SessionId 访问异常

FindHandleByProcessName 和 CloseGame 中遍历进程时,若进程在 GetProcessesByName 后已退出,访问 SessionId 会抛出 InvalidOperationException。改为 foreach + try-catch 逐进程处理,避免整个方法因单个已退出进程而失败。
2026-07-16 10:01:29 +08:00
辉鸭蛋 6a6e785c54 修改采集与锄地的UI 2026-07-16 02:24:15 +08:00
辉鸭蛋 4b7bb5b5a3 Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/GameTask/AutoPathing/PathExecutor.cs
2026-07-16 01:46:08 +08:00
mno bbd892c2de fix: JSON 战斗策略 morePriorities 执行时 count 条件恒为 true (#3296) 2026-07-16 01:32:57 +08:00
辉鸭蛋 206eb284d7 修复 单个界面单个选项选择 中 首次识别到文字,延迟1s重新识别一次 未生效的问题 2026-07-16 01:31:45 +08:00
mnoand辉鸭蛋 7e30466378 fix: 修复CombatCommand当前角色NPE并提取共享执行器CombatScriptExecutor (#3288)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-16 01:12:17 +08:00
mno 9bf2a41e2e feat:为桑多涅重击添加特化逻辑 (#3292) 2026-07-16 00:37:28 +08:00
辉鸭蛋 5ff61ec5bb fixed #3290 2026-07-16 00:29:38 +08:00
huiyadanli 0eb90304c4 Update version to 0.62.1-alpha.2 2026-07-13 15:38:32 +00:00
辉鸭蛋 903a72525f 回滚一个改动 2026-07-13 23:29:36 +08:00
辉鸭蛋 3b028d8939 修复钓鱼图片错误的引用 2026-07-13 23:21:58 +08:00
huiyadanli 7ec3687c53 Update version to 0.62.1-alpha.1 2026-07-12 19:10:43 +00:00
ddaodanand辉鸭蛋 a962d69ac3 修复遮罩指标栏显示原神实际使用显卡的占用率 (#3278)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-13 03:07:03 +08:00
辉鸭蛋 ca91b97aee Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2026-07-13 02:55:21 +08:00
辉鸭蛋 10b04f0045 refactor(MaskWindowViewModel): 移除未使用的ClearHiddenMapPointState方法及其调用
该方法仅被调用一次,删除后不会影响程序功能,同时简化代码结构。
2026-07-13 02:55:19 +08:00
cookie981 075da66bbe fix: 修改配置组的扫描掉落物光柱时长能正确生效了 (#3119) 2026-07-13 02:32:32 +08:00
Tool_tingsuand辉鸭蛋 cb822eb5ed feat: 新增“一键领取奖励”功能 (#3273)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-13 02:20:10 +08:00
mno 1202ad3180 feat: 一条龙支持重复任务和从此执行书签 (#3276) 2026-07-13 02:05:32 +08:00
mnoand辉鸭蛋 8d65f739a5 feat: 添加角色战技赶路功能 (#3280)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-13 02:01:56 +08:00
mno 1631729dd8 feat: 低血量回复时机改为可选项(任何路径点/只在传送点/不回复) (#3283) 2026-07-13 01:54:55 +08:00
mnoand辉鸭蛋 abebd1c9b5 json战斗相关修复 (#3274)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-13 01:47:47 +08:00
Patrick-Ze da35a91dee 添加js脚本读取用户已订阅的脚本路线文件的接口 (#3252) 2026-07-13 01:38:27 +08:00
辉鸭蛋 ff148e9b8c feat(地图遮罩): 修改 #3281 的存储逻辑,按地图数据源隔离点位状态
解决切换不同地图数据源时遮罩状态互相覆盖的问题,将存储改为按数据源分文件存储,新增内存缓存优化读写性能,简化视图模型代码并移除冗余方法,同时添加完善的XML注释提升可维护性。
2026-07-13 01:36:45 +08:00
YufeiV cb3dcace85 feat: 增加地图遮罩中单独标点的隐藏与显示功能 (#3281) 2026-07-13 01:18:35 +08:00
辉鸭蛋 eb1beaadfd fix(TaskTriggerDispatcher): 仅在游戏窗口尺寸实际变化时记录日志
同时添加非零窗口尺寸检查,避免记录无效日志
2026-07-13 01:14:08 +08:00
秋云and辉鸭蛋 4f9fa50e99 fix(tp): optimize map teleport targeting (#3258)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-13 01:10:26 +08:00
辉鸭蛋 4b14e03274 refactor: 重构游戏捕获接口,统一管理截图资源与区域 (#3250)
* refactor(game-capture): 重构游戏捕获接口,统一管理截图资源与区域

新增GameCaptureFrame类封装捕获的Mat帧与对应捕获矩形,实现自动释放Mat资源。修改IGameCapture接口的Capture方法返回类型,更新所有实现类和业务调用代码适配新接口,同时优化窗口捕获区域的计算逻辑,确保捕获区域更准确。

* feat(recognition): 新增基于参考画布的跨分辨率识别搜索功能

无需手动转换不同分辨率下的识别坐标,新增跨分辨率识别搜索适配能力:
- 新增SearchOptions配置类与SearchAnchorMode枚举
- 扩展RecognitionObject添加参考画布相关属性
- 新增ImageRegionReferenceSearchHelper处理坐标转换与模板缩放
- 重构ImageRegion的识别逻辑以兼容参考搜索模式
- 新增对应单元测试覆盖核心场景

* refactor(recognition): 重构游戏识别资源加载管理方式

重构全项目的游戏识别资源加载逻辑,统一使用JSON配置管理识别资源:
- 为AutoEat、AutoFishing、QuickBuy等十余种游戏任务新增Recognition.json识别配置文件
- 删除AutoEatAssets、QuickBuyAssets等近20个冗余的单例资源类文件
- 替换所有硬编码的Assets实例调用,使用统一的工具类获取资源
- 调整项目配置确保识别配置和模板图片正确复制到输出目录
- 优化BaseAssets基类,新增LoadRecognitionObject辅助加载方法
- 修复AutoFishing单元测试中的冗余资源实例创建代码
- 新增NCalc依赖包支持表达式计算需求
- 临时包含了编译输出的依赖库文件

* style(recognition): 优化识别对象加载的错误日志格式

重新调整错误日志的措辞与参数顺序,让日志更易读,便于排查加载失败问题

* 修复(自动音游模块): 修复资源泄漏与任务取消逻辑

为所有可释放的截图区域添加using语句以正确释放非托管资源。修复自动专辑任务中的取消令牌处理逻辑,使用关联令牌源、调整延迟调用的令牌并添加异常处理以避免孤立任务与未处理异常。

* docs(recognition): 为识别JSON配置类添加详细XML文档注释

补充该文件中所有类和属性的XML文档注释,清晰说明每个配置项的作用,提升代码可读性与后续开发的维护便利性。

* 修复code review时候出现的问题

* fix small bug

* refactor(assets): 重构资产管理系统,适配多分辨率并统一获取方式

1. 新增通用资产缓存类`AssetsCache`和`CaptureAssetsCache`,实现线程安全的按分辨率缓存资产
2. 将`MapAssets`、`AutoFightAssets`、`QuickTeleportAssets`等资产类从单例模式改为缓存加载模式
3. 移除`AutoWoodAssets`单例,重构自动伐木任务的资产获取逻辑
4. 替换所有旧的`.Instance`调用为适配当前分辨率的`Get()`方法,修复多分辨率下的资产坐标偏移问题
5. 优化自动拾取逻辑,支持动态使用用户配置的交互键,修复配置不生效的问题
6. 新增`GameTaskManager.LoadAssetImage`方法统一加载和缩放素材
7. 移除多处多余的资产销毁调用,简化资产生命周期管理
8. 新增资产缓存单元测试,验证缓存的线程安全和分辨率适配逻辑

* fix(game-task): 调整游戏窗口大小变化处理逻辑,不再重启截图器

完成原有注释提到的优化,注释窗口大小变化时重启截图器的代码块,更新日志提示并仅更新捕获区域参数
2026-07-13 00:52:35 +08:00
辉鸭蛋 beb0a70f5b Revert "feat: 取消一键强化宏的点击详情菜单动作" (#3272) 2026-07-10 14:07:35 +08:00
DarkFlameMaster 080bf4196b fix:补充自动首领的一条龙配置 (#3265) 2026-07-08 20:43:19 +08:00
quantcat26 d7e7e40465 fix(Metrics): bind the shortcut of Metrics display to LogBoxDisplayHotkey (#3256) 2026-07-08 02:15:53 +08:00
DarkFlameMaster e2111543a7 refactor:优化弹窗的三角识别 (#3254) 2026-07-06 22:52:12 +08:00
DarkFlameMaster d50b09ad69 feat:添加角色网格图标识别,添加更换角色的方法 (#3248) 2026-07-05 15:05:12 +08:00
辉鸭蛋 636b47f3b3 Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/Service/ScriptService.cs
2026-07-05 12:53:57 +08:00
huiyadanli 92b8beab53 Update version to 0.62.0 2026-07-04 16:17:32 +00:00
辉鸭蛋 4beaa4a3d9 新增 skill 2026-07-05 00:15:15 +08:00
辉鸭蛋 beddfe01ba 6.7 类库更新 2026-07-04 22:38:39 +08:00
辉鸭蛋 bf06ba3ce1 fixed #3237 2026-07-03 02:32:03 +08:00
huiyadanli 85d3da2f02 Update version to 0.61.4-alpha.1 2026-07-02 17:53:28 +00:00
躁动的氨气 105e4ccd10 feat: HTML遮罩资源拦截路径修改(适配虚拟机) (#3183) 2026-07-03 01:50:41 +08:00
DarkFlameMaster 5992a9d91b feat:新增合成功能 (#3231) 2026-07-03 01:50:06 +08:00
mnoand辉鸭蛋 5f02b26cd2 feat:建立工厂处理不同的战斗策略入口 (#3196)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-07-03 01:49:40 +08:00
辉鸭蛋 6388c6521c 6.7 角色更新 + OCR兜底 #3238 2026-07-03 01:23:26 +08:00
Jamis db74dec3f6 Update tp.json with new version and waypoints (#3236) 2026-07-02 21:51:35 +08:00
DarkFlameMaster 89edfe7945 fix:AutoDomain适配新版本快捷键改动 (#3230) 2026-07-01 18:31:56 +08:00
辉鸭蛋 deaa565847 Change QQ group link in README
Updated QQ group link for issue feedback.
2026-07-01 11:41:43 +08:00
躁动的氨气 90b812f6a9 feat: 补充html遮罩的js响应 (#3220) 2026-06-22 20:00:16 +08:00
DarkFlameMaster 659143aaf6 fix:将settings持久化保存时机调整到JS脚本运行结束 (#3215) 2026-06-21 20:26:56 +08:00
DarkFlameMaster 114cad1b47 fix:修复地脉花寻路走过头错过交互 (#3211) 2026-06-21 20:18:42 +08:00
Patrick-Ze cfe5e745be feat: 取消一键强化宏的点击详情菜单动作 (#3218) 2026-06-21 20:17:49 +08:00
躁动的氨气 12ee510601 feat: 兑换码弹窗 (#3217) 2026-06-21 20:04:24 +08:00
huiyadanli b3a6da24f9 Update version to 0.61.3-alpha.3 2026-06-20 11:38:24 +00:00
辉鸭蛋 f95ced446c 去掉部分影响Debug性能的 Debug.WriteLine 2026-06-19 23:16:29 +08:00
辉鸭蛋 5eb91c4092 feat(ocr): 优化Paddle OCR检测,新增alpha版默认V6模型配置
重构OCR检测的图像预处理与坐标映射逻辑,修复检测框计算错误,新增小图补全和多种缩放限制类型支持;调整主窗口视图模型的版本检查逻辑,为alpha版本用户升级后自动切换OCR模型;调整PaddleOcrModelConfig枚举项顺序,修复代码文件末尾缺失换行的问题。
2026-06-19 23:03:51 +08:00
躁动的氨气 4bc4516cd8 feat: 添加ppocr-v6模型 (#3202) 2026-06-19 20:58:21 +08:00
DarkFlameMaster 3df57333c2 feat: 给AutoBoss 与 AutoDomain 在本体与JS中添加奖励识别 (#3208) 2026-06-19 19:22:03 +08:00
bling-yshs 13b85c5904 fix: 修复自动幽境危战切换队伍有可能切错boss (#3206) 2026-06-19 19:15:43 +08:00
躁动的氨气and辉鸭蛋 1a3e626af0 feat: 兑换码提醒优化 (#3207)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-06-19 19:12:33 +08:00
辉鸭蛋 376a2442cf Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/App.xaml.cs
2026-06-18 04:08:10 +08:00
躁动的氨气 0c20c74075 fix: HTML遮罩在不同DPI下位置不一致 (#3200) 2026-06-16 01:14:18 +08:00
huiyadanli f91a15515e Update version to 0.61.3-alpha.2 2026-06-11 02:01:46 +00:00
cookie981 63fe6ec8bb fix:重构新一键宏 (#3192) 2026-06-11 09:58:04 +08:00
pboymt 2acdb2c1a1 feat: 新增 MeoW 通知推送支持 (#3187)
* feat: 新增 MeoW 通知推送支持

* fix(MeowNotifier): 增强昵称校验并释放HttpResponseMessage
2026-06-09 00:14:46 +08:00
DarkFlameMaster 740ce67be7 feat:新增自动任务-自动首领讨伐 (#3180) 2026-06-07 20:58:16 +08:00
ddaodanand辉鸭蛋 f9d04bc62b 新增可配置遮罩指标栏 (#3121)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-06-07 12:00:03 +08:00
huiyadanli a83ba61d87 Update version to 0.61.3-alpha.1 2026-06-06 17:30:50 +00:00
ShadowLemoon 974a80eb2b fix(state_machine): 区分状态转场等待与当前节点重试 (#3182) 2026-06-06 14:26:20 +08:00
辉鸭蛋 a33eb1c45f set process priority to normal 2026-06-05 02:50:42 +08:00
躁动的氨气 b561b8db33 feat: 忽略claude (#3179) 2026-06-04 23:04:34 +08:00
Tianxiang Shiand辉鸭蛋 8a7c47b17a fix: 修复 WGC HDR 下传送候选项识别失败 (#3134)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-06-02 23:32:47 +08:00
AI-Avalon 4cb82865d8 Add Japanese localization and docs (#3144) 2026-06-02 23:25:56 +08:00
辉鸭蛋 9479297dcc fixed #2797 复制配置组时配置组中js自定义配置紊乱 2026-06-02 23:11:20 +08:00
huiyadanli d61f804442 Update version to 0.61.2 2026-06-01 13:30:00 +00:00
辉鸭蛋 4747c39ae1 修复 发送webhook请求时,screenshot字段值为空的问题 #2506 2026-05-30 02:13:28 +08:00
huiyadanli 7a6854e7d5 Update version to 0.61.1-alpha.2 2026-05-28 19:19:12 +00:00
辉鸭蛋 6f7c78b474 性能优化(日志模块): 调整日志清理阈值并优化日志输出条件 #3161
将日志文本框的自动清理行数从1000调整为200,减少日志堆积的内存占用。
修改日志输出触发条件,仅当遮罩窗口启用且显示日志框时才写入日志,避免不必要的性能开销。
2026-05-29 03:17:25 +08:00
ShadowLemoon 43701b90f0 refactor: 增强状态机节点注册与重试兜底 (#3159) 2026-05-28 02:08:02 +08:00
huiyadanli 6090cce849 Update version to 0.61.1-alpha.1 2026-05-27 08:55:59 +00:00
cookie981 96cf2d5261 fix:新增一键宏按住时重复(旧)模式 (#3154) 2026-05-27 15:48:14 +08:00
ShadowLemoon 8813235ebf feat: 通过Silero Vad识别对话结束并延后选项选择 (#3130) 2026-05-26 23:48:03 +08:00
cookie981 bbd9634c07 Fix:优化一键宏 (#3150) 2026-05-25 22:56:13 +08:00
ShadowLemoon d7b6ab9365 chore: 调整周日奖励字段名称 (#3149) 2026-05-25 22:53:11 +08:00
ShadowLemoon 13f3951d7f feat: 优化一条龙每周秘境配置与下拉选择显示 (#3142) 2026-05-25 02:58:12 +08:00
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
辉鸭蛋 5096b733b4 feat(GearTriggerPage): 优化齿轮触发器页面布局并添加删除确认提示
将新增触发器按钮从各标签页内部移至标签头部,根据当前选中标签动态显示对应添加按钮
为触发器删除操作添加带有类型区分提示文本的确认弹窗,防止误删
2026-05-18 02:49:05 +08:00
辉鸭蛋 3ac0870169 refactor(gearTriggerPage): 重构触发器页面操作逻辑,改用行内操作按钮
移除全局选中触发器相关的属性、回调及列表选中绑定。将编辑、删除命令改为接收当前行触发器实例作为参数,不再依赖全局选中状态。在列表每行添加操作按钮,替换原顶部工具栏的批量编辑删除功能,同时调整新增按钮布局。
2026-05-18 02:44:51 +08:00
辉鸭蛋 0f05b99d04 refactor(ui页面): 统一采集与锄地和触发器页面的布局风格并清理冗余XAML
调整两个页面的边距与控件样式,移除冗余的网格布局定义和未使用的样式,提升代码可维护性
2026-05-18 02:28:34 +08:00
辉鸭蛋 4978b72107 feat: 新增采集与锄地一键采集工具页面2 2026-05-18 02:05:18 +08:00
辉鸭蛋 3dcc9dde70 feat: 新增采集与锄地一键采集工具页面
新增采集与锄地专用功能页面,支持通过素材名称匹配本地地图追踪任务并一键执行,具体改动如下:
- 新增GatheringAndFarmingPage视图与对应ViewModel,包含角色、食材与特产、掉落物、矿石四个标签页
- 在主窗口导航栏添加采集与锄地页面入口,并将页面注册到应用依赖注入容器
- 优化齿轮任务系统,添加任务组配置属性,实现配置修改自动保存,完善脚本执行参数传递逻辑
- 在任务列表页面新增任务组设置按钮与配置弹窗
- 修复部分代码格式与缩进问题,调整命名空间引用顺序
2026-05-18 02:02:29 +08:00
辉鸭蛋 5f9b8276dc Revert "任务组设置,未review"
This reverts commit 146d455c60.
2026-05-18 01:28:17 +08:00
辉鸭蛋 3cded96c33 Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/BetterGenshinImpact.csproj
2026-05-18 00:49:07 +08:00
cookie981 753c595625 fix:一键宏停止时立即松开所有按键 (#3126) 2026-05-17 23:10:24 +08:00
辉鸭蛋 146d455c60 任务组设置,未review 2026-05-16 22:45:46 +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
辉鸭蛋 e0bdc3a720 历史记录 2026-05-11 22:38:26 +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
辉鸭蛋 7f7a34e9ba feat(gear-task): 引入事件驱动的任务执行与历史记录系统
- 新增 IGearTaskEventBus 接口及默认实现,用于解耦执行器与记录器、UI 投影等消费者
- 新增 IGearTaskResumable 接口,支持任务节点内部恢复(如 Pathing 任务可恢复至特定路径点)
- 重构任务执行流程,使用 GearTaskExecutionRunner 替代旧的 GearTaskExecutionManager
- 实现基于磁盘 JSON 的历史记录存储(IGearTaskHistoryStore),支持执行记录的保存、加载与清理
- 为 PathingGearTask 添加恢复能力,通过 PathingGearTaskResumeState 记录断点状态
- 在 PathExecutor 中集成运行时事件通知,支持路径点进入、完成、传送等事件的发布
- 统一执行事件模型(GearTaskExecutionEvent),包含任务定义、节点路径、时间戳等元数据
- 服务注册更新,使用新的执行器、事件总线、历史记录器等组件
2026-05-11 01:57:29 +08:00
辉鸭蛋 6cdc67c9c3 UI优化 2026-05-10 23:56:49 +08:00
辉鸭蛋 20851919ea UI美化 2026-05-10 20:36:10 +08:00
辉鸭蛋 1dea108516 触发器UI美化 2026-05-10 15:23:05 +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
辉鸭蛋 00e62f80ee perf(geartask): 按需导出路径仓库文件以提升初始化性能
- 将路径仓库的镜像初始化从全量导出改为按需导出,避免首次转换时不必要的文件复制
- 添加目录级导出缓存,避免重复导出同一目录下的文件
- 重构 ScriptRepoUpdater 以支持文件/目录的按需导出功能
2026-05-09 04:52:49 +08:00
辉鸭蛋 0f9bd7f465 fix: 移除冗余的取消令牌传递并集中管理取消令牌
在任务执行时,不再从调用方传递 CancellationContext 的令牌,而是在 GearTaskExecutor 内部统一创建和管理链接的取消令牌。这简化了调用方的代码,并确保了取消令牌的正确生命周期管理。
2026-05-09 04:07:15 +08:00
辉鸭蛋 41f38d9e7a 传入取消ct 2026-05-09 03:55:56 +08:00
辉鸭蛋 ed3ee2c392 无用代码优化 2026-05-09 03:49:28 +08:00
辉鸭蛋 769e08edfd fix: 修复DPI缩放获取和定时触发器同步问题
修复 DpiHelper 在未初始化窗口句柄时获取 DPI 缩放值的问题,现在能正确处理多显示器场景。重构 QuartzSchedulerService 的触发器同步逻辑,确保定时任务正确更新。在添加/编辑触发器时增加 Cron 表达式格式校验,避免无效表达式导致调度失败。同时修复 ScriptService 中任务启动时的线程调度问题。
2026-05-09 02:50:52 +08:00
辉鸭蛋 5a6b074759 Merge branch 'main' into d-v3 2026-05-09 01:14: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
辉鸭蛋 2e8d4b61e3 feat: 原神未在前台时增加定时触发任务确认对话框
在定时触发任务执行前检查原神是否在前台,若不在则显示确认对话框询问用户是否继续执行。防止在用户未准备好时自动启动或切换游戏窗口,提升用户体验和控制权。
2026-05-06 01:45:24 +08:00
辉鸭蛋 cd307bf7b0 refactor: update namespace for gear task classes and improve parameter handling 2026-05-06 01:12:54 +08:00
辉鸭蛋 0653431dd1 Merge branch 'main' into d-v3 2026-05-06 01:08:10 +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
辉鸭蛋 786f2715a7 处理引用类型的任务,处理仓库变动 2026-05-05 03:05:13 +08:00
辉鸭蛋 977b12f9dc Merge remote-tracking branch 'origin/d-v3' into d-v3 2026-05-05 02:30:24 +08:00
辉鸭蛋 17af6e01f8 自动战斗Q技能加入CD判断 2026-05-05 00:01:56 +08:00
辉鸭蛋 20484b1111 Merge branch 'main' into d-v3 2026-05-04 21:07:13 +08:00
辉鸭蛋 5e98ff724f 改名 2026-05-04 21:06:48 +08:00
辉鸭蛋 63bcce3e0b 改名 2026-05-04 21:05:50 +08:00
辉鸭蛋 9a31b347c0 Merge remote-tracking branch 'origin/d-v3' into d-v3 2026-05-04 20:50:50 +08:00
辉鸭蛋 edcbf26a06 Merge branch 'main' into d-v3 2026-05-04 20:50:23 +08:00
辉鸭蛋 e2f84f7edd JS获取当前在小地图上的位置坐标 新增 matchingMethod 的传入 2026-05-04 20:47:49 +08:00
辉鸭蛋 8daa903e8d JS获取当前在小地图上的位置坐标 新增 matchingMethod 的传入 2026-05-04 20:47:21 +08:00
辉鸭蛋 4ad30a725d Merge remote-tracking branch 'origin/d-v3' into d-v3 2026-05-04 19:59:40 +08:00
辉鸭蛋 f61e35f1ef fix style 2026-05-04 19:59:22 +08:00
辉鸭蛋 71833a32ff feat(gear-task): 为定时触发器添加可视化 Cron 表达式选择器
引入新的 CronSchedulePicker 控件,提供预设(每日/每周)和手动两种输入模式,改善用户体验。用户可通过直观界面选择执行时间,无需手动编写复杂的 Cron 表达式。同时更新了默认触发时间并优化了相关验证逻辑。
2026-05-04 16:05:04 +08:00
辉鸭蛋 c920945439 添加执行任务组按钮 2026-05-04 13:46:52 +08:00
辉鸭蛋 b15012ffcd refactor: 移除执行记录相关功能
删除 ExecutionRecord、DailyExecutionRecord 和 ExecutionRecordStorage 类及相关代码
移除 ScriptService 和 ScriptGroupProject 中与执行记录相关的逻辑,包括任务跳过检查和记录保存
简化项目执行流程,专注于核心功能
2026-05-03 19:39:45 +08:00
辉鸭蛋 f0e4ac4db2 Merge branch 'main' into d-v3 2026-05-03 16:43:41 +08:00
辉鸭蛋 de75d02104 fix: 修复禁用HDR时错误删除注册表项的问题
将删除注册表值改为修改值为0,避免HDR设置被完全移除导致游戏可能重新启用HDR
2026-05-03 16:40:03 +08:00
huiyadanli 36c2e25792 Update version to 0.60.2-alpha.3 2026-05-02 14:27:07 +00:00
辉鸭蛋 8ef3d47a7f Merge branch 'main' into d-v3 2026-05-02 22:26:19 +08:00
zhousenyu 6b9ac1b5d0 fix: 任务启动阶段无法通过快捷键正常终止,启动阶段强制关闭游戏时启动按钮无法复位 (#3036) 2026-05-02 19:24:51 +08:00
躁动的氨气and辉鸭蛋 6071b4096f fix: 修复某些js回调在突然终止后弹出的v8报错 (#3072)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-05-02 19:20:47 +08:00
kaedelcb dc1c25ee00 优化添加一条龙任务添加的弹窗UI (#3068) 2026-05-02 18:57:06 +08:00
KangkangTaoand辉鸭蛋 8ca6830c4b fix: 跳过空月祝福使用硬件输入模拟代替窗口消息避免云原神中不生效 (#3080)
* fix: 跳过空月祝福使用硬件输入模拟代替窗口消息避免云原神中不生效

* 加入停顿

---------

Co-authored-by: 辉鸭蛋 <[email protected]>
2026-05-02 18:54:17 +08:00
辉鸭蛋 e5aa33c577 原神HDR自动关闭 2026-05-02 18:23:13 +08:00
辉鸭蛋 a76767499d feat: 更新.gitignore,添加项目规则文档和技能说明 2026-05-02 17:27:56 +08:00
云端客and辉鸭蛋 3470c5e30b feat(genshin): 添加通过OCR识别当前角色UID的功能 (#2988)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-05-02 16:11:03 +08:00
躁动的氨气 10ee93e8bb feat: 为js提供html遮罩 (#2975) 2026-05-02 15:55:34 +08:00
躁动的氨气 255bf653e8 feat: 地图编辑器使用全局战斗策略,避免导出带BOM (#3092) 2026-05-01 18:49:56 +08:00
ddaodan 4a17383f86 修复自动地脉花战后切队与结束检测问题 (#3088) 2026-04-30 10:29:09 +08:00
躁动的氨气 edc5580267 feat: 扩展地图编辑器功能,支持直接运行 (#3090) 2026-04-30 10:15:50 +08:00
辉鸭蛋 dfef6ddf30 优化 后台对话结束,已自动切回游戏前台 的时机 2026-04-29 01:39:06 +08:00
辉鸭蛋 0cc48ce6d8 Disable similarityComment feature
Disable similarity comments in repo-bot configuration.
2026-04-29 00:03:50 +08:00
躁动的氨气 6be85a03af feat: 提高莉奈娅挖矿容错,删除js处的调用接口 (#3073) 2026-04-28 22:57:05 +08:00
火山andcoderabbitai[bot] e78d54ba2a 修改调度器配置设置的默认值,提供新建配置组的部分预设参数 (#3077)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-04-27 19:46:14 +08:00
ddaodan 1fd45c42b1 提醒快捷键与游戏键位冲突 (#3083) 2026-04-27 19:40:38 +08:00
Bread Grocery e06b105365 fix(js): 修复模块被导入时副作用代码被重复执行 (#3070) 2026-04-24 10:32:14 +08:00
huiyadanli 83637172fd Update version to 0.60.2-alpha.2 2026-04-21 11:50:40 +00:00
躁动的氨气 b0a1bb019c fix: 莉奈娅挖矿引用问题 (#3063) 2026-04-20 21:26:21 +08:00
kaedelcb 304147f965 修复游泳检测问题 (#3055) 2026-04-20 13:52:11 +08:00
躁动的氨气 99a17010d2 feat: 使用yolo进行莉奈娅挖矿 (#3058) 2026-04-20 13:49:53 +08:00
ddaodan fb527a13c4 自动地脉花补充战斗中寻敌配置 (#3059) 2026-04-20 13:49:43 +08:00
辉鸭蛋 2ea663b0ff #3054 越界逻辑错误修复 2026-04-16 23:57:57 +08:00
huiyadanli bbf1be3de9 Update version to 0.60.2-alpha.1 2026-04-16 15:40:56 +00:00
kaedelcb 3586e37c69 战斗过程卡切换角色优化 (#3054) 2026-04-16 23:37:52 +08:00
辉鸭蛋 4896d0344a fix(AutoEat): 将复活按键改为跟随快捷使用小道具键位 #2930
复活逻辑不再硬编码为Z键,改为使用`GIActions.QuickUseGadget`模拟输入,使其与游戏内的“快捷使用小道具”键位配置保持一致。
2026-04-16 00:55:28 +08:00
辉鸭蛋 c1d0a53110 OCR不再限制算子 2026-04-16 00:30:21 +08:00
辉鸭蛋 0eedfb6969 实时任务中对遮罩的操作异步化 2026-04-16 00:29:56 +08:00
LXYan2333 d0c02717e8 胡桃 10aaz 宏 (#3049) 2026-04-15 23:34:37 +08:00
kaedelcb 2a53fb9742 新增基于怪物死亡经验判断是否执行聚集材料 (#3051) 2026-04-15 23:34:07 +08:00
ShadowLemoon bd8451a190 perf: 增强幽境任务鲁棒性 (#3050) 2026-04-15 23:33:28 +08:00
辉鸭蛋 ee500b2971 Update OpenAI model version in repo-bot.yml 2026-04-15 11:20:56 +08:00
Yushao Chen (Jerry)andJerryChen97 b0a1715ba3 fix: 移除 TrySwitch 中遗留的调试用 SaveImage 调用 (#3032)
Co-authored-by: JerryChen97 <[email protected]>
2026-04-12 21:57:00 +08:00
ddaodan 33760242ea feat: 地脉花新增"蒙德8-风车镇"路径 (#3029) 2026-04-12 21:56:30 +08:00
Yushao Chen (Jerry)andJerryChen97 7d91fba327 fix: FindActiveIndexRectByColor 方法3 返回 0-based 索引修正为 1-based (#3035)
Co-authored-by: JerryChen97 <[email protected]>
2026-04-12 21:54:16 +08:00
Jamis 8956c306c2 增加支持新地图空之神殿 (#3041) 2026-04-12 21:52:53 +08:00
ddaodan a7dac95468 优化 GitHub Issue 模板 (#3030) 2026-04-11 18:47:25 +08:00
huiyadanli dea40ce177 Update version to 0.60.1 2026-04-09 16:18:49 +00:00
辉鸭蛋 410c3f2a92 处理 Paddle OCR 逻辑可能造成的 JSON 序列化问题 2026-04-10 00:03:19 +08:00
ema 30d11bed4c 替换修复秘境选择控件 (#3019) 2026-04-09 23:21:35 +08:00
郝凯阳 cfebcd0b8d auto tcg: update character card config to v6.5 (#3016) 2026-04-09 18:08:57 +08:00
Jamis 43f2263cfa 增加空之神殿TP点位信息 (#3015) 2026-04-09 18:08:45 +08:00
huiyadanli f9dd661c05 Update version to 0.60.0 2026-04-08 13:41:19 +00:00
躁动的氨气 24128ee64b feat: 莉奈娅挖矿动作 (#2997)
* feat: 莉奈娅挖矿动作

* Add mining action for character 莉奈娅

* Update MiningHandler.cs

* Update MiningHandler.cs

* Update MiningHandler.cs
2026-04-08 19:57:12 +08:00
辉鸭蛋 1255895e7f 删除执行记录的逻辑 2026-04-06 23:25:42 +08:00
辉鸭蛋 0e49ed0ea0 Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/App.xaml.cs
2026-04-06 21:34:59 +08:00
辉鸭蛋 c8d10614c5 翻译排除了一些动态文本的场景 2026-04-06 16:02:56 +08:00
Jamis 5c7e8e8f11 更新6.5.0传送锚点信息 (#3004) 2026-04-06 15:17:35 +08:00
ddaodan 907fe5b3c2 优化通知事件选择界面 (#3001) 2026-04-06 13:08:28 +08:00
ddaodan 4c81109f0d feat: 聊天界面打开时屏蔽热键 (#3000) 2026-04-06 01:42:03 +08:00
辉鸭蛋 11102a4be2 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2026-04-05 20:57:45 +08:00
辉鸭蛋 c1c578d256 fix: 优化适龄提示窗口检测逻辑避免频繁点击 #2992
- 使用OCR识别适龄提示文字,避免仅依赖按钮检测导致的误点击
- 添加1秒检测间隔防止频繁触发OCR识别
- 记录最近识别的文字区域用于后续判断
2026-04-05 20:57:43 +08:00
huiyadanli 1690a727fc Update version to 0.59.2-alpha.3 2026-04-05 12:38:22 +00:00
辉鸭蛋 ee928a6847 优化config.json读取或者写入失败时候的异常处理。读取失败会备份原来的config文件并报错 2026-04-05 20:36:26 +08:00
辉鸭蛋 4ad7db06ae fix(ui): 处理桌面组合禁用时的主题应用异常 #2678
当系统桌面组合功能被禁用时,应用 Mica/Acrylic 主题会抛出 COM 异常(HRESULT: 0x80263001)。现通过异常捕获机制,在检测到此特定错误时回退到纯色背景方案,确保程序在受限环境下仍能正常运行。

- 在 ApplyThemeToWindow 方法中添加异常处理逻辑
- 引入 ApplyFallbackTheme 方法应用纯色后备主题
- 根据主题类型提供对应的后备背景色
2026-04-05 20:21:54 +08:00
ToXz 8a6194f374 feat : Hoyolab map provider with 3 language selector (#2987) 2026-04-05 19:45:57 +08:00
ddaodan b1f1fe913a fix: 修复纪行可选奖励导致流程卡住并补充日志提醒 (#2995) 2026-04-05 01:36:02 +08:00
DarkFlameMaster c8be442943 docs: 给文档链接增加 www 前缀 (#2996) 2026-04-05 01:35:15 +08:00
huiyadanli 3d394475e1 Update version to 0.59.2-alpha.2 2026-04-04 12:26:10 +00:00
辉鸭蛋 da068549fe chore: update MimeKit package version to 4.15.1 2026-04-04 20:23:34 +08:00
辉鸭蛋 ca249206ae 更新依赖包版本与元数据 2026-04-04 20:21:54 +08:00
ddaodan f80814952b feat: 自动地脉花更新挪德卡莱3-月矩力试验设计局的路径 (#2991) 2026-04-03 17:31:05 +08:00
辉鸭蛋 38f41ac573 Merge remote-tracking branch 'origin/main' 2026-04-02 00:36:37 +08:00
辉鸭蛋 399b9d4adb 并发生成SIFT 2026-04-02 00:36:31 +08:00
秋云 091bbb2865 fix: 捕获OpenCV抛出的异常 (#2985) 2026-04-01 10:56:11 +08:00
ddaodan ec7b00e35e fix: 修复自动地脉花领奖流误判和队伍切换回退 (#2981) 2026-03-31 11:01:02 +08:00
ShadowLemoon c5f7a68e79 feat: 通知设置添加超链接查看事件id (#2976) 2026-03-29 21:45:36 +08:00
辉鸭蛋 e0c56a74ea 修改新版自动秘境奖励领取的通知时机,截图能够截到奖励内容 2026-03-29 01:15:15 +08:00
huiyadanli 3f1dc374eb Update version to 0.59.2-alpha.1 2026-03-28 16:33:40 +00:00
辉鸭蛋 eaa412d8c9 Merge remote-tracking branch 'origin/main' 2026-03-29 00:31:29 +08:00
辉鸭蛋 03a4102fe7 Revert "文本识别的模糊匹配功能 (#2799)"
This reverts commit e9d11f7267.
2026-03-29 00:31:13 +08:00
辉鸭蛋 70c5a84bed Revert "尝试修复JSON序列化问题,本质问题是OCR模块,用纯托管 argmax 替代该路径。"
This reverts commit e958e24d4e.
2026-03-29 00:30:41 +08:00
ddaodan 147f466fb9 fix: 修复自动地脉花追踪按钮识别与奖励页树脂点击异常 (#2971) 2026-03-28 20:58:23 +08:00
huiyadanli 4cbdaa6ff8 Update version to 0.59.1 2026-03-26 18:48:16 +00:00
辉鸭蛋 8300d9dd7c 自动烹饪支持自动识别已经满熟练度 #2958 2026-03-27 02:46:03 +08:00
辉鸭蛋 5b2701a68f Merge remote-tracking branch 'origin/main' 2026-03-26 22:13:09 +08:00
辉鸭蛋 3d84638c55 Revert "加入点击 #1599"
This reverts commit 0d8de96e17.
2026-03-26 22:08:45 +08:00
ddaodan 7f6c3c408b fix: avoid party reswitch during auto ley line pathing (#2955) 2026-03-26 19:30:46 +08:00
提瓦特钓鱼玳师 fc7993afda 添加JS脚本文件夹下文件重命名功能 (#2960) 2026-03-26 13:40:33 +08:00
辉鸭蛋 040a5e8417 Merge remote-tracking branch 'origin/main' 2026-03-24 23:34:38 +08:00
辉鸭蛋 1c33bb9282 领取地脉花奖励后扫描周围掉落物光柱,默认关闭 2026-03-24 23:34:30 +08:00
huiyadanli f923a8a4d2 Update version to 0.59.0 2026-03-24 15:27:39 +00:00
辉鸭蛋 f658bf85ee Merge remote-tracking branch 'origin/main' 2026-03-23 02:48:46 +08:00
辉鸭蛋 0d8de96e17 加入点击 #1599 2026-03-23 02:48:40 +08:00
huiyadanli e9413f4214 Update version to 0.58.4-alpha.1 2026-03-22 18:41:24 +00:00
辉鸭蛋 aef3fa913b 自动烹饪修改成独立任务 (#2949) 2026-03-23 02:31:14 +08:00
躁动的氨气 d55b1d867b feat: 开门时适龄提示自动关闭 (#2948) 2026-03-23 02:04:54 +08:00
辉鸭蛋 311c8b2f37 Merge remote-tracking branch 'origin/main' 2026-03-22 15:53:21 +08:00
辉鸭蛋 1a478affb2 后台对话完之后自动将原神切到前台 #2350 2026-03-22 15:53:10 +08:00
辉鸭蛋 da6d956ef1 Comment out '需要更多信息' section
Comment out the '需要更多信息' section in the YAML configuration.
2026-03-22 15:26:56 +08:00
辉鸭蛋 955d7d51d9 Disable AI classification in repo-bot configuration 2026-03-22 15:20:45 +08:00
huiyadanli b4053e9357 Update version to 0.58.3-alpha.4 2026-03-22 06:53:31 +00:00
辉鸭蛋 a0d8133558 删除多余的启动游戏逻辑 #2943 #2942 2026-03-22 14:14:49 +08:00
辉鸭蛋 99f4f54ff7 文案调整 2026-03-22 02:51:56 +08:00
辉鸭蛋 c8a8d6217a 检测到游戏内小地图锁定配置 #1371 2026-03-22 02:48:02 +08:00
辉鸭蛋 cd978327fc fix: 修复最小化时候截图失败导致截图器没法正常截图,导致主界面卡顿的问题 #2939 #2851 2026-03-22 02:13:55 +08:00
辉鸭蛋 b0b13cb36d 删除 Starward 协议注册 相关日志 2026-03-22 01:52:54 +08:00
辉鸭蛋 beb36ff41a fix: 修复地图遮罩关闭时UI状态未正确重置的问题 #2940
当关闭地图遮罩功能时,确保所有挂起的计算任务被清理,并重置UI状态到初始值。同时修复了在配置禁用时UI状态未同步更新的问题。
2026-03-22 01:50:44 +08:00
Tristan 713589734b feat: 自动地脉花支持领奖后扫描掉落物 (#2928) 2026-03-21 16:37:29 +08:00
辉鸭蛋 eedce17a9c chore: update BetterGI.Assets.Other package version to 1.0.15 2026-03-21 12:55:54 +08:00
辉鸭蛋 4572b94122 Merge remote-tracking branch 'origin/main' 2026-03-21 12:31:49 +08:00
辉鸭蛋 5831e3671c 加大对话区判定次数 #2936 2026-03-21 12:31:41 +08:00
ddaodan e46076eaaa chore: 自动忽略历史 Issue (#2931) 2026-03-19 00:16:12 +08:00
辉鸭蛋 c553a49f18 Update repo-bot.yml 2026-03-18 00:29:16 +08:00
秋云 53810d34b8 fix: 优化TpTask惯性导航(误识别),处理初始未识别 (#2920) 2026-03-17 20:12:48 +08:00
ddaodan 875434b492 chore: 接入 Repo Bot Issue 助手 (#2916) 2026-03-17 18:57:37 +08:00
huiyadanli 565510ebe6 Update version to 0.58.3-alpha.3 2026-03-16 18:27:45 +00:00
辉鸭蛋 eec4518605 切换角色问题测试用代码 2026-03-17 02:25:31 +08:00
辉鸭蛋 201cbf1629 关闭开书 #2686 2026-03-17 02:10:06 +08:00
辉鸭蛋 33013fd7a5 OCR修改默认强制推理配置 2026-03-17 01:28:14 +08:00
辉鸭蛋 f9b707b1ac Merge remote-tracking branch 'origin/main' 2026-03-16 21:47:38 +08:00
辉鸭蛋 68ebf2eb4b 修复 E_ACCESSDENIED (0x80070005) 报错。
这是一种导致 he BetterGenshinImpact.View.Pages.HomePage page does not have a parameterless constructor. If you are using Wpf.Ui.Abstractions.INavigationViewPageProvider do not navigate initially and don't use Cache or Precache. 错误的场景
2026-03-16 21:47:25 +08:00
huiyadanli 2c28cc2335 Update version to 0.58.3-alpha.2 2026-03-15 02:47:28 +00:00
辉鸭蛋 47a4983c16 Merge remote-tracking branch 'origin/main' 2026-03-15 10:43:32 +08:00
辉鸭蛋 c5a9427ca7 最后匹配自定义游戏进程名 #2909 2026-03-15 10:43:25 +08:00
huiyadanli 12e6296059 Update version to 0.58.3-alpha.1 2026-03-14 08:22:23 +00:00
辉鸭蛋 cf344b2d39 修复User目录清空后,无法自动创建目录的问题 2026-03-14 16:15:56 +08:00
辉鸭蛋 e958e24d4e 尝试修复JSON序列化问题,本质问题是OCR模块,用纯托管 argmax 替代该路径。 2026-03-14 16:12:11 +08:00
辉鸭蛋 26416b00b5 Merge remote-tracking branch 'origin/main' 2026-03-14 15:56:15 +08:00
mno 54301e1e02 修改check触发检查的时机 (#2904) 2026-03-12 10:01:55 +08:00
Shadow-LemonandShadowLemoon 1e9b72e547 fix: 修复同时存在多个脚本仓库文件夹时迁移优先级出错 (#2906)
Co-authored-by: ShadowLemoon <[email protected]>
2026-03-12 00:08:26 +08:00
辉鸭蛋 d660f79b4c 修改自动战斗ready指令的表现 2026-03-11 23:06:06 +08:00
huiyadanli 48bbad9853 Update version to 0.58.1-alpha.1 2026-03-11 05:35:14 +00:00
Shadow-LemonandShadowLemoon 5dcbd9b577 fix: 修复命令行启动时自动更新阻塞导致 StartGameTask 跳过等待主界面的问题 (#2902)
Co-authored-by: ShadowLemoon <[email protected]>
2026-03-11 09:56:01 +08:00
MistEO bb1f6d7281 ci: check owner for mirrorc (#2901) 2026-03-11 09:53:44 +08:00
FishmanTheMurloc d4ef75344e 选择鱼饵增加等待时间,以降低鱼饵尚未出现时执行动作的频率 (#2900) 2026-03-10 20:41:38 +08:00
huiyadanli f614695a3a Update version to 0.58.0 2026-03-09 16:55:41 +00:00
辉鸭蛋 77306168f9 chore: 更新 BetterGI.Assets.Other 依赖至版本 1.0.13 2026-03-09 23:47:09 +08:00
辉鸭蛋 dee418cbe5 Merge remote-tracking branch 'origin/main' 2026-03-09 23:43:28 +08:00
辉鸭蛋 226785e8a4 Yap 的推理对象改为懒加载。index_2_word.json 修改成 Newtonsoft.Json 反序列化 #2890 2026-03-09 23:43:20 +08:00
DarkFlameMaster 5a5b77266e feat(JS): 支持调用 C#中含out/ref参数的方法 (#2884)
* feat(JS): 支持调用 C#中含out/ref参数的方法

* 新增NewVarOfArr方法用于支持交错数组

* 多删了一行
2026-03-09 23:42:44 +08:00
辉鸭蛋 864efb42a3 fix bug 2026-03-09 03:07:21 +08:00
辉鸭蛋 32582e39a9 Merge remote-tracking branch 'origin/main' 2026-03-08 21:30:47 +08:00
辉鸭蛋 6bcb63e996 修复宝箱图标刚好被遮住的场景 #2889 2026-03-08 21:30:38 +08:00
云端客 65b5032e6e [开放JS 调用 API]自动幽境危战 (#2882) 2026-03-08 21:13:18 +08:00
DarkFlameMaster b9e1c37b67 删除一条龙配置的弹窗主题与主窗口保持一致 (#2887) 2026-03-08 18:01:11 +08:00
guamian a5829ed6bb 尝试修复游泳检测炸内存 (#2883) 2026-03-06 23:06:40 +08:00
DarkFlameMaster 8b7d2353e5 feat(js):地图追踪增加读取目录下的内容等方法 (#2875)
* feat(js):地图追踪增加读取目录下的内容等方法

* refactor(AutoPathingScript): 重构文件操作方法到LimitedFile类

* fix

* docs(AutoPathingScript): 修正方法参数注释中的默认值描述

* 避免重复初始化实例,给恢复游戏窗口焦点的日志也加上当前窗口名
2026-03-05 01:13:52 +08:00
ShadowLemoon c3b8c9e78f 移除幽境危战调试日志 (#2881) 2026-03-05 01:12:44 +08:00
mno b49910873e 添加check动作 (#2864) 2026-03-01 22:10:33 +08:00
Jamis ea6a9a4af2 More granular control over pre-teleport delay (#2866) 2026-03-01 22:10:14 +08:00
辉鸭蛋 a51213dceb Merge remote-tracking branch 'origin/main' 2026-03-01 01:59:59 +08:00
辉鸭蛋 e3c451cd92 不再翻译日志 2026-03-01 01:59:52 +08:00
DarkFlameMaster e69283c3f2 更新蒙德凯瑟琳地图追踪文件 (#2861) 2026-02-28 23:59:29 +08:00
ddaodan 23de87d1a6 feat: 为自动地脉花配置新增万叶与琴的拾取选项 (#2862) 2026-02-28 23:59:04 +08:00
huiyadanli dad2e8ef7d Update version to 0.57.2-alpha.1 2026-02-27 17:14:21 +00:00
辉鸭蛋 7e944e18fb 法尔伽信息补充 2026-02-28 01:04:47 +08:00
辉鸭蛋 f1154e6ef7 地图遮罩改为异步任务,不影响自动拾取 2026-02-28 00:36:10 +08:00
DarkFlameMaster b2d5988d24 fix:适配秘境限时全开的UI改动 (#2854) 2026-02-26 21:38:36 +08:00
郝凯阳 c2b68cfee9 auto tcg: update character card config to v6.4 (#2849) 2026-02-26 18:32:33 +08:00
HSHMENG 6668a89fa7 七圣召唤配置文件中可以设置骰子数量增减 (#2832) 2026-02-26 10:15:53 +08:00
ddaodan 01f1beba0b feat: 自动地脉花独立战斗配置与OCR遮罩 (#2829) 2026-02-26 10:13:38 +08:00
Guest Liang 9e3c8920ba 修复七圣召唤月之五伊涅芙会导致手牌不可调和的死循环 (#2848) 2026-02-26 10:08:44 +08:00
辉鸭蛋 ce31169f66 fix: 修复小地图遮罩在主界面外的显示逻辑 2026-02-26 00:44:26 +08:00
辉鸭蛋 53854e6d28 refactor: 简化进程去重逻辑,直接使用 GroupBy 和 Select
使用 GroupBy 和 Select 直接获取唯一的进程对象,避免创建中间字典和手动释放重复的 Process 对象,使代码更简洁。
2026-02-24 19:29:09 +08:00
huiyadanli 01c506fa13 Update version to 0.57.1-alpha.3 2026-02-24 07:36:36 +00:00
辉鸭蛋 95e0f01753 新增小地图遮罩,在小地图上展示资源点位 (#2830) 2026-02-24 15:34:50 +08:00
DarkFlameMaster 4aaca366f0 feat: JS级联选择 和 秘境选择 滚轮事件禁止穿透至其他窗口 (#2828) 2026-02-24 15:21:20 +08:00
云端客and辉鸭蛋 cac0dfc754 开放自动地脉花 JS调用 (#2789)
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-02-24 11:12:16 +08:00
huiyadanli 847bc8970e Update version to 0.57.1-alpha.2 2026-02-23 16:03:39 +00:00
this-Fish d4d99d34bc feat: 为快速尘歌壶任务增加离开功能,支持进出双向操作 (#2822) 2026-02-23 19:02:45 +08:00
辉鸭蛋 f86abe3ceb 支持任意文件名的启动 (#2819) 2026-02-23 13:18:18 +08:00
躁动的氨气 b1c6e9e4e3 Revert "feat: 自动拾取文本识别帧间连续性检查 (#2676)" (#2817) 2026-02-22 19:38:10 +08:00
DarkFlameMaster d632bdd9fc fix:自动拾取黑名单配置文本框复制剪切时UI短暂无响应 (#2818) 2026-02-22 19:37:47 +08:00
辉鸭蛋 fe61549c95 彻底删除 实验功能 遮罩以原神子窗体方式启动 UseSubform 2026-02-22 18:17:38 +08:00
辉鸭蛋 6832d0f8d8 revert revert #2809 with #2763 , 减轻死锁问题的表现 2026-02-22 18:03:52 +08:00
辉鸭蛋 a872dde7c8 自动拾取排除:「月谕圣牌」收藏 2026-02-22 18:02:26 +08:00
辉鸭蛋 b4cbfdc620 Merge branch 'main' into d-v3 2026-02-22 00:48:46 +08:00
ShadowLemoon 12423edd6e fix: 修复迁移订阅触发时机 (#2811) 2026-02-21 11:46:24 +08:00
huiyadanli 9fe0209122 Update version to 0.57.1-alpha.1 2026-02-20 16:08:23 +00:00
辉鸭蛋 6e49368f0a 修复 #2804,树脂不足时候未终止自动秘境 2026-02-20 23:56:29 +08:00
辉鸭蛋 f80939dad4 去除所有 Cv2.ImRead ,解决中文路径问题 2026-02-20 22:28:45 +08:00
ShadowLemoon f7976b0bbd feat: 根据文件夹名字和内容重合度区分仓库;启动时自动更新仓库和订阅 (#2767)
* feat: 实现启动时自动更新已订阅脚本及多仓库分离存储

- ScriptConfig: 新增 AutoUpdateSubscribedScripts 配置项
- ScriptRepoUpdater: 动态 CenterRepoPath, 按仓库URL分离存储
  - 内容重合度检测(Jaccard系数)判断仓库异同
  - URL→文件夹名持久化映射(repo_folder_mapping.json)
  - repo_updated.json 存放于各自仓库文件夹内
  - AutoUpdateSubscribedScripts 启动时自动更新订阅脚本
  - 静默同步仓库、渠道URL解析、检出更新脚本
- RepoWebBridge: 使用动态路径, 辅助方法改为 internal
- MainWindowViewModel: 启动时调用自动更新

* feat: 基于内容重合度的导入zip仓库

* perf: 合并默认仓库url映射

* perf: 清理兼容字段

* perf: 添加线程锁以避免并发调用

* fix: 缓存FolderMapping、修复重合度异常返回值、目录扫描异常隔离、移除未使用变量

* perf: 优化更新流程

* perf: 内存缓存添加锁

* fix: 修复更新状态逻辑,确保克隆失败时不标记为已更新

* perf: 文件夹映射先写磁盘再写缓存

* refactor: 简化生成唯一文件夹名称的方法,移除不必要的参数

* fix: ResetRepo加写锁并清理URL映射条目

* perf: 优化重合度算法

* docs: 更新注释

* fix: 仅重置实际更新成功的脚本的 hasUpdate 标记

* feat: 手动一键更新按钮

* feat: 订阅路径迁移至独立文件存储并简化更新逻辑

- 订阅数据从 config.json 迁移到 User/subscriptions/{repo}.json 独立文件
- 添加 ReaderWriterLockSlim 保护订阅文件并发读写
- 使用 System.Text.Json + ConfigService.JsonOptions 序列化
- 新增 RepoWebBridge.GetSubscribedScriptPaths() 桥接方法
- 启动时自动从旧 config.json 迁移订阅数据到独立文件
- 合并手动/自动更新为 UpdateAllSubscribedScriptsCore 共用核心
- 移除 hasUpdate 检查,直接全量更新所有订阅脚本
- 移除冗余 logPrefix 参数

* refactor: 简化启动时自动更新调用

- 移除 Task.Run + try-catch 包装,异常处理已内置于方法中
- 直接使用 fire-and-forget 异步调用

* fix: 订阅目录命名改为 PascalCase (Subscriptions)

* refactor: 移除死代码和冗余中间层方法

* fix: ReadSubscriptionFile 异常时记录日志避免订阅数据静默丢失

* fix: 进度条改为Indeterminate模式、异常日志补全、订阅去重、迁移批量写入、锁注释

* refactor: 提取 ReadFolderMappingFromDisk 消除映射方法嵌套 try

* fix: 补全静态方法异常日志、WriteSubscriptionFile异常保护、ManualUpdate注释

* fix: ManualUpdateSubscribedScripts 加 try-catch 兜底并提示用户重置仓库

* fix: Dialog打开时检测后台自动更新状态,自动禁用按钮并显示进度提示

- ScriptRepoUpdater 新增 IsAutoUpdating 标志和 AutoUpdateStateChanged 事件
- ScriptRepoWindow 订阅事件,自动更新期间显示进度条、禁用所有操作按钮并 Toast 提示
- 更新仓库/重置仓库按钮也加上 IsEnabled 绑定 IsUpdating

* fix: 将自动更新调用包裹在 Task.Run 中避免 UI 线程阻塞

AutoUpdateSubscribedScripts 的 await 后续会被 WPF SynchronizationContext
调度回 UI 线程,导致大量 Git checkout 和文件 IO 操作阻塞界面。
用 Task.Run 确保整个流程在线程池执行。

* fix: 进度条分离 IsProgressIndeterminate 属性,按操作类型正确切换确定/不确定模式

* refactor: 消除 pathing 展开重复逻辑、用布尔字段替换字符串比较追踪状态来源、补全锁注释、统一日志方式

* fix: ExpandTopLevelPaths 泛化展开所有 PathMapper 顶层 key 防止误删用户目录,迁移移入锁内

* fix: 命令行启动配置组/一条龙前先等待自动更新订阅脚本完成

* feat: 添加命令行启动时是否先自动更新选项

* fix: 修复按钮位置
2026-02-20 15:09:17 +08:00
Takaranoao e9d11f7267 文本识别的模糊匹配功能 (#2799)
* chore: add AGENTS.md to .gitignore

* feat(config): 新增 AllowDuplicateChar OCR配置项

* refactor(ocr): Rec 暴露protected成员、提取RunInference、支持AllowDuplicateChar

* feat(ocr): 打通 AllowDuplicateChar 参数链 PaddleOcrService → Rec

* feat(ocr): OcrUtils 新增 CreateLabelDict/CreateWeights 工具方法

* feat(helpers): 新增 LruCache 缓存工具类

* feat(ocr): 新增 RecMatch DP模糊匹配识别器

* test(helpers): 新增 LruCache 单元测试

* test(ocr): 新增 RecMatch.GetTarget / CreateLabelDict 单元测试

* fix(ocr): 修复 RecMatch 中权重矩阵乘法的使用方式

* refactor(ocr): 合并 RecMatch 到 Rec,提取可测试静态方法,补充单元测试

将 RecMatch 子类合并到 Rec 中,消除继承关系和重复的批处理逻辑(提取 RunBatch<T>)。
将 GetTarget 核心逻辑和 GetMaxScoreDP 提取为 OcrUtils 静态方法以便独立测试。
重命名测试文件并新增 16 个单元测试覆盖 MapStringToLabelIndices、GetMaxScoreDP、CreateWeights。

* feat(ocr): 将 Rec.RunMatch 暴露给 JS 引擎和内部 C# 代码

新增 IOcrMatchService 接口,提供基于 DP 模糊匹配的 OcrMatch/OcrMatchDirect 方法,
返回 0~1 置信度分数。PaddleOcrService 实现该接口,OcrFactory.PaddleMatch 保证
非 null 返回(引擎不支持时自动回退到普通 OCR + 编辑距离字符串比较)。
BvPage 新增 OcrMatch/WaitForOcrMatch 供 JS 脚本使用,阈值可通过配置调整。

* feat(ui): 为 OCR 配置添加允许重复字符和模糊匹配阈值的设置项

在通用设置页 OCR 配置区域新增两个控件:
- 允许连续重复字符(AllowDuplicateChar)开关
- OCR模糊匹配阈值(OcrMatchDefaultThreshold)输入框

* fix: 修复 PR #2799 代码审查中发现的多项问题

- 修复 Rec.cs 空文本时 score/sb.Length 除零产生 NaN
- 修复 BvPage.cs rect==default 时同一对象被双重 Dispose
- 移除 Rec.cs Finalizer 避免 GC 线程加锁死锁
- 移除 CacheHelper WeakKey 无效功能,简化为直接 Dictionary 查找
- 添加 weights 数组长度与模型输出维度校验
- 修复 CreateLabelDict 空格标签索引冲突
- 修复 GetMaxScoreDP availableCount=0 除零
- 修复 OcrMatchFallbackService Contains 大小写敏感
- 修复 BvPage.cs DefaultRetryInterval=0 除零
- 添加 OcrMatchDefaultThreshold [0,1] 范围约束
- 提取 PaddleOcrService BGRA→BGR 转换辅助方法
- 使用 Interlocked.CompareExchange 修复 OcrFactory Fallback 线程安全
- 增大 LruCacheTests BuilderTest TTL 裕量避免 CI 不稳定
- 更新 .gitignore 注释

* fix: 修复 OcrMatch 归一化分母导致多区域匹配分数过低的 bug,改进 UI

- 修复 GetMaxScoreFlat 中 availableCount 使用非空图像数作为分母,
  导致多文字区域场景下匹配分数被过度稀释的问题,改为使用 target.Length
- AllowDuplicateChar 设置项添加"需重新加载OCR引擎"的提示
- OCR模糊匹配阈值控件从 TextBox 改为 Slider + 数值显示
- 移除 Det 类中有问题的 finalizer(含锁的析构函数可能导致死锁)
- 补充多区域场景的单元测试

* feat(ocr): 添加队伍切换时使用OcrMatch模糊匹配的选项和相关配置

* fix(ui): 更新匹配成功阈值默认值为 0.8

* fix(ocr): 修复队伍切换逻辑中的空值处理和优化代码结构

* refactor: 简化 LruCache,移除弱引用支持和 Builder 模式

- 移除有 TOCTOU bug 的 WeakReference 支持(且无实际使用方)
- CacheItem 类改为 ValueTuple 减少堆分配
- 无过期时不再赋值 DateTime.MaxValue,过期检查短路跳过
- 移除仅剩两参数的 LruCacheBuilder,直接使用构造函数

* fix(ocr): 修复 CreateWeights 中空格字符权重写入错误索引的 bug

复用 CreateLabelDict 构建索引映射,确保空格映射到 labels.Count+1,
与 CreateLabelDict 保持一致。添加对应测试用例。

* fix(ocr): 修复 GCHandle.Alloc 失败时 finally 中 Free 掩盖原始异常的问题

* fix(ocr): 添加队伍选择按钮存在性检查,避免 PartySetupFailedException

* fix(ocr): 调整 OcrMatchDefaultThreshold 的 TickFrequency 为 0.01

* fix(ocr): 修复区域裁剪逻辑,确保裁剪尺寸不为负值

* fix(ocr): 优化字符置信度提取逻辑,直接按目标字符索引查找置信度

* fix(ocr): 修正变量命名以保持一致性,调整方法名大小写

* fix(ocr): 修改 CreateWeights 方法以使用标签字典和标签计数,优化权重创建逻辑

* fix(ocr): 更新 OCR 置信度阈值设置,确保阈值范围为 0.01 到 0.99,并优化相关逻辑
2026-02-20 15:08:46 +08:00
Takaranoao 20fe152630 尝试修复一些ROI越界 (#2808)
* fix: 修复多处 OpenCV ROI 越界导致的断言失败

在低分辨率(如 1280x720)下,多处 Rect 坐标计算未做边界保护,
直接传入 SubMat / new Mat(mat, rect) 时触发 OpenCV ROI 断言崩溃。

修复位置:
- Behaviours.cs: fishBoxRect 计算结果钳位到图像边界,修复钓鱼任务越界
- GridScreen.cs: PostProcess 中幻影格子(插值生成)越界时直接丢弃
- ImageRegion.cs: DeriveCrop 两个重载统一加入坐标钳位与有效性校验
- GetGridIconsTask.cs: CropResizeArtifactSetFilterGridIcon X/Y 坐标加非负保护
- GeniusInvokationControl.cs: 角色区域扩展和 HP 区域 Y 偏移各加边界保护

* chore: 为 AutoFishingTask 鱼饵图标裁剪补充说明注释

* refactor: 提取 Rect 钳位逻辑为共享扩展方法 ClampTo

将 6 处重复的 ROI 钳位代码统一为 CommonExtension.ClampTo 扩展方法,
采用交集语义(坐标钳位时宽高同步缩减,不会扩大矩形)。
删除 AutoLeyLineOutcropTask 中的私有 ClampRect 方法。
2026-02-20 15:08:19 +08:00
huiyadanli 3c883fcf05 Update version to 0.57.0 2026-02-20 05:06:59 +00:00
xytoki a4684ee6f7 Update version to 0.56.4-alpha.4 2026-02-20 01:19:53 +00:00
xytoki edf0c695c6 Update version to 0.56.4-alpha.3 2026-02-19 17:15:20 +00:00
xytoki 12db6280b2 Update version to 0.56.4-alpha.2 2026-02-19 16:05:23 +00:00
huiyadanli ffec4aadbe Update version to 0.56.4-alpha.1 2026-02-19 12:34:30 +00:00
xytoki 368ca18d9f Update version to 0.56.3-alpha.8 2026-02-18 16:36:44 +00:00
xytoki 891c695383 Update version to 0.56.3-alpha.7 2026-02-18 15:49:04 +00:00
辉鸭蛋 53051eff11 Merge remote-tracking branch 'origin/main' 2026-02-18 20:54:34 +08:00
辉鸭蛋 0797f20f26 补充地脉花教程url 2026-02-18 20:54:13 +08:00
mno 77f8013bb0 更正自动拾取掉落物为扫描掉落物光柱 (#2795)
* 更正自动拾取掉落物为扫描掉落物光柱

原表述易引起误会,以为捡东西就要开启,改为更明确的扫描掉落物光柱以说明其功能
同时,该方法仅作为无万叶和琴时的备选方案,效果原差于直接使用聚集材料动作,将原”与万叶配合更佳“更正为”仅在无万叶时备用“

* Update en.json

更正en.json
2026-02-18 20:24:04 +08:00
Takaranoao df8e7288c1 chore: add AGENTS.md to .gitignore (#2798) 2026-02-18 20:23:19 +08:00
辉鸭蛋 b425652909 修改来源,优化日志 2026-02-18 20:10:35 +08:00
辉鸭蛋 a10c9b8a8b Merge branch 'main' into d-v3 2026-02-18 16:17:15 +08:00
辉鸭蛋 e565f4b438 修复后台点击时 “选择对话选项前的延迟” 不生效的问题 2026-02-18 16:13:58 +08:00
辉鸭蛋 a8de2fb41a 尝试修复可能存在的角色识别错误问题 2026-02-18 15:44:58 +08:00
辉鸭蛋 a0584f6fdc feat(script): 向脚本引擎添加新的Bv视觉类
添加BvPage、BvLocator和BvImage类型到脚本引擎的宿主对象中,扩展脚本的视觉识别能力。
2026-02-18 13:03:02 +08:00
辉鸭蛋 44459cbca7 开启地脉花之前的OCR加入延迟 2026-02-18 12:59:43 +08:00
辉鸭蛋 c37ebae3bc Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2026-02-17 23:38:33 +08:00
辉鸭蛋 2f7e64ac57 fix(自动地脉花): 更新图标并改进异常处理日志
- 将自动地脉花功能图标从原图标更改为新图标
- 将自动地脉花任务失败时的日志级别从 Error 调整为 Debug,并添加简化的 Error 日志
- 在自动战斗任务结束时忽略 NormalEndException 和 TaskCanceledException 异常
2026-02-17 23:31:23 +08:00
辉鸭蛋 87c21f85bf fix: 地脉花任务捕获任务取消异常并调整日志级别
将地脉花自动任务中的特定异常捕获扩展为包含 TaskCanceledException,防止任务意外终止。同时将退出奖励界面的失败日志从 Warning 降级为 Debug,避免在正常任务取消时产生干扰性日志。
2026-02-17 22:58:31 +08:00
huiyadanli 7b7efdce80 Update version to 0.56.3-alpha.6 2026-02-17 14:51:14 +00:00
辉鸭蛋 536ed10dbf fix: 修复命令行参数检测和日志翻译的条件逻辑
- 命令行参数检测改为不区分大小写,确保参数匹配的可靠性
- 调试模式下禁用日志翻译,避免开发过程中的翻译干扰
- 仅非中文界面启用翻译日志提供程序,中文界面使用标准日志
2026-02-17 22:45:59 +08:00
辉鸭蛋 67ced40b6b 删除无用日志 2026-02-17 21:57:52 +08:00
辉鸭蛋 f59043d708 feat(触发器): 添加触发器编辑功能
- 在触发器页面添加“编辑选中项”按钮
- 扩展添加触发器对话框以支持编辑模式
- 实现触发器数据的回显和更新逻辑
- 通过绑定动态更新对话框标题
2026-02-17 21:55:42 +08:00
辉鸭蛋 adad7ec087 fix ui bug 2026-02-17 21:19:59 +08:00
辉鸭蛋 cf554cceed Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/App.xaml.cs
#	BetterGenshinImpact/BetterGenshinImpact.csproj
2026-02-17 19:44:44 +08:00
DarkFlameMaster b242d98208 背包计数任务更快定位到武器经验材料 (#2793)
* 背包计数任务更快定位到武器经验材料

* 防止任务取消时鼠标按钮可能卡在按下状态
2026-02-17 19:23:30 +08:00
huiyadanli 28c50211a7 Update version to 0.56.3-alpha.5 2026-02-15 11:06:23 +00:00
辉鸭蛋 9f67726781 I18n v2 (#2709)
* feat(i18n): 添加界面与日志的国际化支持

- 新增 ITranslationService 接口及 JsonTranslationService 实现,提供基于 JSON 的翻译服务
- 添加 TrConverter 转换器,支持通过绑定动态翻译界面文本
- 引入 AutoTranslateInterceptor 行为,自动扫描并翻译界面中的静态文本
- 集成 TranslatingSerilogLoggerProvider,实现日志输出的实时翻译
- 在 App.xaml 中注册全局样式,为 Window、UserControl 和 Page 启用自动翻译

* refactor(AutoTranslateInterceptor): 优化自动翻译拦截器的加载与应用机制

- 移除 HomePage 中冗余的 EnableAutoTranslate 属性设置,改为继承属性
- 通过类构造函数注册全局 Loaded 事件处理器,替代在每个元素上单独添加
- 引入请求队列机制,批量处理待应用翻译的元素,避免重复调度
- 扩展属性类型检查,支持 object 类型以处理更多动态内容场景

* fix: 移除全局自动翻译拦截器以避免冲突

移除在 App.xaml 中为 Window、UserControl 和 Page 全局设置的 AutoTranslateInterceptor,
改为仅在 PickerWindow 中显式启用。这解决了全局样式可能导致的意外行为或冲突。

* feat(ui): 为多个窗口启用自动翻译拦截器

为 MapLabelSearchWindow、ArtifactOcrDialog、PromptDialog 等 14 个窗口添加了 AutoTranslateInterceptor.EnableAutoTranslate 属性,以启用自动翻译拦截功能。

* feat(i18n): 添加国际化目录支持并优化异常处理

* feat(ui): 添加软件UI语言设置并改进翻译服务

- 在通用设置页面新增UI语言选择控件,支持动态切换界面语言
- 修改游戏语言标签为“原神游戏语言”以明确区分
- 改进JsonTranslationService,支持UI语言切换时的实时翻译更新
- 优化AutoTranslateInterceptor,缓存原始文本值并在语言切换时恢复
- 添加属性变更监听机制,确保UI元素在语言切换后正确刷新

* feat(自动翻译): 添加排除自动翻译的依赖属性

在 AutoTranslateInterceptor 中新增 ExcludeAutoTranslate 附加属性,允许对特定依赖对象禁用自动翻译功能。当遍历元素进行翻译时,会检查此属性并跳过已标记排除的元素。

* feat(translation): 为缺失文本翻译添加详细上下文信息

扩展翻译服务以收集缺失文本的详细上下文,包括视图路径、元素类型、属性名等。
重构 `ITranslationService` 接口,引入 `TranslationSourceInfo` 类封装上下文信息。
修改 `AutoTranslateInterceptor` 自动收集 UI 元素信息,`JsonTranslationService` 合并多来源上下文。

* Revert "feat(自动翻译): 添加排除自动翻译的依赖属性"

This reverts commit a1c2334951.

* fix: 跳过 GridViewRowPresenter 中的文本翻译

添加 IsInGridViewRowPresenter 检查,避免在 GridViewRowPresenter 控件内进行自动翻译,防止潜在的界面显示问题。

* fix: 修复自动翻译拦截器在组合框上下文中的误触发

在自动翻译拦截器中添加了 IsInComboBoxContext 方法,用于检测依赖对象是否处于 ComboBox 或其相关弹出菜单的上下文中。当检测到对象位于组合框上下文时,跳过自动翻译逻辑,避免对下拉选项等界面元素进行不必要的翻译操作,从而解决潜在的界面干扰问题。

* feat(translation): 添加缺失翻译上报至 Supabase 的功能

- 新增 IMissingTranslationReporter 接口及 SupabaseMissingTranslationReporter 实现
- 在 JsonTranslationService 中集成缺失翻译上报逻辑
- 添加缺失翻译收集的配置设置(MissingTranslationCollectionSettings)
- 优化缺失翻译文件的序列化格式,将 Source 字段改为紧凑的数字表示
- 移除 ScriptRepoUpdater 中未使用的 using 语句
- 在 App.xaml.cs 中注册 SupabaseMissingTranslationReporter 服务

* fix: 修复自动翻译功能中原始值恢复和重复报告问题

- 移除未使用的法语翻译支持以简化语言选项
- 修复 Supabase 报告序列化时移除冗余字段
- 添加已缺失翻译键的缓存以避免重复报告
- 重构自动翻译拦截器,将原始值存储移至依赖属性
- 修复原始值恢复逻辑,确保正确遍历所有子元素

* feat(ui): 添加更新UI语言文件功能

- 在 ITranslationService 接口中添加 Reload 方法
- 在 JsonTranslationService 中实现 Reload 方法,支持重新加载语言文件并发送变更通知
- 在通用设置页面添加“更新”按钮,点击后从远程仓库下载最新语言文件
- 实现 OnUpdateUiLanguageAsync 命令,支持从 GitHub 和镜像源下载语言文件
- 下载后自动替换本地文件并重新加载翻译服务
2026-02-15 19:03:33 +08:00
ddaodan a2bd48a56f feat: 补充挪德卡莱区域的地脉花独立任务路径数据 (#2790) 2026-02-15 17:59:16 +08:00
辉鸭蛋 b9b251aa13 默认蒙德 2026-02-14 20:39:59 +08:00
huiyadanli 8ab64a70b5 Update version to 0.56.3-alpha.3 2026-02-14 08:37:58 +00:00
ddaodanand辉鸭蛋 c24329eca6 新增:自动地脉花独立任务 (#2583)
* 新增自动地脉花任务代码

* 新增自动地脉花任务资源

* 优化自动地脉花界面文案

* 删除地脉花旧脚本与无用资源

* 完善自动地脉花说明与任务日志

* 完善一条龙地脉花配置与教程入口

* feat: Enhance AutoLeyLineOutcrop functionality and add new pathing data

- Refactored combat text detection logic to improve accuracy.
- Added new regions and positions for "挪德卡莱" in LeyLineOutcropData.json.
- Introduced new pathing files for "挪德卡莱4-望崖营垒" and "挪德卡莱5-厄布拉神柱".
- Updated config.json with new strategies and coordinates for enhanced navigation.
- Improved error handling during party switch operations.
- Removed outdated README.md file from pathing assets.

* 修复一些日志打印

* 移动所有assets文件

* feat: clear drawn content in VisionContext before activating mask window

---------

Co-authored-by: 辉鸭蛋 <[email protected]>
2026-02-14 16:35:17 +08:00
辉鸭蛋 57421b9a45 Update README.md 2026-02-14 16:15:32 +08:00
DarkFlameMaster efc66e6062 feat:AutoDomain支持领奖时切换20/40原粹树脂,仅JS可用 (#2783)
* feat:AutoDomain支持领奖时切换20/40原粹树脂,仅JS可用

* fix bug

* chore

* fix:捕获重试耗尽异常,GameTaskManager资源重载
2026-02-14 16:12:24 +08:00
huiyadanli e8c067f7c0 Update version to 0.56.3-alpha.2 2026-02-13 15:29:26 +00:00
292dc8fb4f feat: 显示后台角色技能cd (#2754)
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: 辉鸭蛋 <[email protected]>
2026-02-13 23:19:32 +08:00
this-Fish 0d466e5022 修改二次拾取,使万叶能再次拾取。 (#2760) 2026-02-13 22:24:27 +08:00
躁动的氨气 908294e2fe feat: 优化地图遮罩UI,添加快捷键 (#2775) 2026-02-13 21:20:28 +08:00
躁动的氨气 b3e2a08a6d feat: 修改仓库页面构建地址 (#2778) 2026-02-13 21:18:25 +08:00
辉鸭蛋 c28aba2bab hide map mask on run task https://github.com/babalae/bettergi-scripts-list/issues/2870 2026-02-13 21:17:30 +08:00
辉鸭蛋 08583c776f Merge remote-tracking branch 'origin/main' 2026-02-10 22:43:27 +08:00
辉鸭蛋 e15a1d7276 触发器多次触发改为30s 2026-02-10 22:43:17 +08:00
躁动的氨气 f80afc0244 fix: 日志遮罩扩大行数显示限制 (#2773) 2026-02-09 21:22:39 +08:00
huiyadanli 2caa6ee9f3 Update version to 0.56.3-alpha.1 2026-02-08 07:27:35 +00:00
Jamis 2f2311aa68 Fix rare welkin moon stuck issue (#2765) 2026-02-08 15:18:43 +08:00
躁动的氨气 4f7afb6a34 fix: 阻止默认的委托和派遣橙色点击 (#2762) 2026-02-08 00:36:09 +08:00
躁动的氨气andcoderabbitai[bot] 2f3ca34704 fix: 键鼠回调改为异步事件分发 (#2741)
* fix: 键鼠回调改为异步事件分发

* 添加队列限制与并行锁

* Update BetterGenshinImpact/Core/Script/Dependence/KeyMouseHook.cs

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

* 只允许外部dispose

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-02-07 16:58:07 +08:00
躁动的氨气 ea1a30a685 fix: 每日委托领奖使用点击屏幕 (#2761) 2026-02-07 16:51:28 +08:00
辉鸭蛋 b61ceae5ea 地图遮罩开关实时生效 2026-02-06 02:46:09 +08:00
this-Fish bf3957d4e8 优化换队拾取 (#2748)
* 优化换队拾取

需要换队拾取拾取时才执行换队拾取操作

* Add files via upload
2026-02-06 00:58:37 +08:00
辉鸭蛋 7c026fcf5f UI变化了后的10s内则所有触发器执行一遍,修复遮罩控件部分场景下残留的问题 2026-02-06 00:43:42 +08:00
ShadowLemoon 50055c3f26 feat: 状态机 (#2712) 2026-02-05 01:48:46 +08:00
躁动的氨气 6b2f2543c4 feat: 支持仓库使用公共资源 (#2716) 2026-02-05 01:48:06 +08:00
Ayu0K a24dd1c778 fix: 修复 RunMulti 中 Mat 所有权语义不明确导致的潜在 Dispose 问题 (#2730) 2026-02-05 01:37:18 +08:00
bling-yshs 2ced2862b3 fix: 修复 JS 脚本 multi-checkbox 配置项删除后仍能读取到旧值的问题 (#2725) 2026-02-05 01:36:08 +08:00
躁动的氨气 73422860af feat: 调整时间使用更短的延时 (#2738) 2026-02-04 19:44:21 +08:00
huiyadanli b5787aa9d3 Update version to 0.56.2 2026-02-03 14:46:22 +00:00
辉鸭蛋 f38e3e05ae 重置选项移动 2026-02-03 21:51:17 +08:00
辉鸭蛋 db67429350 fix: 调整事件触发顺序并修复地图点选择器状态
修复 PointsCanvas 中 ViewportChanged 事件与 Refresh 方法的调用顺序,确保界面正确更新。
在 MaskWindow 中增加关闭地图点选择器的逻辑,避免状态不一致。
2026-02-03 20:56:54 +08:00
辉鸭蛋 5484aea335 Revert "遮罩内 Popup 保持置顶"
This reverts commit ff3e89aa1c.
2026-02-03 20:40:05 +08:00
躁动的氨气 a948c70baf feat: 简化自动战斗日志输出 (#2732) 2026-02-03 17:35:23 +08:00
huiyadanli 688bdcd8ae Update version to 0.56.1 2026-02-02 18:22:32 +00:00
辉鸭蛋 3f2f45e3b1 fix: update BetterGI.Assets.Other package version to 1.0.12 2026-02-03 02:20:48 +08:00
辉鸭蛋 ff3e89aa1c 遮罩内 Popup 保持置顶 2026-02-03 02:19:58 +08:00
huiyadanli ddf1c72ba3 Update version to 0.56.0 2026-02-02 17:08:45 +00:00
辉鸭蛋 a651bbfbe5 优化更新界面UI与交互 2026-02-03 00:59:58 +08:00
kaedelcb a9cf0dcfb3 优化换队拾取和切换队伍 (#2729) 2026-02-03 00:39:39 +08:00
辉鸭蛋 e3caf32b94 Revise asset instructions and GitHub Actions setup
Updated README to reflect changes in asset handling and GitHub Actions.
2026-01-29 16:09:18 +08:00
huiyadanli 0761652e31 Update version to 0.55.2-alpha.2 2026-01-28 17:06:04 +00:00
辉鸭蛋 abc2b5dd19 fix: 修复地图标签搜索窗口DPI缩放和关闭逻辑
修复地图标签搜索窗口在高DPI缩放下的定位问题,调整计算方式以适配系统缩放比例。
同时确保地图点选择器关闭时同步隐藏搜索窗口,避免窗口残留。
2026-01-29 01:02:38 +08:00
辉鸭蛋 200f904a64 fix: 调整日志级别及UI元素位置比例
将米游社地图接口调用失败日志级别从Warning降为Debug,避免频繁警告干扰
调整日志文本框和状态列表的顶部位置及宽度比例,优化界面布局
2026-01-29 00:17:02 +08:00
辉鸭蛋 ab498fa731 fix: 调整截图预览区域尺寸以适应不同分辨率
调整 MaskWindow 中截图预览区域的列宽比例,将固定宽高改为最大宽高并启用拉伸对齐,提升在不同屏幕分辨率下的显示适应性。
2026-01-28 23:42:30 +08:00
辉鸭蛋 42ef97b1cd Revert "feat: 为多个窗口启用自动翻译拦截器"
This reverts commit fc942bd8cd.
2026-01-28 01:24:04 +08:00
辉鸭蛋 3beb762223 Merge remote-tracking branch 'origin/main' 2026-01-28 01:22:24 +08:00
辉鸭蛋 fc942bd8cd feat: 为多个窗口启用自动翻译拦截器
为 MapLabelSearchWindow、ArtifactOcrDialog、PromptDialog 等十三个 WPF 窗口添加了 AutoTranslateInterceptor 行为,以启用自动翻译功能。这确保了应用程序界面的文本内容在需要时可以被正确拦截并处理,提升国际化支持。
2026-01-28 01:22:09 +08:00
ema da80dd02c4 修复部分组件未随主题变更颜色 #2644 (#2699) 2026-01-27 12:28:24 +08:00
辉鸭蛋 9d799510a2 添加定时任务的日志 2025-12-26 00:33:06 +08:00
辉鸭蛋 8e292fcda3 Merge branch 'main' into d-v3 2025-12-23 00:30:26 +08:00
辉鸭蛋 f0efb4d2f6 feat: add GearTask services and refactor Quartz job handling 2025-11-16 17:58:16 +08:00
辉鸭蛋 7b73608950 Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/ViewModel/Pages/ScriptControlViewModel.cs
2025-11-16 00:59:24 +08:00
辉鸭蛋 df0cff5112 热键 2025-10-04 22:05:26 +08:00
辉鸭蛋 95a1cc3dfa 新增触发器与持久化 2025-10-02 22:49:37 +08:00
辉鸭蛋 95e20619d2 清理代码2 2025-10-02 16:04:23 +08:00
辉鸭蛋 ef66e2ff75 关联实际触发器对象的代码清理 2025-10-02 16:00:35 +08:00
辉鸭蛋 d6bfa5f736 优化滚动条 2025-10-02 15:11:48 +08:00
辉鸭蛋 8c94763729 样式修正 2025-10-02 13:28:03 +08:00
辉鸭蛋 15bfbe2839 refactor: update GearTriggerPage layout and improve data templates for triggers 2025-10-02 13:06:18 +08:00
辉鸭蛋 720b0e91cd refactor: remove unused using directive from ScriptRepoUpdater.cs 2025-10-02 12:41:39 +08:00
辉鸭蛋 a015c70c3b refactor: redesign GearTriggerPage layout and improve trigger management 2025-09-30 22:09:08 +08:00
辉鸭蛋 98edd99fed Merge branch 'main' into d-v3
# Conflicts:
#	BetterGenshinImpact/App.xaml.cs
2025-09-28 21:49:21 +08:00
辉鸭蛋 8719a4fbce fix 任务引用 2025-09-28 21:48:36 +08:00
辉鸭蛋 fc0b137689 Refactor gear task handling and improve service retrieval 2025-09-22 21:29:30 +08:00
辉鸭蛋 bd36816730 Merge branch 'main' into d-v3 2025-09-21 14:15:20 +08:00
辉鸭蛋 5723a24ece 代码优化 2025-09-21 14:10:01 +08:00
辉鸭蛋 f1cf9f5d13 集成 Quartz.NET 2025-09-21 02:48:50 +08:00
辉鸭蛋 bf6673d582 Merge branch 'main' into d-v3 2025-09-21 01:48:46 +08:00
辉鸭蛋 acbc1fdb03 Remove Scriban package reference from project file 2025-09-19 01:41:54 +08:00
辉鸭蛋 cd8bc4dd64 Merge branch 'main' into d-v3 2025-09-19 01:35:03 +08:00
辉鸭蛋 e8b8a405f2 补充km+shell 2025-09-19 00:24:18 +08:00
辉鸭蛋 9b831a5730 完善删除按钮 2025-09-19 00:00:44 +08:00
辉鸭蛋 f25c3414f2 Merge branch 'main' into d-v3 2025-09-18 23:28:38 +08:00
辉鸭蛋 6f70ebc4c4 更新任务选择窗口,调整任务添加逻辑,支持单个任务选择和目录结构保持 2025-09-08 00:32:52 +08:00
辉鸭蛋 df062088fc 增强任务选择窗口功能,支持按组引用和逐个添加任务,新增任务数量计算逻辑 2025-09-07 23:50:20 +08:00
辉鸭蛋 4a1842ea6b 移除任务选择窗口的显示模式相关逻辑,始终展示文件和目录,简化代码结构 2025-09-07 17:35:08 +08:00
辉鸭蛋 03580770e1 优化README和JSON内容加载逻辑,支持按需加载以提升性能 2025-09-07 15:12:50 +08:00
辉鸭蛋 a6a1dfd641 更新任务选择窗口的可见性绑定,使用NullToVisibilityConverter替代BooleanToVisibilityConverter 2025-09-07 15:04:24 +08:00
辉鸭蛋 b370d76f8d 新增地图追踪任务选择窗口及相关功能,支持任务选择和显示详细信息 2025-09-07 12:27:54 +08:00
辉鸭蛋 baa5cad656 增强任务节点拖拽逻辑,支持在任务组和根节点下的拖拽操作 2025-09-07 10:26:14 +08:00
辉鸭蛋 b05775653d 新增任务扩展状态属性,支持任务节点的展开状态管理 2025-09-07 10:22:12 +08:00
辉鸭蛋 c549848c4b 移除任务描述属性,新增路径属性以支持任务路径管理 2025-09-07 09:54:59 +08:00
辉鸭蛋 bd3301ff3e 新增启用状态属性,支持父子节点联动更新 2025-09-07 09:10:10 +08:00
辉鸭蛋 7dbca310fa 新增任务拖拽处理器,增强任务节点拖拽验证逻辑 2025-09-07 09:02:38 +08:00
辉鸭蛋 c74ad528ac 增强任务组添加功能,添加节点类型检查以限制任务节点下的操作 2025-09-07 08:54:35 +08:00
辉鸭蛋 459a1b1468 修复JS脚本选择窗口的对话框结果处理,确保正确获取用户选择的脚本 2025-09-07 08:46:44 +08:00
辉鸭蛋 109fee5588 优化JS脚本选择窗口的布局,调整控件属性以提升用户体验 2025-09-07 08:39:10 +08:00
辉鸭蛋 47d1b134a8 调整JS脚本选择窗口的显示名称格式,优化用户界面信息呈现 2025-09-07 08:29:02 +08:00
辉鸭蛋 8e196efe8e 新增搜索功能,优化JS脚本选择窗口的用户体验 2025-09-07 08:14:58 +08:00
辉鸭蛋 e9987c62b1 优化JS脚本选择窗口和任务列表页面的布局,调整控件属性以提升用户体验 2025-09-07 08:07:58 +08:00
辉鸭蛋 b11cdc7411 重构任务节点对话框和JS脚本选择窗口,调整命名空间,优化代码结构 2025-09-07 07:24:03 +08:00
辉鸭蛋 549fc03009 新增任务节点对话框,支持选择JS脚本类型任务,优化用户操作体验 2025-09-07 01:08:42 +08:00
辉鸭蛋 7d8b02a1a0 fix command 2025-09-07 00:21:14 +08:00
辉鸭蛋 2226411331 更新右键菜单,新增多种任务类型选项,优化用户操作体验 2025-09-06 23:49:06 +08:00
辉鸭蛋 c1fa02d9ff 新增任务添加功能,使用下拉按钮替代原按钮,优化用户操作体验 2025-09-06 23:03:12 +08:00
辉鸭蛋 a174118702 调整右键菜单 2025-09-06 22:54:45 +08:00
辉鸭蛋 1af0b6b523 移除可用任务类型下拉框,简化界面设计 2025-09-06 22:27:17 +08:00
辉鸭蛋 56d74a1eba 新增任务定义未选择时的提示信息,改善用户体验 2025-09-06 21:37:44 +08:00
辉鸭蛋 91c4151975 移除任务定义项双击重命名功能,简化界面交互 2025-09-06 21:27:50 +08:00
辉鸭蛋 dae0294fd8 新增无选中任务定义时的提示信息 2025-09-06 21:25:27 +08:00
辉鸭蛋 69c6dddfe1 更新任务定义顺序并实现自动保存功能 2025-09-06 21:00:23 +08:00
辉鸭蛋 348fe9494c 新增窗口 2025-09-06 20:43:00 +08:00
辉鸭蛋 ec63a803b5 优化ui绑定 2025-09-06 16:29:25 +08:00
辉鸭蛋 2b5f35d67a 界面样式优化 2025-09-06 15:47:25 +08:00
辉鸭蛋 05dc5eb381 Merge branch 'main' into d-v3 2025-09-06 15:03:37 +08:00
辉鸭蛋 55f15f6206 任务管理与执行 2025-08-27 02:36:35 +08:00
辉鸭蛋 58e3fbb2e4 feat: update ConvertTaskToData method to handle Children property correctly 2025-08-26 02:11:16 +08:00
辉鸭蛋 a39d202938 feat: add order property to task definitions and implement auto-save on collection changes 2025-08-26 02:05:25 +08:00
辉鸭蛋 7915140acb feat: implement GearTaskStorageService for task definition persistence 2025-08-26 01:31:20 +08:00
辉鸭蛋 d3768501b2 feat: add Scriban package reference to project 2025-08-25 00:47:31 +08:00
辉鸭蛋 b9ce87755f Merge branch 'main' into d-v3 2025-08-24 16:19:51 +08:00
辉鸭蛋 ba12ca3b3a Merge branch 'main' into d-v3 2025-08-24 15:56:31 +08:00
辉鸭蛋 196458ae46 Merge branch 'main' into d-v3 2025-08-19 23:57:49 +08:00
辉鸭蛋 3f6e223a07 Merge branch 'main' into d-v3 2025-08-09 17:24:30 +08:00
辉鸭蛋 4e54f4e292 修复传送进入秘境等待时间过短的问题 #2031 2025-08-09 16:33:51 +08:00
辉鸭蛋 90fdcf3275 Merge remote-tracking branch 'origin/main' into d-v3 2025-08-09 16:13:23 +08:00
辉鸭蛋 83ba4cef8b Merge branch 'main' into d-v3 2025-08-09 08:25:27 +08:00
辉鸭蛋 b78d644101 Add GearTriggerPage and related ViewModel; implement trigger functionality 2025-07-29 23:39:31 +08:00
辉鸭蛋 994db21b3d Add GearTriggerPage and related converters; update UI elements 2025-07-29 23:39:16 +08:00
辉鸭蛋 a59663f4d6 任务列表初始化 2025-07-28 02:00:23 +08:00
辉鸭蛋 907c6dc7bb Merge branch 'main' into d-v3 2025-07-27 21:11:32 +08:00
辉鸭蛋 60f01cc9b6 Merge branch 'main' into d-v3 2025-07-27 20:42:56 +08:00
辉鸭蛋 c474c177f7 作为外部入参 CancellationToken 2025-07-27 17:19:22 +08:00
辉鸭蛋 3e7fe95502 触发器初始化 2025-07-27 16:55:09 +08:00
辉鸭蛋 4c8c4412f1 feat: 添加CSharpReflectionGearTask及其参数类,支持通过反射调用任意C#方法 2025-07-27 14:49:17 +08:00
辉鸭蛋 6fc550d02d 修改脚本基础类 2025-07-27 13:52:53 +08:00
辉鸭蛋 bedd810213 Merge branch 'main' into d-v3 2025-07-26 01:17:47 +08:00
辉鸭蛋 20b2733b42 Merge branch 'main' into d-v3 2025-07-12 15:57:06 +08:00
辉鸭蛋 014360da04 Merge branch 'main' into d-v3 2025-07-04 00:10:26 +08:00
辉鸭蛋 67c2e44bb8 feat: enhance task management UI with TreeListView for better organization 2025-07-03 02:26:16 +08:00
辉鸭蛋 fe2977ce11 feat: implement drag-and-drop functionality for task management in SchedulerPage 2025-07-03 01:26:52 +08:00
辉鸭蛋 6f6c064ead Merge branch 'main' into d-v3 2025-07-03 00:05:52 +08:00
辉鸭蛋 f823b3816f Merge branch 'main' into d-v3 2025-06-25 01:08:08 +08:00
辉鸭蛋 259d4193a8 调度器UI初版 2025-06-13 23:27:28 +08:00
辉鸭蛋 7fbd1ee04e 饼 2025-06-08 23:45:37 +08:00
辉鸭蛋 fda93cf78e 所有类型Task的实现 2025-06-08 22:40:53 +08:00
辉鸭蛋 56d23c47fc Merge branch 'main' into d-v3 2025-06-08 17:53:06 +08:00
辉鸭蛋 beef6fe69b js脚本迁移 2025-05-21 00:03:21 +08:00
辉鸭蛋 17ce6e6d4d 基础对象 2025-05-20 23:14:58 +08:00
辉鸭蛋 739795962f Merge branch 'main' into d-v3 2025-05-19 22:39:59 +08:00
辉鸭蛋 7f1641d9e9 init GearTask 2025-05-19 01:06:01 +08:00
1274 changed files with 114734 additions and 11575 deletions

No files matched your search

+169
View File
@@ -0,0 +1,169 @@
---
name: "release-note-generator"
description: "基于 BetterGI 本地 git 历史和实际 diff,按 GitHub 已发布 Releases 的中文更新日志风格生成发布说明。用于生成 Release Note、版本更新日志、从上一个非 alpha 正式版本到 HEAD 的变更汇总;不得使用 git tag 作为版本依据。"
---
# Release Note Generator
基于本地 git 历史和实际代码 diff 生成 BetterGI 发布说明。发布说明的结构、分类和措辞应贴近 GitHub 已发布 Releases 的历史风格;生成具体内容时不依赖网络,所有变更信息从本地仓库获取。
## 触发时机
- 用户要求生成 Release Note / 更新日志
- 用户要求基于最近提交和实际代码变更做汇总
## 历史 Release 风格
已发布日志的稳定特征:
- 标题通常为 `## <version> <简短主题>`,例如 `0.61.0 原神6.6`、`0.61.2 优化`、`0.60.1 修复老问题`、`0.59 自动烹饪与BUG修复`。
- 大版本或内容较多时,标题下可有一句总览;补丁版本或内容很少时可以直接列 bullet。
- 分类标题使用项目语义,而不是 Conventional Commits 类型。常见分类包括:`版本适配` / `<月之X适配>`、`自动战斗`、`地图追踪`、`地图遮罩`、`独立任务`、`JS脚本` / `JS相关`、`实时任务`、`自动剧情`、`其他`。
- 版本适配类通常放在最前面,包含新角色识别、新地图、传送点/锚点、七圣召唤元数据等。
- `其他` 分类保留,用于 UI、通知、配置、稳定性、OCR、启动器、仓库、文档等无法归入核心模块的内容。
- 条目语言偏简洁直白,可以用“新增/修复/优化/支持/更新/回滚/适配”,不需要营销化。
- PR 号与作者使用纯文本,例如 `(#3132) @haokaiyang`;多个 PR 可以写在同一括号组里,例如 `(#3101 #3108)`。
- 不输出 GitHub 自动生成的 `Contributors`、`Assets`、reaction 等区块。
## 版本边界
禁止执行或参考 `git tag`、`git describe --tags`。版本边界和输出版本号都不能使用 tag 作为依据。
从 HEAD 向后遍历提交历史,匹配**明确以版本号发布为主题的提交**:
- 提交消息必须匹配以下模式之一(大小写不敏感):
- `Update version to X.Y.Z`
- `bump version to X.Y.Z`
- `release X.Y.Z`
- `vX.Y.Z`
- 版本号正则:`\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?`
- 版本号**必须是提交消息的核心主题**,不能只是顺带提及(如 "fix: update package version to 1.0.19" 这种子包更新不算)
- 排除包含 `alpha` 的提交
- 排除仅更新子包/依赖版本的提交
### 通用规则
- 统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入
- 如果 HEAD 附近已经存在当前目标版本的正式版本提交,不要把它作为边界;继续向父提交方向寻找上一个正式版本提交
- 若未找到边界版本,明确说明并使用兜底范围
## 信息采集
### 提交列表
- 使用 `git -c i18n.logOutputEncoding=utf8 -c core.quotepath=false log` 获取提交序列
- 格式:`--pretty=format:"%H%x00%h%x00%an%x00%ae%x00%s%x00%b%x1e"`,字段用 `\x00` 分隔,commit 用 `\x1e` 分隔
- 先用 `git rev-list --count` 取总数,采集后校验一致性
- 读取 commit body,用于提取 `Co-authored-by`、正文中的 PR/Issue 号和补充说明
### Diff 查阅(必须)
- 对每个 commit 必须查阅实际 diff:`git diff <sha>~1..<sha>`
- **不允许仅基于 commit 消息生成说明**,必须结合实际代码改动理解变更内容
- 同一功能的新增 + 后续优化/修复应合并为一条,只记"新增 xxx"
### 作者信息
- 所有作者名前统一加 `@` 前缀
- 从 commit 的 `author email` 解析标识:
- `数字[email protected]` → `@login`
- `[email protected]` → `@login`
- `[email protected]` 等非 noreply 邮箱 → `@author name`(即提交中的 `an` 字段值前加 `@`)
- 从 commit body 的 `Co-authored-by: name <email>` 提取共同作者,并按同样规则解析
- 当作者为 `huiyadanli`(含邮箱 `[email protected]`)时省略 `@author`(项目维护者,无需标注)
- 不需要调用 GitHub API,纯本地解析
## 内容提炼规则
### 合并策略
- 同一功能在同一版本周期内先新增后优化/修复的,只保留"新增 xxx",不单独列优化
- 同一 issue/PR 的多个 commit 合并为一条记录
- 同一文件或模块的多次小改动合并为一条有意义的描述
- 可省略纯内部重构、CI、调试日志清理、无用户影响的格式化,但这些 commit 仍必须被检查并纳入内部覆盖记录
### 分类
优先使用以下历史 Release 常见分类,按顺序输出。只有对应分类下有变更时才输出该分类标题,无变更则跳过不输出。
分类来源于项目已发布 GitHub Releases,与项目实际使用习惯对齐:
| 分类名 | 对应项目模块 | 覆盖范围 |
|--------|-------------|---------|
| 版本适配 / `<月之X适配>` | `Assets/` `AutoFight/Assets/` `AutoGeniusInvokation/Assets/` `AutoTrackPath/Assets/` | 新角色识别数据、新地图添加、传送点/锚点数据更新、七圣召唤角色牌等元数据更新 |
| 自动战斗 | `GameTask/AutoFight` `GameTask/Macro` `GameTask/SkillCd` | 战斗策略、角色切换、技能释放与CD、一键宏、经验值拾取、战后拾取、游泳检测、角色数据(非版本适配类) |
| 地图追踪 | `GameTask/AutoPathing` `GameTask/AutoTrackPath` `GameTask/MapMask` | 路径执行与所有路径处理器(含莉奈娅挖矿、拾取、采矿等 Handler)、地图类型、传送逻辑、地图编辑器(MapPathingPage、MapEditorWebBridge) |
| 地图遮罩 | `GameTask/MapMask` `View/MaskWindow*` `ViewModel/MaskWindow*` `Core/Config/MaskWindowConfig*` | 地图遮罩、日志遮罩、遮罩指标栏、遮罩位置和实时展示 |
| 独立任务 | `GameTask/AutoLeyLineOutcrop` `GameTask/AutoDomain` `GameTask/AutoBoss` `GameTask/AutoStygianOnslaught` `GameTask/AutoCook` `GameTask/AutoWood` `GameTask/AutoFishing` `GameTask/FarmingPlan` `GameTask/AutoSkip` `GameTask/QuickSereniteaPot` | 地脉花、秘境、首领讨伐、幽境危战、烹饪、伐木、钓鱼、养成计划、自动剧情、快速尘歌壶等独立运行的任务 |
| JS脚本 | `Core/Script` `Core/BgiVision` | JS 脚本 API、BvLocator、HTML 遮罩、模块导入、v8 引擎、脚本项目 |
| 实时任务 | `GameTask/TaskTriggerDispatcher*` `GameTask/AutoPick` `GameTask/AutoEat` `GameTask/Common` | 自动拾取、自动吃药、自动跳过、实时触发器、进入游戏与界面检测等 |
| 其他 | — | 无法归入以上分类的杂项(必须保留,即使为空也输出) |
- 归类原则:按**变更所属的项目模块(代码所在目录)**划分,而非按变更类型(新增/修复/优化)或用户感知的子功能划分
- 当一个变更涉及多个模块时,归入其主要逻辑所在的模块
- 版本适配类命名:若能从变更或用户要求明确对应原神版本/月之版本,可用 `<月之X适配>`;否则使用 `版本适配`
- 仅当本轮有多个明确的新功能且难以归入既有模块时,才使用 `新功能`
- 若某项变更无法明确归入上述分类,放入"其他"
- 遇到历史分类未覆盖的新模块,允许 AI 自行新建分类(放在"其他"之前),但分类名必须是项目语义,不要使用 `feat/fix/refactor`
每条记录格式:
```
描述内容 (#PR号) @author
```
- PR 号和作者名均使用纯文本,不加超链接
- 当作者为 `huiyadanli` 时省略 `@author`(项目维护者,无需标注)
- 描述用自然语言,不直接复制 commit 原文
- 移除 `feat:`、`fix:` 等 Conventional Commits 前缀
- PR 号从 commit 消息中提取(如 `(#3111)`)
- 多人参与的记录:`@id1 @id2`
- 合并多个 PR 时格式为 `(#3101 #3108)`,不要写成多个分散条目
### 描述质量
生成后必须做后处理检查,确保表达准确:
- 描述要准确反映实际变更的范围和内容,不能缩小也不能夸大
- 如果 diff 显示新增了一张地图,就写"新增 xxx 地图",而不是"新增 xxx 传送点"
- 如果改动只涉及一个配置项,不要写成整体功能变更
- 面向用户的变更用用户视角描述(功能、体验、问题现象)
- 面向开发者的变更可以保留技术术语(接口、脚本引擎、配置项等)
- 去掉不必要的代码标识符(方法名、类名等),除非它是脚本开发者会直接使用的 API
- 纯内部重构、CI 变更等不影响使用的内容可以省略不列
- 主题句要概括本版本最重要的 2~4 个变化;不要把所有分类机械罗列一遍
- 重要新增功能优先写“新增 xxx”,后续修复/优化并入同一条描述
## 输出格式
输出到 `.claude/documents/ReleaseNotes-<version>.md`(文件名 ASCII)。
输出文件的版本号规则:取边界版本号的**次版本号(minor)加 1**,补丁版本归零。即 `major.(minor+1).0`。例如边界为 `0.60.1`,输出版本号为 `0.61.0`。
若用户明确指定版本号或发布主题,以用户指定为准;否则按上述规则推导。
```markdown
## <version> <版本主题>
<一句话版本主题>
### 分类名1
- 变更描述 (#PR号) @author
- 变更描述 @author
### 分类名2
- 变更描述 (#PR号) @author
### 其他
- 变更描述 @author
```
补丁版本或少量修复可以不分分类,直接输出 bullet;但如果使用分类,仍必须保留 `其他` 分类。
## 质量门槛
- 不允许遗漏检查区间内任意 commit;确认无用户影响的 commit 可以不输出
- 不允许仅基于 commit 标题,必须查阅实际 diff
- 同一功能的多次提交必须合并,不允许出现"新增 xxx""优化 xxx(同功能)"的冗余
- 优先使用历史 Release 分类,不允许自行发明无项目语义的分类名
- "其他"分类必须存在
- 不依赖网络,全部信息从本地 git 获取
- 输出前检查是否漏掉用户可见修复,尤其是同一新功能上线后的后续修复 commit
-22
View File
@@ -1,22 +0,0 @@
---
name: Bug report / 错误报告
about: Create a report to help us improve / 创建报告以帮助我们改进
title: "[bug]请补充标题内容"
labels: bug
---
<!--
请提供下述完整信息以便快速定位问题 / Please provide the following information to quickly locate the problem
-->
- 系统环境 / System Environment:
- BetterGI版本号 / BetterGI Version:
- 问题描述 / Description of the issue:
- 复现步骤 / Reproduction steps:
+74
View File
@@ -0,0 +1,74 @@
name: Bug report / 错误报告
description: 提交可复现的问题,帮助我们定位错误 / Report a reproducible problem
title: "[bug] "
labels:
- BUG
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Checklist before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- label: 我愿意为了解决这个问题尽自己所能 / I am willing to do my part to help resolve this issue
- type: textarea
id: environment
attributes:
label: 系统环境
description: System environment,例如操作系统版本、运行时版本、显卡驱动版本
placeholder: Windows 11 24H2 (26100.3775) / .NET Desktop Runtime 8.0.15 / NVIDIA 572.83
validations:
required: true
- type: input
id: version
attributes:
label: BetterGI 版本号
description: BetterGI Version
placeholder: e.g. 0.58.0
validations:
required: true
- type: textarea
id: description
attributes:
label: 问题描述
description: Describe the actual behavior and impact
placeholder: 请描述实际出现的问题,以及这个问题对使用造成了什么影响 / Describe the actual behavior and impact
validations:
required: true
- type: textarea
id: expected
attributes:
label: 期望结果
description: Expected behavior
placeholder: 请描述你期望出现的正确行为或结果 / Describe the expected behavior or result
validations:
required: true
- type: textarea
id: steps
attributes:
label: 复现步骤
description: Reproduction steps
placeholder: |-
1. 打开…… / Open ...
2. 点击…… / Click ...
3. 出现…… / Observe ...
validations:
required: true
- type: textarea
id: logs
attributes:
label: 日志与附件
description: Logs and attachments,可直接拖拽上传日志文件、压缩包、截图或视频
placeholder: |-
可在这里补充日志和附件说明 / Add logs and attachment notes here:
- 可直接粘贴关键日志片段 / Paste key log snippets directly
- 可拖拽上传日志文件或压缩包 / Drag and drop log files or archives
- 可拖拽上传截图、录屏或演示视频 / Drag and drop screenshots or videos
- 若附件较多,请说明对应的时间点、任务名称或异常现象 / If there are many files, explain the relevant timestamps or symptoms
- 提交前请注意移除账号、路径等隐私信息 / Remove private information before submitting
validations:
required: false
+2 -2
View File
@@ -1,9 +1,9 @@
blank_issues_enabled: false
contact_links:
- name: 官方文档 / Document
url: https://bgi.huiyadan.com/doc.html
url: https://www.bettergi.com/doc.html
about: 请在提出问题前阅读文档 / Read the document before submit the issue
- name: 常见问题 / FAQ
url: https://bgi.huiyadan.com/faq.html
url: https://www.bettergi.com/faq.html
about: 常见的用户提出的问题 / Common questions asked by users
-9
View File
@@ -1,9 +0,0 @@
---
name: I have feature requesting / 我有新功能请求
about: Your request may come as a surprise. / 你的请求也许成为惊喜
title: "[feature] "
labels: feature 功能请求
---
- Your feature requesting / 你的新功能请求
+52
View File
@@ -0,0 +1,52 @@
name: I have feature requesting / 我有功能需求
description: 提出新的功能想法 / Share a feature request
title: "[feature] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate request
required: true
- label: 我已确认当前版本中尚未提供该功能,或至少没有等价实现 / I have confirmed this feature, or an equivalent one, is not already available in the current version
required: true
- label: 我认为这个需求能为更多用户带来明确收益,而不仅仅是个人偏好 / I believe this request provides clear value to a broader group of users, not just my personal preference
required: true
- label: 我理解这个需求可能因实现成本、维护成本或项目方向而暂不采纳 / I understand this request may not be accepted due to implementation cost, maintenance cost, or project direction
required: true
- type: textarea
id: request
attributes:
label: 功能请求
description: Feature Request
placeholder: 请简要说明你希望新增什么能力 / Briefly describe the capability you want to add
validations:
required: true
- type: textarea
id: scenario
attributes:
label: 使用场景
description: Use Case
placeholder: 这个功能要解决什么问题?在哪些场景下使用? / What problem does this feature solve, and when would it be used?
validations:
required: true
- type: textarea
id: impact
attributes:
label: 潜在影响
description: Potential Impact
placeholder: 请说明这个功能是否可能带来新的问题、维护成本、使用门槛或兼容性影响;如果没有,请填写“无” / Describe any potential downsides such as new issues, maintenance cost, usability barriers, or compatibility impact. Write "None" if there are no obvious downsides.
validations:
required: true
- type: textarea
id: extra
attributes:
label: 补充信息
description: Optional
placeholder: "可选,补充示意图、交互草图、参考链接或相关背景信息 / Optional: add mockups, interaction sketches, reference links, or other background information"
validations:
required: false
-5
View File
@@ -1,5 +0,0 @@
---
name: Feel free to express / 随便写写
about: Record something / 简单写写记录记录
---
+22
View File
@@ -0,0 +1,22 @@
name: Feel free to express / 自由描述
description: 记录你想反馈的内容 / Share general feedback
title: "[feedback] "
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复反馈 / I have searched existing issues and confirmed this is not duplicate feedback
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的反馈 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my feedback"
required: true
- type: textarea
id: description
attributes:
label: 描述
description: Description
placeholder: 请描述你想反馈的内容 / Describe what you want to share
validations:
required: true
-9
View File
@@ -1,9 +0,0 @@
---
name: I have a question / 我有疑问
about: Solve your problem / 解决你的疑问
title: "[question] "
labels: question
---
- Problem Description / 问题描述
- 请尽量提供问题相关的截图/日志等内容
+32
View File
@@ -0,0 +1,32 @@
name: I have a question / 我有疑问
description: 提交你的问题,我们会尽量帮助你解决 / Ask a question
title: "[question] "
labels:
- 问题咨询
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复问题 / I have searched existing issues and confirmed this is not a duplicate question
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem"
required: true
- type: textarea
id: question
attributes:
label: 问题描述
description: Problem Description
placeholder: 请清楚描述你的问题 / Clearly describe your question
validations:
required: true
- type: textarea
id: tried
attributes:
label: 已尝试内容
description: Screenshots / logs / what you already tried
placeholder: 可附上截图、日志,以及你已经尝试过的排查过程 / Add screenshots, logs, and what you have already tried
validations:
required: true
-9
View File
@@ -1,9 +0,0 @@
---
name: I have suggestions / 我有建议
about: Your suggestions may benefit everyone / 你的建议可能让所有人受益
title: "[suggestion] "
labels: suggestion
---
- Your suggestions / 你的建议
+32
View File
@@ -0,0 +1,32 @@
name: I have suggestions / 我有建议
description: 分享对项目的改进建议 / Share an improvement suggestion
title: "[suggestion] "
labels:
- 功能建议
body:
- type: checkboxes
id: checks
attributes:
label: 提交确认 / Checklist
description: Please confirm the following before submitting
options:
- label: 我已经搜索过现有 issue,确认这不是重复建议 / I have searched existing issues and confirmed this is not a duplicate suggestion
required: true
- label: "我已阅读过[文档](https://www.bettergi.com/doc.html),确认文档的内容无法解决我的问题或覆盖我的建议 / I have read the [documentation](https://www.bettergi.com/doc.html) and confirmed it does not solve my problem or cover my suggestion"
required: true
- type: textarea
id: suggestion
attributes:
label: 建议内容
description: Suggestion
placeholder: 请描述你的建议内容 / Describe your suggestion
validations:
required: true
- type: textarea
id: benefit
attributes:
label: 预期收益
description: Expected Benefit
placeholder: 这个建议会给用户或项目带来什么帮助? / What benefits would this suggestion bring to users or the project?
validations:
required: true
+229
View File
@@ -0,0 +1,229 @@
runtime:
languageMode: auto
dryRun: false
providers:
openAiCompatible:
enabled: true
baseUrl: https://api.openai.com/v1
model: gpt-5.4
apiStyle: responses
timeoutMs: 30000
issues:
autoProcessing:
skipCreatedBefore: auto
validation:
enabled: true
fallbackTemplateKey: normal
commentAnchor: issue-bot:validation
templates:
- key: bug
detect:
markers:
- bug
titlePrefixes:
- "[bug]"
requiredSections:
- id: environment
aliases:
- 系统环境
- System Environment
- id: version
aliases:
- BetterGI 版本号
- BetterGI Version
- id: description
aliases:
- 问题描述
- Description of the issue
- id: steps
aliases:
- 复现步骤
- Reproduction steps
labels:
whenValid:
- BUG
whenInvalid:
- 需要更多信息
- key: feature
detect:
markers:
- feature
titlePrefixes:
- "[feature]"
requiredSections:
- id: request
aliases:
- 功能请求
- Feature Request
- id: scenario
aliases:
- 使用场景
- Use Case
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: suggestion
detect:
markers:
- suggestion
titlePrefixes:
- "[suggestion]"
requiredSections:
- id: suggestion
aliases:
- 建议内容
- Suggestion
- id: benefit
aliases:
- 预期收益
- Expected Benefit
labels:
whenValid:
- 功能建议
whenInvalid:
- 需要更多信息
- key: question
detect:
markers:
- question
titlePrefixes:
- "[question]"
requiredSections:
- id: question
aliases:
- 问题描述
- Problem Description
- id: tried
aliases:
- 已尝试内容
- What I Tried
labels:
whenValid:
- 问题咨询
whenInvalid:
- 需要更多信息
- key: normal
detect:
markers:
- normal
titlePrefixes:
- "[feedback]"
- "[normal]"
requiredSections:
- id: description
aliases:
- 描述
- Description
labels:
whenValid: []
whenInvalid:
- 需要更多信息
duplicateDetection:
enabled: true
bypassLabels:
- 跳过重复检测
duplicateLabel: 重复
searchResultLimit: 50
candidateLimit: 20
aiReviewMaxCandidates: 3
thresholds:
exact: 0.995
highConfidence: 0.93
reviewMin: 0.82
similarityComment:
enabled: false
commentAnchor: issue-bot:similar-issues
minScore: 0.3
maxCandidates: 3
labeling:
enabled: true
autoCreateMissing: true
managed:
- BUG
- 功能建议
- 问题咨询
- 需要更多信息
- 重复
definitions:
BUG:
color: d73a4a
description: 程序存在缺陷或异常行为。
功能建议:
color: a2eeef
description: 新功能建议或现有功能改进。
问题咨询:
color: d876e3
description: 使用问题、求助或咨询。
# 需要更多信息:
# color: fbca04
# description: 当前 Issue 缺少必要信息。
重复:
color: cfd3d7
description: 已存在相同或高度相似的问题。
keywordRules: []
aiClassification:
enabled: false
maxLabels: 3
minConfidence: 0.65
include: []
exclude:
- BUG
- 功能请求
- 重复
- 不会修复
- 使用问题
- 需要帮助
- 已完成
- 未解决
- 待确认
- P0
- P1
- 需要文档
- 优化点
- 急急急
prompt: 优先给 BetterGI Issue 选择能反映具体功能模块、子系统或使用场景的标签,例如一条龙、调度器、脚本、设置项、地图追踪;避免只选择宽泛的流程或状态标签。
sourceRepository:
owner: babalae
repo: better-genshin-impact
aiHelp:
enabled: true
triggerLabels: []
commentAnchor: issue-bot:ai
projectContext:
enabled: true
includeRepositoryMetadata: true
includeReadme: true
readmeMaxChars: 3000
profile:
name: BetterGI
aliases:
- BGI
- Better Genshin Impact
summary: BetterGI is a desktop automation assistant for Genshin Impact.
techStack:
- C#
- WPF
- .NET
commands:
enabled: true
mentions:
- "@bot"
- "@bettergi-repo-bot"
access: collaborators
fix:
enabled: true
commentAnchor: issue-bot:fix
refresh:
enabled: true
pullRequests:
review:
enabled: false
labeling:
enabled: false
summary:
enabled: false
@@ -7,6 +7,7 @@ on:
jobs:
mirrorchyan_release_note:
if: github.repository_owner == 'babalae'
runs-on: macos-latest
steps:
@@ -7,6 +7,7 @@ on:
jobs:
mirrorchyan:
if: github.repository_owner == 'babalae'
runs-on: windows-latest
steps:
- name: 📥 Download release
+1 -1
View File
@@ -74,7 +74,7 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
repository: A-Little-AnQi/bettergi-script-web
repository: zaodonganqi/bettergi-script-web
- uses: actions/setup-node@v4
with:
node-version: 20
+55
View File
@@ -0,0 +1,55 @@
name: Repo Bot
on:
issues:
types:
- opened
- edited
- reopened
- labeled
issue_comment:
types:
- created
- edited
jobs:
repo-bot:
runs-on: ubuntu-latest
permissions:
issues: write
contents: read
steps:
- name: Detect GitHub App configuration
id: auth-mode
shell: bash
env:
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
run: |
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
echo "use_app=true" >> "$GITHUB_OUTPUT"
else
echo "use_app=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Create GitHub App token
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
- name: Run Repo Bot
uses: ddaodan/bettergi-github-bot@v1
env:
GITHUB_TOKEN: ${{ github.token }}
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
with:
config-path: .github/repo-bot.yml
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
+12 -3
View File
@@ -9,6 +9,7 @@
*.userprefs
# Build results
Build/
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
@@ -30,8 +31,16 @@ github_actions_cache/
# Rider
.idea
.trae
.claude
CLAUDE.md
__pycache__/
# Trae
.trae/*
!.trae/rules/
!.trae/rules/**
!.trae/skills/
!.trae/skills/**
# Claude
.claude/*
+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
```
+62
View File
@@ -0,0 +1,62 @@
---
name: "github-issue-triage"
description: "Reads GitHub issues, extracts reporter details and <=10MB attachments/images, then decides discuss/research vs direct fix vs implementation plan. Invoke when user shares an issue URL."
---
# GitHub Issue Triage
用于处理 GitHub issue 链接,并在结合当前仓库代码后给出执行路径。
## 触发时机
- 用户提供 GitHub issue URL,并希望你分析内容后继续行动
- 需要先读取 issue 创建者信息、附件或图片,再决定如何推进
- 需要判断是先讨论研究、直接修复,还是先制定方案
## 输入
- 必填:GitHub issue URL,例如 `https://github.com/<owner>/<repo>/issues/<id>`
- 可选:用户额外上下文(复现步骤、期望行为、优先级)
## 执行流程
1. 读取 issue 内容
- 获取标题、正文、标签、状态、创建者、创建时间
- 提取创建者在 issue 中提供的关键信息(正文 + 创建者本人评论)
- 区分“创建者信息”与“其他参与者讨论”
2. 收集附件与图片(限制 10MB)
- 从 issue 正文和创建者评论中提取附件/图片链接
- 对每个链接获取文件大小与类型,只有 `<= 10MB` 才下载
- 优先下载图片(png/jpg/jpeg/webp/gif)与问题复现相关附件
- 记录已下载与跳过原因(超限、类型不符、不可访问)
3. 结合代码库研判
- 先做高层语义检索定位相关模块,再做符号/关键字精查
- 找到与 issue 直接相关的代码路径、入口点、可能影响范围
- 判断是否已有类似问题处理逻辑、开关、兜底或已知限制
4. 路径决策
- 讨论研究问题:信息不足、无法稳定复现、需求存在歧义、外部依赖阻塞
- 直接修复问题:根因清晰、改动范围可控、验收标准明确
- 计划方案:涉及跨模块改造、兼容性权衡、需要分阶段实施
5. 执行动作
- 若“直接修复问题”:直接修改代码并完成必要验证
- 若“计划方案”:输出分步计划、影响面、风险与验证策略
- 若“讨论研究问题”:给出需要补充的信息与建议实验步骤
## 输出格式
- Issue 摘要:标题、创建者、关键诉求、复现线索
- 创建者信息提炼:仅保留创建者提供的有效信息
- 附件处理结果:下载清单(<=10MB)与跳过清单(含原因)
- 代码关联分析:相关模块、关键函数、潜在根因
- 决策结论:讨论研究 / 直接修复 / 计划方案
- 下一步:立即执行项
## 质量要求
- 必须优先依据创建者提供的信息,不被无关评论干扰
- 必须在代码层面给出证据,不做纯主观结论
- 决策应可执行,并且与当前仓库结构一致
@@ -0,0 +1,142 @@
---
name: "release-note-generator"
description: "Generates release notes from git commits/diffs and outputs one Chinese MD file. Invoke when user asks for release notes bounded by previous non-alpha version."
---
# Release Note Generator
用于基于当前仓库的 git 历史自动生成发布说明,确保不遗漏提交,并为每条变更记录追加提交人的 GitHub ID(`@id`)。默认输出一个 Markdown 文件到 `.trae/documents` 目录:变更内容。
## 触发时机
- 用户要求生成 Release Note / 更新日志
- 用户要求基于最近提交和实际代码变更做汇总
- 用户要求以“上一个非 alpha 版本”为边界统计变更
## 输入约定
- 默认分支当前 `HEAD`
- 版本边界规则:从最新提交向后遍历,遇到“提交信息包含版本号且不含 alpha”的最近一个提交作为边界
- 若用户指定分支、Tag 或版本正则,优先使用用户指定
- 未指定时,默认输出文档路径为:`.trae/documents/release_notes-<version>.md`
## 实战经验(本项目)
- 不直接依赖终端长输出:大量 `git log` 在终端中容易被截断,导致误判“提交缺失”
- 不用 `|` 等普通分隔符解析:提交标题可能包含分隔符,必须使用 NUL 分隔(`\x00`)保证可解析
- 统一 UTF-8:PowerShell 下中文提交信息可能乱码,调用 git 时需显式设置输出编码
- 避免在 `RunCommand` 的内联脚本中直接硬编码中文常量(标题、分类名、文件名):在 Windows/PowerShell 链路中可能被替换为 `?`
- 发布文件名使用 ASCII:不要在文件名中使用中文(如 `ReleaseNotes-变更内容-<version>.md`),否则编码异常时会变成非法字符 `?` 导致写文件失败
- 中文文案仅放在 Markdown 内容里,并在写入后做一次乱码校验:若出现 `???`、`### ??` 等占位符,必须重新生成
- 明确分支范围:优先使用 `HEAD` 可达历史,必要时用 `--first-parent` 辅助核对发布主线
- 先计数再明细:先取 `rev-list --count`,再逐条采集,最后做数量一致性校验
- 版本边界要可回退:目标版本不存在时,自动回退到最近可识别的“上一非 alpha 版本”并在结果中声明
## 日志采集方式(强制)
- 必须使用 Python 脚本拉取 commit 与 diff,不直接用终端拼接命令产出最终结果
- Python 内通过 `subprocess.run([...], check=True, capture_output=True, text=True, encoding="utf-8", errors="replace")` 调 git
- git 命令需附加编码参数:`-c i18n.logOutputEncoding=utf8 -c core.quotepath=false`
- 提交元数据推荐格式:`--pretty=format:%H%x00%h%x00%an%x00%ae%x00%ad%x00%s%x00`,按 `\x00` 解析
- diff 证据至少包含:
- 区间总览:`git diff --shortstat <base>..<head>`
- 文件变更:`git diff --name-status <base>..<head>`
- 行级统计:`git diff --numstat <base>..<head>`
- 必要时单提交详情:`git show --name-status --numstat --format= <sha>`
- Python 脚本需输出结构化数据(JSON/对象)后再生成 release note 文本
- 若通过终端执行 Python,优先将中文文案写成 `\\uXXXX` 形式或由程序运行期拼接,避免命令传输阶段损坏字符
## 执行流程
1. 获取提交序列(防遗漏)
- 从 `HEAD` 向后扫描提交,定位边界提交 `boundary_commit`
- 使用可识别 SemVer 的正则提取版本号(例如 `v1.2.3`、`1.2.3`)
- 判断“非 alpha”时使用大小写不敏感匹配:提交信息不包含 `alpha`
- 生成统计区间:`(boundary_commit, HEAD]`,边界提交本身不计入变更列表
- 使用 Python 执行 git 并解析 NUL 分隔结果,禁止依赖终端显示内容做解析
2. 完整性校验(必须)
- 先取区间提交总数 `N`
- 再逐条收集区间内每个 commit 的详情
- 输出前校验“已收集条数 == N”,不一致则重新拉取,直到一致
- 若存在 merge,额外给出 `--first-parent` 视角的校验结果,避免发布主线理解偏差
3. 采集每条提交的证据
- 提交元数据:hash、标题、作者、时间
- 实际改动:由 Python 采集 `--name-status`、`--numstat`、`--shortstat` 与必要 diff 片段
- 将提交按功能模块归类(如 UI、任务、配置、脚本、基础设施等)
4. 提炼发布内容
- 先按用户指定分类规则归类;若未指定,使用更接近 GitHub Releases 页面的默认分类顺序:
1) 新功能
2) 地图遮罩
3) 独立任务
4) JS相关
5) 其他
- 分类名尽量贴近业务语义:例如“地图追踪”“自动剧情”“七圣召唤”等可作为二级小节并入对应一级分类
- 无法稳定归类的小变更统一放入“其他”
- 每条摘要都要可追溯到至少一个 commit
- 识别“变更最大点”并在首屏摘要中突出展示
- 主体正文只展示可读的变更描述,不在分类正文中堆叠 hash
- 完整提交清单放在文末,避免正文可读性下降
- 输出文案需去掉 Conventional Commits 前缀:至少移除 `feat:`、`fix:`(区分大小写不敏感),再写入分类正文与完整提交清单
5. 生成提交人 GitHub ID(逐条记录追加 `@id`)
- 必须以“当前方式”解析:对区间内每个 commit 逐条调用 GitHub 提交接口,禁止仅依赖本地 `author name`:
- 接口:`https://api.github.com/repos/<owner>/<repo>/commits/<sha>`
- 请求头至少包含:`Accept: application/vnd.github+json`、`User-Agent: <custom>`
- 解析顺序固定:优先 `author.login`,为空时取 `committer.login`
- 必须保证覆盖全量区间提交:
- 对每个 SHA 单独请求并记录结果
- 输出前校验“已解析 login 数 == 区间提交数”,不一致则进入回退链
- 回退链(仅当 API 某条未命中时):
- 先用“同区间内已解析结果”做映射回填(同 author email / 同 author name)
- 再解析 GitHub noreply 邮箱:
- `[email protected]` -> `@login`
- `[email protected]` -> `@login`
- 再回退 `.atom`:`https://github.com/<owner>/<repo>/commits/<branch>.atom` 按 SHA 匹配 `<entry>` 获取 `<author><name>`
- 最后才允许作者名标准化兜底,并明确标记为推断
- 为每条变更记录绑定对应作者的 `@id`
- 若一条汇总涉及多个 commit,按去重后多作者格式追加:`@id1 @id2`
## 输出格式(强制,需贴近 GitHub Releases 风格)
必须产出 1 个文件:
1. 变更内容文件(全中文)
- 文件路径:`.trae/documents/ReleaseNotes-<version>.md`(文件名必须 ASCII)
- 内容结构(推荐模板):
- 一级标题:`## <version> <版本主题>`(示例:`## 0.58 月之五适配`)
- 开场一句话:版本背景或问候语(可选,1~2 句)
- 分类正文:按以下顺序输出存在内容的分类:
- `新功能`
- `地图遮罩`
- `独立任务`
- `JS相关`
- `其他`(必须保留,即使只有 1 条)
- 分类内每条为单行 bullet,格式:
- `<变更描述> (#PR号可选) @githubId`
- 若某条由多人提交,使用:`@id1 @id2`
- 文末追加“完整提交清单”(倒序,不能缺项,每条带 `@id`)
- 在标题下方补充统计信息:`边界提交 / 区间 / 提交数 / shortstat`
补充要求:
- 变更内容文件必须全中文
- 仅内容全中文;文件名必须为 ASCII,避免 Windows 下出现 `?` 非法路径
- 风格贴近 GitHub Releases:简洁分段、先讲用户可感知变化,再给完整清单
- 正文优先使用自然语言,不直接复制 commit 原文
- 分类不允许缺失“其他”
- 内容中不保留 `feat:`、`fix:` 前缀
- 生成后必须执行乱码检查:若命中 `\\?{2,}` 或 `### \\?+`,视为失败并重生成
## 质量门槛
- 不允许遗漏区间内任意 commit
- 不允许仅基于 commit 标题,必须结合实际代码改动
- 每条变更记录必须带作者 `@id`,不允许只在末尾集中列出
- 必须通过 Python 脚本获取日志与 diff,禁止直接依赖终端长输出结果
- 解析 `@id` 时必须逐条调用 GitHub Commit API(`/repos/<owner>/<repo>/commits/<sha>`),不得以本地昵称直接替代
- 未找到边界版本时,必须明确说明并给出当前采用的兜底范围
- 分类默认遵循“新功能 / 地图遮罩 / 独立任务 / JS相关 / 其他”,其中“其他”必须出现
- Markdown 文件必须实际落盘到仓库中的 `.trae/documents` 目录
- 不允许输出出现乱码占位符(如 `???`、`??` 分类名);发现即判定为不合格
+118
View File
@@ -0,0 +1,118 @@
本项目使用了 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
```
###其他要求
1. 改动时候请不要删除已有的注释,你可以修改,但是不要删!
2. 存在不确定点时主动提问
3. 仅单次使用的代码,不做过度抽象封装
## Code Review Rules
### Output language
- 必须使用简体中文输出代码审查结果。
- 问题标题、问题描述、影响分析和修复建议必须使用中文。
- 类名、方法名、变量名、文件路径、代码片段和错误消息保持原文。
- 专业术语第一次出现时可以采用“中文(English)”格式。
### Review priorities
- 优先检查可能造成崩溃、死锁、资源泄漏和数据竞争的问题。
- 重点检查异步任务、CancellationToken、线程切换和 STA UI 线程使用。
- 重点检查 Mat、Bitmap、Stream、CancellationTokenSource 等 IDisposable 对象是否正确释放。
- 检查游戏输入、截图和多实例场景是否存在共享状态冲突。
- 不要只提出风格问题,除非它会影响正确性、可维护性或性能。
### Finding format
每个问题按以下结构输出:
1. 严重程度
2. 问题位置
3. 问题原因
4. 可能造成的影响
5. 推荐修复方案
+19 -2
View File
@@ -1,4 +1,4 @@
<Application x:Class="BetterGenshinImpact.App"
<Application x:Class="BetterGenshinImpact.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:behavior="clr-namespace:BetterGenshinImpact.View.Behavior"
@@ -13,17 +13,34 @@
<vio:ControlsDictionary />
<ResourceDictionary Source="/View/Controls/WpfUi/FaFontIconStyle.xaml" />
<ResourceDictionary Source="/View/Controls/Drawer/DrawerStyles.xaml" />
<ResourceDictionary Source="/View/Controls/Markdown/Resources/MarkdownStyles.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- ===== 字体 ===== -->
<FontFamily x:Key="TextThemeFontFamily">/Resources/Fonts/MiSans-Regular.ttf#MiSans</FontFamily>
<FontFamily x:Key="DigitalThemeFontFamily">/Resources/Fonts/deluge-led.ttf#Deluge LED</FontFamily>
<!-- ===== 设计令牌 ===== -->
<CornerRadius x:Key="ControlCornerRadius">6</CornerRadius>
<Thickness x:Key="PagePadding">48,20,48,28</Thickness>
<!-- ===== 全局 Converter ===== -->
<bgivc:DomainNameToCascadingItemConverter x:Key="DomainNameConverter" />
<bgivc:AutoBossNameToCascadingItemConverter x:Key="AutoBossNameConverter" />
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
<bgivc:BooleanToVisibilityRevertConverter x:Key="BooleanToVisibilityRevertConverter" />
<bgivc:BooleanToEnableTextConverter x:Key="BooleanToEnableTextConverter" />
<bgivc:InverseBooleanConverter x:Key="InverseBooleanConverter" />
<bgivc:NotNullConverter x:Key="NotNullConverter" />
<bgivc:EnumToKVPConverter x:Key="EnumToKVPConverter" />
<bgivc:EnumToVisibilityConverter x:Key="EnumToVisibilityConverter" />
<bgivc:NullToVisibilityConverter x:Key="NullToVisibilityConverter" />
<bgivc:CultureInfoNameToKVPConverter x:Key="CultureInfoNameToKVPConverter" />
<bgivc:StringToColorConverter x:Key="StringToColorConverter" />
<bgivc:TrConverter x:Key="TrConverter" />
<bgivc:AdaptiveUniformGridColumnsConverter x:Key="AdaptiveUniformGridColumnsConverter" />
<!-- ===== 全局 TextBox 安全剪贴板 ===== -->
<Style BasedOn="{StaticResource DefaultTextBoxStyle}" TargetType="{x:Type TextBox}">
<Setter Property="behavior:ClipboardInterceptor.EnableSafeClipboard" Value="True" />
</Style>
@@ -32,4 +49,4 @@
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
</Application>
+111 -13
View File
@@ -7,22 +7,28 @@ using System.Windows;
using System.Windows.Threading;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Helpers.Win32;
using BetterGenshinImpact.Hutao;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.ChildSession;
using BetterGenshinImpact.Service.Instance;
using BetterGenshinImpact.Service.GearTask;
using BetterGenshinImpact.Service.Interface;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.Service.Notifier;
using BetterGenshinImpact.View;
using BetterGenshinImpact.View.Pages;
using BetterGenshinImpact.View.Windows;
using BetterGenshinImpact.ViewModel;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.ViewModel.Pages.View;
using BetterGenshinImpact.ViewModel.Windows;
using LazyCache;
using Microsoft.Extensions.Caching.Memory;
using BetterGenshinImpact.ViewModel.Windows;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
@@ -33,6 +39,7 @@ using Wpf.Ui;
using Wpf.Ui.DependencyInjection;
using Wpf.Ui.Violeta.Appearance;
using Wpf.Ui.Violeta.Controls;
using Quartz;
// Wine 平台适配
using BetterGenshinImpact.Platform.Wine;
@@ -50,10 +57,9 @@ public partial class App : Application
private static readonly IHost _host = Host.CreateDefaultBuilder()
.CheckIntegration()
.UseElevated()
.UseSingleInstance("BetterGI")
.UseInstanceIpc()
.ConfigureLogging(builder => { builder.ClearProviders(); })
.ConfigureServices(
(context, services) =>
.ConfigureServices((context, services) =>
{
// 提前初始化配置
var configService = new ConfigService();
@@ -68,29 +74,53 @@ public partial class App : Application
services.AddSingleton<IRichTextBox>(richTextBox);
var loggerConfiguration = new LoggerConfiguration()
.Enrich.FromLogContext() // Enable LogContext
.WriteTo.File(logFile,
outputTemplate:
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
"[{Timestamp:HH:mm:ss.fff}] [{Level:u3}] [{CorrelationId}] {SourceContext}{NewLine}{Message}{NewLine}{Exception}{NewLine}",
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 31,
retainedFileTimeLimit: TimeSpan.FromDays(21))
.WriteTo.Console(outputTemplate:
.WriteTo.Console(outputTemplate:
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning);
if (all.MaskWindowConfig.MaskEnabled)
.MinimumLevel.Override("Microsoft.Hosting.Lifetime", LogEventLevel.Warning)
.MinimumLevel.Override("Quartz", LogEventLevel.Information);
if (all.MaskWindowConfig is { MaskEnabled: true, ShowLogBox: true })
{
loggerConfiguration.WriteTo.RichTextBox(richTextBox, LogEventLevel.Information,
"[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}");
}
Log.Logger = loggerConfiguration.CreateLogger();
services.AddSingleton<IMissingTranslationReporter, SupabaseMissingTranslationReporter>();
services.AddSingleton<ITranslationService, JsonTranslationService>();
services.AddLogging(c => c.AddSerilog());
// if ("zh-Hans".Equals(all.OtherConfig.UiCultureInfoName, StringComparison.OrdinalIgnoreCase))
// {
// services.AddLogging(c => c.AddSerilog());
// }
// else
// {
// services.AddLogging(logging =>
// {
// logging.ClearProviders();
// logging.SetMinimumLevel(LogLevel.Debug);
// logging.AddFilter("Microsoft", LogLevel.Warning);
// logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Warning);
// logging.AddFilter("Quartz", LogLevel.Information);
// logging.Services.AddSingleton<ILoggerProvider, TranslatingSerilogLoggerProvider>();
// });
// }
services.AddLocalization();
services.AddNavigationViewPageProvider();
services.AddSingleton(InstanceBootstrap.Current);
services.AddSingleton<InstanceService>();
services.AddHostedService(sp => sp.GetRequiredService<InstanceService>());
// App Host
services.AddHostedService<ApplicationHostService>();
// Page resolver service
@@ -104,6 +134,24 @@ public partial class App : Application
// Main window with navigation
services.AddView<INavigationWindow, MainWindow, MainWindowViewModel>();
services.AddSingleton<NotifyIconViewModel>();
services.AddSingleton<ChildSessionService>();
services.AddTransient<ChildSessionWindowViewModel>();
services.AddTransient<ChildSessionWindow>();
// Quartz.NET 调度器配置
services.AddQuartz(q =>
{
q.UseSimpleTypeLoader();
q.UseInMemoryStore();
q.UseDefaultThreadPool(tp =>
{
tp.MaxConcurrency = 1;
});
});
services.AddQuartzHostedService(q => q.WaitForJobsToComplete = true);
services.AddSingleton<QuartzSchedulerService>();
services.AddHostedService(sp => sp.GetRequiredService<QuartzSchedulerService>());
services.AddGearTaskServices();
// Views
services.AddView<HomePage, HomePageViewModel>();
@@ -117,10 +165,16 @@ public partial class App : Application
services.AddView<KeyMouseRecordPage, KeyMouseRecordPageViewModel>();
services.AddView<JsListPage, JsListViewModel>();
services.AddView<MapPathingPage, MapPathingViewModel>();
services.AddView<GatheringAndFarmingPage, GatheringAndFarmingPageViewModel>();
services.AddView<OneDragonFlowPage, OneDragonFlowViewModel>();
services.AddSingleton<PathingConfigViewModel>();
// services.AddView<PathingConfigView, PathingConfigViewModel>();
services.AddView<KeyBindingsSettingsPage, KeyBindingsSettingsPageViewModel>();
services.AddView<SchedulerPage, SchedulerViewModel>();
services.AddView<GearTaskListPage, GearTaskListPageViewModel>();
services.AddView<GearTriggerPage, GearTriggerPageViewModel>();
services.AddTransient<TaskDefinitionEditWindow>();
services.AddTransient<TaskDefinitionEditWindowViewModel>();
// 一条龙 ViewModels
// services.AddSingleton<CraftViewModel>();
@@ -134,12 +188,15 @@ public partial class App : Application
// services.AddSingleton<TcgViewModel>();
// My Services
services.AddSingleton<DirectInputMonitor>();
services.AddSingleton<RawInputMonitor>();
services.AddSingleton<IRelativeMouseInputMonitorFactory, RelativeMouseInputMonitorFactory>();
services.AddSingleton<OverlayMetricsService>();
services.AddSingleton<TaskTriggerDispatcher>();
services.AddSingleton<NotificationService>();
services.AddHostedService(sp => sp.GetRequiredService<NotificationService>());
services.AddSingleton<NotifierManager>();
services.AddSingleton<IScriptService, ScriptService>();
services.AddSingleton<HutaoNamedPipe>();
services.AddSingleton<BgiOnnxFactory>();
services.AddSingleton<OcrFactory>();
services.AddMemoryCache();
@@ -147,14 +204,19 @@ public partial class App : Application
services.AddSingleton<MemoryFileCache>();
services.AddSingleton<IMihoyoMapApiService, MihoyoMapApiService>();
services.AddSingleton<IKongyingTavernApiService, KongyingTavernApiService>();
services.AddSingleton<IHoYoLabMapApiService, HoYoLabMapApiService>();
services.AddSingleton<IMaskMapPointService, MaskMapPointService>();
services.AddSingleton<GearTaskStorageService>();
services.AddSingleton<GearTriggerStorageService>();
services.AddSingleton(TimeProvider.System);
services.AddSingleton<IServerTimeProvider, ServerTimeProvider>();
// Configuration
//services.Configure<AppConfig>(context.Configuration.GetSection(nameof(AppConfig)));
I18N.Culture = new CultureInfo("zh-Hans"); // #1846
}
)
@@ -176,6 +238,11 @@ public partial class App : Application
{
return _host.Services.GetService(typeof(T)) as T;
}
public static T GetRequiredService<T>() where T : class
{
return _host.Services.GetRequiredService<T>();
}
/// <summary>
/// Gets registered service.
@@ -192,6 +259,7 @@ public partial class App : Application
/// </summary>
protected override async void OnStartup(StartupEventArgs e)
{
Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.Normal;
// Wine 平台适配
WinePlatformAddon.ApplyApplicationConfig();
base.OnStartup(e);
@@ -207,10 +275,19 @@ public partial class App : Application
}
catch (Exception ex)
{
// DEBUG only, no overhead
Debug.WriteLine(ex);
ConsoleHelper.WriteError($"应用程序启动失败: {ex.Message}");
try
{
HandleException(ex);
}
catch (Exception ex2)
{
Debug.WriteLine(ex2);
ConsoleHelper.WriteError($"应用程序启动失败打印日志时又失败了: {ex2.Message}");
}
if (Debugger.IsAttached)
{
Debugger.Break();
@@ -226,12 +303,12 @@ public partial class App : Application
base.OnExit(e);
ConsoleHelper.WriteLine("BetterGI 应用程序正在关闭...");
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
// 释放控制台窗口
ConsoleHelper.FreeConsoleWindow();
}
@@ -255,6 +332,12 @@ public partial class App : Application
{
try
{
// 忽略V8引擎释放后pending的Task回调抛出的异常
if (IsV8EngineReleasedException(e.Exception))
{
return;
}
HandleException(e.Exception);
}
catch (Exception ex)
@@ -267,6 +350,21 @@ public partial class App : Application
}
}
private static bool IsV8EngineReleasedException(Exception? ex)
{
while (ex != null)
{
if (ex.Message?.Contains("V8 object has been released") == true)
{
return true;
}
ex = ex.InnerException;
}
return false;
}
//非UI线程未捕获异常处理事件(例如自己创建的一个子线程)
private static void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
+3 -1
View File
@@ -1,5 +1,7 @@
using System.Windows;
using System.Windows.Media;
using System.Runtime.CompilerServices;
[assembly: DisableDpiAwareness]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
[assembly: InternalsVisibleTo("BetterGenshinImpact.UnitTest")]
+51 -14
View File
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.55.2-alpha.1</Version>
<Version>0.62.2-alpha.1</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -35,6 +35,7 @@
<Resource Include="Resources\Images\*.png" />
<Resource Include="Resources\Images\*.ico" />
<Resource Include="Resources\Fonts\*.ttf" />
<Resource Include="Resources\Json\*.json" />
</ItemGroup>
<ItemGroup>
@@ -43,18 +44,21 @@
<PackageReference Include="BetterGI.VCRuntime" Version="14.44.35208" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.17" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.18" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.10" />
<PackageReference Include="BetterGI.Assets.Map" Version="1.0.19" />
<PackageReference Include="BetterGI.Assets.Model" Version="1.0.29" />
<PackageReference Include="BetterGI.Assets.Other" Version="1.0.17" />
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.2.2" />
<PackageReference Include="DeviceId" Version="6.9.0" />
<PackageReference Include="DeviceId.Windows" Version="6.9.0" />
<PackageReference Include="DeviceId.Windows.Wmi" Version="6.9.0" />
<PackageReference Include="Emoji.Wpf" Version="0.3.4" />
<PackageReference Include="HungarianAlgorithm" Version="2.3.5" />
<PackageReference Include="LibGit2Sharp" Version="0.31.0" />
<PackageReference Include="LazyCache" Version="2.4.0" />
<PackageReference Include="MailKit" Version="4.14.0" />
<PackageReference Include="LibreHardwareMonitorLib" Version="0.9.6" />
<PackageReference Include="MailKit" Version="4.16.0" />
<PackageReference Include="Markdig" Version="1.3.2" />
<PackageReference Include="Meziantou.Framework.Win32.CredentialManager" Version="1.7.4" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.4" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="9.0.4" />
@@ -67,16 +71,19 @@
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.21.0" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="MimeKit" Version="4.14.0" />
<PackageReference Include="MimeKit" Version="4.16.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Extensions" Version="4.11.0.20250507" />
<PackageReference Include="OpenCvSharp4.Windows" Version="4.11.0.20250507" />
<PackageReference Include="Quartz" Version="3.15.0" />
<PackageReference Include="Quartz.Extensions.Hosting" Version="3.15.0" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.122" />
<PackageReference Include="Microsoft.ClearScript.V8" Version="7.4.5" />
<PackageReference Include="Microsoft.ClearScript.V8.Native.win-x64" Version="7.4.5" />
<PackageReference Include="MouseKeyHook" Version="5.7.1" />
<PackageReference Include="NCalc" Version="6.2.0" />
<PackageReference Include="PresentMonFps" Version="2.0.5" />
<PackageReference Include="Sdl.MultiSelectComboBox" Version="1.0.103" />
<PackageReference Include="Semver" Version="3.0.0" />
@@ -84,17 +91,19 @@
<PackageReference Include="Serilog.Sinks.Console" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.File" Version="6.0.0" />
<PackageReference Include="Serilog.Sinks.RichTextBoxEx.Wpf" Version="1.1.0.1" />
<PackageReference Include="System.Drawing.Common" Version="10.0.0" />
<!-- <PackageReference Include="supabase-csharp" Version="0.16.2" />-->
<PackageReference Include="System.Drawing.Common" Version="10.0.7" />
<PackageReference Include="SixLabors.ImageSharp" Version="3.1.11" />
<PackageReference Include="System.IO.Hashing" Version="9.0.4" />
<PackageReference Include="TorchSharp" Version="0.105.0" />
<PackageReference Include="Vanara.PInvoke.CoreAudio" Version="4.1.3" />
<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.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.3" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
<PackageReference Include="YamlDotNet" Version="16.3.0" />
<PackageReference Include="YoloSharp" Version="6.0.3" />
@@ -110,6 +119,9 @@
</ItemGroup>
<ItemGroup>
<None Update="GameTask\**\Recognition.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Assets\Map\**">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
@@ -125,7 +137,10 @@
<None Update="GameTask\AutoFight\Assets\combat_avatar.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoFishing\Assets\1920x1080\**">
<None Update="GameTask\AutoFishing\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoLeyLineOutcrop\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\LogParse\Assets\**">
@@ -143,7 +158,7 @@
<None Update="GameTask\AutoSkip\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoSkip\Assets\hangout.json">
<None Update="GameTask\AutoSkip\Assets\*.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoTrackPath\Assets\tp.json">
@@ -176,6 +191,9 @@
<None Update="GameTask\QuickBuy\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\QuickClaimReward\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\UseRedeemCode\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
@@ -194,6 +212,15 @@
<None Update="GameTask\Common\Element\Assets\1920x1080\in_domain.png">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoDomain\Assets\1920x1080\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="GameTask\AutoBoss\Assets\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="User\I18n\en.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
@@ -220,6 +247,16 @@
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
<Page Update="View\Windows\GearTask\AddTaskNodeDialog.xaml">
<Generator>MSBuild:Compile</Generator>
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
<Page Update="View\Windows\GearTask\JsScriptSelectionWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
+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;
}
}
+33 -9
View File
@@ -1,6 +1,6 @@
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -22,7 +22,10 @@ using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.GetGridIcons;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.MapMask;
using BetterGenshinImpact.GameTask.SkillCd;
using BetterGenshinImpact.GameTask.UseRedeemCode;
namespace BetterGenshinImpact.Core.Config;
@@ -127,11 +130,6 @@ public partial class AllConfig : ObservableObject
/// </summary>
public QuickTeleportConfig QuickTeleportConfig { get; set; } = new();
/// <summary>
/// 自动烹饪配置
/// </summary>
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 自动打牌配置
/// </summary>
@@ -156,6 +154,11 @@ public partial class AllConfig : ObservableObject
/// 自动秘境配置
/// </summary>
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 自动首领讨伐配置
/// </summary>
public AutoBossConfig AutoBossConfig { get; set; } = new();
/// <summary>
@@ -172,12 +175,24 @@ public partial class AllConfig : ObservableObject
/// 自动吃药配置
/// </summary>
public AutoEatConfig AutoEatConfig { get; set; } = new();
/// <summary>
/// 自动地脉花配置
/// </summary>
public AutoLeyLineOutcropConfig AutoLeyLineOutcropConfig { get; set; } = new();
public AutoCookConfig AutoCookConfig { get; set; } = new();
/// <summary>
/// 地图遮罩
/// </summary>
public MapMaskConfig MapMaskConfig { get; set; } = new();
/// <summary>
/// 技能 CD 提示
/// </summary>
public SkillCdConfig SkillCdConfig { get; set; } = new();
/// <summary>
/// 自动使用
/// </summary>
@@ -241,6 +256,11 @@ public partial class AllConfig : ObservableObject
/// </summary>
public HardwareAccelerationConfig HardwareAccelerationConfig { get; set; } = new();
/// <summary>
/// 桌面分身配置
/// </summary>
public ChildSessionConfig ChildSessionConfig { get; set; } = new();
[JsonIgnore]
public Action? OnAnyChangedAction { get; set; }
@@ -257,16 +277,18 @@ public partial class AllConfig : ObservableObject
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
QuickTeleportConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MacroConfig.PropertyChanged += OnAnyPropertyChanged;
HotKeyConfig.PropertyChanged += OnAnyPropertyChanged;
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
AutoBossConfig.PropertyChanged += OnAnyPropertyChanged;
AutoStygianOnslaughtConfig.PropertyChanged += OnAnyPropertyChanged;
AutoArtifactSalvageConfig.PropertyChanged += OnAnyPropertyChanged;
AutoRedeemCodeConfig.PropertyChanged += OnAnyPropertyChanged;
AutoEatConfig.PropertyChanged += OnAnyPropertyChanged;
AutoLeyLineOutcropConfig.PropertyChanged += OnAnyPropertyChanged;
AutoCookConfig.PropertyChanged += OnAnyPropertyChanged;
MapMaskConfig.PropertyChanged += OnAnyPropertyChanged;
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
TpConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -274,6 +296,8 @@ public partial class AllConfig : ObservableObject
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
DevConfig.PropertyChanged += OnAnyPropertyChanged;
HardwareAccelerationConfig.PropertyChanged += OnAnyPropertyChanged;
ChildSessionConfig.PropertyChanged += OnAnyPropertyChanged;
SkillCdConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -286,4 +310,4 @@ public partial class AllConfig : ObservableObject
{
NotificationService.Instance().RefreshNotifiers();
}
}
}
@@ -0,0 +1,38 @@
using System;
using CommunityToolkit.Mvvm.ComponentModel;
namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class ChildSessionConfig : ObservableObject
{
/// <summary>
/// 桌面分身窗口是否置顶。
/// </summary>
[ObservableProperty]
private bool _topmostEnabled = false;
/// <summary>
/// RDP 画面是否自适应窗口。关闭时使用 1:1 显示。
/// </summary>
[ObservableProperty]
private bool _smartSizingEnabled = true;
/// <summary>
/// 桌面分身窗口是否保持 16:9 宽高比。
/// </summary>
[ObservableProperty]
private bool _keepAspectRatio = true;
/// <summary>
/// Alt+Tab、Windows 键等系统组合键是否发送到桌面分身。
/// </summary>
[ObservableProperty]
private bool _sendSystemShortcutsToRemote = true;
/// <summary>
/// 桌面分身是否启用游戏鼠标模式。默认使用普通鼠标模式。
/// </summary>
[ObservableProperty]
private bool _gameMouseModeEnabled = false;
}
@@ -38,6 +38,12 @@ public partial class CommonConfig : ObservableObject
[ObservableProperty]
private bool _screenshotUidCoverEnabled = true;
/// <summary>
/// 是否保存奖励识别调试截图
/// </summary>
[ObservableProperty]
private bool _rewardRecognitionScreenshotEnabled;
/// <summary>
/// 退出时最小化至托盘
/// </summary>
@@ -80,4 +86,22 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _redeemCodeFeedsUpdateVersion = "20251013";
/// <summary>
/// 国服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeCnFeedsNotificationEnabled = true;
/// <summary>
/// 国际服兑换码更新是否允许通知
/// </summary>
[ObservableProperty]
private bool _redeemCodeGlobalFeedsNotificationEnabled;
/// <summary>
/// 当前看过的国际服兑换码推送版本
/// </summary>
[ObservableProperty]
private string _redeemCodeGlobalFeedsUpdateVersion = string.Empty;
}
@@ -47,4 +47,10 @@ public partial class GenshinStartConfig : ObservableObject
[ObservableProperty]
private bool _startGameWithCmd = false;
/// <summary>
/// 启动前自动关闭原神 HDR(删除原神 HDR 对应注册表键)
/// </summary>
[ObservableProperty]
private bool _autoDisableGenshinHdrEnabled = true;
}
@@ -14,10 +14,10 @@ public partial class HardwareAccelerationConfig : ObservableObject
private InferenceDeviceType _inferenceDevice = InferenceDeviceType.Cpu;
/// <summary>
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认关闭。
/// 是否强制OCR使用CPU推理。在某些环境上使用GPU进行OCR推理会导致性能下降(比如很多使用DirectML推理的情况下)。默认开启。
/// </summary>
[ObservableProperty]
private bool _cpuOcr = false;
private bool _cpuOcr = true;
#region 一般GPU加速设置
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -82,6 +82,12 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickBuyHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
[ObservableProperty]
private string _oneKeyClaimRewardHotkey = "";
[ObservableProperty]
private string _oneKeyClaimRewardHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
[ObservableProperty]
private string _quickSereniteaPotHotkey = "";
@@ -100,6 +106,13 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _quickTeleportTickHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 技能CD提示开关
[ObservableProperty]
private string _skillCdEnabledHotkey = "";
[ObservableProperty]
private string _skillCdEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 截图
[ObservableProperty]
@@ -156,6 +169,13 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _autoFishingGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动烹饪开始/停止
[ObservableProperty]
private string _autoCookGameHotkey = "";
[ObservableProperty]
private string _autoCookGameHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 自动寻路
[ObservableProperty]
private string _autoTrackPathHotkey = "";
@@ -212,6 +232,13 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _logBoxDisplayHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 遮罩指标栏展示
[ObservableProperty]
private string _overlayMetricsDisplayHotkey = "";
[ObservableProperty]
private string _overlayMetricsDisplayHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 键鼠录制/停止
[ObservableProperty]
private string _keyMouseMacroRecordHotkey = "";
@@ -237,4 +264,11 @@ public partial class HotKeyConfig : ObservableObject
[ObservableProperty]
private string _onedragonHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
// 地图遮罩开关
[ObservableProperty]
private string _mapMaskEnabledHotkey = "";
[ObservableProperty]
private string _mapMaskEnabledHotkeyType = HotKeyTypeEnum.KeyboardMonitor.ToString();
}
@@ -1,4 +1,5 @@
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.QuickClaimReward;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -67,4 +68,22 @@ public partial class MacroConfig : ObservableObject
/// </summary>
[ObservableProperty]
private int _combatMacroPriority = 1;
/// <summary>
/// 一键领取奖励快捷键模式
/// </summary>
[ObservableProperty]
private string _oneKeyClaimRewardHotkeyMode = OneKeyClaimRewardTask.ClickOnceMode;
/// <summary>
/// 一键领取奖励未找到领取图标时滚轮下滑
/// </summary>
[ObservableProperty]
private bool _oneKeyClaimRewardScrollDownEnabled;
/// <summary>
/// 一键领取奖励滚轮下滑幅度
/// </summary>
[ObservableProperty]
private int _oneKeyClaimRewardScrollDownAmount = 2;
}
@@ -1,6 +1,8 @@
using CommunityToolkit.Mvvm.ComponentModel;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
@@ -10,6 +12,30 @@ namespace BetterGenshinImpact.Core.Config;
[Serializable]
public partial class MaskWindowConfig : ObservableObject
{
public const int MinCrosshairLineWidth = 1;
public const int MaxCrosshairLineWidth = 100;
public const int MinCrosshairSize = 1;
public const int MaxCrosshairSize = 1000;
public const int MinCrosshairGap = 0;
public const int MaxCrosshairGap = 1000;
// 指标栏布局和遮罩里其它元素一样按 1920x1080 折算比例保存,默认放在状态栏/日志上方以避开游戏底部 UI。
public const double DefaultMetricsLeftRatio = 20.0 / 1920;
public const double DefaultMetricsTopRatio = 744.0 / 1080;
public const double DefaultMetricsWidthRatio = 477.0 / 1920;
public const double DefaultMetricsHeightRatio = 58.0 / 1080;
// 这些是开发评审过程中曾下发过的默认布局;用户没有手动调整时迁移到最新默认值,避免旧默认继续挡住游戏 UI。
private static readonly (double Left, double Top, double Width, double Height)[] LegacyMetricsLayouts =
[
(4.0 / 1920, 4.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(600.0 / 1920, 16.0 / 1080, 720.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 58.0 / 1080),
(20.0 / 1920, 724.0 / 1080, 760.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 42.0 / 1080),
(20.0 / 1920, 760.0 / 1080, 477.0 / 1920, 58.0 / 1080)
];
/// <summary>
/// 方位提示是否启用
/// </summary>
@@ -57,6 +83,81 @@ public partial class MaskWindowConfig : ObservableObject
[NonSerialized]
public static readonly Rect UidCoverRightBottomRect = new(1920 - 1685, 1080 - 1053, 178, 22);
/// <summary>
/// 准星是否启用
/// </summary>
[ObservableProperty]
private bool _crosshairEnabled;
/// <summary>
/// 准星类型
/// </summary>
[ObservableProperty]
private CrosshairType _crosshairType = CrosshairType.Crosshair;
/// <summary>
/// 准星颜色(十六进制)
/// </summary>
[ObservableProperty]
private string _crosshairColor = "#FFFFFF";
/// <summary>
/// 准星线宽
/// </summary>
[ObservableProperty]
private int _crosshairLineWidth = 4;
/// <summary>
/// 准星大小
/// </summary>
[ObservableProperty]
private int _crosshairSize = 30;
/// <summary>
/// 中心点与十字线的间隔(仅 DotCrosshair 类型)
/// </summary>
[ObservableProperty]
private int _crosshairGap = 10;
partial void OnCrosshairLineWidthChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairLineWidth, MaxCrosshairLineWidth);
if (value != clampedValue)
{
CrosshairLineWidth = clampedValue;
}
}
partial void OnCrosshairSizeChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairSize, MaxCrosshairSize);
if (value != clampedValue)
{
CrosshairSize = clampedValue;
}
}
partial void OnCrosshairGapChanged(int value)
{
var clampedValue = Math.Clamp(value, MinCrosshairGap, MaxCrosshairGap);
if (value != clampedValue)
{
CrosshairGap = clampedValue;
}
}
/// <summary>
/// 自定义准星图片路径
/// </summary>
[ObservableProperty]
private string? _crosshairImagePath;
/// <summary>
/// 自定义图片缩放方式
/// </summary>
[ObservableProperty]
private CrosshairScaleMode _crosshairScaleMode = CrosshairScaleMode.Original;
/// <summary>
/// 显示FPS
/// </summary>
@@ -64,11 +165,13 @@ public partial class MaskWindowConfig : ObservableObject
private bool _showFps = false;
/// <summary>
/// 作为原神子窗体
/// 有些bug没解决
/// 显示遮罩指标栏
/// </summary>
[ObservableProperty]
private bool _useSubform = false;
private bool _showOverlayMetrics = false;
// 配置文件里使用 string key 便于兼容旧版本,读取后由 EnsureOverlayMetricItems 约束回固定枚举集合。
public Dictionary<string, bool> OverlayMetricItems { get; set; } = OverlayMetricItemDefaults.CreateDefaultItems();
/// <summary>
/// 遮罩文本透明度 (0.0-1.0)
@@ -83,10 +186,10 @@ public partial class MaskWindowConfig : ObservableObject
private double _logTextBoxLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _logTextBoxTopRatio = 832.0 / 1080;
private double _logTextBoxTopRatio = 822.0 / 1080;
[ObservableProperty]
private double _logTextBoxWidthRatio = 477.0 / 1920;
private double _logTextBoxWidthRatio = 480.0 / 1920;
[ObservableProperty]
private double _logTextBoxHeightRatio = 188.0 / 1080;
@@ -95,11 +198,113 @@ public partial class MaskWindowConfig : ObservableObject
private double _statusListLeftRatio = 20.0 / 1920;
[ObservableProperty]
private double _statusListTopRatio = 807.0 / 1080;
private double _statusListTopRatio = 790.0 / 1080;
[ObservableProperty]
private double _statusListWidthRatio = 477.0 / 1920;
private double _statusListWidthRatio = 480.0 / 1920;
[ObservableProperty]
private double _statusListHeightRatio = 24.0 / 1080;
[ObservableProperty]
private double _metricsLeftRatio = DefaultMetricsLeftRatio;
[ObservableProperty]
private double _metricsTopRatio = DefaultMetricsTopRatio;
[ObservableProperty]
private double _metricsWidthRatio = DefaultMetricsWidthRatio;
[ObservableProperty]
private double _metricsHeightRatio = DefaultMetricsHeightRatio;
public void ResetOverlayMetricsLayout()
{
MetricsLeftRatio = DefaultMetricsLeftRatio;
MetricsTopRatio = DefaultMetricsTopRatio;
MetricsWidthRatio = DefaultMetricsWidthRatio;
MetricsHeightRatio = DefaultMetricsHeightRatio;
}
public void MigrateLegacyOverlayMetricsLayout()
{
if (LegacyMetricsLayouts.Any(layout =>
IsSameRatio(MetricsLeftRatio, layout.Left)
&& IsSameRatio(MetricsTopRatio, layout.Top)
&& IsSameRatio(MetricsWidthRatio, layout.Width)
&& IsSameRatio(MetricsHeightRatio, layout.Height)))
{
ResetOverlayMetricsLayout();
}
}
private static bool IsSameRatio(double left, double right)
{
return Math.Abs(left - right) < 0.0000001;
}
public void EnsureOverlayMetricItems()
{
// 旧配置可能缺少新指标或残留废弃指标,这里统一补默认项并移除非法 key,避免 UI 渲染任意字符串。
OverlayMetricItems ??= [];
// TriggerInterval 第一版展示的是配置值,现已替换为 PeakProcessingCost;保留用户原来的勾选状态。
const string legacyTriggerIntervalKey = "TriggerInterval";
var peakProcessingCostKey = OverlayMetricItem.PeakProcessingCost.ToString();
if (OverlayMetricItems.TryGetValue(legacyTriggerIntervalKey, out var legacyEnabled)
&& !OverlayMetricItems.ContainsKey(peakProcessingCostKey))
{
OverlayMetricItems[peakProcessingCostKey] = legacyEnabled;
}
foreach (var item in OverlayMetricItemDefaults.AllItems)
{
var key = item.ToString();
if (!OverlayMetricItems.ContainsKey(key))
{
OverlayMetricItems[key] = OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
}
var validKeys = OverlayMetricItemDefaults.AllItems.Select(item => item.ToString()).ToHashSet();
foreach (var key in OverlayMetricItems.Keys.Where(key => !validKeys.Contains(key)).ToList())
{
OverlayMetricItems.Remove(key);
}
}
public bool IsOverlayMetricEnabled(OverlayMetricItem item)
{
return OverlayMetricItems != null && OverlayMetricItems.TryGetValue(item.ToString(), out var enabled)
? enabled
: OverlayMetricItemDefaults.IsEnabledByDefault(item);
}
public void SetOverlayMetricEnabled(OverlayMetricItem item, bool enabled)
{
EnsureOverlayMetricItems();
OverlayMetricItems[item.ToString()] = enabled;
OnPropertyChanged(nameof(OverlayMetricItems));
}
}
/// <summary>
/// 准星类型
/// </summary>
public enum CrosshairType
{
Crosshair,
Diagonal,
Dot,
DotCrosshair,
Custom
}
/// <summary>
/// 自定义准星图片缩放方式
/// </summary>
public enum CrosshairScaleMode
{
Original,
Fit
}
@@ -1,6 +1,7 @@
using System;
using System;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.Helpers;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -13,10 +14,24 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _name = string.Empty;
// 下次执行的任务 Id(为空表示从头开始)
[ObservableProperty]
private string _nextTaskId = string.Empty;
/// <summary>
/// 所有任务的开关状态
/// 所有任务的开关状态(键为任务 Id)
/// </summary>
public Dictionary<string, bool> TaskEnabledList { get; set; } = new();
/// <summary>
/// 任务执行顺序(任务 Id 列表),用于显式恢复 TaskList 顺序
/// </summary>
public List<string> TaskOrder { get; set; } = new();
/// <summary>
/// 任务定义(Id → 任务名),用于支持同名任务重复添加
/// </summary>
public Dictionary<string, string> TaskDefinitions { get; set; } = new();
// 合成树脂的国家
[ObservableProperty]
@@ -36,6 +51,67 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private bool _weeklyDomainEnabled = false;
#region 自动首领讨伐配置
[ObservableProperty]
private string _autoBossName = string.Empty;
[ObservableProperty]
private string _autoBossStrategyName = "根据队伍自动选择";
[ObservableProperty]
private string _autoBossTeamName = string.Empty;
[ObservableProperty]
private bool _autoBossSpecifyRunCount = false;
[ObservableProperty]
private int _autoBossRunCount = 1;
[ObservableProperty]
private bool _autoBossUseTransientResin = false;
[ObservableProperty]
private bool _autoBossUseFragileResin = false;
[ObservableProperty]
private int _autoBossReviveRetryCount = 3;
[ObservableProperty]
private bool _autoBossReturnToStatueAfterEachRound = false;
[ObservableProperty]
private bool _autoBossRewardRecognitionEnabled = false;
partial void OnAutoBossSpecifyRunCountChanged(bool value)
{
if (value)
{
return;
}
AutoBossUseTransientResin = false;
AutoBossUseFragileResin = false;
}
partial void OnAutoBossRunCountChanged(int value)
{
if (value < 1)
{
AutoBossRunCount = 1;
}
}
partial void OnAutoBossReviveRetryCountChanged(int value)
{
if (value < 0)
{
AutoBossReviveRetryCount = 0;
}
}
#endregion
// 领取每日奖励的好感队伍名称
[ObservableProperty]
@@ -45,13 +121,13 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private int _minResinToKeep = 0;
// 领取每日奖励的好感数量
// 普通周日或限时奖励选项
[ObservableProperty]
private string _sundayEverySelectedValue = "0";
// 领取每日奖励的好感数量
// 每周秘境的全局限时奖励选项,单日留空时使用
[ObservableProperty]
private string _sundaySelectedValue = "0";
private string _sundayWeeklySelectedValue = "0";
// 尘歌壶传送方式,1. 地图传送 2. 尘歌壶道具
[ObservableProperty]
@@ -61,6 +137,87 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private List<string> _secretTreasureObjects = new();
// 地脉花一条龙模式(跳过部分准备流程)
[ObservableProperty]
private bool _leyLineOneDragonMode = false;
// 地脉花运行日期设置
[ObservableProperty]
private bool _leyLineRunMonday = true;
[ObservableProperty]
private bool _leyLineRunTuesday = true;
[ObservableProperty]
private bool _leyLineRunWednesday = true;
[ObservableProperty]
private bool _leyLineRunThursday = true;
[ObservableProperty]
private bool _leyLineRunFriday = true;
[ObservableProperty]
private bool _leyLineRunSaturday = true;
[ObservableProperty]
private bool _leyLineRunSunday = true;
// 地脉花每日类型与国家配置(为空则使用独立任务配置)
[ObservableProperty]
private string _leyLineMondayType = string.Empty;
[ObservableProperty]
private string _leyLineMondayCountry = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayType = string.Empty;
[ObservableProperty]
private string _leyLineTuesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayType = string.Empty;
[ObservableProperty]
private string _leyLineWednesdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineThursdayType = string.Empty;
[ObservableProperty]
private string _leyLineThursdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineFridayType = string.Empty;
[ObservableProperty]
private string _leyLineFridayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayType = string.Empty;
[ObservableProperty]
private string _leyLineSaturdayCountry = string.Empty;
[ObservableProperty]
private string _leyLineSundayType = string.Empty;
[ObservableProperty]
private string _leyLineSundayCountry = string.Empty;
// 地脉花刷取次数(0 表示使用独立任务配置)
[ObservableProperty]
private int _leyLineRunCount = 0;
// 地脉花树脂耗尽模式
[ObservableProperty]
private bool _leyLineResinExhaustionMode = false;
// 地脉花刷取次数取小值(仅耗尽模式生效)
[ObservableProperty]
private bool _leyLineOpenModeCountMin = false;
#region 每周秘境配置
//周一
@@ -69,6 +226,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _mondayDomainName = string.Empty;
[ObservableProperty]
private string _mondaySelectedValue = "0";
//周二
@@ -77,6 +237,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _tuesdayDomainName = string.Empty;
[ObservableProperty]
private string _tuesdaySelectedValue = "0";
//周三
[ObservableProperty]
@@ -84,6 +247,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _wednesdayDomainName = string.Empty;
[ObservableProperty]
private string _wednesdaySelectedValue = "0";
//周四
[ObservableProperty]
@@ -91,6 +257,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _thursdayDomainName = string.Empty;
[ObservableProperty]
private string _thursdaySelectedValue = "0";
//周五
[ObservableProperty]
@@ -98,6 +267,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _fridayDomainName = string.Empty;
[ObservableProperty]
private string _fridaySelectedValue = "0";
//周六
[ObservableProperty]
@@ -105,6 +277,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _saturdayDomainName = string.Empty;
[ObservableProperty]
private string _saturdaySelectedValue = "0";
//周日
[ObservableProperty]
@@ -113,6 +288,9 @@ public partial class OneDragonFlowConfig : ObservableObject
[ObservableProperty]
private string _sundayDomainName = string.Empty;
[ObservableProperty]
private string _sundaySelectedValue = "0";
// 完成后操作
[ObservableProperty]
private string _completionAction = string.Empty;
@@ -126,21 +304,93 @@ public partial class OneDragonFlowConfig : ObservableObject
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => (MondayPartyName, MondayDomainName,SundaySelectedValue),
DayOfWeek.Tuesday => (TuesdayPartyName, TuesdayDomainName,SundaySelectedValue),
DayOfWeek.Wednesday => (WednesdayPartyName, WednesdayDomainName,SundaySelectedValue),
DayOfWeek.Thursday => (ThursdayPartyName, ThursdayDomainName,SundaySelectedValue),
DayOfWeek.Friday => (FridayPartyName, FridayDomainName,SundaySelectedValue),
DayOfWeek.Saturday => (SaturdayPartyName, SaturdayDomainName,SundaySelectedValue),
DayOfWeek.Sunday => (SundayPartyName, SundayDomainName,SundaySelectedValue),
_ => (PartyName, DomainName,SundaySelectedValue)
DayOfWeek.Monday => (GetWeeklyPartyName(MondayPartyName), GetWeeklyDomainName(MondayDomainName), GetWeeklySelectedValue(MondaySelectedValue)),
DayOfWeek.Tuesday => (GetWeeklyPartyName(TuesdayPartyName), GetWeeklyDomainName(TuesdayDomainName), GetWeeklySelectedValue(TuesdaySelectedValue)),
DayOfWeek.Wednesday => (GetWeeklyPartyName(WednesdayPartyName), GetWeeklyDomainName(WednesdayDomainName), GetWeeklySelectedValue(WednesdaySelectedValue)),
DayOfWeek.Thursday => (GetWeeklyPartyName(ThursdayPartyName), GetWeeklyDomainName(ThursdayDomainName), GetWeeklySelectedValue(ThursdaySelectedValue)),
DayOfWeek.Friday => (GetWeeklyPartyName(FridayPartyName), GetWeeklyDomainName(FridayDomainName), GetWeeklySelectedValue(FridaySelectedValue)),
DayOfWeek.Saturday => (GetWeeklyPartyName(SaturdayPartyName), GetWeeklyDomainName(SaturdayDomainName), GetWeeklySelectedValue(SaturdaySelectedValue)),
DayOfWeek.Sunday => (GetWeeklyPartyName(SundayPartyName), GetWeeklyDomainName(SundayDomainName), GetWeeklySelectedValue(SundaySelectedValue)),
_ => (PartyName, DomainName, SundayWeeklySelectedValue)
};
}
else
{
return (PartyName, DomainName,SundayEverySelectedValue);
return (PartyName, DomainName, SundayEverySelectedValue);
}
}
private string GetWeeklyPartyName(string partyName)
{
return string.IsNullOrWhiteSpace(partyName) ? PartyName : partyName;
}
private string GetWeeklyDomainName(string domainName)
{
return string.IsNullOrWhiteSpace(domainName) ? DomainName : domainName;
}
private string GetWeeklySelectedValue(string selectedValue)
{
return string.IsNullOrWhiteSpace(selectedValue) || selectedValue == "0" ? SundayWeeklySelectedValue : selectedValue;
}
public bool ShouldRunLeyLineToday()
{
if (!LeyLineRunMonday
&& !LeyLineRunTuesday
&& !LeyLineRunWednesday
&& !LeyLineRunThursday
&& !LeyLineRunFriday
&& !LeyLineRunSaturday
&& !LeyLineRunSunday)
{
return true;
}
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
return dayOfWeek switch
{
DayOfWeek.Monday => LeyLineRunMonday,
DayOfWeek.Tuesday => LeyLineRunTuesday,
DayOfWeek.Wednesday => LeyLineRunWednesday,
DayOfWeek.Thursday => LeyLineRunThursday,
DayOfWeek.Friday => LeyLineRunFriday,
DayOfWeek.Saturday => LeyLineRunSaturday,
DayOfWeek.Sunday => LeyLineRunSunday,
_ => true
};
}
public (string type, string country) GetLeyLineConfigForToday(AutoLeyLineOutcropConfig fallback)
{
var serverTime = ServerTimeHelper.GetServerTimeNow();
var dayOfWeek = (serverTime.Hour >= 4 ? serverTime : serverTime.AddDays(-1)).DayOfWeek;
var (type, country) = dayOfWeek switch
{
DayOfWeek.Monday => (LeyLineMondayType, LeyLineMondayCountry),
DayOfWeek.Tuesday => (LeyLineTuesdayType, LeyLineTuesdayCountry),
DayOfWeek.Wednesday => (LeyLineWednesdayType, LeyLineWednesdayCountry),
DayOfWeek.Thursday => (LeyLineThursdayType, LeyLineThursdayCountry),
DayOfWeek.Friday => (LeyLineFridayType, LeyLineFridayCountry),
DayOfWeek.Saturday => (LeyLineSaturdayType, LeyLineSaturdayCountry),
DayOfWeek.Sunday => (LeyLineSundayType, LeyLineSundayCountry),
_ => (string.Empty, string.Empty)
};
if (string.IsNullOrWhiteSpace(type))
{
type = fallback.LeyLineOutcropType;
}
if (string.IsNullOrWhiteSpace(country))
{
country = fallback.Country;
}
return (type, country);
}
#endregion
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -121,4 +121,4 @@ public partial class OtherConfig : ObservableObject
/// </summary>
[ObservableProperty]
private string _uiCultureInfoName = "zh-Hans";
}
}
@@ -0,0 +1,85 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace BetterGenshinImpact.Core.Config;
public enum OverlayMetricItem
{
GameFps,
ProcessingCost,
PeakProcessingCost,
CaptureCost,
TriggerCost,
SkippedTicks,
CpuUsage,
GpuUsage,
MemoryUsage
}
public static class OverlayMetricItemDefaults
{
// 显式顺序同时决定遮罩三行三列显示顺序和设置页复选框顺序,不要随手改回 Enum.GetValues。
public static IReadOnlyList<OverlayMetricItem> AllItems { get; } =
[
OverlayMetricItem.GameFps,
OverlayMetricItem.ProcessingCost,
OverlayMetricItem.PeakProcessingCost,
OverlayMetricItem.CaptureCost,
OverlayMetricItem.TriggerCost,
OverlayMetricItem.SkippedTicks,
OverlayMetricItem.GpuUsage,
OverlayMetricItem.CpuUsage,
OverlayMetricItem.MemoryUsage
];
public static Dictionary<string, bool> CreateDefaultItems()
{
return AllItems.ToDictionary(item => item.ToString(), IsEnabledByDefault);
}
public static bool IsEnabledByDefault(OverlayMetricItem item)
{
// 默认只开启低风险的常用实时指标;硬件传感器项由用户按需开启,读不到时也不会占位显示。
return item is OverlayMetricItem.GameFps
or OverlayMetricItem.ProcessingCost
or OverlayMetricItem.PeakProcessingCost
or OverlayMetricItem.CaptureCost
or OverlayMetricItem.SkippedTicks
or OverlayMetricItem.MemoryUsage;
}
public static string GetDisplayName(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏帧率",
OverlayMetricItem.ProcessingCost => "处理耗时",
OverlayMetricItem.PeakProcessingCost => "峰值耗时",
OverlayMetricItem.CaptureCost => "截图耗时",
OverlayMetricItem.TriggerCost => "触发器耗时",
OverlayMetricItem.SkippedTicks => "跳过次数",
OverlayMetricItem.CpuUsage => "CPU占用",
OverlayMetricItem.GpuUsage => "显卡占用",
OverlayMetricItem.MemoryUsage => "内存占用",
_ => item.ToString()
};
}
public static string GetToolTipText(OverlayMetricItem item)
{
return item switch
{
OverlayMetricItem.GameFps => "游戏当前渲染帧率。",
OverlayMetricItem.ProcessingCost => "BetterGI 每轮截图、识别和触发器处理的总耗时。",
OverlayMetricItem.PeakProcessingCost => "最近 5 秒内 BetterGI 单轮处理耗时的峰值。",
OverlayMetricItem.CaptureCost => "单次获取游戏画面的耗时。",
OverlayMetricItem.TriggerCost => "本轮实际执行触发器的总耗时。",
OverlayMetricItem.SkippedTicks => "上一轮未结束导致本秒跳过的调度次数。",
OverlayMetricItem.CpuUsage => "CPU 总占用率,读取不到时自动隐藏。",
OverlayMetricItem.GpuUsage => "原神当前使用显卡的整体占用率,按最繁忙 GPU 引擎计算;不可用时自动隐藏。",
OverlayMetricItem.MemoryUsage => "系统内存占用率,读取不到时自动隐藏。",
_ => string.Empty
};
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using System;
@@ -29,7 +29,24 @@ public partial class PathingConditionConfig : ObservableObject
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 低血量回复时机
private RecoverTiming? _recoverTiming;
public RecoverTiming RecoverTiming
{
get
{
if (_recoverTiming is null)
{
// 首次读取时从旧字段自动迁移
_recoverTiming = RecoverTimingMigration.Migrate(_onlyInTeleportRecover);
}
return _recoverTiming.Value;
}
set => SetProperty(ref _recoverTiming, value);
}
// 使用小道具的间隔时间(ms)
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
@@ -8,12 +8,28 @@ using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Core.Config;
public enum RecoverTiming
{
AnyWaypoint,
OnlyTeleport,
Never
}
/// <summary>
/// 从旧字段 OnlyInTeleportRecover 迁移到 RecoverTiming 枚举的共享方法
/// </summary>
internal static class RecoverTimingMigration
{
public static RecoverTiming Migrate(bool onlyInTeleportRecover)
=> onlyInTeleportRecover ? RecoverTiming.OnlyTeleport : RecoverTiming.AnyWaypoint;
}
[Serializable]
public partial class PathingPartyConfig : ObservableObject
{
// 配置是否启用,不启用会使用地图追踪内的条件配置
[ObservableProperty]
private bool _enabled = false;
private bool _enabled = true;
// 是否启用自动拾取
[ObservableProperty]
@@ -21,6 +37,9 @@ public partial class PathingPartyConfig : ObservableObject
// 切换到队伍的名称
[ObservableProperty]
private string _partyName = string.Empty;
[JsonIgnore]
public bool SkipPartySwitch { get; set; }
// 切换队伍前是否前往须弥七天神像
[ObservableProperty]
@@ -68,7 +87,24 @@ public partial class PathingPartyConfig : ObservableObject
// 只在传送传送点时复活
[ObservableProperty]
private bool _onlyInTeleportRecover = false;
// 低血量回复时机
private RecoverTiming? _recoverTiming;
public RecoverTiming RecoverTiming
{
get
{
if (_recoverTiming is null)
{
// 首次读取时从旧字段自动迁移
_recoverTiming = RecoverTimingMigration.Migrate(_onlyInTeleportRecover);
}
return _recoverTiming.Value;
}
set => SetProperty(ref _recoverTiming, value);
}
//允许在jsScript脚本中使用此地图追踪配置
[ObservableProperty]
private bool _jsScriptUseEnabled = true;
@@ -121,10 +157,69 @@ public partial class PathingPartyConfig : ObservableObject
//启用自动战斗配置
[ObservableProperty]
private bool _autoFightEnabled = false;
private bool _autoFightEnabled = true;
[ObservableProperty]
private AutoFightConfig _autoFightConfig = new();
// 赶路通用临界距离(米),节点小于此距离时触发接近/切换模式
[ObservableProperty]
private int _distance = 45;
/// <summary>
/// 接近停止距离(米),强制小于等于 <see cref="Distance"/>,越界时自动使用 Distance 的值。
/// </summary>
[ObservableProperty]
private int _approachStopDistance = 25;
partial void OnDistanceChanged(int value)
{
if (ApproachStopDistance > value)
{
ApproachStopDistance = value;
}
}
partial void OnApproachStopDistanceChanged(int value)
{
if (value > Distance)
{
_approachStopDistance = Distance;
}
}
[JsonIgnore]
public List<string> HurryOnAvatarList { get; } = ["","自动","玛薇卡","闲云","桑多涅","恰斯卡","流浪者","伊法","希诺宁"];
[JsonIgnore]
public List<string> TravelModeList { get; } = ["精准靠近","连续赶路"];
[ObservableProperty]
private string _hurryOnAvatar = "";
[ObservableProperty]
private string _travelMode = "精准靠近";
/// <summary>
/// 接近节点时切人步行
/// </summary>
[ObservableProperty]
private bool _switchToWalkEnabled = false;
[ObservableProperty]
private bool _mwkFlyEnabled = true;
/// <summary>
/// 玛薇卡跳飞开关
/// </summary>
[ObservableProperty]
private bool _mwkJumpFlyEnabled = true;
/// <summary>
/// 跳飞间隔(秒),闲云使用其1/2值
/// </summary>
[ObservableProperty]
private double _mwkJumpFlyIntervalSeconds = 1;
public static PathingPartyConfig BuildDefault()
{
// 即便是不启用的情况下也设置默认值,减少后续使用的判断
@@ -132,6 +227,7 @@ public partial class PathingPartyConfig : ObservableObject
return new PathingPartyConfig
{
OnlyInTeleportRecover = pathingConditionConfig.OnlyInTeleportRecover,
RecoverTiming = pathingConditionConfig.RecoverTiming,
UseGadgetIntervalMs = pathingConditionConfig.UseGadgetIntervalMs,
AutoEatEnabled = pathingConditionConfig.AutoEatEnabled
};
@@ -50,4 +50,10 @@ public partial class ScriptConfig : ObservableObject
// 仓库新手教程是否已阅读
[ObservableProperty] private bool _guideStatus = false;
// 是否在启动时自动更新已订阅的脚本
[ObservableProperty] private bool _autoUpdateSubscribedScripts = false;
// 命令行启动时是否先自动更新已订阅脚本再执行命令
[ObservableProperty] private bool _autoUpdateBeforeCommandLineRun = false;
}
@@ -1,55 +1,130 @@
using BetterGenshinImpact.Core.Recorder;
using Microsoft.Extensions.Logging;
using SharpDX.DirectInput;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Monitor;
public class DirectInputMonitor : IDisposable
public sealed class DirectInputMonitor(ILogger<DirectInputMonitor> logger) : RelativeMouseInputMonitorBase(logger)
{
private bool _isRunning = true;
private const int Interval = 5;
private readonly object _captureLock = new();
private CaptureContext? _captureContext;
private readonly Mouse _mouse;
public static int Interval = 5;
public DirectInputMonitor()
protected override void StartCore()
{
var directInput = new DirectInput();
_mouse = new Mouse(directInput);
_mouse.SetCooperativeLevel(IntPtr.Zero, CooperativeLevel.Background | CooperativeLevel.NonExclusive);
}
public MouseState GetMouseState()
{
_mouse.Acquire();
return _mouse.GetCurrentState();
}
public void Start()
{
Task.Run(() =>
Mouse? mouse = null;
try
{
while (_isRunning)
mouse = new Mouse(directInput);
mouse.SetCooperativeLevel(
IntPtr.Zero,
CooperativeLevel.Background | CooperativeLevel.NonExclusive);
mouse.Acquire();
var context = new CaptureContext(directInput, mouse);
lock (_captureLock)
{
_mouse.Acquire();
MouseState state = _mouse.GetCurrentState();
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveBy(state, Kernel32.GetTickCount());
Thread.Sleep(Interval); // 10ms, equivalent to CLOCKS_PER_SEC/100
context.CaptureTask = Task.Run(() => Capture(context));
_captureContext = context;
}
});
}
catch
{
mouse?.Dispose();
directInput.Dispose();
throw;
}
}
public void Stop()
protected override void StopCore()
{
_isRunning = false;
CaptureContext? context;
lock (_captureLock)
{
context = _captureContext;
_captureContext = null;
context?.CancellationTokenSource.Cancel();
}
if (context == null)
{
return;
}
var captureTask = context.CaptureTask;
if (captureTask != null &&
Environment.CurrentManagedThreadId != context.CaptureThreadId)
{
try
{
captureTask.Wait();
}
catch (AggregateException ex) when (ex.InnerExceptions.All(x => x is OperationCanceledException))
{
// 正常取消
}
}
}
public void Dispose()
private void Capture(CaptureContext context)
{
_mouse.Dispose();
context.CaptureThreadId = Environment.CurrentManagedThreadId;
try
{
while (!context.CancellationTokenSource.IsCancellationRequested)
{
context.Mouse.Acquire();
MouseState state = context.Mouse.GetCurrentState();
// Debug.WriteLine($"{state.X} {state.Y} {state.Buttons[0]} {state.Buttons[1]}");
if (state is not { X: 0, Y: 0 })
{
var timestamp = DateTime.UtcNow.AddMilliseconds(-Interval);
Publish(new RelativeMouseMoveEventArgs(state.X, state.Y, timestamp));
}
if (context.CancellationTokenSource.Token.WaitHandle.WaitOne(Interval))
{
break;
}
}
}
catch (Exception ex)
{
if (!context.CancellationTokenSource.IsCancellationRequested)
{
Logger.LogError(ex, "DirectInput 相对鼠标捕获异常终止");
}
}
finally
{
lock (_captureLock)
{
if (ReferenceEquals(_captureContext, context))
{
_captureContext = null;
}
}
context.Mouse.Dispose();
context.DirectInput.Dispose();
context.CancellationTokenSource.Dispose();
}
}
private sealed class CaptureContext(DirectInput directInput, Mouse mouse)
{
public DirectInput DirectInput { get; } = directInput;
public Mouse Mouse { get; } = mouse;
public CancellationTokenSource CancellationTokenSource { get; } = new();
public Task? CaptureTask { get; set; }
public int CaptureThreadId { get; set; }
}
}
@@ -0,0 +1,233 @@
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Core.Monitor;
/// <summary>
/// 在本地会话中约束并隐藏鼠标。所有调用应来自同一个 UI 线程,
/// 以便成对恢复 ShowCursor 的显示计数。
/// </summary>
internal sealed class LocalCursorCapture(ILogger logger) : IDisposable
{
private const int MaxCursorHideAttempts = 64;
private const int SmXVirtualScreen = 76;
private const int SmYVirtualScreen = 77;
private const int SmCxVirtualScreen = 78;
private const int SmCyVirtualScreen = 79;
private NativeRect _previousClipRect;
private Rectangle _appliedBounds;
private bool _hasPreviousClipRect;
private bool _isCaptureSessionActive;
private bool _isRestrictionApplied;
private bool _isDisposed;
private int _cursorHideCallCount;
internal void Capture(Rectangle bounds)
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
if (bounds.Width <= 0 || bounds.Height <= 0)
{
throw new ArgumentOutOfRangeException(
nameof(bounds),
bounds,
"鼠标限制区域必须具有有效宽度和高度。");
}
if (!_isCaptureSessionActive)
{
var clipRectRead = NativeMethods.GetClipCursor(out _previousClipRect);
if (!clipRectRead)
{
logger.LogWarning(
"读取现有鼠标限制区域失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
_hasPreviousClipRect =
clipRectRead && !IsVirtualDesktopBounds(_previousClipRect);
_isCaptureSessionActive = true;
}
if (_isRestrictionApplied && _appliedBounds == bounds)
{
return;
}
var clipRect = NativeRect.FromRectangle(bounds);
if (!NativeMethods.ClipCursor(ref clipRect))
{
var exception = new Win32Exception(
Marshal.GetLastWin32Error(),
"限制本地鼠标到桌面分身窗口失败");
if (!_isRestrictionApplied)
{
Release();
}
throw exception;
}
_appliedBounds = bounds;
if (!_isRestrictionApplied)
{
HideCursor();
_isRestrictionApplied = true;
}
}
internal void ReleaseTemporarily()
{
ObjectDisposedException.ThrowIf(_isDisposed, this);
if (!_isCaptureSessionActive || !_isRestrictionApplied)
{
return;
}
if (!NativeMethods.ReleaseClipCursor(IntPtr.Zero))
{
throw new Win32Exception(
Marshal.GetLastWin32Error(),
"临时解除本地鼠标限制失败");
}
var centerX = _appliedBounds.Left + _appliedBounds.Width / 2;
var centerY = _appliedBounds.Top + _appliedBounds.Height / 2;
if (!NativeMethods.SetCursorPos(centerX, centerY))
{
logger.LogWarning(
"将本地鼠标移动到桌面分身控件中心失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
RestoreCursorVisibility();
_isRestrictionApplied = false;
_appliedBounds = Rectangle.Empty;
}
internal void Release()
{
if (!_isCaptureSessionActive)
{
return;
}
var restored = _hasPreviousClipRect
? NativeMethods.ClipCursor(ref _previousClipRect)
: NativeMethods.ReleaseClipCursor(IntPtr.Zero);
if (!restored)
{
logger.LogWarning(
"恢复本地鼠标限制区域失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
RestoreCursorVisibility();
_hasPreviousClipRect = false;
_isCaptureSessionActive = false;
_isRestrictionApplied = false;
_appliedBounds = Rectangle.Empty;
}
public void Dispose()
{
if (_isDisposed)
{
return;
}
Release();
_isDisposed = true;
GC.SuppressFinalize(this);
}
private void HideCursor()
{
var displayCount = 0;
do
{
displayCount = NativeMethods.ShowCursor(false);
_cursorHideCallCount++;
}
while (displayCount >= 0 && _cursorHideCallCount < MaxCursorHideAttempts);
if (displayCount >= 0)
{
logger.LogWarning(
"隐藏本地鼠标时 ShowCursor 显示计数仍为 {DisplayCount}",
displayCount);
}
}
private void RestoreCursorVisibility()
{
while (_cursorHideCallCount > 0)
{
_ = NativeMethods.ShowCursor(true);
_cursorHideCallCount--;
}
}
private static bool IsVirtualDesktopBounds(NativeRect rect)
{
var left = NativeMethods.GetSystemMetrics(SmXVirtualScreen);
var top = NativeMethods.GetSystemMetrics(SmYVirtualScreen);
var width = NativeMethods.GetSystemMetrics(SmCxVirtualScreen);
var height = NativeMethods.GetSystemMetrics(SmCyVirtualScreen);
return rect.Left == left
&& rect.Top == top
&& rect.Right == left + width
&& rect.Bottom == top + height;
}
[StructLayout(LayoutKind.Sequential)]
private struct NativeRect
{
public int Left;
public int Top;
public int Right;
public int Bottom;
internal static NativeRect FromRectangle(Rectangle rectangle)
{
return new NativeRect
{
Left = rectangle.Left,
Top = rectangle.Top,
Right = rectangle.Right,
Bottom = rectangle.Bottom
};
}
}
private static class NativeMethods
{
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool GetClipCursor(out NativeRect rect);
[DllImport("user32.dll", EntryPoint = "ClipCursor", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ClipCursor(ref NativeRect rect);
[DllImport("user32.dll", EntryPoint = "ClipCursor", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool ReleaseClipCursor(nint rect);
[DllImport("user32.dll")]
internal static extern int ShowCursor(
[MarshalAs(UnmanagedType.Bool)] bool show);
[DllImport("user32.dll")]
internal static extern int GetSystemMetrics(int index);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool SetCursorPos(int x, int y);
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recorder;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
@@ -100,7 +100,12 @@ public partial class MouseKeyMonitor
private void GlobalHookKeyDown(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyDown: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, Kernel32.GetTickCount());
GlobalKeyMouseRecord.Instance.GlobalHookKeyDown(e, DateTime.UtcNow);
if (SystemControl.IsGenshinImpactActive())
{
ChatUiHotkeyGuard.PrimeFromChatKey(e.KeyCode);
}
// 热键按下事件
HotKeyDown(sender, e);
@@ -138,7 +143,7 @@ public partial class MouseKeyMonitor
private void GlobalHookKeyUp(object? sender, KeyEventArgs e)
{
// Debug.WriteLine("KeyUp: \t{0}", e.KeyCode);
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, Kernel32.GetTickCount());
GlobalKeyMouseRecord.Instance.GlobalHookKeyUp(e, DateTime.UtcNow);
// 热键松开事件
HotKeyUp(sender, e);
@@ -183,7 +188,7 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseDownExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseDown: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e);
GlobalKeyMouseRecord.Instance.GlobalHookMouseDown(e, DateTime.UtcNow);
if (e.Button != MouseButtons.Left)
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
@@ -193,7 +198,7 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseUpExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseUp: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e);
GlobalKeyMouseRecord.Instance.GlobalHookMouseUp(e, DateTime.UtcNow);
if (e.Button != MouseButtons.Left)
if (MouseHook.AllMouseHooks.TryGetValue(e.Button, out var hook))
@@ -203,13 +208,13 @@ public partial class MouseKeyMonitor
private void GlobalHookMouseMoveExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t System Timestamp: {2}", e.Button, e.Location, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e);
GlobalKeyMouseRecord.Instance.GlobalHookMouseMoveTo(e, DateTime.UtcNow);
}
private void GlobalHookMouseWheelExt(object? sender, MouseEventExtArgs e)
{
// Debug.WriteLine("MouseMove: {0}; \t Location: {1};\t Delta: {2};\t System Timestamp: {3}", e.Button, e.Location, e.Delta, e.Timestamp);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e);
GlobalKeyMouseRecord.Instance.GlobalHookMouseWheel(e, DateTime.UtcNow);
}
public void Unsubscribe()
@@ -0,0 +1,497 @@
using Microsoft.Extensions.Logging;
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Interop;
using System.Windows.Threading;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Monitor;
public sealed class RawInputMonitor(ILogger<RawInputMonitor> logger)
: RelativeMouseInputMonitorBase(logger)
{
private static readonly TimeSpan InitializationTimeout = TimeSpan.FromSeconds(10);
private const ushort GenericDesktopUsagePage = 0x01;
private const ushort MouseUsage = 0x02;
private const ushort KeyBreakFlag = 0x01;
private const ushort InvalidVirtualKey = 0x00FF;
private static readonly nint HwndMessage = new(-3);
// 键盘输入不再复用相对鼠标监听器的采集生命周期,避免覆盖 RDP ActiveX 的进程级注册。
private readonly object _sourceLock = new();
private RawInputThreadContext? _context;
private long _lifecycleVersion;
protected override void StartCore()
{
RawInputThreadContext context;
lock (_sourceLock)
{
_lifecycleVersion++;
if (_context != null)
{
return;
}
context = new RawInputThreadContext();
context.Thread = new Thread(() => RunMessageLoop(context))
{
IsBackground = true,
Name = "BetterGI RawInput Monitor"
};
context.Thread.SetApartmentState(ApartmentState.STA);
_context = context;
}
try
{
context.Thread.Start();
}
catch
{
ClearContext(context);
context.Initialized.Dispose();
throw;
}
if (!context.Initialized.Wait(InitializationTimeout))
{
ClearContext(context);
RequestStop(context);
throw new TimeoutException(
$"Raw Input 采集线程初始化超过 {InitializationTimeout.TotalSeconds:0} 秒。");
}
context.Initialized.Dispose();
if (context.InitializationException == null)
{
return;
}
ClearContext(context);
throw new InvalidOperationException("Raw Input 初始化失败", context.InitializationException);
}
protected override void StopCore()
{
RawInputThreadContext? context;
long stopVersion;
lock (_sourceLock)
{
stopVersion = ++_lifecycleVersion;
context = _context;
}
if (context?.Dispatcher == null || context.Thread == null)
{
return;
}
if (Thread.CurrentThread == context.Thread)
{
_ = context.Dispatcher.BeginInvoke(
DispatcherPriority.Send,
new Action(() => StopOnMessageThread(context, stopVersion)));
return;
}
bool stopped;
try
{
stopped = context.Dispatcher.Invoke(
() => StopOnMessageThread(context, stopVersion),
DispatcherPriority.Send);
}
catch (TaskCanceledException)
{
return;
}
catch (InvalidOperationException)
{
return;
}
if (stopped)
{
context.Thread.Join();
}
}
internal static bool TryGetRelativeMovement(
in User32.RAWINPUT rawInput,
out int deltaX,
out int deltaY)
{
deltaX = 0;
deltaY = 0;
if (rawInput.header.dwType != User32.RIM_TYPE.RIM_TYPEMOUSE)
{
return false;
}
var mouse = rawInput.data.mouse;
if ((mouse.usFlags & User32.MouseState.MOUSE_MOVE_ABSOLUTE) != 0)
{
return false;
}
deltaX = mouse.lLastX;
deltaY = mouse.lLastY;
return deltaX != 0 || deltaY != 0;
}
internal static bool TryGetRelativeMovementFromBuffer(
nint rawInputBuffer,
uint rawInputSize,
out int deltaX,
out int deltaY)
{
deltaX = 0;
deltaY = 0;
var headerSize = Marshal.SizeOf<User32.RAWINPUTHEADER>();
var mouseSize = Marshal.SizeOf<RawMouseData>();
if (rawInputSize < headerSize + mouseSize)
{
return false;
}
var header = Marshal.PtrToStructure<User32.RAWINPUTHEADER>(rawInputBuffer);
if (header.dwType != User32.RIM_TYPE.RIM_TYPEMOUSE)
{
return false;
}
var mouse = Marshal.PtrToStructure<RawMouseData>(IntPtr.Add(rawInputBuffer, headerSize));
if ((mouse.Flags & (ushort)User32.MouseState.MOUSE_MOVE_ABSOLUTE) != 0)
{
return false;
}
deltaX = mouse.LastX;
deltaY = mouse.LastY;
return deltaX != 0 || deltaY != 0;
}
internal static bool TryGetKeyboardInputFromBuffer(
nint rawInputBuffer,
uint rawInputSize,
out ushort virtualKey,
out ushort scanCode,
out ushort flags,
out bool isKeyDown)
{
virtualKey = 0;
scanCode = 0;
flags = 0;
isKeyDown = false;
var headerSize = Marshal.SizeOf<User32.RAWINPUTHEADER>();
var keyboardSize = Marshal.SizeOf<RawKeyboardData>();
if (rawInputSize < headerSize + keyboardSize)
{
return false;
}
var header = Marshal.PtrToStructure<User32.RAWINPUTHEADER>(rawInputBuffer);
if (header.dwType != User32.RIM_TYPE.RIM_TYPEKEYBOARD)
{
return false;
}
var keyboard = Marshal.PtrToStructure<RawKeyboardData>(
IntPtr.Add(rawInputBuffer, headerSize));
if (keyboard.VirtualKey == InvalidVirtualKey)
{
return false;
}
virtualKey = keyboard.VirtualKey;
scanCode = keyboard.MakeCode;
flags = keyboard.Flags;
isKeyDown = (keyboard.Flags & KeyBreakFlag) == 0;
return true;
}
private void RunMessageLoop(RawInputThreadContext context)
{
try
{
context.Dispatcher = Dispatcher.CurrentDispatcher;
context.HwndSource = new HwndSource(new HwndSourceParameters("BetterGI RawInput Monitor")
{
ParentWindow = HwndMessage,
WindowStyle = 0
});
context.HwndSource.AddHook(WindowProc);
RegisterRawInput(context);
context.Registered = true;
if (Volatile.Read(ref context.StopRequested) != 0)
{
throw new OperationCanceledException("Raw Input 初始化已取消。");
}
context.InitializationSucceeded = true;
context.Initialized.Set();
Dispatcher.Run();
}
catch (Exception ex)
{
if (!context.InitializationSucceeded)
{
context.InitializationException = ex;
context.Initialized.Set();
}
Logger.LogError(ex, "Raw Input 消息窗口异常终止");
}
finally
{
CleanupContext(context);
lock (_sourceLock)
{
if (ReferenceEquals(_context, context))
{
_context = null;
_lifecycleVersion++;
}
}
}
}
private bool StopOnMessageThread(RawInputThreadContext context, long stopVersion)
{
lock (_sourceLock)
{
if (stopVersion != _lifecycleVersion || !ReferenceEquals(_context, context))
{
return false;
}
CleanupContext(context);
_context = null;
context.Dispatcher?.BeginInvokeShutdown(DispatcherPriority.Send);
return true;
}
}
private void ClearContext(RawInputThreadContext context)
{
lock (_sourceLock)
{
if (ReferenceEquals(_context, context))
{
_context = null;
_lifecycleVersion++;
}
}
}
private static void RequestStop(RawInputThreadContext context)
{
Interlocked.Exchange(ref context.StopRequested, 1);
try
{
context.Dispatcher?.BeginInvokeShutdown(DispatcherPriority.Send);
}
catch (InvalidOperationException)
{
// Dispatcher 已关闭,无需再次请求退出。
}
}
private void RegisterRawInput(RawInputThreadContext context)
{
var devices = new[]
{
new User32.RAWINPUTDEVICE
{
usUsagePage = GenericDesktopUsagePage,
usUsage = MouseUsage,
dwFlags = User32.RIDEV.RIDEV_INPUTSINK,
hwndTarget = context.HwndSource!.Handle
}
};
if (!User32.RegisterRawInputDevices(
devices,
(uint)devices.Length,
(uint)Marshal.SizeOf<User32.RAWINPUTDEVICE>()))
{
throw new Win32Exception(Marshal.GetLastWin32Error(), "注册 Raw Input 鼠标设备失败");
}
}
private void CleanupContext(RawInputThreadContext context)
{
if (context.Registered)
{
var devices = new[]
{
new User32.RAWINPUTDEVICE
{
usUsagePage = GenericDesktopUsagePage,
usUsage = MouseUsage,
dwFlags = User32.RIDEV.RIDEV_REMOVE,
hwndTarget = HWND.NULL
}
};
if (!User32.RegisterRawInputDevices(
devices,
(uint)devices.Length,
(uint)Marshal.SizeOf<User32.RAWINPUTDEVICE>()))
{
Logger.LogWarning(
"注销 Raw Input 鼠标设备失败,Win32Error: {Win32Error}",
Marshal.GetLastWin32Error());
}
context.Registered = false;
}
if (context.HwndSource != null)
{
context.HwndSource.RemoveHook(WindowProc);
context.HwndSource.Dispose();
context.HwndSource = null;
}
}
private nint WindowProc(
nint hwnd,
int message,
nint wParam,
nint lParam,
ref bool handled)
{
if (message != (int)User32.WindowMessage.WM_INPUT)
{
return IntPtr.Zero;
}
try
{
ProcessRawInput(lParam);
}
catch (Exception ex)
{
Logger.LogError(ex, "读取 Raw Input 鼠标数据失败");
}
// 保持 handled = false,让默认窗口过程完成 WM_INPUT 的必要清理。
handled = false;
return IntPtr.Zero;
}
private void ProcessRawInput(nint rawInputHandle)
{
uint size = 0;
uint headerSize = (uint)Marshal.SizeOf<User32.RAWINPUTHEADER>();
var handle = new User32.HRAWINPUT(rawInputHandle);
if (User32.GetRawInputData(
handle,
User32.RID.RID_INPUT,
IntPtr.Zero,
ref size,
headerSize) == uint.MaxValue)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (size == 0)
{
return;
}
var buffer = Marshal.AllocHGlobal(checked((int)size));
try
{
var readSize = size;
uint result = User32.GetRawInputData(
handle,
User32.RID.RID_INPUT,
buffer,
ref readSize,
headerSize);
if (result == uint.MaxValue)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
var timestamp = DateTime.UtcNow;
if (TryGetRelativeMovementFromBuffer(buffer, readSize, out int deltaX, out int deltaY))
{
Publish(new RelativeMouseMoveEventArgs(deltaX, deltaY, timestamp));
return;
}
}
finally
{
Marshal.FreeHGlobal(buffer);
}
}
private sealed class RawInputThreadContext
{
public Thread? Thread { get; set; }
public Dispatcher? Dispatcher { get; set; }
public HwndSource? HwndSource { get; set; }
public ManualResetEventSlim Initialized { get; } = new();
public Exception? InitializationException { get; set; }
public bool InitializationSucceeded { get; set; }
public bool Registered { get; set; }
public int StopRequested;
}
[StructLayout(LayoutKind.Sequential)]
private readonly struct RawMouseData
{
public ushort Flags { get; init; }
public ushort Reserved { get; init; }
public ushort ButtonFlags { get; init; }
public short ButtonData { get; init; }
public uint RawButtons { get; init; }
public int LastX { get; init; }
public int LastY { get; init; }
public uint ExtraInformation { get; init; }
}
[StructLayout(LayoutKind.Sequential)]
private readonly struct RawKeyboardData
{
public ushort MakeCode { get; init; }
public ushort Flags { get; init; }
public ushort Reserved { get; init; }
public ushort VirtualKey { get; init; }
public uint Message { get; init; }
public uint ExtraInformation { get; init; }
}
}
@@ -0,0 +1,60 @@
using System;
namespace BetterGenshinImpact.Core.Monitor;
public enum RelativeMouseInputType
{
DirectInput,
RawInput
}
public sealed class RelativeMouseMoveEventArgs(int deltaX, int deltaY, DateTime timestamp) : EventArgs
{
public int DeltaX { get; } = deltaX;
public int DeltaY { get; } = deltaY;
public DateTime Timestamp { get; } = timestamp;
}
public interface IRelativeMouseInputMonitor
{
/// <summary>
/// 订阅相对鼠标移动事件。首个订阅会启动采集,最后一个订阅释放后停止采集。
/// 回调在采集线程执行,需要操作 UI 时由订阅方自行切换到 UI 线程。
/// </summary>
IDisposable Subscribe(EventHandler<RelativeMouseMoveEventArgs> handler);
}
public interface IRelativeMouseInputMonitorFactory
{
IRelativeMouseInputMonitor Get(RelativeMouseInputType type);
}
public sealed class RawKeyboardInputEventArgs(
ushort virtualKey,
ushort scanCode,
ushort flags,
bool isKeyDown,
DateTime timestamp) : EventArgs
{
public ushort VirtualKey { get; } = virtualKey;
public ushort ScanCode { get; } = scanCode;
public ushort Flags { get; } = flags;
public bool IsKeyDown { get; } = isKeyDown;
public DateTime Timestamp { get; } = timestamp;
}
public interface IRawKeyboardInputMonitor
{
/// <summary>
/// 订阅 Raw Input 键盘事件。首个鼠标或键盘订阅会启动采集,
/// 最后一个订阅释放后停止采集。回调在采集线程执行。
/// 包含 RDP ActiveX 的进程不应直接实现此接口,否则会覆盖 RDP 的键盘 Raw Input 注册。
/// </summary>
IDisposable SubscribeKeyboard(EventHandler<RawKeyboardInputEventArgs> handler);
}
@@ -0,0 +1,171 @@
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
namespace BetterGenshinImpact.Core.Monitor;
public abstract class RelativeMouseInputMonitorBase(ILogger logger) : IRelativeMouseInputMonitor, IDisposable
{
private readonly object _subscriptionLock = new();
private readonly Dictionary<long, EventHandler<RelativeMouseMoveEventArgs>> _handlers = [];
private long _nextSubscriptionId;
private bool _isStarted;
private bool _isStopping;
private bool _isDisposed;
protected ILogger Logger { get; } = logger;
public IDisposable Subscribe(EventHandler<RelativeMouseMoveEventArgs> handler)
{
ArgumentNullException.ThrowIfNull(handler);
long subscriptionId;
lock (_subscriptionLock)
{
while (_isStopping)
{
System.Threading.Monitor.Wait(_subscriptionLock);
}
ObjectDisposedException.ThrowIf(_isDisposed, this);
subscriptionId = ++_nextSubscriptionId;
_handlers.Add(subscriptionId, handler);
if (!_isStarted)
{
try
{
StartCore();
_isStarted = true;
}
catch
{
_handlers.Remove(subscriptionId);
throw;
}
}
}
return new Subscription(this, subscriptionId);
}
protected void Publish(RelativeMouseMoveEventArgs eventArgs)
{
EventHandler<RelativeMouseMoveEventArgs>[] handlers;
lock (_subscriptionLock)
{
if (_isDisposed || _handlers.Count == 0)
{
return;
}
handlers = _handlers.Values.ToArray();
}
foreach (var handler in handlers)
{
try
{
handler(this, eventArgs);
}
catch (Exception ex)
{
Logger.LogError(ex, "相对鼠标移动事件订阅方执行失败");
}
}
}
protected abstract void StartCore();
protected abstract void StopCore();
public virtual void Dispose()
{
bool shouldStop;
lock (_subscriptionLock)
{
while (_isStopping)
{
System.Threading.Monitor.Wait(_subscriptionLock);
}
if (_isDisposed)
{
return;
}
_isDisposed = true;
_handlers.Clear();
shouldStop = _isStarted;
_isStarted = false;
_isStopping = shouldStop;
}
if (shouldStop)
{
try
{
StopCore();
}
finally
{
CompleteStop();
}
}
GC.SuppressFinalize(this);
}
private void Unsubscribe(long subscriptionId)
{
bool shouldStop;
lock (_subscriptionLock)
{
if (_isDisposed || !_handlers.Remove(subscriptionId))
{
return;
}
shouldStop = _handlers.Count == 0 && _isStarted;
if (shouldStop)
{
_isStarted = false;
_isStopping = true;
}
}
if (shouldStop)
{
try
{
StopCore();
}
finally
{
CompleteStop();
}
}
}
private void CompleteStop()
{
lock (_subscriptionLock)
{
_isStopping = false;
System.Threading.Monitor.PulseAll(_subscriptionLock);
}
}
private sealed class Subscription(RelativeMouseInputMonitorBase owner, long subscriptionId) : IDisposable
{
private RelativeMouseInputMonitorBase? _owner = owner;
public void Dispose()
{
Interlocked.Exchange(ref _owner, null)?.Unsubscribe(subscriptionId);
}
}
}
@@ -0,0 +1,18 @@
using System;
namespace BetterGenshinImpact.Core.Monitor;
public sealed class RelativeMouseInputMonitorFactory(
DirectInputMonitor directInputMonitor,
RawInputMonitor rawInputMonitor) : IRelativeMouseInputMonitorFactory
{
public IRelativeMouseInputMonitor Get(RelativeMouseInputType type)
{
return type switch
{
RelativeMouseInputType.DirectInput => directInputMonitor,
RelativeMouseInputType.RawInput => rawInputMonitor,
_ => throw new ArgumentOutOfRangeException(nameof(type), type, "不支持的相对鼠标输入类型")
};
}
}
@@ -44,4 +44,14 @@ public readonly record struct OcrVersionConfig(
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
public static OcrVersionConfig PpOcrV6 = new(
"PP-OCRv6",
OcrImgMode.BGR,
false,
new OcrNormalizeImage(
1.0f / 255.0f,
[0.485f, 0.456f, 0.406f],
[0.229f, 0.224f, 0.225f]
), new OcrShape(3, 320, 48));
}
@@ -1,4 +1,4 @@
using System;
using System;
using System.Globalization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
@@ -100,6 +100,9 @@ public class OcrFactory : IDisposable
PaddleOcrModelConfig.V5 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V5),
PaddleOcrModelConfig.V6 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V6),
PaddleOcrModelConfig.V4 =>
new PaddleOcrService(App.ServiceProvider.GetRequiredService<BgiOnnxFactory>(),
PaddleOcrService.PaddleOcrModelType.V4),
@@ -120,7 +123,6 @@ public class OcrFactory : IDisposable
};
}
public Task Unload()
{
if (_paddleOcrService is not IDisposable disposable)
@@ -13,8 +13,17 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
{
private readonly InferenceSession _session = bgiOnnxFactory.CreateInferenceSession(model, true);
/// <summary>Gets or sets the maximum size for resizing the input image.</summary>
public int? MaxSize { get; set; } = 960;
/// <summary>Gets or sets the detection side length limit used by the Python det preprocess.</summary>
public int LimitSideLen { get; set; } = 960;
/// <summary>Gets or sets the maximum size limit after resizing.</summary>
public int MaxSideLimit { get; set; } = 4000;
/// <summary>Gets or sets the side length limit type. Supports max/min/resize_long.</summary>
public string LimitType { get; set; } = "max";
/// <summary>Gets or sets the shortest side threshold used for tiny-image upscaling.</summary>
public int SmallImageLimitSideLen { get; set; } = 64;
/// <summary>Gets or sets the size for dilation during preprocessing.</summary>
public int? DilatedSize { get; set; } = 2;
@@ -71,20 +80,24 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
var contours = dilated.FindContoursAsArray(RetrievalModes.List, ContourApproximationModes.ApproxSimple);
// var size = src.Size();
var scaleRate = 1.0 * src.Width / resizedSize.Width;
// PaddleOCR Python keeps ratio_h/ratio_w separately. Because we align det resize to that behavior,
// map contour points back with independent X/Y scales before building rotated rects.
var scaleX = 1.0 * src.Width / resizedSize.Width;
var scaleY = 1.0 * src.Height / resizedSize.Height;
var rects = contours
.Where(x => BoxScoreThreshold == null || GetScore(x, pred) > BoxScoreThreshold)
.Select(contour =>
contour.Select(point => new Point2f((float)(point.X * scaleX), (float)(point.Y * scaleY))).ToArray())
.Select(Cv2.MinAreaRect)
.Where(x => x.Size.Width > MinSize && x.Size.Height > MinSize)
.Select(rect =>
{
var minEdge = Math.Min(rect.Size.Width, rect.Size.Height);
Size2f newSize = new(
(rect.Size.Width + UnclipRatio * minEdge) * scaleRate,
(rect.Size.Height + UnclipRatio * minEdge) * scaleRate);
RotatedRect largerRect = new(rect.Center * scaleRate, newSize, rect.Angle);
rect.Size.Width + UnclipRatio * minEdge,
rect.Size.Height + UnclipRatio * minEdge);
RotatedRect largerRect = new(rect.Center, newSize, rect.Angle);
return largerRect;
})
.OrderBy(v => v.Center.Y)
@@ -107,11 +120,14 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
// DetResizeForTest resize_long
using (var resized = MatResize(padded, MaxSize))
// Align with PaddleOCR Python DetResizeForTest:
// 1. tiny image padding when h + w < 64
// 2. keep current max/960 behavior for normal images
// 3. switch to limit_type=min for very small crops so det can see the text
using (var resized = MatResizeForDetection(padded))
{
resizedSize = new Size(resized.Width, resized.Height);
padded = MatPadding32(resized);
padded = resized.Clone();
}
using (var _ = padded)
@@ -150,19 +166,80 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
/// <summary>
/// 按比例缩放图像,保持长边不超过 maxSize。
/// 按 PaddleOCR Python 的 DetResizeForTest 思路缩放图像:
/// 小图先补边,再按 max/min/resize_long 规则缩放,并对齐到 32 的倍数。
/// </summary>
/// <param name="src"></param>
/// <param name="maxSize"></param>
/// <returns></returns>
private static Mat MatResize(Mat src, int? maxSize)
private Mat MatResizeForDetection(Mat src)
{
if (maxSize == null) return src.Clone();
using var preprocessed = PrepareTinyImage(src);
var size = src.Size();
var longEdge = Math.Max(size.Width, size.Height);
var scaleRate = 1.0 * maxSize.Value / longEdge;
return scaleRate < 1.0 ? src.Resize(default, scaleRate, scaleRate) : src.Clone();
var size = preprocessed.Size();
var height = size.Height;
var width = size.Width;
var limitSideLen = LimitSideLen;
var limitType = LimitType;
if (Math.Min(height, width) < SmallImageLimitSideLen)
{
limitSideLen = SmallImageLimitSideLen;
limitType = "min";
}
var ratio = CalculateResizeRatio(width, height, limitSideLen, limitType);
var resizeHeight = (int)(height * ratio);
var resizeWidth = (int)(width * ratio);
if (Math.Max(resizeHeight, resizeWidth) > MaxSideLimit)
{
var maxSideRatio = 1.0 * MaxSideLimit / Math.Max(resizeHeight, resizeWidth);
resizeHeight = (int)(resizeHeight * maxSideRatio);
resizeWidth = (int)(resizeWidth * maxSideRatio);
}
resizeHeight = Math.Max((int)Math.Round(resizeHeight / 32.0) * 32, 32);
resizeWidth = Math.Max((int)Math.Round(resizeWidth / 32.0) * 32, 32);
if (resizeWidth <= 0 || resizeHeight <= 0)
{
throw new InvalidOperationException(
$"Invalid det resize target size: {resizeWidth}x{resizeHeight}, src={width}x{height}");
}
using var resized = preprocessed.Resize(new Size(resizeWidth, resizeHeight));
return MatPadding32(resized);
}
private static Mat PrepareTinyImage(Mat src)
{
if (src.Width + src.Height >= 64)
{
return src.Clone();
}
var newHeight = Math.Max(32, src.Height);
var newWidth = Math.Max(32, src.Width);
var padded = new Mat(newHeight, newWidth, src.Type(), Scalar.Black);
src.CopyTo(padded[new Rect(0, 0, src.Width, src.Height)]);
return padded;
}
private static double CalculateResizeRatio(int width, int height, int limitSideLen, string limitType)
{
return limitType switch
{
"max" => Math.Max(height, width) > limitSideLen
? 1.0 * limitSideLen / Math.Max(height, width)
: 1.0,
"min" => Math.Min(height, width) < limitSideLen
? 1.0 * limitSideLen / Math.Min(height, width)
: 1.0,
"resize_long" => 1.0 * limitSideLen / Math.Max(height, width),
_ => throw new ArgumentOutOfRangeException(nameof(limitType), limitType,
"limitType only supports max/min/resize_long")
};
}
private static float GetScore(Point[] contour, Mat pred)
@@ -197,4 +274,4 @@ public class Det(BgiOnnxModel model, OcrVersionConfig config, BgiOnnxFactory bgi
}
public string GetConfigName => config.Name;
}
}
@@ -7,6 +7,7 @@ using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using YamlDotNet.Core;
@@ -100,7 +101,7 @@ public class PaddleOcrService : IOcrService, IDisposable
recognitionModel,
recognitionVersion,
recLabel ?? (() => DefaultRecLabelFunc(recognitionModel)),
TestImagePath);
preHeatImagePath ?? TestImagePath);
}
public (Det, Rec) Build(BgiOnnxFactory onnxFactory)
@@ -129,6 +130,12 @@ public class PaddleOcrService : IOcrService, IDisposable
BgiOnnxModel.PaddleOcrRecV5,
OcrVersionConfig.PpOcrV5);
public static readonly PaddleOcrModelType V6 = Create(
BgiOnnxModel.PaddleOcrDetV6,
OcrVersionConfig.PpOcrV6,
BgiOnnxModel.PaddleOcrRecV6,
OcrVersionConfig.PpOcrV6);
public static readonly PaddleOcrModelType V5Latin = Create(
BgiOnnxModel.PaddleOcrDetV5,
OcrVersionConfig.PpOcrV5,
@@ -246,7 +253,7 @@ public class PaddleOcrService : IOcrService, IDisposable
_localRecModel = modelsRec;
// 预热模型
using var preHeatImageMat = Cv2.ImRead(modelType.PreHeatImagePath) ??
using var preHeatImageMat = Bv.ImRead(modelType.PreHeatImagePath) ??
throw new FileNotFoundException($"预热图片未找到: {modelType.PreHeatImagePath}");
// Debug输出结果
var preHeatResult = RunAll(preHeatImageMat, 1);
@@ -284,7 +291,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var str = _localRecModel.Run(mat).Text;
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
// Debug.WriteLine($"PaddleOcrWithoutDetector 耗时 {time.TotalMilliseconds}ms 结果: {str}");
return str;
}
@@ -293,7 +300,7 @@ public class PaddleOcrService : IOcrService, IDisposable
var startTime = Stopwatch.GetTimestamp();
var result = RunAll(mat);
var time = Stopwatch.GetElapsedTime(startTime);
Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
// Debug.WriteLine($"PaddleOcr 耗时 {time.TotalMilliseconds}ms 结果: {result.Text}");
return result;
}
@@ -2,7 +2,6 @@ using System;
using System.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using BetterGenshinImpact.Core.Recognition.OCR.Engine.data;
@@ -95,21 +94,33 @@ public class Rec(
// .AsParallel()
.Select(src =>
{
using var channel3 = src.Channels() switch
Mat? channel3 = default;
try
{
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
channel3 = src.Channels() switch
{
4 => src.CvtColor(ColorConversionCodes.BGRA2BGR),
1 => src.CvtColor(ColorConversionCodes.GRAY2BGR),
3 => src,
var x => throw new Exception($"Unexpect src channel: {x}, allow: (1/3/4)")
};
var result = OcrUtils.ResizeNormImg(channel3, new OcrShape(3, maxWidth, modelHeight),
out var owner);
lock (owners)
{
owners.Add(owner);
}
return result;
return result;
}
finally
{
// Only dispose Mats created in this scope
if (channel3 != null && !ReferenceEquals(channel3, src))
{
channel3.Dispose();
}
}
})
.Select(inputTensor =>
{
@@ -141,46 +152,46 @@ public class Rec(
{
var resultArray = resultTensor.Item2;
var resultShape = resultTensor.Item1;
GCHandle dataHandle = default;
try
{
dataHandle = GCHandle.Alloc(resultArray, GCHandleType.Pinned);
var dataPtr = dataHandle.AddrOfPinnedObject();
var labelCount = resultShape[2];
var charCount = resultShape[1];
var labelCount = resultShape[2];
var charCount = resultShape[1];
return Enumerable.Range(0, resultShape[0])
.Select(i =>
return Enumerable.Range(0, resultShape[0])
.Select(i =>
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
var batchOffset = i * charCount * labelCount;
for (var n = 0; n < charCount; ++n)
{
StringBuilder sb = new();
var lastIndex = 0;
float score = 0;
for (var n = 0; n < charCount; ++n)
var rowOffset = batchOffset + n * labelCount;
var maxVal = float.MinValue;
var maxIndex = 0;
for (var c = 0; c < labelCount; c++)
{
using var mat = Mat.FromPixelData(1, labelCount, MatType.CV_32FC1,
dataPtr + (n + i * charCount) * labelCount * sizeof(float));
var maxIdx = new int[2];
mat.MinMaxIdx(out _, out var maxVal, [], maxIdx);
if (maxIdx[1] > 0 && !(n > 0 && maxIdx[1] == lastIndex))
var value = resultArray[rowOffset + c];
if (value > maxVal)
{
score += (float)maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIdx[1], labels));
maxVal = value;
maxIndex = c;
}
lastIndex = maxIdx[1];
}
return new OcrRecognizerResult(sb.ToString(), score / sb.Length);
})
.ToArray();
}
finally
{
dataHandle.Free();
}
if (maxIndex > 0 && !(n > 0 && maxIndex == lastIndex))
{
score += maxVal;
sb.Append(OcrUtils.GetLabelByIndex(maxIndex, labels));
}
lastIndex = maxIndex;
}
var text = sb.ToString();
return new OcrRecognizerResult(text, text.Length > 0 ? score / text.Length : 0);
})
.ToArray();
}).ToArray();
}
public string GetConfigName => config.Name;
}
}
@@ -407,11 +407,11 @@ public class BgiOnnxFactory
break;
case ProviderType.Cpu:
sessionOptions.AppendExecutionProvider_CPU();
if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
{
sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
}
// if (model.Name.Contains("PpOcr") || model.Name.Contains("Yap"))
// {
// sessionOptions.IntraOpNumThreads = 2; // 限制算子内部并行线程数
// sessionOptions.InterOpNumThreads = 1; // 限制算子间并行线程数(顺序执行)
// }
break;
case ProviderType.Dnnl:
sessionOptions.AppendExecutionProvider_Dnnl();
@@ -44,12 +44,35 @@ public class BgiOnnxModel
/// </summary>
public static readonly BgiOnnxModel BgiWorld = Register("BgiTree", @"Assets\Model\World\bgi_world.onnx");
/// <summary>
/// 矿物识别模型
/// </summary>
public static readonly BgiOnnxModel BgiMine = Register("BgiMine", @"Assets\Model\Mine\bgi_mine.onnx");
/// <summary>
/// 角色识别
/// </summary>
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>
/// 队伍配置角色头像识别模型
/// </summary>
public static readonly BgiOnnxModel AvatarGridIcon =
Register("AvatarGridIcon", @"Assets\Model\AvatarGridIcon\avatar.onnx");
/// <summary>
/// Silero 人声检测模型
/// </summary>
public static readonly BgiOnnxModel SileroVad =
Register("SileroVad", @"Assets\Model\Vad\silero_vad.onnx");
/// <summary>
/// paddleOCR V4 检测模型
/// </summary>
@@ -62,6 +85,12 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrDetV5 =
Register("PpOcrDetV5", @"Assets\Model\PaddleOCR\Det\V5\PP-OCRv5_mobile_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 检测模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrDetV6 =
Register("PpOcrDetV6", @"Assets\Model\PaddleOCR\Det\V6\PP-OCRv6_small_det_infer\slim.onnx");
/// <summary>
/// paddleOCR V4 识别模型
/// </summary>
@@ -80,6 +109,12 @@ public class BgiOnnxModel
public static readonly BgiOnnxModel PaddleOcrRecV5 =
Register("PpOcrRecV5", @"Assets\Model\PaddleOCR\Rec\V5\PP-OCRv5_mobile_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V6 识别模型
/// </summary>
public static readonly BgiOnnxModel PaddleOcrRecV6 =
Register("PpOcrRecV6", @"Assets\Model\PaddleOCR\Rec\V6\PP-OCRv6_small_rec_infer\slim.onnx");
/// <summary>
/// paddleOCR V5 拉丁文 识别模型
/// </summary>
@@ -139,4 +174,4 @@ public class BgiOnnxModel
RegisteredModels.Add(model);
return model;
}
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Config;
using Microsoft.ML.OnnxRuntime;
using Microsoft.ML.OnnxRuntime.Tensors;
using OpenCvSharp;
@@ -8,9 +8,9 @@ using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Text.Json;
using BetterGenshinImpact.Core.Recognition.OCR.Engine;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
@@ -31,7 +31,7 @@ public class PickTextInference : ITextInference
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
_wordDictionary = JsonSerializer.Deserialize<Dictionary<int, string>>(json) ??
_wordDictionary = JsonConvert.DeserializeObject<Dictionary<int, string>>(json) ??
throw new Exception("index_2_word.json deserialize failed");
}
@@ -116,4 +116,4 @@ public class PickTextInference : ITextInference
return new DenseTensor<float>(memory, [1, 1, 32, 384]);
}
}
}
@@ -6,7 +6,7 @@ namespace BetterGenshinImpact.Core.Recognition.ONNX.SVTR;
public class TextInferenceFactory
{
public static ITextInference Pick { get; } = Create(OcrEngineTypes.YapModel);
public static readonly Lazy<ITextInference> Pick = new(() => Create(OcrEngineTypes.YapModel));
public static ITextInference Create(OcrEngineTypes type)
{
@@ -87,4 +87,24 @@ public static class CommonExtension
{
return list.ConvertAll(ToPoint2d);
}
/// <summary>
/// 将矩形钳位到指定尺寸范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, int maxWidth, int maxHeight)
{
int x1 = Math.Clamp(rect.X, 0, maxWidth);
int y1 = Math.Clamp(rect.Y, 0, maxHeight);
int x2 = Math.Clamp(rect.X + rect.Width, 0, maxWidth);
int y2 = Math.Clamp(rect.Y + rect.Height, 0, maxHeight);
return new Rect(x1, y1, x2 - x1, y2 - y1);
}
/// <summary>
/// 将矩形钳位到 Mat 范围内(交集语义),防止 OpenCV ROI 越界
/// </summary>
public static Rect ClampTo(this Rect rect, Mat mat)
{
return rect.ClampTo(mat.Cols, mat.Rows);
}
}
@@ -1,6 +1,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
@@ -24,7 +26,7 @@ public static class Feature2DExtensions
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
{
Mat trainDescriptors = new();
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
var img = Bv.ImRead(trainImagePath, ImreadModes.Grayscale);
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
@@ -191,6 +193,53 @@ public static class Feature2DExtensions
return transformedCenter[0];
}
public static Point2f KnnMatchLocal(
this Feature2D feature2D,
KeyPointFeatureBlock[][] splitBlocks,
Mat trainDescriptors,
Size trainImageSize,
Rect searchRect,
Mat queryMat,
Mat? queryMatMask = null,
int expandCells = 2)
{
if (splitBlocks.Length == 0 || splitBlocks[0].Length == 0)
{
return default;
}
try
{
var (rowStart, rowEnd, colStart, colEnd) = KeyPointFeatureBlockHelper.GetCellRange(
trainImageSize,
splitBlocks.Length,
splitBlocks[0].Length,
searchRect);
var mergedBlock = KeyPointFeatureBlockHelper.MergeFeaturesInRange(
splitBlocks,
trainDescriptors,
rowStart - expandCells,
rowEnd + expandCells,
colStart - expandCells,
colEnd + expandCells);
var descriptors = mergedBlock.Descriptor;
if (mergedBlock.KeyPointArray.Length == 0 || descriptors == null || descriptors.Empty())
{
descriptors?.Dispose();
return default;
}
using (descriptors)
{
return feature2D.KnnMatch(mergedBlock.KeyPointArray, descriptors, queryMat, queryMatMask);
}
}
catch
{
return default;
}
}
public static Point2f[] KnnMatchCorners(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
@@ -259,4 +308,4 @@ public static class Feature2DExtensions
}
#endregion Knn匹配
}
}
@@ -1,4 +1,4 @@
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections.Generic;
@@ -153,7 +153,7 @@ public class MatchTemplateHelper
/// <param name="imgSubList"></param>
/// <param name="threshold"></param>
/// <returns></returns>
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, List<Mat> imgSubList, double threshold = 0.8)
public static List<Rect> MatchMultiPicForOnePic(Mat srcMat, IReadOnlyList<Mat> imgSubList, double threshold = 0.8)
{
List<Rect> list = [];
foreach (var sub in imgSubList)
@@ -10,4 +10,5 @@ public enum PaddleOcrModelConfig
V5Latin = 4,
V5Eslav = 5,
V5Korean = 6,
}
V6 = 8,
}
@@ -0,0 +1,109 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Area;
using OpenCvSharp;
using System;
using System.Collections.Concurrent;
using System.IO;
namespace BetterGenshinImpact.Core.Recognition;
public static class RecognitionAssets
{
private static readonly ConcurrentDictionary<RecognitionAssetCacheKey, RecognitionObject> Cache = new();
public static RecognitionObject Get(string taskName, string objectName, Region region)
{
ArgumentNullException.ThrowIfNull(region);
return Get(taskName, objectName, region.Width, region.Height);
}
public static RecognitionObject Get(string taskName, string objectName)
{
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
return Get(taskName, objectName, captureRect.Width, captureRect.Height);
}
public static RecognitionObject Get(string taskName, string objectName, int captureWidth, int captureHeight)
{
var key = new RecognitionAssetCacheKey(taskName, objectName, captureWidth, captureHeight);
var recognitionObject = Cache.GetOrAdd(key, static cacheKey => Load(cacheKey));
return recognitionObject;
}
public static void Clear(string taskName, string objectName)
{
foreach (var key in Cache.Keys)
{
if (string.Equals(key.TaskName, taskName, StringComparison.Ordinal)
&& string.Equals(key.ObjectName, objectName, StringComparison.Ordinal))
{
Cache.TryRemove(key, out _);
}
}
}
public static void ClearTask(string taskName)
{
foreach (var key in Cache.Keys)
{
if (string.Equals(key.TaskName, taskName, StringComparison.Ordinal))
{
Cache.TryRemove(key, out _);
}
}
}
public static void ClearAll()
{
Cache.Clear();
}
private static RecognitionObject Load(RecognitionAssetCacheKey key)
{
return RecognitionObjectJsonLoader.LoadFromFile(
Global.Absolute($@"GameTask\{key.TaskName}\Assets\Recognition.json"),
key.ObjectName,
new RecognitionObjectJsonLoadContext
{
CaptureHeight = key.CaptureHeight,
CaptureWidth = key.CaptureWidth,
TemplateLoader = (template, mode) => LoadTemplateImage(key.TaskName, template, key.CaptureWidth, key.CaptureHeight, mode),
});
}
private static Mat LoadTemplateImage(string taskName, string assetName, int captureWidth, int captureHeight, ImreadModes flags)
{
var assetsFolder = Global.Absolute($@"GameTask\{taskName}\Assets\{captureWidth}x{captureHeight}");
if (!Directory.Exists(assetsFolder))
{
assetsFolder = Global.Absolute($@"GameTask\{taskName}\Assets\1920x1080");
}
if (!Directory.Exists(assetsFolder))
{
throw new FileNotFoundException($"未找到{taskName}的素材文件夹");
}
var filePath = Path.Combine(assetsFolder, assetName);
if (!File.Exists(filePath))
{
throw new FileNotFoundException($"未找到{taskName}中的{assetName}文件");
}
using var stream = File.OpenRead(filePath);
var mat = Mat.FromStream(stream, flags);
if (captureWidth < 1920)
{
using (mat)
{
return ResizeHelper.Resize(mat, captureWidth / 1920d);
}
}
return mat;
}
private readonly record struct RecognitionAssetCacheKey(string TaskName, string ObjectName, int CaptureWidth, int CaptureHeight);
}
@@ -5,6 +5,7 @@ using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using Size = OpenCvSharp.Size;
namespace BetterGenshinImpact.Core.Recognition;
@@ -18,6 +19,7 @@ public class RecognitionObject
/// <summary>
/// 感兴趣的区域
/// 直接指定区域进行搜索,当这个值存在时
/// </summary>
public Rect RegionOfInterest { get; set; }
@@ -26,6 +28,24 @@ public class RecognitionObject
/// </summary>
public string? Name { get; set; }
/// <summary>
/// 模板图或者识别区域所在捕获区域的画布大小,比如 1920 x 1080、3840 x 2160 等。对应模板图的截取来源图像大小
/// </summary>
public Size? ReferenceImageSize { get; set; }
/// <summary>
/// 模板图或者识别区域在截取来源图像的位置和大小信息。
/// 在识别时,输入图大于 SourceRect
/// 模板匹配时 ReferenceBoundingBox.Width = TemplateImageMat.Width && ReferenceBoundingBox.Height = TemplateImageMat.Height,类似于bbox
/// </summary>
public Rect? ReferenceBoundingBox { get; set; }
/// <summary>
/// 查找位置的时候,相关参数,不指定会用默认的机制进行查找
/// </summary>
public SearchOptions? SearchOptions { get; set; }
#region 模板匹配
/// <summary>
@@ -93,7 +113,7 @@ public class RecognitionObject
/// 二值化阈值,默认 128
/// </summary>
public int BinaryThreshold { get; set; } = 128;
public RecognitionObject InitTemplate()
{
if (TemplateImageMat != null && TemplateImageGreyMat == null)
@@ -249,6 +269,15 @@ public class RecognitionObject
RecognitionType = this.RecognitionType,
RegionOfInterest = this.RegionOfInterest,
Name = this.Name,
ReferenceImageSize = this.ReferenceImageSize,
ReferenceBoundingBox = this.ReferenceBoundingBox,
SearchOptions = this.SearchOptions == null
? null
: new SearchOptions
{
AnchorMode = this.SearchOptions.AnchorMode,
ExpandSize = this.SearchOptions.ExpandSize
},
// 模板匹配相关属性
TemplateImageMat = this.TemplateImageMat, // 注意:Mat 是引用类型,克隆后仍然指向同一内存
@@ -0,0 +1,285 @@
using Newtonsoft.Json;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Recognition;
/// <summary>
/// `Recognition.json` 文件根对象。
/// </summary>
public sealed class RecognitionObjectJsonFile
{
/// <summary>
/// 配置文件版本号。
/// 当前实现固定使用 `1`。
/// </summary>
[JsonProperty("version")]
public int Version { get; set; } = 1;
/// <summary>
/// 公共变量表。
/// 值为表达式字符串,可在 `roi`、`reference.bbox` 等表达式中复用。
/// 常用内置变量有 `cw`、`ch`、`cx`、`cy`、`s`。
/// </summary>
[JsonProperty("vars")]
public Dictionary<string, string> Vars { get; set; } = [];
/// <summary>
/// 公共区域表达式表。
/// 值为返回 `Rect` 的表达式字符串,其他字段可通过 `@别名` 引用。
/// 常用于复用 ROI 定义。
/// </summary>
[JsonProperty("regions")]
public Dictionary<string, string> Regions { get; set; } = [];
/// <summary>
/// 公共模板别名表。
/// 值为模板图片文件名或路径,`template` 可通过 `@别名` 引用。
/// </summary>
[JsonProperty("templates")]
public Dictionary<string, string> Templates { get; set; } = [];
/// <summary>
/// 识别对象集合。
/// Key 为对象名,也就是调用 `RecognitionAssets.Get(taskName, objectName, ...)` 时的 `objectName`。
/// </summary>
[JsonProperty("objects")]
public Dictionary<string, RecognitionObjectJsonConfig> Objects { get; set; } = [];
}
/// <summary>
/// 单个识别对象的 JSON 配置。
/// </summary>
public sealed class RecognitionObjectJsonConfig
{
/// <summary>
/// 可选的运行时名称。
/// 不填时:
/// 模板匹配默认取模板文件名(不含扩展名);
/// 其他类型默认取 objects 下的对象名。
/// </summary>
[JsonProperty("name")]
public string? Name { get; set; }
/// <summary>
/// 识别类型。
/// 文本必须与 `RecognitionTypes` 枚举名一致,例如 `TemplateMatch`、`OcrMatch`、`ColorMatch`。
/// </summary>
[JsonProperty("type")]
public string? Type { get; set; }
/// <summary>
/// 模板图片文件名、相对路径或模板别名。
/// 仅 `TemplateMatch` 使用;支持写成 `@模板别名`。
/// </summary>
[JsonProperty("template")]
public string? Template { get; set; }
/// <summary>
/// 模板图片加载模式。
/// 文本必须与 OpenCV `ImreadModes` 枚举名一致;不填默认 `Color`。
/// </summary>
[JsonProperty("templateMode")]
public string? TemplateMode { get; set; }
/// <summary>
/// 感兴趣区域(ROI)。
/// 值为返回 `Rect` 的表达式字符串,也可写成 `@区域别名`。
/// </summary>
[JsonProperty("roi")]
public string? Roi { get; set; }
/// <summary>
/// 模板匹配阈值。
/// 仅模板匹配常用;不填时沿用 `RecognitionObject` 默认值。
/// </summary>
[JsonProperty("threshold")]
public double? Threshold { get; set; }
/// <summary>
/// 是否启用三通道模板匹配。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("use3Channels")]
public bool? Use3Channels { get; set; }
/// <summary>
/// 模板匹配算法。
/// 文本必须与 OpenCV `TemplateMatchModes` 枚举名一致,例如 `CCoeffNormed`、`CCorrNormed`。
/// </summary>
[JsonProperty("templateMatchMode")]
public string? TemplateMatchMode { get; set; }
/// <summary>
/// 是否启用模板遮罩。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("useMask")]
public bool? UseMask { get; set; }
/// <summary>
/// 遮罩颜色,使用 HTML 颜色格式,例如 `#00FF00`。
/// 当 `useMask=true` 时用于生成遮罩。
/// </summary>
[JsonProperty("maskColor")]
public string? MaskColor { get; set; }
/// <summary>
/// 识别成功时是否绘制调试框。
/// </summary>
[JsonProperty("draw")]
public bool? Draw { get; set; }
/// <summary>
/// 调试框颜色,使用 HTML 颜色格式,例如 `#FF0000`。
/// </summary>
[JsonProperty("drawColor")]
public string? DrawColor { get; set; }
/// <summary>
/// 调试框线宽。
/// </summary>
[JsonProperty("drawWidth")]
public float? DrawWidth { get; set; }
/// <summary>
/// 单次模板匹配最多返回多少个结果。
/// 仅 `TemplateMatch` 使用;`-1` 表示不限制。
/// </summary>
[JsonProperty("maxMatchCount")]
public int? MaxMatchCount { get; set; }
/// <summary>
/// 是否先做二值化再进行模板匹配。
/// 仅 `TemplateMatch` 使用。
/// </summary>
[JsonProperty("useBinaryMatch")]
public bool? UseBinaryMatch { get; set; }
/// <summary>
/// 二值化阈值。
/// 当 `useBinaryMatch=true` 时使用。
/// </summary>
[JsonProperty("binaryThreshold")]
public int? BinaryThreshold { get; set; }
/// <summary>
/// 颜色转换方式。
/// 文本必须与 OpenCV `ColorConversionCodes` 枚举名一致,例如 `BGR2RGB`、`BGR2HSV`、`BGR2GRAY`。
/// </summary>
[JsonProperty("colorCode")]
public string? ColorCode { get; set; }
/// <summary>
/// 颜色下界。
/// 用于 `ColorMatch` / `ColorRangeAndOcr` 等颜色范围识别,长度支持 1 到 4 个数字。
/// </summary>
[JsonProperty("lowerColor")]
public List<double>? LowerColor { get; set; }
/// <summary>
/// 颜色上界。
/// 用于 `ColorMatch` / `ColorRangeAndOcr` 等颜色范围识别,长度支持 1 到 4 个数字。
/// </summary>
[JsonProperty("upperColor")]
public List<double>? UpperColor { get; set; }
/// <summary>
/// 颜色匹配要求的最小命中点数。
/// 主要用于 `ColorMatch`。
/// </summary>
[JsonProperty("matchCount")]
public int? MatchCount { get; set; }
/// <summary>
/// OCR 引擎。
/// 文本必须与 `OcrEngineTypes` 枚举名一致;当前通常写 `Paddle`。
/// </summary>
[JsonProperty("ocrEngine")]
public string? OcrEngine { get; set; }
/// <summary>
/// OCR 结果替换表。
/// Key 为期望文本,Value 为会被替换到该文本的一组误识别写法。
/// </summary>
[JsonProperty("replace")]
public Dictionary<string, List<string>> Replace { get; set; } = [];
/// <summary>
/// OCR 全包含匹配。
/// 列表中的所有文本都命中时才算成功。
/// </summary>
[JsonProperty("allContains")]
public List<string> AllContains { get; set; } = [];
/// <summary>
/// OCR 任一包含匹配。
/// 列表中任意一个文本命中就算成功。
/// </summary>
[JsonProperty("oneContains")]
public List<string> OneContains { get; set; } = [];
/// <summary>
/// OCR 正则匹配列表。
/// 列表中的所有正则都命中时才算成功。
/// </summary>
[JsonProperty("regex")]
public List<string> Regex { get; set; } = [];
/// <summary>
/// OCR 目标文本。
/// 常用于多 OCR 结果筛选,或与其他 OCR 匹配配置配合使用。
/// </summary>
[JsonProperty("text")]
public string? Text { get; set; }
/// <summary>
/// 模板参考信息。
/// 用于描述模板来源截图尺寸和原始包围盒,方便后续定位或搜索扩展。
/// </summary>
[JsonProperty("reference")]
public RecognitionReferenceJsonConfig? Reference { get; set; }
/// <summary>
/// 搜索扩展配置。
/// 用于指定锚点和扩展范围。
/// </summary>
[JsonProperty("search")]
public RecognitionSearchJsonConfig? Search { get; set; }
}
/// <summary>
/// 模板参考信息配置。
/// </summary>
public sealed class RecognitionReferenceJsonConfig
{
/// <summary>
/// 模板来源截图尺寸,格式为 `[width, height]`。
/// </summary>
[JsonProperty("size")]
public List<int>? Size { get; set; }
/// <summary>
/// 模板在来源截图中的包围盒,值为返回 `Rect` 的表达式字符串。
/// </summary>
[JsonProperty("bbox")]
public string? Bbox { get; set; }
}
/// <summary>
/// 搜索扩展配置。
/// </summary>
public sealed class RecognitionSearchJsonConfig
{
/// <summary>
/// 搜索锚点。
/// 文本必须与 `SearchAnchorMode` 枚举名一致。
/// </summary>
[JsonProperty("anchor")]
public string? Anchor { get; set; }
/// <summary>
/// 在锚点附近额外扩展的搜索尺寸,格式为 `[width, height]`。
/// </summary>
[JsonProperty("expand")]
public List<int>? Expand { get; set; }
}
@@ -0,0 +1,530 @@
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using NCalc;
using Newtonsoft.Json;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace BetterGenshinImpact.Core.Recognition;
public sealed class RecognitionObjectJsonLoadContext
{
public required int CaptureWidth { get; init; }
public required int CaptureHeight { get; init; }
public required Func<string, ImreadModes, Mat> TemplateLoader { get; init; }
public IReadOnlyDictionary<string, object>? ExtraParameters { get; init; }
}
public static class RecognitionObjectJsonLoader
{
private sealed class LoggerTag;
private static readonly ILogger Logger = App.GetLogger<LoggerTag>();
public static RecognitionObject LoadFromFile(string filePath, string objectName, RecognitionObjectJsonLoadContext context)
{
ArgumentNullException.ThrowIfNull(filePath);
ArgumentNullException.ThrowIfNull(objectName);
ArgumentNullException.ThrowIfNull(context);
try
{
var json = File.ReadAllText(filePath, Encoding.UTF8);
var config = JsonConvert.DeserializeObject<RecognitionObjectJsonFile>(json)
?? throw new InvalidOperationException($"无法解析 RecognitionObject 配置文件: {filePath}");
return Load(config, objectName, context);
}
catch (Exception ex)
{
Logger.LogError(ex,
"Recognition 加载失败: {ObjectName} @ {CaptureWidth}x{CaptureHeight}, file={FilePath}",
objectName,
context.CaptureWidth,
context.CaptureHeight,
filePath);
throw;
}
}
public static RecognitionObject Load(RecognitionObjectJsonFile config, string objectName, RecognitionObjectJsonLoadContext context)
{
ArgumentNullException.ThrowIfNull(config);
ArgumentNullException.ThrowIfNull(objectName);
ArgumentNullException.ThrowIfNull(context);
try
{
if (!config.Objects.TryGetValue(objectName, out var objectConfig))
{
throw new KeyNotFoundException($"未找到名称为 {objectName} 的 RecognitionObject 配置");
}
return new Loader(config, context).BuildRecognitionObject(objectName, objectConfig);
}
catch (Exception ex)
{
Logger.LogError(ex,
"Recognition 构建失败: {ObjectName} @ {CaptureWidth}x{CaptureHeight}",
objectName,
context.CaptureWidth,
context.CaptureHeight);
throw;
}
}
private sealed class Loader
{
private static readonly string[] RectFunctionNames =
[
"rect",
"cutLeft",
"cutRight",
"cutTop",
"cutBottom",
"cutLeftTop",
"cutRightTop",
"cutLeftBottom",
"cutRightBottom",
];
private readonly RecognitionObjectJsonFile _config;
private readonly RecognitionObjectJsonLoadContext _context;
private readonly Rect _captureRect;
private readonly double _assetScale;
private readonly Dictionary<string, double> _resolvedVars = new(StringComparer.Ordinal);
private readonly HashSet<string> _resolvingVars = new(StringComparer.Ordinal);
private readonly HashSet<string> _functionNames = new(RectFunctionNames, StringComparer.Ordinal);
public Loader(RecognitionObjectJsonFile config, RecognitionObjectJsonLoadContext context)
{
_config = config;
_context = context;
_captureRect = new Rect(0, 0, context.CaptureWidth, context.CaptureHeight);
_assetScale = context.CaptureWidth < 1920 ? context.CaptureWidth / 1920d : 1d;
}
public RecognitionObject BuildRecognitionObject(string objectName, RecognitionObjectJsonConfig config)
{
var recognitionType = ParseEnumExact<RecognitionTypes>(config.Type, nameof(config.Type));
string? templateName = null;
if (recognitionType == RecognitionTypes.TemplateMatch)
{
templateName = ResolveTemplate(config.Template, objectName);
}
var recognitionObject = new RecognitionObject
{
Name = ResolveName(objectName, config, recognitionType, templateName),
RecognitionType = recognitionType,
};
if (!string.IsNullOrWhiteSpace(config.Roi))
{
recognitionObject.RegionOfInterest = EvaluateRect(config.Roi);
}
if (config.Threshold.HasValue)
{
recognitionObject.Threshold = config.Threshold.Value;
}
if (config.Use3Channels.HasValue)
{
recognitionObject.Use3Channels = config.Use3Channels.Value;
}
if (!string.IsNullOrWhiteSpace(config.TemplateMatchMode))
{
recognitionObject.TemplateMatchMode = ParseEnumExact<TemplateMatchModes>(config.TemplateMatchMode, nameof(config.TemplateMatchMode));
}
if (config.UseMask.HasValue)
{
recognitionObject.UseMask = config.UseMask.Value;
}
if (!string.IsNullOrWhiteSpace(config.MaskColor))
{
recognitionObject.MaskColor = ParseColor(config.MaskColor);
}
if (config.Draw.HasValue)
{
recognitionObject.DrawOnWindow = config.Draw.Value;
}
if (!string.IsNullOrWhiteSpace(config.DrawColor) || config.DrawWidth.HasValue)
{
var drawColor = !string.IsNullOrWhiteSpace(config.DrawColor)
? ParseColor(config.DrawColor)
: recognitionObject.DrawOnWindowPen.Color;
var drawWidth = config.DrawWidth ?? recognitionObject.DrawOnWindowPen.Width;
recognitionObject.DrawOnWindowPen = new Pen(drawColor, drawWidth);
}
if (config.MaxMatchCount.HasValue)
{
recognitionObject.MaxMatchCount = config.MaxMatchCount.Value;
}
if (config.UseBinaryMatch.HasValue)
{
recognitionObject.UseBinaryMatch = config.UseBinaryMatch.Value;
}
if (config.BinaryThreshold.HasValue)
{
recognitionObject.BinaryThreshold = config.BinaryThreshold.Value;
}
if (!string.IsNullOrWhiteSpace(config.ColorCode))
{
recognitionObject.ColorConversionCode = ParseEnumExact<ColorConversionCodes>(config.ColorCode, nameof(config.ColorCode));
}
if (config.LowerColor is { Count: > 0 })
{
recognitionObject.LowerColor = BuildScalar(config.LowerColor, nameof(config.LowerColor));
}
if (config.UpperColor is { Count: > 0 })
{
recognitionObject.UpperColor = BuildScalar(config.UpperColor, nameof(config.UpperColor));
}
if (config.MatchCount.HasValue)
{
recognitionObject.MatchCount = config.MatchCount.Value;
}
if (!string.IsNullOrWhiteSpace(config.OcrEngine))
{
recognitionObject.OcrEngine = ParseEnumExact<OcrEngineTypes>(config.OcrEngine, nameof(config.OcrEngine));
}
if (config.Replace.Count > 0)
{
recognitionObject.ReplaceDictionary = config.Replace.ToDictionary(
pair => pair.Key,
pair => pair.Value.ToArray(),
StringComparer.Ordinal);
}
if (config.AllContains.Count > 0)
{
recognitionObject.AllContainMatchText = [.. config.AllContains];
}
if (config.OneContains.Count > 0)
{
recognitionObject.OneContainMatchText = [.. config.OneContains];
}
if (config.Regex.Count > 0)
{
recognitionObject.RegexMatchText = [.. config.Regex];
}
if (!string.IsNullOrWhiteSpace(config.Text))
{
recognitionObject.Text = config.Text;
}
if (config.Reference?.Size is { Count: 2 })
{
recognitionObject.ReferenceImageSize = new OpenCvSharp.Size(config.Reference.Size[0], config.Reference.Size[1]);
}
if (!string.IsNullOrWhiteSpace(config.Reference?.Bbox))
{
recognitionObject.ReferenceBoundingBox = EvaluateRect(config.Reference.Bbox);
}
if (config.Search != null)
{
recognitionObject.SearchOptions = new SearchOptions();
if (!string.IsNullOrWhiteSpace(config.Search.Anchor))
{
recognitionObject.SearchOptions.AnchorMode = ParseEnumExact<SearchAnchorMode>(config.Search.Anchor, nameof(config.Search.Anchor));
}
if (config.Search.Expand is { Count: 2 })
{
recognitionObject.SearchOptions.ExpandSize = new OpenCvSharp.Size(config.Search.Expand[0], config.Search.Expand[1]);
}
}
if (recognitionType == RecognitionTypes.TemplateMatch)
{
var loadMode = ParseTemplateMode(config.TemplateMode);
recognitionObject.TemplateImageMat = _context.TemplateLoader(templateName!, loadMode);
}
return recognitionObject.InitTemplate();
}
private string ResolveName(string objectName, RecognitionObjectJsonConfig config, RecognitionTypes recognitionType, string? templateName)
{
if (!string.IsNullOrWhiteSpace(config.Name))
{
return config.Name;
}
if (recognitionType == RecognitionTypes.TemplateMatch && !string.IsNullOrWhiteSpace(templateName))
{
return Path.GetFileNameWithoutExtension(templateName);
}
return objectName;
}
private ImreadModes ParseTemplateMode(string? templateMode)
{
return string.IsNullOrWhiteSpace(templateMode)
? ImreadModes.Color
: ParseEnumExact<ImreadModes>(templateMode, nameof(templateMode));
}
private string ResolveTemplate(string? template, string objectName)
{
if (string.IsNullOrWhiteSpace(template))
{
throw new InvalidOperationException($"对象 {objectName} 缺少 template 配置");
}
var resolved = template.Trim();
while (resolved.StartsWith('@'))
{
var alias = resolved[1..];
if (!_config.Templates.TryGetValue(alias, out resolved))
{
throw new KeyNotFoundException($"未找到模板别名 {alias}");
}
}
return resolved;
}
private Rect EvaluateRect(string expression)
{
var resolved = ResolveRegionExpression(expression);
var value = EvaluateValue(resolved);
return value switch
{
Rect rect => rect,
_ => throw new InvalidOperationException($"表达式 {expression} 未返回 Rect")
};
}
private string ResolveRegionExpression(string expression)
{
var resolved = expression.Trim();
while (resolved.StartsWith('@'))
{
var alias = resolved[1..];
if (!_config.Regions.TryGetValue(alias, out resolved))
{
throw new KeyNotFoundException($"未找到区域别名 {alias}");
}
}
return resolved;
}
private object EvaluateValue(string expression, string? skipVarName = null)
{
var normalizedExpression = NormalizeExpression(expression);
var ncalcExpression = new Expression(normalizedExpression);
foreach (var (name, value) in BuildParameters(skipVarName))
{
ncalcExpression.Parameters[name] = value;
}
ncalcExpression.Functions["rect"] = args => BuildRect(args.Evaluate(0), args.Evaluate(1), args.Evaluate(2), args.Evaluate(3));
ncalcExpression.Functions["cutLeft"] = args => _captureRect.CutLeft(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutRight"] = args => _captureRect.CutRight(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutTop"] = args => _captureRect.CutTop(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutBottom"] = args => _captureRect.CutBottom(ToDouble(args.Evaluate(0)));
ncalcExpression.Functions["cutLeftTop"] = args => _captureRect.CutLeftTop(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutRightTop"] = args => _captureRect.CutRightTop(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutLeftBottom"] = args => _captureRect.CutLeftBottom(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
ncalcExpression.Functions["cutRightBottom"] = args => _captureRect.CutRightBottom(ToDouble(args.Evaluate(0)), ToDouble(args.Evaluate(1)));
return ncalcExpression.Evaluate();
}
private Dictionary<string, object> BuildParameters(string? skipVarName = null)
{
var parameters = new Dictionary<string, object>(StringComparer.Ordinal)
{
["cw"] = _captureRect.Width,
["ch"] = _captureRect.Height,
["cx"] = _captureRect.X,
["cy"] = _captureRect.Y,
["s"] = _assetScale,
};
if (_context.ExtraParameters != null)
{
foreach (var (name, value) in _context.ExtraParameters)
{
parameters[name] = value;
}
}
foreach (var varName in _config.Vars.Keys)
{
if (string.Equals(varName, skipVarName, StringComparison.Ordinal))
{
continue;
}
parameters[varName] = ResolveVariable(varName);
}
return parameters;
}
private double ResolveVariable(string name)
{
if (_resolvedVars.TryGetValue(name, out var resolvedValue))
{
return resolvedValue;
}
if (!_config.Vars.TryGetValue(name, out var expression))
{
throw new KeyNotFoundException($"未找到变量 {name}");
}
if (!_resolvingVars.Add(name))
{
throw new InvalidOperationException($"变量 {name} 存在循环引用");
}
try
{
var value = ToDouble(EvaluateValue(expression, name));
_resolvedVars[name] = value;
return value;
}
finally
{
_resolvingVars.Remove(name);
}
}
private string NormalizeExpression(string expression)
{
var normalized = expression;
var parameterNames = GetParameterNames()
.OrderByDescending(name => name.Length)
.ToList();
foreach (var parameterName in parameterNames)
{
if (_functionNames.Contains(parameterName))
{
continue;
}
var pattern = $@"(?<![\w\]]){Regex.Escape(parameterName)}(?![\w\(])";
normalized = Regex.Replace(normalized, pattern, $"[{parameterName}]");
}
return normalized;
}
private IEnumerable<string> GetParameterNames()
{
yield return "cw";
yield return "ch";
yield return "cx";
yield return "cy";
yield return "s";
if (_context.ExtraParameters != null)
{
foreach (var name in _context.ExtraParameters.Keys)
{
yield return name;
}
}
foreach (var name in _config.Vars.Keys)
{
yield return name;
}
}
private static Rect BuildRect(object? x, object? y, object? width, object? height)
{
return new Rect(
(int)Math.Round(ToDouble(x)),
(int)Math.Round(ToDouble(y)),
(int)Math.Round(ToDouble(width)),
(int)Math.Round(ToDouble(height)));
}
private static Scalar BuildScalar(IReadOnlyList<double> values, string fieldName)
{
return values.Count switch
{
1 => new Scalar(values[0]),
2 => new Scalar(values[0], values[1]),
3 => new Scalar(values[0], values[1], values[2]),
4 => new Scalar(values[0], values[1], values[2], values[3]),
_ => throw new InvalidOperationException($"{fieldName} 必须是 1 到 4 个数字"),
};
}
private static TEnum ParseEnumExact<TEnum>(string? value, string fieldName) where TEnum : struct, Enum
{
if (string.IsNullOrWhiteSpace(value))
{
throw new InvalidOperationException($"{fieldName} 不能为空");
}
if (Enum.TryParse<TEnum>(value, false, out var parsed))
{
return parsed;
}
throw new InvalidOperationException($"{fieldName} 的值 {value} 不是有效的 {typeof(TEnum).Name}");
}
private static Color ParseColor(string value)
{
return ColorTranslator.FromHtml(value);
}
private static double ToDouble(object? value)
{
return value switch
{
null => 0d,
byte byteValue => byteValue,
short shortValue => shortValue,
int intValue => intValue,
long longValue => longValue,
float floatValue => floatValue,
double doubleValue => doubleValue,
decimal decimalValue => (double)decimalValue,
_ => Convert.ToDouble(value, CultureInfo.InvariantCulture),
};
}
}
}
@@ -0,0 +1,32 @@
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition;
public class SearchOptions
{
/// <summary>
/// 搜索锚定点。当输入图与参考图宽高比不一致时,决定缩放后的参考画布贴向哪一侧。
/// 这个缩放规则需要和待匹配 UI 在不同分辨率下的布局缩放规则保持一致。
/// </summary>
public SearchAnchorMode AnchorMode { get; set; } = SearchAnchorMode.Auto;
/// <summary>
/// 在预测框外额外扩展的像素大小。未指定时默认四周各扩展 10px。
/// </summary>
public Size? ExpandSize { get; set; }
}
/// <summary>
/// 参考搜索的锚定方式。
/// 元素在画布右/下侧时通常使用右/下锚定,元素在左/上侧时通常使用左/上锚定;
/// 居中元素使用中心锚定,按画布中心加偏移进行缩放。
/// </summary>
public enum SearchAnchorMode
{
Auto,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
Center
}
@@ -1,11 +1,11 @@
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Windows;
using Gma.System.MouseKeyHook;
using Microsoft.Extensions.Logging;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Diagnostics;
@@ -23,7 +23,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
private readonly Dictionary<Keys, bool> _keyDownState = [];
private DirectInputMonitor? _directInputMonitor;
private IDisposable? _relativeMouseSubscription;
private readonly System.Timers.Timer _timer = new();
@@ -37,44 +37,78 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_timer.Interval = 50; // ms
}
public async Task StartRecord()
public async Task<bool> StartRecord(
RelativeMouseInputType inputType = RelativeMouseInputType.DirectInput)
{
if (!TaskContext.Instance().IsInitialized)
{
Toast.Warning("请先在启动页,启动截图器再使用本功能");
return;
return false;
}
if (Status != KeyMouseRecorderStatus.Stop)
{
Toast.Warning("已经在录制状态,请不要重复启动录制功能");
return;
return false;
}
Status = KeyMouseRecorderStatus.Start;
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
for (var i = 3; i >= 1; i--)
var taskTriggerStopped = false;
try
{
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
SystemControl.ActivateWindow();
_logger.LogInformation("录制:{Text}", "实时任务已暂停");
_logger.LogInformation("注意:录制时遇到主界面(鼠标永远在界面中心)和其他界面(鼠标可自由移动,比如地图等)的切换,请把手离开鼠标等待录制模式切换日志");
for (var i = 3; i >= 1; i--)
{
_logger.LogInformation("{Sec}秒后启动录制...", i);
await Task.Delay(1000);
}
TaskTriggerDispatcher.Instance().StopTimer();
taskTriggerStopped = true;
_recorder = new KeyMouseRecorder();
var monitorFactory = App.GetService<IRelativeMouseInputMonitorFactory>()
?? throw new InvalidOperationException("相对鼠标捕获工厂未注册");
_relativeMouseSubscription = monitorFactory
.Get(inputType)
.Subscribe(RelativeMouseMoved);
_timer.Start();
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:已启动,相对鼠标捕获方式:{InputType}", inputType);
return true;
}
catch (Exception ex)
{
_timer.Stop();
try
{
_relativeMouseSubscription?.Dispose();
}
catch (Exception disposeException)
{
_logger.LogWarning(disposeException, "清理相对鼠标捕获订阅失败");
}
_relativeMouseSubscription = null;
_recorder = null;
TaskTriggerDispatcher.Instance().StopTimer();
if (taskTriggerStopped)
{
TaskTriggerDispatcher.Instance().StartTimer();
}
_timer.Start();
_recorder = new KeyMouseRecorder();
_directInputMonitor = new DirectInputMonitor();
_directInputMonitor.Start();
Status = KeyMouseRecorderStatus.Recording;
_logger.LogInformation("录制:{Text}", "已启动");
Status = KeyMouseRecorderStatus.Stop;
_logger.LogError(ex, "启动键鼠录制失败,相对鼠标捕获方式:{InputType}", inputType);
await ThemedMessageBox.ErrorAsync(
$"启动键鼠录制失败:{ex.Message}",
"键鼠录制启动失败");
return false;
}
}
public string StopRecord()
@@ -84,27 +118,30 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
throw new InvalidOperationException("未处于录制中状态,无法停止");
}
var macro = _recorder?.ToJsonMacro() ?? string.Empty;
_recorder = null;
_directInputMonitor?.Stop();
_directInputMonitor?.Dispose();
_directInputMonitor = null;
_timer.Stop();
_logger.LogInformation("录制:{Text}", "结束录制");
var recorder = _recorder;
_recorder = null;
var relativeMouseSubscription = _relativeMouseSubscription;
_relativeMouseSubscription = null;
TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
return macro;
try
{
relativeMouseSubscription?.Dispose();
return recorder?.ToJsonMacro() ?? string.Empty;
}
finally
{
_logger.LogInformation("录制:{Text}", "结束录制");
TaskTriggerDispatcher.Instance().StartTimer();
Status = KeyMouseRecorderStatus.Stop;
}
}
public void Tick(object? sender, EventArgs e)
{
var ra = TaskControl.CaptureToRectArea();
var iconRa = ra.Find(ElementAssets.Instance.FriendChat);
var iconRa = ra.Find(ElementRecognition.Get("FriendChat", ra));
var exist = iconRa.IsExist();
if (exist != _isInMainUi)
{
@@ -115,7 +152,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
ra.Dispose();
}
public void GlobalHookKeyDown(KeyEventArgs e, uint time)
public void GlobalHookKeyDown(KeyEventArgs e, DateTime time)
{
// 排除热键
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.KeyMouseMacroRecordHotkey)
@@ -142,7 +179,7 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
_recorder?.KeyDown(e, time);
}
public void GlobalHookKeyUp(KeyEventArgs e, uint time)
public void GlobalHookKeyUp(KeyEventArgs e, DateTime time)
{
if (e.KeyCode.ToString() == TaskContext.Instance().Config.HotKeyConfig.Test1Hotkey)
{
@@ -157,42 +194,42 @@ public class GlobalKeyMouseRecord : Singleton<GlobalKeyMouseRecord>
}
}
public void GlobalHookMouseDown(MouseEventExtArgs e)
public void GlobalHookMouseDown(MouseEventExtArgs e, DateTime time)
{
// Debug.WriteLine($"MouseDown: {e.Button}");
_recorder?.MouseDown(e);
_recorder?.MouseDown(e, time);
}
public void GlobalHookMouseUp(MouseEventExtArgs e)
public void GlobalHookMouseUp(MouseEventExtArgs e, DateTime time)
{
// Debug.WriteLine($"MouseUp: {e.Button}");
_recorder?.MouseUp(e);
_recorder?.MouseUp(e, time);
}
public void GlobalHookMouseMoveTo(MouseEventExtArgs e)
public void GlobalHookMouseMoveTo(MouseEventExtArgs e, DateTime time)
{
if (_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMove: {e.X}, {e.Y}");
_recorder?.MouseMoveTo(e);
_recorder?.MouseMoveTo(e, time);
}
public void GlobalHookMouseWheel(MouseEventExtArgs e)
public void GlobalHookMouseWheel(MouseEventExtArgs e, DateTime time)
{
// Debug.WriteLine($"MouseWheel: {e.Delta}");
_recorder?.MouseWheel(e);
_recorder?.MouseWheel(e, time);
}
public void GlobalHookMouseMoveBy(MouseState state, uint time)
private void RelativeMouseMoved(object? sender, RelativeMouseMoveEventArgs e)
{
if (state is { X: 0, Y: 0 } || !_isInMainUi)
if (e is { DeltaX: 0, DeltaY: 0 } || !_isInMainUi)
{
return;
}
// Debug.WriteLine($"MouseMoveBy: {state.X}, {state.Y}");
_recorder?.MouseMoveBy(state, time);
// Debug.WriteLine($"MouseMoveBy: {e.DeltaX}, {e.DeltaY}");
_recorder?.MouseMoveBy(e);
}
}
@@ -1,4 +1,4 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
@@ -49,7 +49,7 @@ public class KeyMouseMacroPlayer
public static async Task PlayMacro(List<MacroEvent> macroEvents, CancellationToken ct)
{
WorkingArea = PrimaryScreen.WorkingArea;
var startTime = Kernel32.GetTickCount();
var startTime = DateTime.UtcNow;
foreach (var e in macroEvents)
{
if (ct.IsCancellationRequested)
@@ -57,14 +57,14 @@ public class KeyMouseMacroPlayer
return;
}
var timeToWait = e.Time - (Kernel32.GetTickCount() - startTime);
var timeToWait = e.Time - (DateTime.UtcNow - startTime).TotalMilliseconds;
if (timeToWait < 0)
{
TaskControl.Logger.LogDebug("无法原速重放事件{Event},落后{TimeToWait}ms", e.Type.ToString(), (-timeToWait).ToString("F0"));
}
else
{
await Task.Delay((int)timeToWait, ct);
await Task.Delay(TimeSpan.FromMilliseconds(timeToWait), ct);
}
switch (e.Type)
@@ -209,4 +209,4 @@ public class KeyMouseMacroPlayer
{
return y * 65535 * 1d / WorkingArea.Height;
}
}
}
@@ -1,15 +1,14 @@
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Recorder.Model;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map;
using Gma.System.MouseKeyHook;
using SharpDX.DirectInput;
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows.Forms;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Recorder;
@@ -17,7 +16,7 @@ public class KeyMouseRecorder
{
public List<MacroEvent> MacroEvents { get; } = [];
public uint StartTime { get; set; } = Kernel32.GetTickCount();
public DateTime StartTime { get; set; } = DateTime.UtcNow;
public DateTime LastOrientationDetection { get; set; } = DateTime.UtcNow;
@@ -114,27 +113,27 @@ public class KeyMouseRecorder
return JsonSerializer.Serialize(keyMouseScript, JsonOptions);
}
public void KeyDown(KeyEventArgs e, uint time)
public void KeyDown(KeyEventArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyDown,
KeyCode = e.KeyValue,
Time = time - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void KeyUp(KeyEventArgs e, uint time)
public void KeyUp(KeyEventArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.KeyUp,
KeyCode = e.KeyValue,
Time = time - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void MouseDown(MouseEventExtArgs e)
public void MouseDown(MouseEventExtArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
@@ -142,11 +141,11 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = e.Timestamp - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void MouseUp(MouseEventExtArgs e)
public void MouseUp(MouseEventExtArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
@@ -154,32 +153,32 @@ public class KeyMouseRecorder
MouseX = e.X,
MouseY = e.Y,
MouseButton = e.Button.ToString(),
Time = e.Timestamp - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void MouseMoveTo(MouseEventExtArgs e)
public void MouseMoveTo(MouseEventExtArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveTo,
MouseX = e.X,
MouseY = e.Y,
Time = e.Timestamp - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void MouseWheel(MouseEventExtArgs e)
public void MouseWheel(MouseEventExtArgs e, DateTime time)
{
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseWheel,
MouseY = e.Delta, // 120 的倍率
Time = e.Timestamp - StartTime
Time = (time - StartTime).TotalMilliseconds
});
}
public void MouseMoveBy(MouseState state, uint time)
public void MouseMoveBy(RelativeMouseMoveEventArgs e)
{
int? cao = null;
@@ -196,9 +195,9 @@ public class KeyMouseRecorder
MacroEvents.Add(new MacroEvent
{
Type = MacroEventType.MouseMoveBy,
MouseX = state.X,
MouseY = state.Y,
Time = time - 5 - StartTime,
MouseX = e.DeltaX,
MouseY = e.DeltaY,
Time = (e.Timestamp - StartTime).TotalMilliseconds,
CameraOrientation = cao,
});
}
@@ -1,42 +1,114 @@
using BetterGenshinImpact.Model;
using System;
using BetterGenshinImpact.Model;
using System.Threading;
namespace BetterGenshinImpact.Core.Script;
public class CancellationContext : Singleton<CancellationContext>
{
public CancellationTokenSource Cts { get; set; } = new();
private readonly object _sync = new();
public CancellationTokenSource Cts { get; private set; } = new();
public bool IsManualStop { get; private set; }
public bool IsCancellationRequested
{
get
{
lock (_sync)
{
return !disposed && Cts.IsCancellationRequested;
}
}
}
private bool disposed;
public CancellationToken GetActiveToken()
{
lock (_sync)
{
if (disposed)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
return Cts.Token;
}
}
public void Set()
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
lock (_sync)
{
Cts = new CancellationTokenSource();
IsManualStop = false;
disposed = false;
}
}
public void ManualCancel()
{
if (!disposed)
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
IsManualStop = true;
Cts.Cancel();
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
}
}
public void Cancel()
{
if (!disposed)
CancellationTokenSource cts;
lock (_sync)
{
Cts.Cancel();
if (disposed)
{
return;
}
cts = Cts;
}
try
{
cts.Cancel();
}
catch (ObjectDisposedException)
{
// 并发 Clear 可能已释放 CTS,这里视为已取消/已清理。
}
}
public void Clear()
{
Cts.Dispose();
disposed = true;
CancellationTokenSource cts;
lock (_sync)
{
if (disposed)
{
return;
}
cts = Cts;
disposed = true;
}
cts.Dispose();
}
}
@@ -1,4 +1,4 @@
using System;
using System;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
@@ -12,11 +12,13 @@ public class AutoPathingScript
{
private object? _config = null;
private string _rootPath;
private readonly LimitedFile _autoPathingFile;
public AutoPathingScript(string rootPath, object? config)
{
_config = config;
_rootPath = rootPath;
_autoPathingFile = new LimitedFile(Global.Absolute(@"User\AutoPathing"));
}
public async Task Run(string json)
@@ -59,7 +61,48 @@ public class AutoPathingScript
/// <param name="path">在 `\User\AutoPathing` 目录下获取文件</param>
public async Task RunFileFromUser(string path)
{
var json = await new LimitedFile(Global.Absolute(@"User\AutoPathing")).ReadText(path);
var json = await AutoPathingFile.ReadText(path);
await Run(json);
}
/// <summary>
/// 判断 AutoPathing 目录下的路径是否存在
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>存在返回 true,否则返回 false</returns>
public bool IsExists(string subPath) => AutoPathingFile.IsExists(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件返回 true,否则返回 false</returns>
public bool IsFile(string subPath) => AutoPathingFile.IsFile(subPath);
/// <summary>
/// 判断 AutoPathing 目录下的路径是否为文件夹
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的路径</param>
/// <returns>是文件夹返回 true,否则返回 false</returns>
public bool IsFolder(string subPath) => AutoPathingFile.IsFolder(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件夹的内容(非递归方式)
/// 目录不存在时返回空数组,不会自动创建目录
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的子目录路径,默认为相对根目录</param>
/// <returns>文件夹内所有文件和文件夹的相对路径数组,出错时返回空数组</returns>
public string[] ReadPathSync(string subPath = "./") => AutoPathingFile.ReadPathSync(subPath);
/// <summary>
/// 读取 AutoPathing 目录下指定文件的文本内容
/// </summary>
/// <param name="subPath">相对于 User\AutoPathing 的文件路径</param>
/// <returns>文件文本内容,读取失败时返回空字符串</returns>
public string ReadTextSync(string subPath) => AutoPathingFile.ReadTextSync(subPath);
/// <summary>
/// LimitedFile 实例,用于操作 AutoPathing 目录
/// </summary>
private LimitedFile AutoPathingFile => _autoPathingFile;
}
@@ -0,0 +1,34 @@
using Microsoft.ClearScript;
using System;
using System.Reflection;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class CustomHostFunctions : HostFunctions
{
/// <summary>
/// 创建指定维度的交错数组变量
/// </summary>
/// <typeparam name="T">数组元素类型</typeparam>
/// <param name="dimensions">数组维度</param>
/// <returns>交错数组变量</returns>
public object NewVarOfArr<T>(int dimensions)
{
try
{
Type arrayType = typeof(T);
for (int i = 0; i < dimensions; i++)
{
arrayType = arrayType.MakeArrayType();
}
MethodInfo newVarMethod = typeof(HostFunctions).GetMethod(nameof(newVar))!;
MethodInfo genericMethod = newVarMethod.MakeGenericMethod(arrayType);
return genericMethod.Invoke(this, new object?[] { null })!;
}
catch (Exception ex)
{
throw new InvalidOperationException($"创建维度为 {dimensions} 的数组失败: {ex.Message}", ex);
}
}
}
@@ -1,9 +1,11 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoEat;
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.GameTask.AutoCook;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoWood;
@@ -16,9 +18,14 @@ using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.Common;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -186,13 +193,24 @@ public class Dispatcher
return null;
}
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
return null;
return await new AutoDomainTask(new AutoDomainParam(0, path)).Start(cancellationToken);
case "AutoBoss":
var autoBossConfig = TaskContext.Instance().Config.AutoBossConfig;
if (taskSettingsPageViewModel.GetFightStrategy(autoBossConfig.StrategyName, out var autoBossPath))
{
return null;
}
return await new AutoBossTask(new AutoBossParam(autoBossPath)).Start(cancellationToken);
case "AutoFishing":
await new AutoFishingTask(AutoFishingTaskParam.BuildFromSoloTaskConfig(soloTask.Config)).Start(
cancellationToken);
return null;
case "AutoCook":
await new AutoCookTask().Start(cancellationToken);
return null;
case "AutoEat":
{
string? foodName = soloTask.Config == null ? null : ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "foodName", (string?)null);
@@ -265,16 +283,15 @@ public class Dispatcher
GridScreenName gridScreenName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "gridScreenName", (GridScreenName?)null) ?? throw new Exception("gridScreenName为空或错误");
string? itemName = ScriptObjectConverter.GetValue((ScriptObject)soloTask.Config, "itemName", (string?)null);
IEnumerable<string>? itemNames = ScriptObjectConverter.GetValue<string>((ScriptObject)soloTask.Config, "itemNames");
if (itemName != null && itemNames != null)
CountInventoryItemParam param = new()
{
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时使用");
}
if (itemName == null && itemNames == null)
{
throw new ArgumentException($"参数{nameof(itemName)}和{nameof(itemNames)}不能同时为空");
}
var result = await new CountInventoryItem(gridScreenName, itemName, itemNames).Start(cancellationToken);
if (itemName != null)
GridScreenName = gridScreenName,
ItemName = itemName,
ItemNames = itemNames?.ToList() ?? []
};
var result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
{
return result;
}
@@ -312,7 +329,7 @@ public class Dispatcher
/// <param name="param">秘境任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
public async Task<Dictionary<string, int>> RunAutoDomainTask(AutoDomainParam param, CancellationToken? customCt = null)
{
if (param == null)
{
@@ -320,9 +337,26 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoDomainTask(param).Start(cancellationToken);
return await new AutoDomainTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动首领讨伐任务
/// </summary>
/// <param name="param">自动首领讨伐任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task<Dictionary<string, int>> RunAutoBossTask(AutoBossParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动首领讨伐任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
return await new AutoBossTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动战斗任务
/// </summary>
@@ -337,6 +371,101 @@ public class Dispatcher
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoFightTask(param).Start(cancellationToken);
var factory = GameTask.AutoFight.Factory.CombatTaskFactoryProvider.GetFactory(param.CombatStrategyPath);
var fightTask = factory.CreateTask(param);
await fightTask.Start(cancellationToken);
}
/// <summary>
/// 运行简易战斗策略脚本。
/// 使用策略语言直接控制角色执行动作(如 e、q、attack 等),适合快速操作。
/// </summary>
/// <param name="script">策略字符串,支持逗号/换行/分号分隔指令,可选角色名前缀</param>
/// <param name="avatarName">指定操作的角色名(可选,不指定则操作当前角色)</param>
/// <param name="customCt">自定义取消令牌</param>
public async Task RunCombatScript(string script, string? avatarName = null, CancellationToken? customCt = null)
{
if (string.IsNullOrWhiteSpace(script))
{
throw new ArgumentException("策略字符串不能为空", nameof(script));
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
// 1. 解析策略字符串(ParseContext 已处理全角符号、注释、分号/逗号分隔)
var combatScript = CombatScriptParser.ParseContext(script, validate: false, defaultAvatarName: avatarName);
if (combatScript.CombatCommands.Count == 0) return;
_logger.LogInformation("执行 {Text}", "简易策略脚本");
await CombatScriptExecutor.ExecuteAsync(combatScript, cancellationToken, _logger);
}
/// <summary>
/// 运行自动地脉花任务
/// </summary>
/// <param name="param">自动地脉花任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoLeyLineOutcropTask(AutoLeyLineOutcropParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动地脉花任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoLeyLineOutcropTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行自动幽境危战任务
/// </summary>
/// <param name="param">自动幽境危战任务参数</param>
/// <param name="customCt">自定义取消令牌</param>
/// <returns></returns>
public async Task RunAutoStygianOnslaughtTask(AutoStygianOnslaughtParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "自动幽境危战任务参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
await new AutoStygianOnslaughtTask(param).Start(cancellationToken);
}
/// <summary>
/// 运行背包物品计数任务。
/// </summary>
/// <param name="param">背包物品计数参数。</param>
/// <param name="customCt">自定义取消令牌。</param>
/// <returns>单物品返回数量;多物品返回名称到数量的脚本对象。</returns>
public async Task<object?> RunCountInventoryItemTask(CountInventoryItemParam param, CancellationToken? customCt = null)
{
if (param == null)
{
throw new ArgumentNullException(nameof(param), "背包物品计数参数不能为空");
}
CancellationToken cancellationToken = customCt ?? CancellationContext.Instance.Cts.Token;
object result = await new CountInventoryItem(param).Start(cancellationToken);
if (param.ItemName != null)
{
return result;
}
else
{
dynamic expando = new ExpandoObject();
var expandoDict = (IDictionary<string, object>)expando;
foreach (var kvp in (Dictionary<string, int>)result)
{
expandoDict[kvp.Key] = kvp.Value;
}
return expandoDict;
}
}
}
@@ -16,12 +16,14 @@ using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
{
private RECT captureAreaRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
private readonly ILogger<Genshin> _logger = App.GetLogger<Genshin>();
/// <summary>
/// 游戏宽度
@@ -43,6 +45,15 @@ public class Genshin
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 通过 OCR 识别当前角色的 UID
/// </summary>
/// <returns>UID 数字,如果识别失败则返回 0</returns>
public Task<int> Uid()
{
return Task.FromResult(Bv.Uid());
}
public Lazy<NavigationInstance> LazyNavigationInstance { get; } = new(() =>
{
var matchingMethod = TaskContext.Instance().Config.PathingConditionConfig.MapMatchingMethod;
@@ -66,7 +77,6 @@ public class Genshin
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, mapName, force);
}
public async Task Tp(double x, double y, bool force)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, MapTypes.Teyvat.ToString(), force);
@@ -113,6 +123,23 @@ public class Genshin
await tpTask.MoveMapTo(x, y, MapTypes.Teyvat.ToString());
}
/// <summary>
/// 点击大地图上的指定坐标。
/// </summary>
/// <remarks>
/// 该方法会先把目标移动到大地图的可点击安全区域,再执行一次点击。
/// </remarks>
/// <param name="x">目标X坐标。</param>
/// <param name="y">目标Y坐标。</param>
/// <param name="forceCountry">强制指定移动大地图时先切换的国家,默认为null。</param>
public async Task ClickMapPoint(double x, double y, string? forceCountry = null)
{
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
await tpTask.CheckInBigMapUi();
await tpTask.SwitchRecentlyCountryMap(x, y, forceCountry);
await tpTask.ClickMapPoint(x, y, MapTypes.Teyvat.ToString());
}
/// <summary>
/// 移动大地图到指定坐标
/// </summary>
@@ -207,6 +234,11 @@ public class Genshin
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
public Point2f? GetPositionFromMapWithMatchingMethod(string matchingMethod)
{
return GetPositionFromMapWithMatchingMethod(nameof(MapTypes.Teyvat), matchingMethod);
}
public float GetCameraOrientation()
{
@@ -221,14 +253,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));
@@ -269,12 +305,37 @@ public class Genshin
{
return await new SwitchPartyTask().Start(partyName, CancellationContext.Instance.Cts.Token);
}
catch (PartySetupFailedException ex)
catch (PartySetupFailedException)
{
return false;//释放失败状态到JS,否则失败后会退出任务。
return false;//释放失败状态给调用方,否则失败后会退出任务。
}
}
/// <summary>
/// 按槽位重组当前队伍角色。
/// </summary>
/// <param name="slot1">1 号位角色名。</param>
/// <param name="slot2">2 号位角色名。</param>
/// <param name="slot3">3 号位角色名。</param>
/// <param name="slot4">4 号位角色名。</param>
/// <returns>完成保存并返回主界面返回 true;参数无效、目标角色未找到或流程失败返回 false。</returns>
/// <remarks>
/// 未传入的槽位默认跳过;空字符串表示跳过对应槽位。
/// 调用示例:<c>await genshin.SwitchCharacter("胡桃", "夜兰", "", "钟离");</c>
/// 该方法表示重组队伍槽位角色,不是按数字键切换当前出战角色。
/// </remarks>
public async Task<bool> SwitchCharacter(string slot1 = "", string slot2 = "", string slot3 = "", string slot4 = "")
{
try
{
return await new SwitchCharacterStateMachineTask().Start(slot1, slot2, slot3, slot4, CancellationContext.Instance.Cts.Token);
}
catch (PartySetupFailedException)
{
return false;
}
}
/// <summary>
/// 清除当前调度器的队伍缓存
/// </summary>
@@ -343,6 +404,18 @@ public class Genshin
await new GoToCraftingBenchTask().Start(country, CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 在当前已打开的合成界面中合成指定材料。
/// </summary>
/// <param name="materialName">目标成品材料名。</param>
/// <param name="quantity">目标合成个数,必须大于 0。</param>
/// <param name="materialType">材料筛选类型;为空时从物品模型 CSV 中读取。</param>
/// <returns>合成执行结果。</returns>
public async Task<CraftMaterialResult> CraftMaterial(string materialName, int quantity, string? materialType = null)
{
return await new CraftMaterialTask(materialName, quantity, materialType).Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 返回主界面
/// </summary>
@@ -418,4 +491,17 @@ public class Genshin
throw new ArgumentException($"无效的分钟值: {minute},必须是 0-59 之间的整数字符", nameof(minute));
await new SetTimeTask().Start(h, m, CancellationContext.Instance.Cts.Token, skip);
}
}
// /// <summary>
// /// 莉奈娅挖矿,调试使用,暂时注释
// /// </summary>
// /// <param name="mineCount">射箭次数,默认1</param>
// /// <param name="scanRounds">大循环寻矿次数。不传则默认5;传单个数字时与射箭次数相同</param>
// public async Task StartMining(int? mineCount = null, int? scanRounds = null)
// {
// var actualMine = mineCount ?? 1;
// var actualScan = scanRounds ?? (mineCount ?? 5);
// if (actualScan < actualMine) actualScan = actualMine;
// await new LinneaMiningTask(actualScan, actualMine).Start(CancellationContext.Instance.Cts.Token);
// }
}
@@ -0,0 +1,410 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Dependence;
/// <summary>
/// HTML遮罩层 - JS脚本依赖类
/// 提供窗口管理与消息通信功能
/// </summary>
public class HtmlMask : IDisposable
{
private static readonly JsonSerializerOptions _jsonOptions = new()
{
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false
};
/// <summary>
/// 通信消息结构
/// </summary>
public class Message
{
public string Url { get; set; } = "";
public JsonElement? Data { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string? RequestId { get; set; }
}
/// <summary>
/// 脚本到HTML的待推送队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _toHtmlQueues = new();
/// <summary>
/// HTML到脚本的消息队列
/// </summary>
private static readonly ConcurrentDictionary<string, ConcurrentQueue<Message>> _fromHtmlQueues = new();
/// <summary>
/// JS到HTML请求的等待句柄,用于request-response匹配
/// </summary>
private static readonly ConcurrentDictionary<string, TaskCompletionSource<string>> _jsPendingRequests = new();
/// <summary>
/// requestId到windowId的映射,用于窗口关闭时取消对应的pending请求
/// </summary>
private static readonly ConcurrentDictionary<string, string> _requestWindowMap = new();
private readonly string _workDir;
private readonly List<string> _openedWindows = [];
private readonly object _openedWindowsLock = new();
private bool _disposed;
public HtmlMask(string workDir)
{
_workDir = workDir;
}
#region 窗口管理
/// <summary>
/// 显示HTML遮罩窗口
/// </summary>
public string Show(string url, string? id = null)
{
try
{
if (string.IsNullOrWhiteSpace(url))
throw new ArgumentException("URL不能为空");
string finalUrl;
if (url.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
finalUrl = url;
}
else
{
// 禁止 file:// 绝对路径,仅允许脚本目录下的相对路径
string absPath = ScriptUtils.NormalizePath(_workDir, url);
finalUrl = new Uri(absPath).AbsoluteUri;
}
string windowId = HtmlMaskWindow.Show(finalUrl, id, _workDir);
_toHtmlQueues[windowId] = new ConcurrentQueue<Message>();
_fromHtmlQueues[windowId] = new ConcurrentQueue<Message>();
lock (_openedWindowsLock) { _openedWindows.Add(windowId); }
return windowId;
}
catch (Exception ex)
{
TaskControl.Logger.LogError(ex, "打开HTML遮罩失败: {Url}", url);
throw;
}
}
/// <summary>
/// 关闭指定窗口
/// </summary>
public bool Close(string id)
{
lock (_openedWindowsLock) { _openedWindows.Remove(id); }
CleanupQueues(id);
return HtmlMaskWindow.Close(id);
}
/// <summary>
/// 关闭所有由本实例打开的窗口
/// </summary>
public void CloseAll()
{
List<string> windows;
lock (_openedWindowsLock)
{
windows = [.. _openedWindows];
_openedWindows.Clear();
}
foreach (var windowId in windows)
{
CleanupQueues(windowId);
HtmlMaskWindow.Close(windowId);
}
}
/// <summary>
/// 获取所有窗口ID
/// </summary>
public string[] GetWindowIds() => HtmlMaskWindow.GetWindowIds();
/// <summary>
/// 窗口是否存在
/// </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 消息通信
/// <summary>
/// 发送消息到HTML(单向推送)
/// </summary>
public void Send(string windowId, string url, string jsonData)
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData)
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 响应 HTML 页面通过 window.htmlMask.request(...) 发起的请求。
/// </summary>
/// <param name="windowId">HTML 遮罩窗口 ID。</param>
/// <param name="requestId">从 Receive/Poll/PollAll 返回消息的 requestId 字段取得,不能由脚本自行生成。</param>
/// <param name="jsonData">响应数据,必须是合法 JSON 字符串。</param>
public void Respond(string windowId, string requestId, string jsonData)
{
if (string.IsNullOrWhiteSpace(requestId))
throw new ArgumentException("requestId cannot be empty", nameof(requestId));
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = "/__response__",
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
}
/// <summary>
/// 发送请求到HTML并等待响应
/// </summary>
/// <param name="windowId">目标窗口ID</param>
/// <param name="url">接口路径</param>
/// <param name="jsonData">JSON数据</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Request(string windowId, string url, string jsonData, int timeoutMs = 0)
{
var requestId = Guid.NewGuid().ToString("N");
var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
_jsPendingRequests[requestId] = tcs;
_requestWindowMap[requestId] = windowId;
try
{
if (!HtmlMaskWindow.Exists(windowId) || !_toHtmlQueues.TryGetValue(windowId, out var queue))
throw new InvalidOperationException($"HTML遮罩窗口不存在或已关闭: {windowId}");
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(jsonData),
RequestId = requestId
});
HtmlMaskWindow.NotifyFlush(windowId);
if (timeoutMs > 0)
{
using var cts = new System.Threading.CancellationTokenSource(timeoutMs);
await using var registration = cts.Token.Register(() =>
{
if (_jsPendingRequests.TryRemove(requestId, out var pending))
pending.TrySetResult(null!);
});
return await tcs.Task;
}
return await tcs.Task;
}
catch (OperationCanceledException)
{
return null;
}
finally
{
_jsPendingRequests.TryRemove(requestId, out _);
_requestWindowMap.TryRemove(requestId, out _);
}
}
/// <summary>
/// 等待接收来自HTML的一条消息
/// </summary>
/// <param name="windowId">窗口ID</param>
/// <param name="timeoutMs">超时毫秒,0表示无限等待</param>
public async Task<string?> Receive(string windowId, int timeoutMs = 0)
{
if (!_fromHtmlQueues.TryGetValue(windowId, out var queue))
return null;
var sw = System.Diagnostics.Stopwatch.StartNew();
while (true)
{
if (queue.TryDequeue(out var message))
return JsonSerializer.Serialize(message, _jsonOptions);
if (_disposed || !_fromHtmlQueues.ContainsKey(windowId) || !HtmlMaskWindow.Exists(windowId))
return null;
if (timeoutMs > 0 && sw.ElapsedMilliseconds > timeoutMs)
return null;
await Task.Delay(50);
}
}
/// <summary>
/// 轮询来自HTML的消息(非阻塞)
/// </summary>
public string? Poll(string windowId)
{
if (_fromHtmlQueues.TryGetValue(windowId, out var queue) &&
queue.TryDequeue(out var message))
{
return JsonSerializer.Serialize(message, _jsonOptions);
}
return null;
}
/// <summary>
/// 批量获取来自HTML的所有消息
/// </summary>
public string PollAll(string windowId)
{
var messages = new List<Message>();
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var message))
{
messages.Add(message);
}
}
return JsonSerializer.Serialize(messages, _jsonOptions);
}
#endregion
#region 内部方法
/// <summary>
/// 将待推送队列中的消息通过回调逐一发出
/// </summary>
internal static void FlushPendingMessages(string windowId, Action<string> postAction)
{
if (_toHtmlQueues.TryGetValue(windowId, out var queue))
{
while (queue.TryDequeue(out var msg))
{
postAction(JsonSerializer.Serialize(msg, _jsonOptions));
}
}
}
/// <summary>
/// HTML端发来的消息入队,如果是JS请求的响应则直接resolve
/// </summary>
internal static void SendFromHtml(string windowId, string url, string data, string? requestId = null)
{
// 匹配JS端pending的request
if (requestId != null && _jsPendingRequests.TryRemove(requestId, out var tcs))
{
var parsed = ParseData(data);
tcs.TrySetResult(parsed != null ? parsed.Value.GetRawText() : "null");
return;
}
// 普通消息入队
if (_fromHtmlQueues.TryGetValue(windowId, out var queue))
{
queue.Enqueue(new Message
{
Url = url,
Data = ParseData(data),
RequestId = requestId
});
}
}
private static JsonElement? ParseData(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return null;
try
{
using var doc = JsonDocument.Parse(json);
return doc.RootElement.Clone();
}
catch
{
// 不是合法JSON,作为纯文本包装
return JsonSerializer.SerializeToElement(json, _jsonOptions);
}
}
private static void CleanupQueues(string windowId)
{
_toHtmlQueues.TryRemove(windowId, out _);
_fromHtmlQueues.TryRemove(windowId, out _);
// 取消该窗口关联的待响应请求
foreach (var kvp in _requestWindowMap)
{
if (kvp.Value == windowId && _jsPendingRequests.TryRemove(kvp.Key, out var tcs))
{
tcs.TrySetCanceled();
}
}
}
#endregion
public void Dispose()
{
if (_disposed) return;
_disposed = true;
CloseAll();
}
}
@@ -1,5 +1,7 @@
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using BetterGenshinImpact.Core.Monitor;
using BetterGenshinImpact.GameTask;
@@ -40,6 +42,9 @@ public class KeyMouseHook: IDisposable
private EventHandler<MouseEventExtArgs>? _mouseMoveExtHandler;
private EventHandler<MouseEventExtArgs>? _mouseWheelExtHandler;
private readonly object _mouseMoveLock = new();
private DateTime _lastProcessMouseMoveTime = DateTime.MinValue;
private readonly ILogger<KeyMouseHook> _logger = App.GetLogger<KeyMouseHook>();
/// <summary>
@@ -110,182 +115,259 @@ public class KeyMouseHook: IDisposable
}
}
private readonly System.Threading.Channels.Channel<Action> _eventChannel =
System.Threading.Channels.Channel.CreateBounded<Action>(
new System.Threading.Channels.BoundedChannelOptions(2048)
{
FullMode = System.Threading.Channels.BoundedChannelFullMode.Wait,
SingleReader = true,
SingleWriter = false
});
private readonly CancellationTokenSource _cts = new();
public KeyMouseHook()
{
// 启动后台事件处理器,确保不阻塞钩子线程
_ = Task.Run(async () =>
{
try
{
var reader = _eventChannel.Reader;
while (await reader.WaitToReadAsync(_cts.Token))
{
while (reader.TryRead(out var action))
{
try
{
action();
}
catch (Exception ex)
{
// 内部错误已在 action 闭包中通过 HandleCallbackException 处理
}
}
}
}
catch (OperationCanceledException) { }
catch (Exception ex)
{
_logger.LogError(ex, "键鼠钩子后台处理器发生异常");
}
});
// 初始化事件处理程序
_keyDownHandler = (_, args) =>
{
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if (_keyDownDataCallbacks.Count == 0 && _keyDownCodeCallbacks.Count == 0) return;
var keyDownDataCallbacksCopy = new List<ScriptObject>(_keyDownDataCallbacks);
var keyDownCodeCallbacksCopy = new List<ScriptObject>(_keyDownCodeCallbacks);
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
// 调用KeyData回调
foreach (var callback in keyDownDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyDownCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘按下回调");
}
};
_keyUpHandler = (_, args) =>
{
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if (_keyUpDataCallbacks.Count == 0 && _keyUpCodeCallbacks.Count == 0) return;
var keyUpDataCallbacksCopy = new List<ScriptObject>(_keyUpDataCallbacks);
var keyUpCodeCallbacksCopy = new List<ScriptObject>(_keyUpCodeCallbacks);
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
var keyDataStr = args.KeyData.ToString();
var keyCodeStr = args.KeyCode.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
callback.InvokeAsFunction(args.KeyData.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(args.KeyCode.ToString());
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
// 调用KeyData回调
foreach (var callback in keyUpDataCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyDataStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
// 调用KeyCode回调
foreach (var callback in keyUpCodeCallbacksCopy)
{
try
{
callback.InvokeAsFunction(keyCodeStr);
}
catch (Exception ex)
{
HandleCallbackException(ex, "键盘释放事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略键盘释放回调");
}
};
_mouseDownExtHandler = (_, args) =>
{
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if (_mouseDownCallbacks.Count == 0) return;
var mouseDownCallbacksCopy = new List<ScriptObject>(_mouseDownCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
foreach (var callback in mouseDownCallbacksCopy)
{
try
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
foreach (var callback in mouseDownCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标按下事件");
return;
}
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标按下回调");
}
};
_mouseUpExtHandler = (_, args) =>
{
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if (_mouseUpCallbacks.Count == 0) return;
var mouseUpCallbacksCopy = new List<ScriptObject>(_mouseUpCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
foreach (var callback in mouseUpCallbacksCopy)
var buttonStr = args.Button.ToString();
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseUpCallbacksCopy)
{
try
{
callback.InvokeAsFunction(buttonStr, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
}
}))
{
try
{
callback.InvokeAsFunction(args.Button.ToString(), localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标释放事件");
return;
}
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标释放回调");
}
};
_mouseMoveExtHandler = (_, args) =>
{
if (_mouseMoveCallbacks.Count == 0) return;
var now = DateTime.Now;
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if ((now - _lastProcessMouseMoveTime).TotalMilliseconds < 10) return;
_lastProcessMouseMoveTime = now;
var mouseMoveCallbacksCopy = new List<ScriptObject>(_mouseMoveCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
foreach (var callback in mouseMoveCallbacksCopy)
{
try
if (!_eventChannel.Writer.TryWrite(() =>
{
// 获取回调的间隔时间
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval))
foreach (var callback in mouseMoveCallbacksCopy)
{
// 获取上次调用时间
if (_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
try
{
// 计算时间差
var timeSpan = now - lastTime;
// 如果时间差大于等于间隔时间,则执行回调
if (timeSpan.TotalMilliseconds >= interval)
lock (_mouseMoveLock)
{
callback.InvokeAsFunction(localX, localY);
// 更新上次调用时间
_lastMouseMoveCallbackTimes[callback] = now;
if (_mouseMoveCallbackIntervals.TryGetValue(callback, out var interval) &&
_lastMouseMoveCallbackTimes.TryGetValue(callback, out var lastTime))
{
var timeSpan = now - lastTime;
if (timeSpan.TotalMilliseconds >= interval)
{
callback.InvokeAsFunction(localX, localY);
_lastMouseMoveCallbackTimes[callback] = now;
}
}
}
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标移动事件");
return;
}
}))
{
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标移动回调");
}
};
_mouseWheelExtHandler = (_, args) =>
{
// 创建回调列表的副本,避免迭代期间修改集合导致异常
if (_mouseWheelCallbacks.Count == 0) return;
var mouseWheelCallbacksCopy = new List<ScriptObject>(_mouseWheelCallbacks);
// 转换为局部坐标
var (localX, localY) = ConvertToLocalCoordinates(args.X, args.Y);
foreach (var callback in mouseWheelCallbacksCopy)
var delta = args.Delta;
if (!_eventChannel.Writer.TryWrite(() =>
{
foreach (var callback in mouseWheelCallbacksCopy)
{
try
{
callback.InvokeAsFunction(delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
}
}))
{
try
{
callback.InvokeAsFunction(args.Delta, localX, localY);
}
catch (Exception ex)
{
HandleCallbackException(ex, "鼠标滚轮事件");
return;
}
_logger.LogWarning("事件队列已满或已关闭,忽略鼠标滚轮回调");
}
};
@@ -376,6 +458,8 @@ public class KeyMouseHook: IDisposable
{
if (disposing)
{
_cts.Cancel();
_eventChannel.Writer.TryComplete();
// 移除所有事件监听器
if (_keyDownHandler != null)
{
@@ -1,5 +1,7 @@
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.Core.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using OpenCvSharp;
@@ -13,6 +15,7 @@ public class LimitedFile(string rootPath)
{
/// <summary>
/// 读取指定文件夹内所有文件和文件夹的路径(非递归方式)。
/// 目录不存在时返回空数组
/// </summary>
/// <param name="folderPath">文件夹路径(相对于根目录)</param>
/// <returns>文件夹内所有文件和文件夹的路径数组</returns>
@@ -21,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();
@@ -43,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>
@@ -72,6 +96,44 @@ public class LimitedFile(string rootPath)
}
}
/// <summary>
/// 判断指定路径是否为文件
/// </summary>
/// <param name="path">文件路径(相对于根目录)</param>
/// <returns>如果是文件则返回 true,否则返回 false</returns>
public bool IsFile(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsFile 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// 判断指定的文件或目录是否存在
/// </summary>
/// <param name="path">文件或目录路径(相对于根目录)</param>
/// <returns>如果存在返回 true,否则返回 false</returns>
public bool IsExists(string path)
{
try
{
string normalizedPath = NormalizePath(path);
return File.Exists(normalizedPath) || Directory.Exists(normalizedPath);
}
catch (Exception ex)
{
TaskControl.Logger.LogError("IsExists 异常: {Message}", ex.Message);
return false;
}
}
/// <summary>
/// Normalize and validate a path.
/// </summary>
@@ -447,4 +509,51 @@ public class LimitedFile(string rootPath)
return true;
}
/// <summary>
/// 重命名文件或文件夹(相对于根目录)
/// </summary>
/// <param name="oldPath">原路径</param>
/// <param name="newPath">新路径</param>
/// <returns>是否重命名成功</returns>
public bool RenamePathSync(string oldPath, string newPath)
{
try
{
// 标准化路径
oldPath = NormalizePath(oldPath);
newPath = NormalizePath(newPath);
// 检查原路径是否存在
if (!File.Exists(oldPath) && !Directory.Exists(oldPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 原路径不存在 {Path}", oldPath);
return false;
}
//验证扩展名合法性
if (File.Exists(oldPath) && !IsValid(newPath))
{
TaskControl.Logger.LogError("RenamePathSync 异常: 新文件路径不合法 {Path}", newPath);
return false;
}
// 确保目标目录存在
string? directoryPath = Path.GetDirectoryName(newPath);
if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
// 执行重命名
Directory.Move(oldPath, newPath);
return true;
}
catch (Exception ex)
{
TaskControl.Logger.LogError("RenamePathSync 异常: {Message}", ex.Message);
return false;
}
}
}
@@ -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,18 +1,24 @@
using System;
using System;
using System.Collections.Generic;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.BgiVision;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Core.Script.Utils;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.GameTask.AutoBoss;
using BetterGenshinImpact.GameTask.AutoFight;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoLeyLineOutcrop;
using BetterGenshinImpact.GameTask.AutoSkip;
using BetterGenshinImpact.GameTask.AutoStygianOnslaught;
using BetterGenshinImpact.GameTask.Model.GameUI;
namespace BetterGenshinImpact.Core.Script;
@@ -71,16 +77,33 @@ public class EngineExtend
engine.AddHostType("ServerTime", typeof(ServerTime));
engine.AddHostType("AutoDomainParam", typeof(AutoDomainParam));
engine.AddHostType("AutoBossParam", typeof(AutoBossParam));
engine.AddHostType("CountInventoryItemParam", typeof(CountInventoryItemParam));
engine.AddHostType("GridScreenName", typeof(GridScreenName));
engine.AddHostType("ItemIconRecognitionMode", typeof(ItemIconRecognitionMode));
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#的类型
engine.AddHostType(typeof(Task));
// 新的BvPage类
engine.AddHostType("BvPage", typeof(BvPage));
engine.AddHostType("BvLocator", typeof(BvLocator));
engine.AddHostType("BvImage", typeof(BvImage));
engine.AddHostObject("host", new CustomHostFunctions());
// HTML 遮罩
engine.AddHostObject("htmlMask", new HtmlMask(workDir));
// 导入 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>();
@@ -18,7 +18,6 @@ using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.FarmingPlan;
using BetterGenshinImpact.GameTask.LogParse;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
@@ -194,20 +193,6 @@ public partial class ScriptGroupProject : ObservableObject
public async Task Run()
{
//执行记录
ExecutionRecord executionRecord = new ExecutionRecord()
{
ServerStartTime =
GroupInfo?.Config.PathingConfig.TaskCompletionSkipRuleConfig.IsBoundaryTimeBasedOnServerTime ?? false
? ServerTimeHelper.GetServerTimeNow()
: DateTimeOffset.Now,
StartTime = DateTime.Now,
GroupName = GroupInfo?.Name ?? "",
FolderName = FolderName,
ProjectName = Name,
Type = Type
};
ExecutionRecordStorage.SaveExecutionRecord(executionRecord);
if (Type == "Javascript")
{
if (Project == null)
@@ -216,13 +201,16 @@ public partial class ScriptGroupProject : ObservableObject
}
JsScriptSettingsObject ??= new ExpandoObject();
// 清理配置中的无效值
CleanInvalidSettingsValues();
var pathingPartyConfig = GroupInfo?.Config.PathingConfig;
await Project.ExecuteAsync(JsScriptSettingsObject, pathingPartyConfig);
}
else if (Type == "KeyMouse")
{
// 加载并执行
var json = await File.ReadAllTextAsync(Global.Absolute(@$"User\KeyMouseScript\{Name}"));
var json = await File.ReadAllTextAsync(Path.Combine(KeyMouseRecordPageViewModel.ScriptPath, Name));
await KeyMouseMacroPlayer.PlayMacro(json, CancellationContext.Instance.Cts.Token, false);
}
else if (Type == "Pathing")
@@ -242,7 +230,6 @@ public partial class ScriptGroupProject : ObservableObject
await pathingTask.Pathing(task);
executionRecord.IsSuccessful = pathingTask.SuccessEnd;
OtherConfig.AutoRestart autoRestart = TaskContext.Instance().Config.OtherConfig.AutoRestartConfig;
if (!pathingTask.SuccessEnd)
{
@@ -308,18 +295,6 @@ public partial class ScriptGroupProject : ObservableObject
var task = new ShellTask(ShellTaskParam.BuildFromConfig(Name, shellConfig ?? new ShellConfig()));
await task.Start(CancellationContext.Instance.Cts.Token);
}
if (Type != "Pathing")
{
executionRecord.IsSuccessful = true;
}
executionRecord.ServerEndTime =
GroupInfo?.Config.PathingConfig.TaskCompletionSkipRuleConfig.IsBoundaryTimeBasedOnServerTime ?? false
? ServerTimeHelper.GetServerTimeNow()
: DateTimeOffset.Now;
executionRecord.EndTime = DateTime.Now;
ExecutionRecordStorage.SaveExecutionRecord(executionRecord);
}
partial void OnTypeChanged(string value)
@@ -336,6 +311,67 @@ public partial class ScriptGroupProject : ObservableObject
{
OnPropertyChanged(nameof(ScheduleDesc));
}
/// <summary>
/// 清理 JsScriptSettingsObject 中不在 settings.json 定义的 Options 列表中的无效值
/// </summary>
private void CleanInvalidSettingsValues()
{
if (Project == null || JsScriptSettingsObject == null)
{
return;
}
try
{
// 加载 settings.json 中定义的配置项
var settingItems = Project.Manifest.LoadSettingItems(Project.ProjectPath);
if (settingItems.Count == 0)
{
return;
}
var settingsDict = JsScriptSettingsObject as IDictionary<string, object?>;
if (settingsDict == null)
{
return;
}
// 遍历所有 multi-checkbox 类型的配置项
foreach (var item in settingItems.Where(i => i.Type == "multi-checkbox"))
{
if (!settingsDict.ContainsKey(item.Name))
{
continue;
}
// 获取当前保存的值
var savedValue = settingsDict[item.Name];
List<string>? checkedValues = null;
if (savedValue is List<string> stringList)
{
checkedValues = stringList;
}
else if (savedValue is List<object> objectList)
{
checkedValues = objectList.Select(i => (string)i).ToList();
settingsDict[item.Name] = checkedValues;
}
// 清理不在 Options 列表中的无效值
if (checkedValues != null && item.Options != null)
{
checkedValues.RemoveAll(value => !item.Options.Contains(value));
}
}
}
catch (Exception ex)
{
// 清理失败不影响脚本执行,只记录日志
TaskControl.Logger.LogDebug(ex, "清理JS脚本配置中的无效值时发生异常");
}
}
}
public class ScriptGroupProjectExtensions
@@ -0,0 +1,189 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.ClearScript;
using Microsoft.ClearScript.JavaScript;
namespace BetterGenshinImpact.Core.Script
{
public class PackageDocumentLoader : DefaultDocumentLoader
{
private readonly string _scriptRootPath;
public PackageDocumentLoader(string scriptRootPath)
{
_scriptRootPath = Path.GetFullPath(scriptRootPath);
}
public override async Task<Document> LoadDocumentAsync(DocumentSettings settings, DocumentInfo? sourceInfo, string specifier, DocumentCategory category, DocumentContextCallback contextCallback)
{
string? targetPath = ResolvePhysicalPath(settings, sourceInfo, specifier);
// ResolvePhysicalPath 可能因 sourceInfo 为空而失败,直接从脚本根目录兜底
if (targetPath == null || !File.Exists(targetPath))
{
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(uri) { Category = ModuleCategory.Standard };
return CacheDocument(new StringDocument(documentInfo, processedCode), false);
}
throw new FileNotFoundException($"不支持的模块导入类型: '{specifier}' (仅支持 .js 文件)", specifier);
}
/// <summary>
/// js重写
/// </summary>
public string RewriteScriptCode(string code, string currentFilePath)
{
if (string.IsNullOrEmpty(code)) return code;
string result = code.Replace("../../../packages", "packages");
// 拦截资源导入
var resourceRegex = new Regex(@"import\s+([\w\d_*$]+|[\s\S]*?)\s+from\s+(['""])([^'""\n]+)(['""])");
result = resourceRegex.Replace(result, match =>
{
string importPart = match.Groups[1].Value.Trim();
string quote = match.Groups[2].Value;
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("\\", "/");
bool isJs = resourceFullPath.EndsWith(".js", StringComparison.OrdinalIgnoreCase);
bool isImage = IsImageFile(resourceFullPath);
// 图片 -> Mat
if (isImage)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadImageMatSync({quote}{normalizedPath}{quote});";
}
// 非 JS 资源 -> 文本内容
if (!isJs)
{
if (importPart.StartsWith("{")) return match.Value;
return $"const {importPart} = file.ReadTextSync({quote}{normalizedPath}{quote});";
}
}
return match.Value;
});
return result;
}
private string? ResolvePhysicalPath(DocumentSettings settings, DocumentInfo? sourceInfo, string 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)
{
if (specifier.StartsWith("packages/", StringComparison.OrdinalIgnoreCase))
{
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))
{
string? dir = Path.GetDirectoryName(referrer);
if (dir != null)
{
return ProbeFile(Path.GetFullPath(Path.Combine(dir, specifier)));
}
}
}
if (!string.IsNullOrEmpty(searchPath))
{
var paths = searchPath.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var p in paths)
{
string combined = Path.Combine(p, specifier);
string? found = ProbeFile(combined);
if (found != null) return found;
}
}
return ProbeFile(Path.Combine(_scriptRootPath, specifier));
}
private string? ProbeFile(string path)
{
try
{
var normalized = Path.GetFullPath(path);
if (File.Exists(normalized)) return normalized;
if (File.Exists(normalized + ".js")) return normalized + ".js";
}
catch { }
return null;
}
private static bool IsImageFile(string path)
{
if (string.IsNullOrEmpty(path)) return false;
string ext = Path.GetExtension(path).ToLower();
string[] imageExtensions = { ".png", ".jpg", ".jpeg", ".bmp", ".tiff", ".webp" };
return imageExtensions.Contains(ext);
}
}
}
@@ -2,13 +2,18 @@ using BetterGenshinImpact.Core.Config;
using Microsoft.ClearScript;
using Microsoft.ClearScript.V8;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.View;
using Microsoft.ClearScript.JavaScript;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Core.Script.Project;
@@ -29,6 +34,7 @@ public class ScriptProject
{
throw new DirectoryNotFoundException("脚本文件夹不存在:" + ProjectPath);
}
ManifestFile = Path.GetFullPath(Path.Combine(ProjectPath, "manifest.json"));
if (!File.Exists(ManifestFile))
{
@@ -46,6 +52,7 @@ public class ScriptProject
{
return null;
}
var stackPanel = new StackPanel
{
Margin = new Thickness(0, 0, 20, 0) // 给右侧滚动条留出位置
@@ -69,33 +76,60 @@ public class ScriptProject
return scrollViewer;
}
public IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig = null)
private IScriptEngine BuildScriptEngine(PathingPartyConfig? partyConfig)
{
IScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
EngineExtend.InitHost(engine, ProjectPath, Manifest.Library,partyConfig);
V8ScriptEngine engine = new V8ScriptEngine(V8ScriptEngineFlags.UseCaseInsensitiveMemberBinding | V8ScriptEngineFlags.EnableTaskPromiseConversion);
// packages 依赖和资源重载
var loader = new PackageDocumentLoader(ProjectPath);
engine.DocumentSettings.Loader = loader;
// 添加 packages 到搜索路径
var libraries = new HashSet<string>(Manifest.Library ?? Array.Empty<string>())
{
".",
"./packages"
};
var libraryList = libraries.ToList();
EngineExtend.InitHost(engine, ProjectPath, libraryList.ToArray(), partyConfig);
return engine;
}
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig=null)
public async Task ExecuteAsync(dynamic? context = null, PathingPartyConfig? partyConfig = null)
{
// 默认值
GlobalMethod.SetGameMetrics(1920, 1080);
// 加载代码
var code = await LoadCode();
var engine = BuildScriptEngine(partyConfig);
// 使用自定义加载器解析脚本文件
var loader = (PackageDocumentLoader)engine.DocumentSettings.Loader;
if (context != null)
{
// 写入配置的内容
engine.AddHostObject("settings", context);
}
try
{
if (Manifest.Library.Length != 0)
bool useModule = Manifest.Library.Length != 0 ||
code.Contains("import ", StringComparison.Ordinal) ||
code.Contains("export ", StringComparison.Ordinal);
if (useModule)
{
// 清除Document缓存
DocumentLoader.Default.DiscardCachedDocuments();
var evaluation = engine.Evaluate(new DocumentInfo { Category = ModuleCategory.Standard }, code);
string mainScriptPath = Path.Combine(ProjectPath, Manifest.Main);
string runtimeCode = loader.RewriteScriptCode(code, mainScriptPath);
var documentInfo = new DocumentInfo(new Uri(mainScriptPath)) { Category = ModuleCategory.Standard };
var evaluation = engine.Evaluate(documentInfo, runtimeCode);
if (evaluation is Task task) await task;
}
else
@@ -111,6 +145,16 @@ public class ScriptProject
}
finally
{
// 终止代码执行
try
{
engine.Interrupt();
}
catch (Exception e)
{
TaskControl.Logger.LogError(e, "中断脚本执行异常:" + e.Message);
}
engine.Dispose();
}
}
@@ -125,4 +169,4 @@ public class ScriptProject
return code;
}
}
}
File diff suppressed because it is too large. Load diff
@@ -84,7 +84,7 @@ public class FileAccessBridge
// if (!string.IsNullOrEmpty(directory))
// Directory.CreateDirectory(directory);
File.WriteAllText(fullPath, content, Encoding.UTF8);
File.WriteAllText(fullPath, content, new UTF8Encoding(false));
}
catch (Exception ex)
{
@@ -1,13 +1,11 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Policy;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
using Wpf.Ui.Violeta.Controls;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.Service;
using Serilog.Core;
namespace BetterGenshinImpact.Core.Script.WebView;
@@ -23,4 +21,17 @@ public class MapEditorWebBridge
{
TaskContext.Instance().Config.DevConfig.RecordMapName = mapName;
}
}
public async Task RunPathing(string json)
{
await ScriptService.StartGameTask();
SystemControl.ActivateWindow();
await new TaskRunner().RunThreadAsync(async () =>
{
var task = PathingTask.BuildFromJson(json);
var pathExecutor = new PathExecutor(CancellationContext.Instance.Cts.Token);
pathExecutor.PartyConfig = new PathingPartyConfig { AutoFightEnabled = false };
await pathExecutor.Pathing(task);
});
}
}
@@ -78,6 +78,28 @@ public sealed class RepoWebBridge
return await File.ReadAllTextAsync(userConfigPath);
}
/// <summary>
/// 获取当前仓库的已订阅脚本路径列表(JSON 数组)。
/// 相比 GetUserConfigJson() 更轻量,仅返回当前仓库的订阅路径。
/// </summary>
public string GetSubscribedScriptPaths()
{
try
{
var paths = ScriptRepoUpdater.GetSubscribedPathsForCurrentRepo();
if (paths.Count > 0)
{
return Newtonsoft.Json.JsonConvert.SerializeObject(paths);
}
return "[]";
}
catch
{
return "[]";
}
}
public Task<string> GetFile(string relPath)
{
try
@@ -183,7 +205,7 @@ public sealed class RepoWebBridge
throw new FileNotFoundException("找不到原始 repo.json 文件");
}
string targetPath = Path.Combine(ScriptRepoUpdater.ReposPath, "repo_updated.json");
string targetPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
File.Copy(repoJsonPath, targetPath, overwrite: true);
@@ -228,10 +250,7 @@ public sealed class RepoWebBridge
private static string GetRepoJsonPath()
{
string updatedRepoJsonPath = Path.Combine(
Path.GetDirectoryName(Path.Combine(ScriptRepoUpdater.ReposPath, "bettergi-scripts-list-git"))!,
"repo_updated.json"
);
string updatedRepoJsonPath = ScriptRepoUpdater.RepoUpdatedJsonPath;
if (File.Exists(updatedRepoJsonPath))
{
@@ -245,7 +264,7 @@ public sealed class RepoWebBridge
return repoJson ?? throw new FileNotFoundException("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
}
private static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
internal static void ProcessPathRecursively(JArray array, string[] pathParts, int currentIndex)
{
foreach (JObject item in array.OfType<JObject>())
{
@@ -263,7 +282,7 @@ public sealed class RepoWebBridge
}
}
private static void ResetHasUpdateFlag(JObject node)
internal static void ResetHasUpdateFlag(JObject node)
{
if (node["hasUpdate"] is { Type: JTokenType.Boolean } hasUpdate &&
(bool)hasUpdate)
@@ -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)
@@ -0,0 +1,167 @@
# BetterGI 多实例命名管道协议
## 设计目标
协议不再使用 InstanceId,也不要求根实例保存“由谁启动了谁”的进程树。实例关系只由
当前 Windows 用户、Windows Session、进程用途和进程 ID 决定。
当前协议版本为 `v2`,规则如下:
- 每个 Windows 用户最多有一个根 BetterGI;
- 根 BetterGI 是该用户固定根管道的持有者,通常运行在主桌面 Session;
- 与根不在同一个 Session 的 BetterGI 是桌面分身 BetterGI;
- WebView 无论在哪个 Session 启动,都是根 BetterGI 的直接客户端;
- 桌面分身 BetterGI 只能查询和访问相同 Session 中的 WebView;
- 同一个 Session 只允许一个 BetterGI,WebView 则允许多个并通过进程 ID 精确寻址。
独立任务的选择面板、任务下发和状态回传不在当前实现范围内。
## 管道和 Windows 用户隔离
每个 Windows 用户只有一个固定根管道:
```text
BetterGI.v2.user-<Windows用户SID>.root
```
命名管道名称在整台计算机上可见,而不是按 Windows Session 隔离。因此根 BetterGI、
桌面分身 BetterGI 和 WebView 即使运行在不同 Session,也能连接同一个固定端点。
管道 ACL 只允许当前 Windows 用户 SID 完全控制,并显式拒绝 `Network` SID,所以
不同 Windows 用户分别拥有自己的根 BetterGI,彼此不会注册到对方的实例组中。
协议内容不敏感,不使用密钥、令牌、InstanceId 或父实例 ID。根端从已连接的命名管道
句柄调用 Windows API 获取客户端真实进程 ID,再由进程 ID取得真实 Windows Session;
客户端提交的用途只用于区分 BetterGI 与 WebView,不能伪造进程或 Session 身份。
## 启动参数
客户端用途仅使用:
```text
--instance <childSession|webview>
```
- `--instance childSession` 表示该进程只能作为桌面分身客户端,根暂时不存在时也不会
自行成为根;
- `--instance webview` 表示该进程只能作为 WebView 客户端;
- 不带 `--instance` 的 BetterGI 会先竞争固定根管道。竞争成功即成为根;竞争失败则
连接已有根,由根根据真实 Session 决定是转发重复启动还是注册为桌面分身。
应用自身重启时额外传递:
```text
--restart-from-pid <旧进程ID>
```
新进程会等待旧进程退出,再竞争根管道或替换同 Session 中的旧客户端连接。该参数只用于
消除重启交接期间的竞态,不作为长期身份。
## 连接拓扑和访问规则
```text
某个 Windows 用户的根 BetterGI
├─ Session 2 的桌面分身 BetterGI(最多一个)
├─ Session 3 的桌面分身 BetterGI(最多一个)
├─ Session 1 的 WebView(可多个,以进程 ID 区分)
├─ Session 2 的 WebView(可多个,以进程 ID 区分)
└─ Session 3 的 WebView(可多个,以进程 ID 区分)
```
所有客户端都直接连接根管道,不在桌面分身下面建立二级管道。这样根重启后只需恢复一个
固定端点,客户端也只需重连一个固定名称。
WebView 访问规则:
- 根 BetterGI 可以查询和访问全部 WebView;
- 桌面分身 BetterGI 只能查询与自己 Windows Session 相同的 WebView;
- 单播通过 WebView 进程 ID 精确定位;
- 组播由调用方先查询可见 WebView,再逐个发送,不在协议中维护易失的实例组。
## 连接建立和重复启动
客户端连接固定根管道后,首先发送 `connection.open`。根根据管道连接的真实进程 ID 和
Session 处理:
1. `webview`:按进程 ID 注册,可在断线后替换旧连接。
2. BetterGI 与根位于相同 Session:视为重复启动,把业务启动参数转发给根窗口,然后
新进程退出。
3. BetterGI 与根位于不同 Session:注册为桌面分身。
4. 同一 Session 已有桌面分身:把业务启动参数转发给已有进程,然后新进程退出。
5. 旧连接已经失效,或 `--restart-from-pid` 指向该 Session 中被替换的进程:接受新连接。
## 断线、闪退和退出语义
桌面分身 BetterGI 与 WebView 在根管道断开后,每秒尝试重新连接固定根管道,且没有总
超时时间。因此根 BetterGI 闪退、被结束进程或隔很久后才重新启动,都不改变客户端的
发现地址;新根取得固定管道后,仍存活的客户端会自动重新注册。
正常关闭根 BetterGI 时,现有 `ChildSessionService.Dispose` 流程继续主动断开 RDP 并
注销桌面分身 Session。只有未执行正常释放流程的闪退场景,桌面分身才会留存并等待根
恢复。
连接断开即移除对应运行时记录,不把客户端清单持久化。根重启后的关系由仍存活的客户端
重新连接重建,避免把已经退出的 PID 当作在线实例。
## 帧格式
同一条连接同时承载 JSON 控制消息和二进制相对鼠标批次。整数使用小端序。
```text
uint32 payloadLength
byte payloadType
byte[] payload
```
`payloadLength` 最大为 1 MiB。
| payloadType | 内容 |
| --- | --- |
| `1` | UTF-8 JSON 控制消息 |
| `2` | 相对鼠标二进制批次 |
JSON 信封的主要字段:
```json
{
"version": 2,
"requestId": "00000000-0000-0000-0000-000000000000",
"operation": "ping",
"success": true,
"errorCode": null,
"errorMessage": null,
"data": {}
}
```
响应使用相同 `requestId`,并将 `operation` 设为 `response`。信封中不再传输
`sourceInstanceId`。
当前控制操作:
| 操作 | 用途 |
| --- | --- |
| `ping` | 检查连接并读取端点描述 |
| `connection.open` | 客户端声明用途,根按真实 PID/Session 注册或转发激活 |
| `activation.dispatch` | 根向已有 BetterGI 转发二次启动参数 |
| `input.relativeMouse.subscribe` | 桌面分身请求根开始转发相对鼠标 |
| `input.relativeMouse.unsubscribe` | 桌面分身停止转发相对鼠标 |
| `input.relativeMouse.state` | 预留的相对鼠标状态通知名称 |
| `webview.list` | 查询当前调用方可见的 WebView |
| `webview.send` | 根按目标进程 ID 向 WebView 单播 |
| `webview.message` | 根向目标 WebView 下发消息 |
相对鼠标批次结构:
```text
uint16 sampleCount // 1..64
uint64 firstSequence
int64 baseUtcTicks
repeat sampleCount:
int32 deltaX
int32 deltaY
int32 timestampOffsetUs
```
发送端最多等待 5 ms 或累计 64 个样本后发送。队列拥塞时将后续位移合并,避免阻塞
Raw Input 采集线程。根 BetterGI 仅在游戏鼠标模式已启用、桌面分身窗口可见、RDP 已连接且
`Input Capture Window` 具有键盘焦点时转发。
@@ -0,0 +1,469 @@
# Recognition.json 编写说明
本文档说明各任务目录下 `Assets\Recognition.json` 的写法,用于将普通静态 `RecognitionObject` 配置化,并通过 `RecognitionAssets.Get(...)` 动态加载。
## 1. 文件位置
每个任务自己的识别配置文件放在:
```text
BetterGenshinImpact\GameTask\<任务名>\Assets\Recognition.json
```
例如:
```text
BetterGenshinImpact\GameTask\AutoSkip\Assets\Recognition.json
BetterGenshinImpact\GameTask\Common\Element\Assets\Recognition.json
```
调用方式通常是:
```csharp
RecognitionAssets.Get("AutoSkip", "Collect", region);
RecognitionAssets.Get("AutoFight", "Confirm", width, height);
ElementRecognition.Get("PaimonMenu", region);
```
其中第二个参数就是 `objects` 下的对象名。
## 2. 基本结构
```json
{
"version": 1,
"vars": {},
"regions": {},
"templates": {},
"objects": {}
}
```
各字段含义:
- `version`:配置版本号,目前固定写 `1`
- `vars`:公共变量,供表达式复用
- `regions`:公共区域表达式,供 `roi` / `reference.bbox` 通过 `@别名` 引用
- `templates`:公共模板别名,供 `template` 通过 `@别名` 引用
- `objects`:识别对象定义集合
## 3. 一个最小示例
```json
{
"version": 1,
"regions": {
"topLeftQuarter": "rect(0, 0, cw / 4, ch / 4)"
},
"objects": {
"PaimonMenu": {
"type": "TemplateMatch",
"template": "paimon_menu.png",
"roi": "@topLeftQuarter",
"draw": false
}
}
}
```
说明:
- `PaimonMenu` 是对象名,也是调用时的 `objectName`
- `type` 必须与 `RecognitionTypes` 枚举文本完全一致
- `template` 是模板文件名
- `roi` 可以直接写表达式,也可以引用 `regions` 中的别名
- 模板匹配场景下如果不写 `name`,运行时名称默认使用模板名,因此通常可以省略
## 4. 表达式系统
`roi`、`reference.bbox`、`vars` 中的值都支持表达式,底层由 NCalc 解析。
### 4.1 内置变量
- `cw`:当前截图宽度
- `ch`:当前截图高度
- `cx`:当前截图区域左上角 X
- `cy`:当前截图区域左上角 Y
- `s`:资源缩放系数
- 当截图宽度小于 1920 时,`s = cw / 1920`
- 其他情况 `s = 1`
### 4.2 支持的函数
- `rect(x, y, w, h)`:创建矩形
- `cutLeft(percent)`:截取左侧比例区域
- `cutRight(percent)`:截取右侧比例区域
- `cutTop(percent)`:截取上侧比例区域
- `cutBottom(percent)`:截取下侧比例区域
- `cutLeftTop(widthPercent, heightPercent)`:截取左上区域
- `cutRightTop(widthPercent, heightPercent)`:截取右上区域
- `cutLeftBottom(widthPercent, heightPercent)`:截取左下区域
- `cutRightBottom(widthPercent, heightPercent)`:截取右下区域
### 4.3 示例
```json
{
"vars": {
"topBarHeight": "100 * s"
},
"regions": {
"inventoryTopRight": "rect(cw * 3 / 4, 0, cw / 4, topBarHeight)",
"pageCloseWhite": "rect(cw - cw / 8, 0, cw / 8, ch / 8)",
"leftBottom": "cutLeftBottom(0.2, 0.2)"
}
}
```
## 5. 模板别名和区域别名
### 5.1 区域别名
在 `regions` 中先定义:
```json
"regions": {
"option": "rect(cw / 2, ch / 12, cw - cw / 2 - cw / 6, ch - ch / 12 - 10)"
}
```
再在对象里引用:
```json
"roi": "@option"
```
### 5.2 模板别名
在 `templates` 中先定义:
```json
"templates": {
"pageClose": "page_close.png"
}
```
再在对象里引用:
```json
"template": "@pageClose"
```
适合多个对象共用同一模板,或者模板文件名比较长的时候。
## 6. objects 常用字段
下面只列常用和当前加载器支持的字段。
### 6.1 通用字段
- `name`
- 可选
- 运行时名称
- 模板匹配通常可以省略
- `type`
- 必填
- 必须与 `RecognitionTypes` 一致
- 常见值:
- `TemplateMatch`
- `ColorMatch`
- `OcrMatch`
- `Ocr`
- `ColorRangeAndOcr`
- `roi`
- 可选
- 返回 `Rect` 的表达式,或 `@区域别名`
- `draw`
- 可选
- 是否绘制调试框
- `drawColor`
- 可选
- 调试框颜色,HTML 颜色格式,例如 `#FF0000`
- `drawWidth`
- 可选
- 调试框线宽
## 7. TemplateMatch 字段
适用于 `type = "TemplateMatch"`。
- `template`
- 必填
- 模板文件名、相对路径或 `@模板别名`
- `templateMode`
- 可选
- 对应 OpenCV `ImreadModes`
- 默认 `Color`
- `threshold`
- 可选
- 匹配阈值
- 默认通常为 `0.8`
- `use3Channels`
- 可选
- 是否使用三通道匹配
- `templateMatchMode`
- 可选
- 对应 OpenCV `TemplateMatchModes`
- 常见值:
- `CCoeffNormed`
- `CCorrNormed`
- `SqDiff`
- `useMask`
- 可选
- 是否启用遮罩
- `maskColor`
- 可选
- 遮罩颜色,HTML 颜色格式
- `maxMatchCount`
- 可选
- 最大匹配数量
- 不限制时可不填
- `useBinaryMatch`
- 可选
- 是否先二值化再匹配
- `binaryThreshold`
- 可选
- 二值化阈值
示例:
```json
"SubmitGoods": {
"type": "TemplateMatch",
"template": "submit_goods.png",
"roi": "rect(0, 0, cw / 2, ch / 3)",
"threshold": 0.9,
"use3Channels": true,
"templateMatchMode": "CCorrNormed",
"draw": true
}
```
## 8. ColorMatch / ColorRangeAndOcr 字段
适用于颜色范围识别相关场景。
- `colorCode`
- 可选
- 对应 OpenCV `ColorConversionCodes`
- 常见值:
- `BGR2RGB`
- `BGR2HSV`
- `BGR2GRAY`
- `lowerColor`
- 可选
- 颜色下界
- 支持 1 到 4 个数字
- `upperColor`
- 可选
- 颜色上界
- 支持 1 到 4 个数字
- `matchCount`
- 可选
- 至少命中的像素点数量
示例:
```json
"SomeColorMark": {
"type": "ColorMatch",
"roi": "rect(0, 0, cw / 4, ch / 4)",
"colorCode": "BGR2HSV",
"lowerColor": [90, 80, 80],
"upperColor": [130, 255, 255],
"matchCount": 10
}
```
## 9. OCR / OcrMatch 字段
适用于 `type = "Ocr"` 或 `type = "OcrMatch"`。
- `ocrEngine`
- 可选
- 对应 `OcrEngineTypes`
- 当前通常写 `Paddle`
- `text`
- 可选
- 用于 OCR 结果筛选的目标文本
- `replace`
- 可选
- OCR 误识别替换表
- `allContains`
- 可选
- 所有文本都包含才算成功
- `oneContains`
- 可选
- 任一文本包含即成功
- `regex`
- 可选
- 正则表达式列表
- 当前实现要求列表中的所有正则都命中
示例:
```json
"PlayingText": {
"type": "OcrMatch",
"roi": "rect(100 * s, 35 * s, 85 * s, 35 * s)",
"oneContains": [
"播放",
"暂停",
"继续"
],
"draw": true
}
```
`replace` 示例:
```json
"replace": {
"播放": ["播故", "搰放"],
"继续": ["绫续"]
}
```
## 10. reference 字段
`reference` 用于记录模板截图来源信息,便于后续按参考尺寸或原始包围盒做定位扩展。
字段:
- `size`
- 格式 `[width, height]`
- 表示模板来源截图尺寸
- `bbox`
- 返回 `Rect` 的表达式
- 表示模板在来源截图中的包围盒
示例:
```json
"reference": {
"size": [1920, 1080],
"bbox": "rect(1680, 32, 180, 72)"
}
```
## 11. search 字段
`search` 用于描述锚点和额外扩展区域。
字段:
- `anchor`
- 对应 `SearchAnchorMode` 枚举名
- `expand`
- 格式 `[width, height]`
- 表示搜索时向外扩展的尺寸
示例:
```json
"search": {
"anchor": "Center",
"expand": [120, 80]
}
```
## 12. 推荐写法
- 普通模板匹配对象优先只写 `type`、`template`、`roi`、`threshold`
- 重复使用的区域优先抽到 `regions`
- 重复使用的模板优先抽到 `templates`
- 可通过表达式描述的 ROI 尽量写进 JSON,不再写死在 C# 里
- 普通静态对象不要再回退到 `XXXAssets` 字段里缓存,直接调用 `RecognitionAssets.Get(...)`
- 模板匹配对象通常不需要手写 `name`
## 13. 不建议放进 JSON 的场景
下面这些仍然更适合保留在 C# 里:
- 需要运行时变量替换,而且变量来源复杂
- 需要动态拼接多份 Mat / 模板列表
- 需要依赖特殊 OpenCV 预处理逻辑
- 需要依赖外部配置、业务状态或复杂流程控制
- ROI 不是单纯表达式,而是与多个运行时对象联动
这类对象可以继续保留在对应任务类或专用 helper 中。
## 14. 排错建议
如果加载失败,当前日志会输出类似:
```text
Recognition 加载失败: Collect @ 1920x1080, file=...
Recognition 构建失败: Collect @ 1920x1080
```
建议优先检查:
1. `type` 是否和枚举名完全一致
2. `templateMatchMode`、`templateMode`、`colorCode`、`ocrEngine`、`anchor` 是否和对应枚举名完全一致
3. `template` 引用的模板文件或模板别名是否存在
4. `roi` / `bbox` 表达式是否能返回 `Rect`
5. `@区域别名`、`@模板别名`、`vars` 引用的名字是否存在
6. `lowerColor` / `upperColor` 数组长度是否在 1 到 4 之间
## 15. 一个较完整示例
```json
{
"version": 1,
"vars": {
"topBarHeight": "100 * s"
},
"regions": {
"topLeftQuarter": "rect(0, 0, cw / 4, ch / 4)",
"inventoryTopRight": "rect(cw * 3 / 4, 0, cw / 4, topBarHeight)"
},
"templates": {
"menu": "paimon_menu.png"
},
"objects": {
"PaimonMenu": {
"type": "TemplateMatch",
"template": "@menu",
"roi": "@topLeftQuarter",
"threshold": 0.8,
"draw": false
},
"Inventory": {
"type": "TemplateMatch",
"template": "inventory.png",
"roi": "@inventoryTopRight",
"draw": false
},
"ConfirmText": {
"type": "OcrMatch",
"roi": "rect(cw / 2, ch / 2, 200 * s, 80 * s)",
"oneContains": ["确认", "确定"]
}
}
}
```
@@ -96,40 +96,40 @@ public class AutoArtifactSalvageTask : ISoloTask
switch (gridScreenName)
{
case GridScreenName.Weapons:
recognitionObjectChecked = ElementAssets.Instance.BagWeaponChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagWeaponUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagWeaponChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagWeaponUnchecked");
break;
case GridScreenName.Artifacts:
recognitionObjectChecked = ElementAssets.Instance.BagArtifactChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagArtifactUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagArtifactChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagArtifactUnchecked");
break;
case GridScreenName.CharacterDevelopmentItems:
recognitionObjectChecked = ElementAssets.Instance.BagCharacterDevelopmentItemChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagCharacterDevelopmentItemUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagCharacterDevelopmentItemChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagCharacterDevelopmentItemUnchecked");
break;
case GridScreenName.Food:
recognitionObjectChecked = ElementAssets.Instance.BagFoodChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagFoodUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagFoodChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagFoodUnchecked");
break;
case GridScreenName.Materials:
recognitionObjectChecked = ElementAssets.Instance.BagMaterialChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagMaterialUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagMaterialChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagMaterialUnchecked");
break;
case GridScreenName.Gadget:
recognitionObjectChecked = ElementAssets.Instance.BagGadgetChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagGadgetUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagGadgetChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagGadgetUnchecked");
break;
case GridScreenName.Quest:
recognitionObjectChecked = ElementAssets.Instance.BagQuestChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagQuestUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagQuestChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagQuestUnchecked");
break;
case GridScreenName.PreciousItems:
recognitionObjectChecked = ElementAssets.Instance.BagPreciousItemChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagPreciousItemUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagPreciousItemChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagPreciousItemUnchecked");
break;
case GridScreenName.Furnishings:
recognitionObjectChecked = ElementAssets.Instance.BagFurnishingChecked;
recognitionObjectUnchecked = ElementAssets.Instance.BagFurnishingUnchecked;
recognitionObjectChecked = ElementRecognition.Get("BagFurnishingChecked");
recognitionObjectUnchecked = ElementRecognition.Get("BagFurnishingUnchecked");
break;
default:
throw new NotSupportedException($"背包不支持的界面:{gridScreenName.GetDescription()}");
@@ -147,7 +147,7 @@ public class AutoArtifactSalvageTask : ISoloTask
if (Bv.IsInPromptDialog(ra))
{
// 如果存在物品过期提示,则点击确认按钮
Bv.ClickWhiteConfirmButton(ra.DeriveCrop(0, 0, ra.Width, ra.Height - ra.Height * 0.2));
Bv.ClickWhiteConfirmButton(ra, new Rect(0, 0, ra.Width, (int)Math.Round(ra.Height - ra.Height * 0.2)));
Sleep(300, ct);
return false;
}
@@ -199,7 +199,7 @@ public class AutoArtifactSalvageTask : ISoloTask
// 点击分解按钮打开分解界面
using var ra2 = CaptureToRectArea();
using var salvageBtn = ra2.Find(ElementAssets.Instance.BtnArtifactSalvage);
using var salvageBtn = ra2.Find(ElementRecognition.Get("BtnArtifactSalvage", ra2));
if (salvageBtn.IsExist())
{
salvageBtn.Click();
@@ -258,7 +258,7 @@ public class AutoArtifactSalvageTask : ISoloTask
}
}
using var quickSelectConfirmBtn = ra4.Find(ElementAssets.Instance.BtnWhiteConfirm);
using var quickSelectConfirmBtn = ra4.Find(ElementRecognition.Get("BtnWhiteConfirm", ra4));
if (quickSelectConfirmBtn.IsExist())
{
quickSelectConfirmBtn.Click();
@@ -268,7 +268,7 @@ public class AutoArtifactSalvageTask : ISoloTask
// 点击分解
using var ra5 = CaptureToRectArea();
var salvageBtnConfirm = ra5.Find(ElementAssets.Instance.BtnArtifactSalvageConfirm);
var salvageBtnConfirm = ra5.Find(ElementRecognition.Get("BtnArtifactSalvageConfirm", ra5));
if (salvageBtnConfirm.IsExist())
{
salvageBtnConfirm.Click();
@@ -812,4 +812,4 @@ public class AutoArtifactSalvageTask : ISoloTask
/// </summary>
Selected
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1018 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 484 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 284 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

@@ -0,0 +1,107 @@
{
"info": {
"authors": [],
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"description": "",
"enable_monster_loot_split": false,
"last_modified_time": 1755828864835,
"map_name": "Teyvat",
"name": "未命名路径",
"tags": [],
"type": "collect",
"version": "1.0"
},
"positions": [
{
"action": "",
"action_params": "",
"id": 1,
"move_mode": "walk",
"type": "teleport",
"x": 2289.0078125,
"y": -1197.31640625
},
{
"action": "combat_script",
"action_params": "wait(1.5)",
"id": 2,
"move_mode": "walk",
"type": "target",
"x": 2270.921875,
"y": -1181.94580078125
},
{
"action": "",
"action_params": "",
"id": 3,
"move_mode": "walk",
"type": "target",
"x": 2266.435546875,
"y": -1173.31787109375
},
{
"action": "",
"action_params": "",
"id": 4,
"move_mode": "walk",
"type": "path",
"x": 2238.7578125,
"y": -1184.73046875
},
{
"action": "",
"action_params": "",
"id": 5,
"move_mode": "fly",
"type": "path",
"x": 2215.11328125,
"y": -1197.294921875
},
{
"action": "",
"action_params": "",
"id": 6,
"move_mode": "walk",
"type": "path",
"x": 2191.3359375,
"y": -1214.46533203125
},
{
"action": "",
"action_params": "",
"id": 7,
"move_mode": "walk",
"type": "path",
"x": 2119.0048828125,
"y": -1231.728515625
},
{
"action": "",
"action_params": "",
"id": 8,
"move_mode": "walk",
"type": "path",
"x": 2117.5,
"y": -1254.09521484375
},
{
"action": "stop_flying",
"action_params": "",
"id": 9,
"move_mode": "fly",
"type": "path",
"x": 2114.4345703125,
"y": -1308.1357421875
},
{
"action": "",
"action_params": "",
"id": 10,
"move_mode": "run",
"type": "path",
"x": 2110.509765625,
"y": -1331.59130859375
}
]
}
@@ -0,0 +1,58 @@
{
"info": {
"name": "千年珍珠骏麟前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753791394637,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 4851.81982421875,
"y": 4802.15673828125,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 4837.4677734375,
"y": 4798.37158203125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 4780.36767578125,
"y": 4788.42822265625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
},
{
"id": 4,
"x": 4766.72998046875,
"y": 4786.763671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -0,0 +1,103 @@
{
"info": {
"name": "半永恒统辖矩阵前往",
"type": "collect",
"authors": [
{
"name": "Tool_tingsu",
"links": ""
}
],
"version": "1.0",
"description": "",
"map_name": "Teyvat",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch",
"tags": [],
"last_modified_time": 1753788953823,
"enable_monster_loot_split": false
},
"positions": [
{
"id": 1,
"x": 5150.287109375,
"y": -2787.1591796875,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 5167.76123046875,
"y": -2787.11328125,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 5192.0302734375,
"y": -2787.052734375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 5206.9306640625,
"y": -2786.9921875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 5215.41357421875,
"y": -2787.46875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 6,
"x": 5234.9130859375,
"y": -2787.0947265625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 7,
"x": 5243.3876953125,
"y": -2793.0263671875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 8,
"x": 5254.2939453125,
"y": -2788.7001953125,
"type": "path",
"move_mode": "jump",
"action": "",
"action_params": ""
},
{
"id": 9,
"x": 5269.052734375,
"y": -2787.484375,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
}
]
}
@@ -0,0 +1,58 @@
{
"info": {
"name": "前往古岩龙蜥",
"type": "collect",
"author": "柒叶子",
"version": "1.0",
"description": "前往古岩龙蜥",
"bgi_version": "0.52.0",
"map_match_method": "TemplateMatch"
},
"positions": [
{
"id": 1,
"x": 1669.650390625,
"y": 341.86962890625,
"type": "teleport",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 2,
"x": 1674.890625,
"y": 345.15625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 3,
"x": 1573.65234375,
"y": 254.67041015625,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 4,
"x": 1533.3095703125,
"y": 229.28857421875,
"type": "path",
"move_mode": "walk",
"action": "",
"action_params": ""
},
{
"id": 5,
"x": 1485.296875,
"y": 208.9697265625,
"type": "path",
"move_mode": "fly",
"action": "stop_flying",
"action_params": ""
}
]
}
Loaded 100 of 1274 files, more files were not shown because too many files have changed in this diff. Show more