Compare commits

..
154 Commits
Author SHA1 Message Date
辉鸭蛋 0351cc7410 0.41.0 2025-02-06 16:51:00 +08:00
辉鸭蛋 33dc5f7d42 fix tptask 2025-02-06 14:11:19 +08:00
辉鸭蛋 bb49feb19e offline package 2025-02-06 02:38:46 +08:00
辉鸭蛋 749cae4dc2 improve the recognition rate of orange option text 2025-02-06 02:16:57 +08:00
辉鸭蛋 472c169603 use R2 to distribute script files 2025-02-06 01:37:42 +08:00
辉鸭蛋 f76c877882 support only local script repo 2025-02-05 22:23:31 +08:00
辉鸭蛋 328b5f21cc add pyro_collect 2025-02-05 21:59:42 +08:00
辉鸭蛋 5118308e9d fight: kazuha cd opt 2025-02-05 21:43:05 +08:00
辉鸭蛋 d3bd62b2c4 fix party switch task
修复切换队伍时,第五个队伍无法被选中的问题
2025-02-05 21:10:08 +08:00
辉鸭蛋 9463827582 new banner 2025-02-05 10:51:05 +08:00
辉鸭蛋 445e9b8030 Merge remote-tracking branch 'origin/main' 2025-02-05 10:32:51 +08:00
辉鸭蛋 7fb04270b1 update warning text 2025-02-05 10:30:18 +08:00
辉鸭蛋 46d4045fd5 Merge pull request #1106 from MisakaAldrich/main
添加企业微信通知
2025-02-05 10:26:54 +08:00
起个名字好难 2c59fe70ad Merge branch 'babalae:main' into main 2025-02-05 00:10:12 +08:00
起个名字好难 8afcf9ddff 添加企业微信通知 2025-02-05 00:08:52 +08:00
起个名字好难 184d186c9c 添加企业微信通知 2025-02-04 23:10:58 +08:00
辉鸭蛋 eeecb5b44f pathing: auto skip config2 2025-02-04 21:48:25 +08:00
辉鸭蛋 31fcf9cedf fix WindowStartupLocation without Owner
修复脚本订阅和配置组运行的提示框在高DPI显示屏下跑到屏幕外的问题
2025-02-04 21:06:13 +08:00
辉鸭蛋 75449f8ced pathing: auto skip config 2025-02-04 20:46:14 +08:00
辉鸭蛋 202ac61242 fix #1100 2025-02-04 20:25:31 +08:00
辉鸭蛋 7ec0d649cb Merge pull request #1054 from Scarlet1ssimo/webhook
[Test In Progress] Feature: Notification-based Webhook Infrastructure
2025-02-04 17:12:55 +08:00
辉鸭蛋 92516c26d2 支持配置要通知的事件 2025-02-04 17:11:53 +08:00
辉鸭蛋 151b383c40 添加飞书通知 2025-02-03 19:28:09 +08:00
辉鸭蛋 644c3d0193 更多任务支持 2025-02-03 15:54:19 +08:00
辉鸭蛋 1efd8d9454 重构通知模块 2025-02-03 15:02:25 +08:00
辉鸭蛋 f8bcbcedf7 Merge pull request #1098 from Scighost/main
Fix the issue of WebView2 UserDataFolder cannot be created
2025-02-02 23:15:10 +08:00
Scighost e44c55eb03 Fix the issue of WebView2 UserDataFolder cannot be created 2025-02-02 22:46:43 +08:00
辉鸭蛋 7040a441f2 Merge pull request #1086 from Yang-z/main
auto pathing: add `Orientation` to `WaypointType`
2025-02-02 15:07:00 +08:00
辉鸭蛋 297618b95f fix windows notify 2025-02-01 23:03:25 +08:00
辉鸭蛋 33d742bd4d Merge branch 'main' into pr/1054 2025-02-01 22:16:36 +08:00
辉鸭蛋 1eee073adb 1. 修正 Orientation 大写的问题
2. 美化了是否作为 target 点位接近的
2025-02-01 18:11:51 +08:00
辉鸭蛋 0fe4e86bc0 more genshin settings check 2025-02-01 16:01:07 +08:00
辉鸭蛋 c2709544fa allow full folder security 2025-02-01 13:33:05 +08:00
辉鸭蛋 f109ac5a14 MSIAfterburner warning 2025-02-01 10:43:52 +08:00
辉鸭蛋 e735cacb17 fix bettergi://start not valid 2025-02-01 10:23:05 +08:00
辉鸭蛋 06b142b8b2 more check for script repo 2025-02-01 08:59:24 +08:00
辉鸭蛋 98ef56b233 Merge pull request #1087 from Scarlet1ssimo/ffopt
bugfix: 战斗结束检测
2025-02-01 07:58:28 +08:00
Scarlet c2e028c529 optimize: fight finish detection 2025-01-31 16:41:42 -06:00
Yang-z 90b8a37389 auto pathing: add Orientation to WaypointType 2025-01-31 22:19:02 +08:00
辉鸭蛋 09a520a92f remove invalid link 2025-01-31 19:06:28 +08:00
辉鸭蛋 a9f9946db6 Merge remote-tracking branch 'origin/main' 2025-01-31 19:03:10 +08:00
辉鸭蛋 982aa7834b Merge pull request #1085 from Yang-z/main
auto pathing: reduce the startup time of `MoveCloseTo`
2025-01-31 19:02:53 +08:00
辉鸭蛋 dfa0c75a15 0.40.1 2025-01-31 18:13:21 +08:00
辉鸭蛋 854baad420 test code 2025-01-31 18:13:09 +08:00
Yang-z 547a56b932 auto pathing: reduce the startup time of MoveCloseTo 2025-01-31 18:03:48 +08:00
辉鸭蛋 7d7289ac16 release all key after fight #1073 2025-01-30 10:36:49 +08:00
辉鸭蛋 70a8d544fd ui: win10 not display switch blur button 2025-01-30 10:29:14 +08:00
辉鸭蛋 137ba4384a new e detect 2025-01-30 09:55:52 +08:00
辉鸭蛋 99932e972d Merge remote-tracking branch 'origin/main' 2025-01-30 08:08:09 +08:00
辉鸭蛋 b14de9ed20 auto domain: SendInput instead of PostMessage 2025-01-30 08:07:51 +08:00
辉鸭蛋 bc286d3b47 Merge pull request #1066 from mfkvfhpdx/main
修改了几个warning警告的地方,添加路径追踪任务时,增加排除已选择目录的筛选条件,调度器任务右键新增根据文件夹移除功能。
2025-01-29 22:59:56 +08:00
辉鸭蛋 2536b14af1 fist run not init key binding 2025-01-29 22:58:23 +08:00
辉鸭蛋 c3cffff4f3 fix CheckInBigMapUi 2025-01-29 22:23:12 +08:00
辉鸭蛋 8cffb01f0a fix method confusion 2025-01-29 17:44:38 +08:00
辉鸭蛋 9694919759 new orange option judge 2025-01-29 16:17:52 +08:00
辉鸭蛋 67df9f298a if it is a target waypoint type, it will continue to approach the target after a falling attack
如果是target路径点类型,下落攻击后会继续靠近目标
2025-01-29 15:03:37 +08:00
辉鸭蛋 47d88e67c9 opt 2025-01-29 14:34:07 +08:00
辉鸭蛋 b130351d8d bgi.huiyadan.com -> bettergi.com 2025-01-29 08:41:11 +08:00
辉鸭蛋 8b52aea9a3 ui dispatcher 2025-01-29 08:12:48 +08:00
辉鸭蛋 efde38439d tp exception 2025-01-29 08:12:32 +08:00
辉鸭蛋 e42c886bbe fix domain tp 2025-01-28 16:23:43 +08:00
辉鸭蛋 3e114ad358 添加windows通知 2025-01-28 13:12:14 +08:00
辉鸭蛋 4196f05f21 replace HttpContent with another data structure 2025-01-28 08:49:24 +08:00
辉鸭蛋 2cdabcf689 Merge pull request #1071 from physligl/main
修改传送任务中大地图移动的逻辑
2025-01-28 06:56:12 +08:00
秋云 f7cbc03f3d Merge branch 'babalae:main' into main 2025-01-28 02:39:58 +08:00
秋云 ce7c88f8e8 根据临近传送点的距离确定地图缩放,根据缩放等级确定当前剩余的距离。 2025-01-28 02:38:26 +08:00
辉鸭蛋 670bb3adad 修改序列化方式,添加测试数据 2025-01-27 20:47:17 +08:00
辉鸭蛋 6c16296b1b 修改 notify config 的获取方式 2025-01-27 20:13:53 +08:00
mfkvfhpdx 770edfab8a Merge branch 'babalae:main' into main 2025-01-27 15:15:26 +08:00
zjl 6a14a8c342 修改了几个warning警告的地方,添加路径追踪任务时,增加排除已选择目录的筛选条件,调度器任务右键新增根据文件夹移除功能。 2025-01-27 15:14:28 +08:00
辉鸭蛋 f19ee557b2 Merge branch 'main' into webhook 2025-01-27 13:57:23 +08:00
辉鸭蛋 2d0a7b5da8 typo 2025-01-27 13:56:27 +08:00
辉鸭蛋 ff92365bb4 Merge remote-tracking branch 'origin/main' 2025-01-27 12:32:16 +08:00
辉鸭蛋 81c84b94a5 Merge pull request #984 from babalae/readme-fix
Update README.md
2025-01-27 10:44:37 +08:00
辉鸭蛋 3fea7963ce Update README.md 2025-01-27 10:44:19 +08:00
辉鸭蛋 3ce54801c6 notify icon: check update 2025-01-27 09:22:11 +08:00
mfkvfhpdx 7b259e0329 Merge branch 'babalae:main' into main 2025-01-27 08:43:31 +08:00
zjl 8fdc664400 恢复版本 2025-01-27 08:42:33 +08:00
zjl 247580c04f Merge remote-tracking branch 'origin/main' 2025-01-27 08:28:21 +08:00
zjl 9de4fd4dfa 恢复代码 1 2025-01-27 08:17:41 +08:00
zjl bdaace9c8b 修正一个可能引发空指针的问题 2025-01-27 08:16:23 +08:00
辉鸭蛋 e30e919539 fix NullReferenceException #1063 2025-01-27 08:14:23 +08:00
zjl 3019d1aefa 修正一个可能引发空指针的问题 2025-01-27 08:14:14 +08:00
辉鸭蛋 8d4038d2e8 new appveyor build 2025-01-27 08:03:16 +08:00
辉鸭蛋 489d13dbcf add 蓝砚 in ElementalCollectAvatarConfigs 2025-01-26 23:48:13 +08:00
辉鸭蛋 7091da2c9f Merge remote-tracking branch 'origin/main' 2025-01-26 23:20:13 +08:00
辉鸭蛋 945085c34c typo 2025-01-26 23:10:17 +08:00
mfkvfhpdx 5513931fb6 Merge branch 'babalae:main' into main 2025-01-26 22:19:14 +08:00
辉鸭蛋 9a421860d0 Merge pull request #1062 from cx05121/main
拾取黑名单添加“蓝砚”
2025-01-26 21:43:51 +08:00
曦 edaf5ac443 more pick black item 2025-01-26 21:35:20 +08:00
mfkvfhpdx 8e9776f17c Merge branch 'babalae:main' into main 2025-01-26 18:49:27 +08:00
zjl 54e062d490 恢复上一个版本 2025-01-26 18:48:28 +08:00
辉鸭蛋 0468854ac5 fix auto fight NPE 2025-01-26 18:47:35 +08:00
zjl 10cb31af57 修正当战斗脚本中人员不在队伍是引发的异常 2025-01-26 18:46:42 +08:00
mfkvfhpdx 3cca2f329d Merge branch 'babalae:main' into main 2025-01-26 18:42:50 +08:00
辉鸭蛋 af0a869c70 shutdown when user config migrate 2025-01-26 17:09:19 +08:00
辉鸭蛋 f0baf74dc8 0.40.0 2025-01-26 14:02:17 +08:00
辉鸭蛋 8862f57958 Merge remote-tracking branch 'origin/main' 2025-01-26 12:56:21 +08:00
辉鸭蛋 bd72e6420d fist run old version clear 2025-01-26 12:55:57 +08:00
mfkvfhpdx 8c45a02deb 调整日志分析一些字段为0时显示为空,增加了异常情况统计(复活、重试、传送失败、战斗超时)。 (#1056)
* 调整日志分析一些字段为0时显示为空,增加了异常情况统计(复活、重试、传送失败、战斗超时)。

* 修正一个赋值错误

* 日志分析表格,使隔行颜色样式不一样

* 增加了锄地延时,通过控制延时相对精确的显示怪物数量

* 删除不必要的输出

* 调度器任务,增加 任务倒序排列功能。调度器配置增加“不在某时执行”,当执行完一个路线后,如果时间为当前配置的时间(范围:0-23),则此路径追踪任务后续都将都跳过,适用于连续执行的兜底任务,例如想通宵挂机,并且在4点后,开始执行新的任务。
2025-01-26 11:17:19 +08:00
mfkvfhpdx 0dd1dffccb Merge branch 'babalae:main' into main 2025-01-26 08:55:08 +08:00
辉鸭蛋 9ba3447ab1 modify the position of the UI for map teleportation settings
修改地图传送设置ui的位置
2025-01-26 00:20:01 +08:00
辉鸭蛋 218029b2e6 0.39.7 2025-01-25 23:53:15 +08:00
辉鸭蛋 718db28e51 update ui icon 2025-01-25 23:48:14 +08:00
辉鸭蛋 b639b1902e fix solo task run 2025-01-25 23:36:24 +08:00
辉鸭蛋 e97e04f9db auto music: more config
千音雅集支持更多的参数控制,以及文案和界面优化
2025-01-25 23:03:50 +08:00
mfkvfhpdx 7a07719bf8 Merge branch 'babalae:main' into main 2025-01-25 22:30:57 +08:00
zjl d0f985408e 调度器任务,增加 任务倒序排列功能。调度器配置增加“不在某时执行”,当执行完一个路线后,如果时间为当前配置的时间(范围:0-23),则此路径追踪任务后续都将都跳过,适用于连续执行的兜底任务,例如想通宵挂机,并且在4点后,开始执行新的任务。 2025-01-25 22:29:37 +08:00
辉鸭蛋 4b65370e9f Revert #1059 2025-01-25 16:54:37 +08:00
辉鸭蛋 5259b1f351 startOneDragon command line #998 2025-01-25 16:49:05 +08:00
辉鸭蛋 1afeb0818a #974 2025-01-25 15:55:36 +08:00
辉鸭蛋 99ab38d950 Merge remote-tracking branch 'origin/main' 2025-01-25 13:57:59 +08:00
辉鸭蛋 1d5f5c772e update ui 2025-01-25 13:55:19 +08:00
辉鸭蛋 869050283b Merge pull request #1045 from FishmanTheMurloc/main
使用行为树对自动钓鱼进行了改写,以利往后的优化
2025-01-25 13:53:15 +08:00
FishmanTheMurloc bb692a476e 添加纳塔鱼和鱼饵;添加鱼大类ray以合并两种细分的formalo ray和divda ray 2025-01-25 13:06:04 +08:00
FishmanTheMurloc 518ed95dbe Merge branch 'babalae:main' into main 2025-01-25 12:05:46 +08:00
辉鸭蛋 987e723b8c BetterGI.exe startOneDragon 2025-01-25 10:31:30 +08:00
辉鸭蛋 3c84f3817d auto tcg: fix error 2025-01-24 22:48:25 +08:00
mfkvfhpdx 319e88bb0c Merge branch 'babalae:main' into main 2025-01-24 22:39:45 +08:00
辉鸭蛋 6beb9fddba Merge pull request #1058 from physligl/main
增加了地图移动的相关参数设置的界面
2025-01-24 22:00:18 +08:00
秋云 020c841bc2 Merge branch 'babalae:main' into main 2025-01-24 20:42:18 +08:00
秋云 b445c71e52 增加了地图移动的相关参数设置。 2025-01-24 20:38:45 +08:00
mfkvfhpdx 56e110d11f Merge branch 'babalae:main' into main 2025-01-24 20:30:14 +08:00
辉鸭蛋 a5e1478ecf revert & dash 2025-01-24 19:48:45 +08:00
zjl 72cc9d8d01 Merge remote-tracking branch 'origin/main' 2025-01-24 19:20:59 +08:00
zjl 39b7176b4d 删除不必要的输出 2025-01-24 19:20:47 +08:00
mfkvfhpdx 6fcf213631 Merge branch 'babalae:main' into main 2025-01-24 19:20:08 +08:00
zjl 7c620429c3 增加了锄地延时,通过控制延时相对精确的显示怪物数量 2025-01-24 19:19:09 +08:00
辉鸭蛋 158688d435 fix patch 1 2025-01-24 18:08:56 +08:00
辉鸭蛋 8caa52e988 Acrylic first 2025-01-24 01:21:09 +08:00
辉鸭蛋 82275bd1e5 Merge remote-tracking branch 'origin/main' 2025-01-24 00:16:49 +08:00
辉鸭蛋 4129510029 0.39.6 2025-01-24 00:16:25 +08:00
辉鸭蛋 917ba1460d fix some bug 2025-01-24 00:16:11 +08:00
zjl d70ed4314a 日志分析表格,使隔行颜色样式不一样 2025-01-23 23:04:58 +08:00
秋云 3cc3eb44a4 fix typos. 2025-01-23 23:00:57 +08:00
zjl 07efcbde4f 修正一个赋值错误 2025-01-23 22:58:38 +08:00
zjl d33e54c50f Merge remote-tracking branch 'origin/main' 2025-01-23 22:54:15 +08:00
zjl f7779af01b 调整日志分析一些字段为0时显示为空,增加了异常情况统计(复活、重试、传送失败、战斗超时)。 2025-01-23 22:53:59 +08:00
辉鸭蛋 29f219aee9 Merge pull request #1055 from mfkvfhpdx/main
调整删除逻辑,软链接目录直接删除目录而非文件递归删除,方便引入自己的目录,防止订阅全部时被删除。
2025-01-23 12:50:36 +08:00
Scarlet cb84ae36d0 feat: integrate send() method into notification to allow for shorter call 2025-01-22 12:34:42 -06:00
zjl 1af75ecc64 调整删除逻辑,软链接目录直接删除目录而非文件递归删除,方便引入自己的目录,防止订阅全部时被删除。 2025-01-22 22:31:19 +08:00
Scarlet 2181e74a30 feat: unify factories; allow creating from actual params to instantiate a builder 2025-01-21 23:42:31 -06:00
Scarlet ec7ecbf9e0 remove unused references 2025-01-21 22:54:51 -06:00
Scarlet 50513613de feature: notification-based webhook 2025-01-21 22:22:27 -06:00
辉鸭蛋 39d7422ab9 new world model 2025-01-21 23:09:47 +08:00
辉鸭蛋 12cc958705 updater 2025-01-21 23:01:35 +08:00
辉鸭蛋 197e991a89 0.39.5 2025-01-21 22:51:57 +08:00
辉鸭蛋 6ee4318d24 Merge pull request #1036 from mfkvfhpdx/main
调整“按日锄地摩拉统计”为“按日摩拉收益统计”,并增加统计突发事件委托收益。
2025-01-21 22:47:09 +08:00
mfkvfhpdx 6fcc0685e6 Merge branch 'babalae:main' into main 2025-01-21 08:33:33 +08:00
mfkvfhpdx 0b17dc30fe Merge branch 'babalae:main' into main 2025-01-20 13:39:56 +08:00
zjl 919818a424 调度器配置增加 “根据技能CD优化出招人员”配置。根据填入人或人和cd,来决定当此人元素战技cd未结束时,跳过此人出招,来优化战斗流程,可填入人名或人名数字(用逗号分隔),多种用分号分隔,例如:白术;钟离,12;,如果人名,则用内置cd检查(或填入数字也小于0),如果是人名和数字,则把数字当做出招cd(秒)。 2025-01-19 22:11:47 +08:00
FishmanTheMurloc 28cc3fb3e3 使用行为树对自动钓鱼进行了改写,以利往后的优化 2025-01-19 17:46:11 +08:00
zjl ae954fceb8 调整“按日锄地摩拉统计”为“按日摩拉收益统计”,并增加统计突发事件委托收益。 2025-01-18 22:37:57 +08:00
辉鸭蛋 a6fc3aac76 Update README.md 2025-01-08 01:21:56 +08:00
148 changed files with 3639 additions and 2009 deletions

No files matched your search

-1
View File
@@ -29,4 +29,3 @@ node_modules/
# Rider
.idea
_ReSharper.Caches/
@@ -1,19 +0,0 @@
<Project Sdk="MSTest.Sdk/3.6.4">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<UseVSTest>true</UseVSTest>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj" />
</ItemGroup>
</Project>
@@ -1,52 +0,0 @@
namespace BetterGenshinImpact.CombatScript.Test;
[TestClass]
public sealed class ScriptEmitTest
{
[TestMethod]
public void TestEmit()
{
ScriptUnit scriptUnit = new(
[
new CommentSymbol("测试注释"),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("钟离"), [new SpaceTriviaSymbol()], new(
[
new WalkSymbol(WalkDirection.Backward, [new DoubleSymbol(0.1)], [], new CommaTriviaSymbol()),
new SkillSymbol(true, [new HoldSymbol()], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WaitSymbol([new DoubleSymbol(0.3)], [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new WalkSymbol(WalkDirection.Forward, [new DoubleSymbol(0.1)], [new SpaceTriviaSymbol()], default),
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("芙宁娜"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], default)
])),
new LineBreakTriviaSymbol(),
new AvatarInstructionListSymbol(new("行秋"), [new SpaceTriviaSymbol()], new(
[
new SkillSymbol(true, [], new CommaTriviaSymbol()),
new BurstSymbol(true, [new SpaceTriviaSymbol()], new CommaTriviaSymbol()),
new SkillSymbol(true, [new SpaceTriviaSymbol()], default),
])),
]);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
[TestMethod]
public void TestParse()
{
ReadOnlySpan<char> raw = """
// 测试注释
钟离 s(0.1),e(hold),wait(0.3),w(0.1)
芙宁娜 e,q
行秋 e,q,e
""";
ScriptUnit scriptUnit = SymbolParser.Parse(raw);
Console.WriteLine(scriptUnit.Emit(new SymbolEmitter()));
}
}
@@ -1,31 +0,0 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class AttackSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public AttackSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public AttackSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("attack", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -1,24 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarInstructionListSymbol : BaseSymbol
{
public AvatarInstructionListSymbol(AvatarSymbol avatar, ImmutableArray<TriviaSymbol> triviaList, InstructionListSymbol instructionList)
{
Avatar = avatar;
TriviaList = triviaList;
InstructionList = instructionList;
}
public AvatarSymbol Avatar { get; }
public ImmutableArray<TriviaSymbol> TriviaList { get; }
public InstructionListSymbol InstructionList { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Avatar).Append(TriviaList).Append(InstructionList);
}
}
@@ -1,16 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class AvatarSymbol : BaseSymbol
{
public AvatarSymbol(string name)
{
Name = name;
}
public string Name { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Name);
}
}
@@ -1,6 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class BaseSymbol : ISymbol
{
public abstract void Emit(ISymbolEmitter emitter);
}
@@ -1,9 +0,0 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>disable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
@@ -1,25 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class BurstSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public BurstSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public BurstSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("burst", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "q";
public bool IsAlias { get; }
}
@@ -1,31 +0,0 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class ChargeSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public ChargeSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public ChargeSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("charge", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -1,17 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommaTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(',');
}
}
public sealed class SemicolonTriviaSymbol : TriviaSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(';');
}
}
@@ -1,16 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class CommentSymbol : TriviaSymbol
{
public CommentSymbol(string comment)
{
Comment = comment;
}
public string Comment { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("//").Append(Comment);
}
}
@@ -1,31 +0,0 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class DashSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public DashSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
}
public DashSymbol(ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("dash", leadingTriviaList, tailingTrivia)
{
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -1,16 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class DoubleSymbol : BaseSymbol, IParameterSymbol
{
public DoubleSymbol(double value)
{
Value = value;
}
public double Value { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Value);
}
}
@@ -1,9 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public sealed class HoldSymbol : BaseSymbol, IParameterSymbol
{
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append("hold");
}
}
@@ -1,8 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasAlias
{
public string AliasName { get; }
public bool IsAlias { get; }
}
@@ -1,10 +0,0 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public interface IInstructionSymbolHasDuration
{
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -1,5 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public interface IParameterSymbol : ISymbol
{
}
@@ -1,6 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbol
{
void Emit(ISymbolEmitter emitter);
}
@@ -1,14 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public interface ISymbolEmitter
{
string Emit();
ISymbolEmitter Append(char value);
ISymbolEmitter Append(char value, int repeatCount);
ISymbolEmitter Append(double value);
ISymbolEmitter Append(string value);
}
@@ -1,18 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class InstructionListSymbol : BaseSymbol
{
public InstructionListSymbol(ImmutableArray<InstructionSymbol> instructions)
{
Instructions = instructions;
}
public ImmutableArray<InstructionSymbol> Instructions { get; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(Instructions);
}
}
@@ -1,59 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public abstract class InstructionSymbol : BaseSymbol
{
protected InstructionSymbol(string name, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = false;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
protected InstructionSymbol(string name, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
Name = name;
HasParameterList = true;
ParameterList = parameterList;
LeadingTriviaList = leadingTriviaList;
TailingTrivia = tailingTrivia;
}
public string Name { get; }
public bool HasParameterList { get; }
public ImmutableArray<IParameterSymbol> ParameterList { get; }
public ImmutableArray<TriviaSymbol> LeadingTriviaList { get; }
public TriviaSymbol? TailingTrivia { get; set; }
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(LeadingTriviaList);
if (this is IInstructionSymbolHasAlias {IsAlias: true } hasAlias)
{
emitter.Append(hasAlias.AliasName);
}
else
{
emitter.Append(Name);
}
if (HasParameterList)
{
emitter.Append('(');
emitter.Append(ParameterList);
emitter.Append(')');
}
if (TailingTrivia is not null)
{
emitter.Append(TailingTrivia);
}
}
}
@@ -1,35 +0,0 @@
using System;
using System.Collections.Frozen;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class InstructionThrowHelper
{
public static void ThrowIfParameterListIsDefault(ImmutableArray<IParameterSymbol> parameterList)
{
if (parameterList.IsDefault)
{
throw new ArgumentException($"Parameter list can not be default.");
}
}
public static void ThrowIfParameterListCountNotCorrect(ImmutableArray<IParameterSymbol> parameterList, FrozenSet<int> allowedCounts)
{
if (!allowedCounts.Contains(parameterList.Length))
{
throw new ArgumentException($"Instruction parameter count not correct.");
}
}
public static void ThrowIfParameterAtIndexIsNot<T>(ImmutableArray<IParameterSymbol> parameterList, int index, out T symbol)
where T : IParameterSymbol
{
if (parameterList.Length <= index || parameterList[index] is not T result)
{
throw new ArgumentException($"Instruction's parameter at index {index} must be a {typeof(T).Name}.");
}
symbol = result;
}
}
@@ -1,25 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class JumpSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public JumpSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0]);
IsAlias = isAlias;
}
public JumpSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("jump", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "j";
public bool IsAlias { get; }
}
@@ -1,28 +0,0 @@
using System;
namespace BetterGenshinImpact.CombatScript;
public class LineBreakTriviaSymbol : TriviaSymbol
{
private readonly string lineBreak;
public LineBreakTriviaSymbol()
{
lineBreak = Environment.NewLine;
}
public LineBreakTriviaSymbol(string lineBreak)
{
if (lineBreak is not ("\r\n" or "\n" or "\r" or ";"))
{
throw new ArgumentException("Invalid line break.");
}
this.lineBreak = lineBreak;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(lineBreak);
}
}
@@ -1,23 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public sealed class ScriptUnit
{
public ScriptUnit(ImmutableArray<ISymbol> symbols)
{
Symbols = symbols;
}
public ImmutableArray<ISymbol> Symbols { get; }
public string Emit(ISymbolEmitter emitter)
{
foreach (ref readonly ISymbol symbol in Symbols.AsSpan())
{
symbol.Emit(emitter);
}
return emitter.Emit();
}
}
@@ -1,30 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class SkillSymbol : InstructionSymbol, IInstructionSymbolHasAlias
{
public SkillSymbol(bool isAlias, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [0, 1]);
if (parameterList.Length is 1)
{
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out HoldSymbol _);
}
IsAlias = isAlias;
}
public SkillSymbol(bool isAlias, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("skill", leadingTriviaList, tailingTrivia)
{
IsAlias = isAlias;
}
public string AliasName { get; } = "e";
public bool IsAlias { get; }
}
@@ -1,21 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public class SpaceTriviaSymbol : TriviaSymbol
{
private readonly int count;
public SpaceTriviaSymbol()
{
count = 1;
}
public SpaceTriviaSymbol(int count)
{
this.count = count;
}
public override void Emit(ISymbolEmitter emitter)
{
emitter.Append(' ', count);
}
}
@@ -1,37 +0,0 @@
using System.Text;
namespace BetterGenshinImpact.CombatScript;
public sealed class SymbolEmitter : ISymbolEmitter
{
private readonly StringBuilder builder = new();
public string Emit()
{
return builder.ToString();
}
public ISymbolEmitter Append(char value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(char value, int repeatCount)
{
builder.Append(value, repeatCount);
return this;
}
public ISymbolEmitter Append(double value)
{
builder.Append(value);
return this;
}
public ISymbolEmitter Append(string value)
{
builder.Append(value);
return this;
}
}
@@ -1,23 +0,0 @@
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolEmitterExtensions
{
public static ISymbolEmitter Append(this ISymbolEmitter emitter, ISymbol symbol)
{
symbol.Emit(emitter);
return emitter;
}
public static ISymbolEmitter Append<TSymbol>(this ISymbolEmitter emitter, ImmutableArray<TSymbol> symbolList)
where TSymbol : ISymbol
{
foreach(ref readonly TSymbol symbol in symbolList.AsSpan())
{
symbol.Emit(emitter);
}
return emitter;
}
}
@@ -1,193 +0,0 @@
using System;
using System.Collections.Immutable;
using System.Runtime.CompilerServices;
namespace BetterGenshinImpact.CombatScript;
public static class SymbolParser
{
public static ScriptUnit Parse(ReadOnlySpan<char> raw)
{
ImmutableArray<ISymbol>.Builder symbols = ImmutableArray.CreateBuilder<ISymbol>();
ParseLines(raw, symbols);
return new(symbols.ToImmutable());
}
private static void ParseLines(ReadOnlySpan<char> raw, ImmutableArray<ISymbol>.Builder symbols)
{
bool skipNextRange = false;
ref readonly char end = ref raw[^1];
foreach(Range range in raw.SplitAny(['\r', '\n', ';']))
{
if (skipNextRange)
{
skipNextRange = false;
continue;
}
int offset = range.End.GetOffset(raw.Length);
if (offset >= raw.Length)
{
break;
}
ref readonly char peek = ref raw[offset];
LineBreakTriviaSymbol lineBreakTrivia;
if (peek is '\r')
{
if (Unsafe.IsAddressLessThan(in peek, in end) && Unsafe.Add(ref Unsafe.AsRef(in peek), 1) is '\n')
{
// It's a CRLF
lineBreakTrivia = new("\r\n");
skipNextRange = true;
}
else
{
// It's a CR
lineBreakTrivia = new("\r");
}
}
else if (peek is '\n')
{
// It's a LF
lineBreakTrivia = new("\n");
}
else if (peek is ';')
{
lineBreakTrivia = new(";");
}
else
{
throw new InvalidOperationException($"Failed to parse line break trivia at {range}.");
}
if (ParseLine(raw[range]) is { } symbol)
{
symbols.Add(symbol);
}
symbols.Add(lineBreakTrivia);
}
}
private static ISymbol? ParseLine(ReadOnlySpan<char> raw)
{
if (raw.IsEmpty)
{
return default;
}
if (raw.StartsWith("//"))
{
return new CommentSymbol(raw[2..].ToString());
}
int indexOfSpace = raw.IndexOf(' ');
ReadOnlySpan<char> avatarIdentifier = raw[..indexOfSpace];
AvatarSymbol avatarSymbol = new(avatarIdentifier.ToString());
ImmutableArray<TriviaSymbol> triviaList = ParseTriviaList(raw[indexOfSpace..], out int advanced);
InstructionListSymbol listSymbol = ParseInstructionList(raw[(indexOfSpace + advanced)..]);
return new AvatarInstructionListSymbol(avatarSymbol, triviaList, listSymbol);
}
private static InstructionListSymbol ParseInstructionList(ReadOnlySpan<char> raw)
{
ImmutableArray<InstructionSymbol>.Builder builder = ImmutableArray.CreateBuilder<InstructionSymbol>();
foreach (Range range in raw.Split(','))
{
ReadOnlySpan<char> current = raw[range];
ImmutableArray<TriviaSymbol> leadingTriviaList = ParseTriviaList(current, out int advanced);
if (ParseInstruction(current[advanced..], leadingTriviaList) is { } symbol)
{
builder.Add(symbol);
}
}
return new(builder.ToImmutable());
}
private static InstructionSymbol? ParseInstruction(ReadOnlySpan<char> raw, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
{
if (raw.IsEmpty)
{
return default;
}
switch (raw[0])
{
// attack|a
case 'a':
break;
// burst
case 'b':
return new BurstSymbol(false, [], leadingTriviaList, tailingTrivia);
break;
// charge
case 'c':
break;
// dash|d
case 'd':
break;
// jump|j
case 'j':
break;
// q
case 'q':
return new BurstSymbol(true, [], leadingTriviaList, tailingTrivia);
break;
// skill|s
case 's':
break;
// wait|walk|w
case 'w':
break;
}
return default;
}
// Handle ','&' '
private static ImmutableArray<TriviaSymbol> ParseTriviaList(ReadOnlySpan<char> raw, out int advanced)
{
advanced = 0;
if (raw.IsEmpty)
{
return ImmutableArray<TriviaSymbol>.Empty;
}
ImmutableArray<TriviaSymbol>.Builder builder = ImmutableArray.CreateBuilder<TriviaSymbol>();
int spaceCount = 0;
foreach (ref readonly char value in raw)
{
advanced++;
if (value is ' ')
{
spaceCount++;
}
else
{
if (spaceCount is not 0)
{
builder.Add(new SpaceTriviaSymbol(spaceCount));
spaceCount = 0;
}
if (value is ',')
{
builder.Add(new CommaTriviaSymbol());
}
else
{
break;
}
}
}
return builder.ToImmutable();
}
}
@@ -1,5 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public abstract class TriviaSymbol : BaseSymbol
{
}
@@ -1,23 +0,0 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WaitSymbol : InstructionSymbol, IInstructionSymbolHasDuration
{
public WaitSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("wait", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
}
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -1,9 +0,0 @@
namespace BetterGenshinImpact.CombatScript;
public enum WalkDirection
{
Forward,
Backward,
Left,
Right
}
@@ -1,70 +0,0 @@
using System;
using System.Collections.Immutable;
namespace BetterGenshinImpact.CombatScript;
public class WalkSymbol : InstructionSymbol, IInstructionSymbolHasAlias, IInstructionSymbolHasDuration, IParameterSymbol
{
public WalkSymbol(WalkDirection direction, ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [1]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out DoubleSymbol doubleSymbol);
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
Direction = direction;
IsAlias = true;
}
// Used for parameter
public WalkSymbol(WalkDirection direction, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", leadingTriviaList, tailingTrivia)
{
Direction = direction;
IsAlias = true;
}
public WalkSymbol(ImmutableArray<IParameterSymbol> parameterList, ImmutableArray<TriviaSymbol> leadingTriviaList, TriviaSymbol? tailingTrivia)
: base("walk", parameterList, leadingTriviaList, tailingTrivia)
{
InstructionThrowHelper.ThrowIfParameterListIsDefault(parameterList);
InstructionThrowHelper.ThrowIfParameterListCountNotCorrect(parameterList, [2]);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 0, out WalkSymbol directionAlias);
InstructionThrowHelper.ThrowIfParameterAtIndexIsNot(parameterList, 1, out DoubleSymbol doubleSymbol);
Direction = directionAlias.Direction;
HasDuration = true;
Duration = TimeSpan.FromSeconds(doubleSymbol.Value);
IsAlias = false;
}
public string AliasName
{
get
{
return Direction switch
{
WalkDirection.Forward => "w",
WalkDirection.Backward => "s",
WalkDirection.Left => "a",
WalkDirection.Right => "d",
_ => throw new ArgumentOutOfRangeException(),
};
}
}
public bool IsAlias { get; }
public WalkDirection Direction { get; }
public bool HasDuration { get; }
public TimeSpan Duration { get; }
}
@@ -61,7 +61,7 @@ internal class HsvTestWindow
Cv2.CreateTrackbar("High S", _windowDetectionName, ref _highS, MaxValue, on_high_S_thresh_trackbar);
Cv2.CreateTrackbar("Low V", _windowDetectionName, ref _lowV, MaxValue, on_low_V_thresh_trackbar);
Cv2.CreateTrackbar("High V", _windowDetectionName, ref _highV, MaxValue, on_high_V_thresh_trackbar);
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\自动战斗\队伍识别\bsz1.png", ImreadModes.Color);
var frame = Cv2.ImRead(@"E:\HuiTask\更好的原神\自动秘境\Q识别\拼图\2.png", ImreadModes.Color);
Mat frameHsv = new Mat();
// Convert from BGR to HSV colorspace
Cv2.CvtColor(frame, frameHsv, ColorConversionCodes.BGR2HSV);
-20
View File
@@ -19,10 +19,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BetterGenshinImpact.Test",
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Fischless.WindowsInput", "Fischless.WindowsInput\Fischless.WindowsInput.csproj", "{9D00BC7A-9280-4AC9-8951-4502EDB71B76}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript", "BetterGenshinImpact.CombatScript\BetterGenshinImpact.CombatScript.csproj", "{57C278F9-F62A-480A-B929-B0E5D8174194}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BetterGenshinImpact.CombatScript.Test", "BetterGenshinImpact.CombatScript.Test\BetterGenshinImpact.CombatScript.Test.csproj", "{09427DA8-665E-441A-A576-C11FBC6F9E5C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -87,22 +83,6 @@ Global
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|Any CPU.Build.0 = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.ActiveCfg = Release|x64
{9D00BC7A-9280-4AC9-8951-4502EDB71B76}.Release|x64.Build.0 = Release|x64
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|Any CPU.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.ActiveCfg = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Debug|x64.Build.0 = Debug|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|Any CPU.Build.0 = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.ActiveCfg = Release|Any CPU
{57C278F9-F62A-480A-B929-B0E5D8174194}.Release|x64.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.ActiveCfg = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Debug|x64.Build.0 = Debug|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|Any CPU.Build.0 = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.ActiveCfg = Release|Any CPU
{09427DA8-665E-441A-A576-C11FBC6F9E5C}.Release|x64.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+2
View File
@@ -185,6 +185,8 @@ public partial class App : Application
protected override async void OnExit(ExitEventArgs e)
{
base.OnExit(e);
TempManager.CleanUp();
await _host.StopAsync();
_host.Dispose();
Binary file not shown.

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 136 KiB

@@ -10,7 +10,7 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\Images\logo.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.39.4</AssemblyVersion>
<AssemblyVersion>0.41.0</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
@@ -47,6 +47,7 @@
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.DirectML" Version="1.18.1" />
<PackageReference Include="Microsoft.ML.OnnxRuntime.Managed" Version="1.18.1" />
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications" Version="7.1.3" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.2592.51" />
<PackageReference Include="Ookii.Dialogs.Wpf" Version="5.0.1" />
<PackageReference Include="OpenCvSharp4.WpfExtensions" Version="4.8.0.20230708" />
@@ -147,6 +148,7 @@
<ItemGroup>
<Folder Include="GameTask\OneDragon\" />
<Folder Include="Service\Notification\Builder\" />
<Folder Include="User\AutoPathing\" />
</ItemGroup>
+7 -3
View File
@@ -17,6 +17,7 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoTrackPath;
namespace BetterGenshinImpact.Core.Config;
@@ -175,7 +176,11 @@ public partial class AllConfig : ObservableObject
/// 原神按键绑定配置
/// </summary>
public KeyBindingsConfig KeyBindingsConfig { get; set; } = new();
/// <summary>
/// 传送相关配置
/// </summary>
public TpConfig TpConfig { get; set; } = new();
[JsonIgnore]
public Action? OnAnyChangedAction { get; set; }
@@ -188,7 +193,6 @@ public partial class AllConfig : ObservableObject
NotificationConfig.PropertyChanged += OnAnyPropertyChanged;
NotificationConfig.PropertyChanged += OnNotificationPropertyChanged;
KeyBindingsConfig.PropertyChanged += OnAnyPropertyChanged;
AutoPickConfig.PropertyChanged += OnAnyPropertyChanged;
AutoSkipConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFishingConfig.PropertyChanged += OnAnyPropertyChanged;
@@ -200,7 +204,7 @@ public partial class AllConfig : ObservableObject
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
AutoMusicGameConfig.PropertyChanged += OnAnyPropertyChanged;
TpConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
}
@@ -39,4 +39,10 @@ public partial class CommonConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _isFirstRun = true;
/// <summary>
/// 这个版本是否运行过
/// </summary>
[ObservableProperty]
private string _runForVersion = string.Empty;
}
@@ -69,6 +69,10 @@ public partial class PathingPartyConfig : ObservableObject
[ObservableProperty]
private bool _soloTaskUseFightEnabled = false;
//不在某时执行
[ObservableProperty]
private string _skipDuring = "";
// 使用小道具的间隔时间
[ObservableProperty]
private int _useGadgetIntervalMs = 0;
@@ -35,7 +35,11 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
public static readonly string ReposTempPath = Path.Combine(ReposPath, "Temp");
// 中央仓库信息地址
public static readonly string CenterRepoInfoUrl = "https://raw.githubusercontent.com/babalae/bettergi-scripts-list/refs/heads/main/repo.json";
public static readonly List<string> CenterRepoInfoUrls =
[
"https://raw.githubusercontent.com/babalae/bettergi-scripts-list/refs/heads/main/repo.json",
"https://r2-script.bettergi.com/github_mirror/repo.json",
];
// 中央仓库解压后文件夹名
public static readonly string CenterRepoUnzipName = "bettergi-scripts-list-main";
@@ -88,10 +92,12 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
public async Task<(string, bool)> UpdateCenterRepo()
{
// 测速并获取信息
var res = await ProxySpeedTester.GetFastestProxyAsync(CenterRepoInfoUrl);
// 解析信息
var fastProxyUrl = res.Item1;
var jsonString = res.Item2;
var (fastUrl, jsonString) = await ProxySpeedTester.GetFastestUrlAsync(CenterRepoInfoUrls);
if (string.IsNullOrEmpty(jsonString))
{
throw new Exception("从互联网下载最新的仓库信息失败");
}
var (time, url, file) = ParseJson(jsonString);
var updated = false;
@@ -110,9 +116,10 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
{
needDownload = true;
}
if (needDownload)
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url));
await DownloadRepoAndUnzip(url);
updated = true;
}
@@ -128,7 +135,7 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
// 检查是否需要更新
if (long.Parse(time) > long.Parse(time2))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url2));
await DownloadRepoAndUnzip(url2);
updated = true;
}
@@ -246,6 +253,7 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
Content = $"检测到{(formClipboard ? "剪切板上存在" : "")}脚本订阅链接,解析后需要导入的脚本为:{pathJson}。\n是否导入并覆盖此文件或者文件夹下的脚本?",
CloseButtonText = "关闭",
PrimaryButtonText = "确认导入",
Owner = Application.Current.MainWindow,
WindowStartupLocation = WindowStartupLocation.CenterOwner,
};
@@ -316,7 +324,31 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
Toast.Information("获取最新仓库信息中...");
// 更新仓库
var (repoPath, _) = await Task.Run(UpdateCenterRepo);
string repoPath;
try
{
(repoPath, _) = await Task.Run(UpdateCenterRepo);
}
catch (Exception e)
{
Toast.Warning("获取最新仓库信息失败,尝试使用本地已有仓库信息");
try
{
repoPath = FindCenterRepoPath();
}
catch
{
await MessageBox.ErrorAsync("本地无仓库信息,请至少成功更新一次脚本仓库信息!");
return;
}
}
if (string.IsNullOrEmpty(repoPath))
{
await MessageBox.ErrorAsync("本地无仓库信息,请至少成功更新一次脚本仓库信息!");
return;
}
// // 收集将被覆盖的文件和文件夹
// var filesToOverwrite = new List<string>();
@@ -393,7 +425,7 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
{
// 目标文件所在文件夹不存在时创建它
Directory.CreateDirectory(Path.GetDirectoryName(destPath)!);
if (File.Exists(destPath))
{
File.Delete(destPath);
@@ -490,4 +522,4 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
}
}
}
}
}
@@ -6,6 +6,7 @@ using System.Security.Policy;
using System.Threading.Tasks;
using BetterGenshinImpact.ViewModel.Message;
using CommunityToolkit.Mvvm.Messaging;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script.WebView;
@@ -21,39 +22,32 @@ public class RepoWebBridge
{
try
{
// var needUpdate = false;
// string? localRepoJsonPath = null;
// if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
// {
// localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
// if (localRepoJsonPath is null)
// {
// needUpdate = true;
// }
// }
// else
// {
// needUpdate = true;
// }
//
// if (needUpdate)
// {
// await ScriptRepoUpdater.Instance.UpdateCenterRepo();
// }
await ScriptRepoUpdater.Instance.UpdateCenterRepo();
}
catch (Exception e)
{
Toast.Warning($"更新仓库信息失败:{e.Message}");
}
try
{
if (!Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
{
throw new Exception("仓库文件夹不存在,请至少成功更新一次仓库!");
}
var localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("repo.json 不存在,可能是更新仓库信息失败!");
throw new Exception("repo.json 仓库索引文件不存在,请至少成功更新一次仓库!");
}
var json = await File.ReadAllTextAsync(localRepoJsonPath);
return json;
}
catch (Exception e)
{
await MessageBox.ShowAsync(e.Message, "获取仓库信息失败!");
await MessageBox.ShowAsync(e.Message, "获取仓库信息失败");
return "";
}
}
@@ -70,4 +64,4 @@ public class RepoWebBridge
await MessageBox.ShowAsync(e.Message, "订阅脚本链接失败!");
}
}
}
}
@@ -30,6 +30,7 @@ using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using static Vanara.PInvoke.Kernel32;
@@ -43,8 +44,6 @@ public class AutoDomainTask : ISoloTask
private readonly AutoDomainParam _taskParam;
private readonly PostMessageSimulator _simulator;
private readonly YoloV8Predictor _predictor;
private readonly AutoDomainConfig _config;
@@ -55,10 +54,8 @@ public class AutoDomainTask : ISoloTask
public AutoDomainTask(AutoDomainParam taskParam)
{
_taskParam = taskParam;
AutoFightAssets.DestroyInstance();
_simulator = TaskContext.Instance().PostMessageSimulator;
_taskParam = taskParam;
_predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(@"Assets\Model\Domain\bgi_tree.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
@@ -72,9 +69,9 @@ public class AutoDomainTask : ISoloTask
public async Task Start(CancellationToken ct)
{
_ct = ct;
Init();
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Started().Build()); // TODO: 通知后续需要删除迁移
Notify.Event(NotificationEvent.DomainStart).Success("自动秘境启动");
// 3次复活重试
for (int i = 0; i < 3; i++)
@@ -91,6 +88,7 @@ public class AutoDomainTask : ISoloTask
{
Logger.LogWarning("自动秘境:{Text}", "复活后重试秘境...");
await Delay(2000, ct);
Notify.Event(NotificationEvent.DomainRetry).Error("存在角色死亡,复活后重试秘境...");
continue;
}
else
@@ -106,6 +104,7 @@ public class AutoDomainTask : ISoloTask
await Delay(2000, ct);
await ArtifactSalvage();
Notify.Event(NotificationEvent.DomainEnd).Success("自动秘境结束");
}
private async Task DoDomain()
@@ -161,12 +160,10 @@ public class AutoDomainTask : ISoloTask
{
Logger.LogInformation("体力已经耗尽,结束自动秘境");
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Success().Build());
break;
}
NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Progress().Build());
Notify.Event(NotificationEvent.DomainReward).Success("自动秘境奖励领取");
}
}
@@ -287,7 +284,7 @@ public class AutoDomainTask : ISoloTask
private async Task EnterDomain()
{
var fightAssets = AutoFightContext.Instance.FightAssets;
var fightAssets = AutoFightAssets.Instance;
// 进入秘境
for (int i = 0; i < 3; i++) // 3次重试 有时候会拾取晶蝶
@@ -299,9 +296,9 @@ public class AutoDomainTask : ISoloTask
Logger.LogInformation("自动秘境:{Text}", "进入秘境");
// 秘境开门动画 5s
await Delay(5000, _ct);
}
}
else
{
{
await Delay(800, _ct);
}
}
@@ -332,7 +329,7 @@ public class AutoDomainTask : ISoloTask
while (retryTimes < 120)
{
retryTimes++;
using var cactRectArea = CaptureToRectArea().Find(AutoFightContext.Instance.FightAssets.ClickAnyCloseTipRa);
using var cactRectArea = CaptureToRectArea().Find(AutoFightAssets.Instance.ClickAnyCloseTipRa);
if (!cactRectArea.IsEmpty())
{
await Delay(1000, _ct);
@@ -368,7 +365,7 @@ public class AutoDomainTask : ISoloTask
await Task.Run((Action)(() =>
{
_simulator.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
Sleep(30, _ct);
// 组合键好像不能直接用 postmessage
if (!_config.WalkToF)
@@ -395,7 +392,7 @@ public class AutoDomainTask : ISoloTask
}
finally
{
_simulator.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyUp);
Sleep(50);
if (!_config.WalkToF)
{
@@ -436,6 +433,7 @@ public class AutoDomainTask : ISoloTask
finally
{
Logger.LogInformation("自动战斗线程结束");
combatScenes.AfterTask();
}
}, cts.Token);
@@ -494,7 +492,7 @@ public class AutoDomainTask : ISoloTask
{
using var ra = CaptureToRectArea();
var endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsUpperRect);
var endTipsRect = ra.DeriveCrop(AutoFightAssets.Instance.EndTipsUpperRect);
var text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
if (text.Contains("挑战") || text.Contains("达成"))
{
@@ -502,7 +500,7 @@ public class AutoDomainTask : ISoloTask
return true;
}
endTipsRect = ra.DeriveCrop(AutoFightContext.Instance.FightAssets.EndTipsRect);
endTipsRect = ra.DeriveCrop(AutoFightAssets.Instance.EndTipsRect);
text = OcrFactory.Paddle.Ocr(endTipsRect.SrcGreyMat);
if (text.Contains("自动") || text.Contains("退出"))
{
@@ -610,13 +608,13 @@ public class AutoDomainTask : ISoloTask
if (rightKeyDown)
{
// 先松开D键
_simulator.KeyUp(moveRightKey);
Simulation.SendInput.Keyboard.KeyUp(moveRightKey);
rightKeyDown = false;
}
if (!leftKeyDown)
{
_simulator.KeyDown(moveLeftKey);
Simulation.SendInput.Keyboard.KeyDown(moveLeftKey);
leftKeyDown = true;
}
}
@@ -628,13 +626,13 @@ public class AutoDomainTask : ISoloTask
if (leftKeyDown)
{
// 先松开A键
_simulator.KeyUp(moveLeftKey);
Simulation.SendInput.Keyboard.KeyUp(moveLeftKey);
leftKeyDown = false;
}
if (!rightKeyDown)
{
_simulator.KeyDown(moveRightKey);
Simulation.SendInput.Keyboard.KeyDown(moveRightKey);
rightKeyDown = true;
}
}
@@ -643,14 +641,14 @@ public class AutoDomainTask : ISoloTask
// 树在中间 松开所有键
if (rightKeyDown)
{
_simulator.KeyUp(moveRightKey);
Simulation.SendInput.Keyboard.KeyUp(moveRightKey);
prevKey = moveRightKey;
rightKeyDown = false;
}
if (leftKeyDown)
{
_simulator.KeyUp(moveLeftKey);
Simulation.SendInput.Keyboard.KeyUp(moveLeftKey);
prevKey = moveLeftKey;
leftKeyDown = false;
}
@@ -663,7 +661,9 @@ public class AutoDomainTask : ISoloTask
backwardsAndForwardsCount++;
}
_simulator.KeyPress(moveLeftKey, 60);
Simulation.SendInput.Keyboard.KeyDown(moveLeftKey);
Sleep(60);
Simulation.SendInput.Keyboard.KeyUp(moveLeftKey);
prevKey = moveLeftKey;
}
else if (treeMiddleX > middleX)
@@ -673,12 +673,16 @@ public class AutoDomainTask : ISoloTask
backwardsAndForwardsCount++;
}
_simulator.KeyPress(moveRightKey, 60);
Simulation.SendInput.Keyboard.KeyDown(moveRightKey);
Sleep(60);
Simulation.SendInput.Keyboard.KeyUp(moveRightKey);
prevKey = moveRightKey;
}
else
{
_simulator.KeyPress(moveForwardKey, 60);
Simulation.SendInput.Keyboard.KeyDown(moveForwardKey);
Sleep(60);
Simulation.SendInput.Keyboard.KeyUp(moveForwardKey);
Sleep(500, _ct);
treeCts.Cancel();
break;
@@ -694,13 +698,13 @@ public class AutoDomainTask : ISoloTask
{
if (leftKeyDown)
{
_simulator.KeyUp(moveLeftKey);
Simulation.SendInput.Keyboard.KeyUp(moveLeftKey);
leftKeyDown = false;
}
if (!rightKeyDown)
{
_simulator.KeyDown(moveRightKey);
Simulation.SendInput.Keyboard.KeyDown(moveRightKey);
rightKeyDown = true;
}
}
@@ -708,13 +712,13 @@ public class AutoDomainTask : ISoloTask
{
if (rightKeyDown)
{
_simulator.KeyUp(moveRightKey);
Simulation.SendInput.Keyboard.KeyUp(moveRightKey);
rightKeyDown = false;
}
if (!leftKeyDown)
{
_simulator.KeyDown(moveLeftKey);
Simulation.SendInput.Keyboard.KeyDown(moveLeftKey);
leftKeyDown = true;
}
}
@@ -723,7 +727,9 @@ public class AutoDomainTask : ISoloTask
if (backwardsAndForwardsCount >= _config.LeftRightMoveTimes)
{
// 左右移动5次说明已经在树中心了
_simulator.KeyPress(moveForwardKey, 60);
Simulation.SendInput.Keyboard.KeyDown(moveForwardKey);
Sleep(60);
Simulation.SendInput.Keyboard.KeyUp(moveForwardKey);
Sleep(500, _ct);
treeCts.Cancel();
break;
@@ -842,7 +848,7 @@ public class AutoDomainTask : ISoloTask
break;
}
var useCondensedResinRa = CaptureToRectArea().Find(AutoFightContext.Instance.FightAssets.UseCondensedResinRa);
var useCondensedResinRa = CaptureToRectArea().Find(AutoFightAssets.Instance.UseCondensedResinRa);
if (!useCondensedResinRa.IsEmpty())
{
useCondensedResinRa.Click();
@@ -882,13 +888,13 @@ public class AutoDomainTask : ISoloTask
// 优先点击继续
using var confirmRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
using var confirmRectArea = ra.Find(AutoFightAssets.Instance.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
if (isLastTurn)
{
// 最后一回合 退出
var exitRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ExitRa);
var exitRectArea = ra.Find(AutoFightAssets.Instance.ExitRa);
if (!exitRectArea.IsEmpty())
{
exitRectArea.Click();
@@ -906,7 +912,7 @@ public class AutoDomainTask : ISoloTask
if (condensedResinCount == 0 && fragileResinCount < 20)
{
// 没有体力了退出
var exitRectArea = ra.Find(AutoFightContext.Instance.FightAssets.ExitRa);
var exitRectArea = ra.Find(AutoFightAssets.Instance.ExitRa);
if (!exitRectArea.IsEmpty())
{
exitRectArea.Click();
@@ -937,7 +943,7 @@ public class AutoDomainTask : ISoloTask
var ra = CaptureToRectArea();
// 浓缩树脂
var condensedResinCountRa = ra.Find(AutoFightContext.Instance.FightAssets.CondensedResinCountRa);
var condensedResinCountRa = ra.Find(AutoFightAssets.Instance.CondensedResinCountRa);
if (!condensedResinCountRa.IsEmpty())
{
// 图像右侧就是浓缩树脂数量
@@ -948,7 +954,7 @@ public class AutoDomainTask : ISoloTask
}
// 脆弱树脂
var fragileResinCountRa = ra.Find(AutoFightContext.Instance.FightAssets.FragileResinCountRa);
var fragileResinCountRa = ra.Find(AutoFightAssets.Instance.FragileResinCountRa);
if (!fragileResinCountRa.IsEmpty())
{
// 图像右侧就是脆弱树脂数量
@@ -12,6 +12,7 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
public List<Rect> AvatarSideIconRectList; // 侧边栏角色头像 非联机状态下
public List<Rect> AvatarIndexRectList; // 侧边栏角色头像对应的白色块 非联机状态下
public Rect ERect;
public Rect ECooldownRect;
public Rect QRect;
public Rect EndTipsUpperRect; // 挑战达成提示
public Rect EndTipsRect;
@@ -47,6 +48,8 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
(int)(355 * AssetScale), (int)(465 * AssetScale));
ERect = new Rect(CaptureRect.Width - (int)(267 * AssetScale), CaptureRect.Height - (int)(132 * AssetScale),
(int)(77 * AssetScale), (int)(77 * AssetScale));
ECooldownRect = new Rect(CaptureRect.Width - (int)(241 * AssetScale), CaptureRect.Height - (int)(97 * AssetScale),
(int)(41 * AssetScale), (int)(18 * AssetScale));
QRect = new Rect(CaptureRect.Width - (int)(157 * AssetScale), CaptureRect.Height - (int)(165 * AssetScale),
(int)(110 * AssetScale), (int)(110 * AssetScale));
// 小道具位置 1920-133,800,60,50
@@ -25,6 +25,13 @@ public partial class AutoFightConfig : ObservableObject
/// </summary>
[ObservableProperty]
private bool _fightFinishDetectEnabled = true;
/// <summary>
/// 根据技能CD优化出招人员
/// 根据填入人或人和cd,来决定当此人元素战技cd未结束时,跳过此人出招,来优化战斗流程,可填入人名或人名数字(用逗号分隔),
/// 多种用分号分隔,例如:白术;钟离,12;,如果人名,则用内置cd检查,如果是人名和数字,则把数字当做出招cd(秒)。
/// </summary>
[ObservableProperty] private string _actionSchedulerByCd = "";
[Serializable]
public partial class FightFinishDetectConfig : ObservableObject
{
@@ -1,27 +1,27 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.Model;
// using BetterGenshinImpact.Core.Simulator;
// using BetterGenshinImpact.GameTask.AutoFight.Assets;
// using BetterGenshinImpact.Model;
//
// namespace BetterGenshinImpact.GameTask.AutoFight;
namespace BetterGenshinImpact.GameTask.AutoFight;
/// <summary>
/// 自动战斗上下文
/// 请在启动BetterGI以后再初始化
/// </summary>
public class AutoFightContext : Singleton<AutoFightContext>
{
private AutoFightContext()
{
Simulator = TaskContext.Instance().PostMessageSimulator;
}
/// <summary>
/// find资源
/// </summary>
public AutoFightAssets FightAssets => AutoFightAssets.Instance;
/// <summary>
/// 战斗专用的PostMessage模拟键鼠操作
/// </summary>
public readonly PostMessageSimulator Simulator;
}
// /// <summary>
// /// 自动战斗上下文
// /// 请在启动BetterGI以后再初始化
// /// </summary>
// public class AutoFightContext : Singleton<AutoFightContext>
// {
// private AutoFightContext()
// {
// Simulator = TaskContext.Instance().PostMessageSimulator;
// }
//
// /// <summary>
// /// find资源
// /// </summary>
// public AutoFightAssets FightAssets => AutoFightAssets.Instance;
//
// /// <summary>
// /// 战斗专用的PostMessage模拟键鼠操作
// /// </summary>
// public readonly PostMessageSimulator Simulator;
// }
@@ -26,6 +26,7 @@ public class AutoFightParam : BaseTaskParam
FightFinishDetectEnabled = autoFightConfig.FightFinishDetectEnabled;
PickDropsAfterFightEnabled = autoFightConfig.PickDropsAfterFightEnabled;
KazuhaPickupEnabled = autoFightConfig.KazuhaPickupEnabled;
ActionSchedulerByCd = autoFightConfig.ActionSchedulerByCd;
FinishDetectConfig.FastCheckEnabled = autoFightConfig.FinishDetectConfig.FastCheckEnabled;
FinishDetectConfig.FastCheckParams = autoFightConfig.FinishDetectConfig.FastCheckParams;
@@ -47,6 +48,7 @@ public class AutoFightParam : BaseTaskParam
public int Timeout { get; set; } = 120;
public bool KazuhaPickupEnabled = true;
public string ActionSchedulerByCd = "";
}
@@ -202,6 +202,7 @@ public class AutoFightTask : ISoloTask
throw new Exception("识别队伍角色失败");
}
var actionSchedulerByCd = ParseStringToDictionary(_taskParam.ActionSchedulerByCd);
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
// 新的取消token
@@ -221,7 +222,8 @@ public class AutoFightTask : ISoloTask
return;
}*/
var fightEndFlag = false;
string lastFighttName = "";
string lastFightName = "";
string skipFightName = "";
//统计切换人打架次数
var countFight = 0;
// 战斗操作
@@ -242,6 +244,34 @@ public class AutoFightTask : ISoloTask
break;
}
//根据元素技能冷却事件优化出招流程,只有当人物切换后才会触发检查
double skillCd;
if (lastFightName != command.Name && actionSchedulerByCd.TryGetValue(command.Name,out skillCd))
{
var avatar = combatScenes.SelectAvatar(command.Name);
if (avatar == null)
{
continue;
}
if (skillCd < 0)
{
skillCd = FindMax([avatar.SkillCd,avatar.SkillHoldCd]);
}
var dif=(DateTime.UtcNow - avatar.LastSkillTime);
//当技能未冷却时,跳过此次出招
if ((DateTime.UtcNow -avatar.LastSkillTime).TotalSeconds < skillCd)
{
if (skipFightName != command.Name)
{
Logger.LogInformation($"{command.Name}cd冷却为{skillCd}秒,剩余{skillCd-dif.TotalSeconds}秒,跳过此次行动");
}
skipFightName = command.Name;
continue;
}
}
command.Execute(combatScenes);
//统计战斗人次
if (i == combatCommands.Count - 1 || command.Name != combatCommands[i + 1].Name)
@@ -249,7 +279,7 @@ public class AutoFightTask : ISoloTask
countFight++;
}
lastFighttName = command.Name;
lastFightName = command.Name;
if (!fightEndFlag && _taskParam is { FightFinishDetectEnabled: true })
{
//处于最后一个位置,或者当前执行人和下一个人名字不一样的情况,满足一定条件(开启快速检查,并且检查时间大于0或人名存在配置)检查战斗
@@ -341,12 +371,13 @@ public class AutoFightTask : ISoloTask
{
var time = DateTime.UtcNow - kazuha.LastSkillTime;
//当万叶cd大于3时或战斗人次少于2时(通常无怪物情况下),此时不再触发万叶拾取,
if (!(countFight < 2 || lastFighttName == "枫原万叶" && time.TotalSeconds > 3))
if (!(countFight < 2 || lastFightName == "枫原万叶" && time.TotalSeconds > 3))
{
Logger.LogInformation("使用枫原万叶长E拾取掉落物");
await Delay(300, ct);
if (kazuha.TrySwitch())
{
time = DateTime.UtcNow - kazuha.LastSkillTime;
if (time.TotalMilliseconds > 0 && time.TotalSeconds <= kazuha.SkillHoldCd)
{
Logger.LogInformation("枫原万叶长E技能可能处于冷却中,等待 {Time} s", time.TotalSeconds);
@@ -427,7 +458,7 @@ public class AutoFightTask : ISoloTask
await Delay(450, _ct);
var ra = CaptureToRectArea();
var b3 = ra.SrcMat.At<Vec3b>(50, 790); //进度条颜色
var whiteTile = ra.SrcMat.At<Vec3b>(50, 772); //白块
var whiteTile = ra.SrcMat.At<Vec3b>(50, 768); //白块
if (IsWhite(whiteTile.Item2, whiteTile.Item1, whiteTile.Item0) && IsYellow(b3.Item2, b3.Item1, b3.Item0) /* AreDifferencesWithinBounds(_finishDetectConfig.BattleEndProgressBarColor, (b3.Item0, b3.Item1, b3.Item2), _finishDetectConfig.BattleEndProgressBarColorTolerance)*/)
{
Logger.LogInformation("识别到战斗结束");
@@ -436,7 +467,8 @@ public class AutoFightTask : ISoloTask
}
Simulation.SendInput.SimulateAction(GIActions.Drop);
Logger.LogInformation($"未识别到战斗结束{b3.Item0},{b3.Item1},{b3.Item2}");
Logger.LogInformation($"未识别到战斗结束yellow{b3.Item0},{b3.Item1},{b3.Item2}");
Logger.LogInformation($"未识别到战斗结束white{whiteTile.Item0},{whiteTile.Item1},{whiteTile.Item2}");
/**
if (!Bv.IsInMainUi(ra))
{
@@ -447,10 +479,6 @@ public class AutoFightTask : ISoloTask
_lastFightFlagTime = DateTime.Now;
return false;
// }
return false;
}
bool IsYellow(int r, int g, int b)
@@ -470,6 +498,53 @@ public class AutoFightTask : ISoloTask
(g >= 240 && g <= 255) &&
(b >= 240 && b <= 255);
}
static double FindMax(double[] numbers)
{
if (numbers == null || numbers.Length == 0)
{
throw new ArgumentException("The array is empty or null.");
}
double max = numbers[0]>10000 ? 0 : numbers[0];
foreach (var num in numbers)
{
var cpnum = numbers[0]>10000 ? 0 : num;
max = Math.Max(max, num);
}
return max;
}
private static Dictionary<string, double> ParseStringToDictionary(string input,double defaultValue=-1)
{
var dictionary = new Dictionary<string, double>();
if (string.IsNullOrEmpty(input))
{
return dictionary; // 返回空字典
}
string[] pairs = input.Split(';', StringSplitOptions.RemoveEmptyEntries);
foreach (var pair in pairs)
{
var parts = pair.Split(',', StringSplitOptions.TrimEntries);
if (parts.Length > 0)
{
string name = parts[0];
double value = defaultValue;
if (parts.Length > 1 && double.TryParse(parts[1], out var parsedValue))
{
value = parsedValue;
}
dictionary[name] = value;
}
}
return dictionary;
}
private bool HasFightFlagByYolo(ImageRegion imageRegion)
{
@@ -18,6 +18,7 @@ using BetterGenshinImpact.GameTask.Common.BgiVision;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -55,7 +56,7 @@ public class Avatar
/// 长按元素战技CD
/// </summary>
public double SkillHoldCd { get; set; }
/// <summary>
/// 最近一次使用元素战技的时间
/// </summary>
@@ -119,7 +120,7 @@ public class Avatar
{
Logger.LogWarning("检测到复苏界面,存在角色被击败,前往七天神像复活");
// 先打开地图
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE); // NOTE: 此处按下Esc是为了关闭复苏界面,无需改键
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE); // NOTE: 此处按下Esc是为了关闭复苏界面,无需改键
Sleep(600, Ct);
Simulation.SendInput.SimulateAction(GIActions.OpenMap);
// tp 到七天神像复活
@@ -155,23 +156,24 @@ public class Avatar
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
}
// Debug.WriteLine($"切换到{Index}号位");
// Cv2.ImWrite($"log/切换.png", region.SrcMat);
Sleep(250, Ct);
@@ -210,19 +212,19 @@ public class Avatar
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
@@ -254,23 +256,24 @@ public class Avatar
switch (Index)
{
case 1:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember1);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember1);
break;
case 2:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember2);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember2);
break;
case 3:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember3);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember3);
break;
case 4:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember4);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember4);
break;
case 5:
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SwitchMember5);
Simulation.SendInput.SimulateAction(GIActions.SwitchMember5);
break;
default:
break;
}
Sleep(250);
}
}
@@ -314,7 +317,7 @@ public class Avatar
{
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
// 剪裁出队伍区域
var teamRa = region.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRect);
var teamRa = region.DeriveCrop(AutoFightAssets.Instance.TeamRect);
var blockX = NameRect.X + NameRect.Width * 2 - 10;
var block = teamRa.DeriveCrop(new Rect(blockX, NameRect.Y, teamRa.Width - blockX, NameRect.Height * 2));
// Cv2.ImWrite($"block_{Name}.png", block.SrcMat);
@@ -337,7 +340,7 @@ public class Avatar
else
{
// 剪裁出IndexRect区域
var teamRa = region.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRect);
var teamRa = region.DeriveCrop(AutoFightAssets.Instance.TeamRect);
var blockX = NameRect.X + NameRect.Width * 2 - 10;
var indexBlock = teamRa.DeriveCrop(new Rect(blockX + IndexRect.X, NameRect.Y + IndexRect.Y, IndexRect.Width, IndexRect.Height));
// Cv2.ImWrite($"indexBlock_{Name}.png", indexBlock.SrcMat);
@@ -365,7 +368,7 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
ms -= 200;
Sleep(200, Ct);
}
@@ -387,7 +390,7 @@ public class Avatar
{
if (Name == "纳西妲")
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Sleep(300, Ct);
for (int j = 0; j < 10; j++)
{
@@ -396,22 +399,22 @@ public class Avatar
}
Sleep(300); // 持续操作不应该被cts取消
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
}
else if (Name == "坎蒂丝")
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyDown);
Thread.Sleep(3000);
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyUp);
}
else
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.Hold);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.Hold);
}
}
else
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalSkill, KeyType.KeyPress);
Simulation.SendInput.SimulateAction(GIActions.ElementalSkill, KeyType.KeyPress);
}
Sleep(200, Ct);
@@ -436,8 +439,9 @@ public class Avatar
/// </summary>
public double GetSkillCurrentCd(ImageRegion imageRegion)
{
var eRa = imageRegion.DeriveCrop(AutoFightContext.Instance.FightAssets.ERect);
var text = OcrFactory.Paddle.Ocr(eRa.SrcGreyMat);
var eRa = imageRegion.DeriveCrop(AutoFightAssets.Instance.ECooldownRect);
var eRaWhite = OpenCvCommonHelper.InRangeHsv(eRa.SrcMat, new Scalar(0, 0, 235), new Scalar(0, 25, 255));
var text = OcrFactory.Paddle.OcrWithoutDetector(eRaWhite);
return StringUtils.TryParseDouble(text);
}
@@ -455,7 +459,7 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.ElementalBurst);
Simulation.SendInput.SimulateAction(GIActions.ElementalBurst);
Sleep(200, Ct);
var region = CaptureToRectArea();
@@ -490,7 +494,7 @@ public class Avatar
// /// </summary>
// public double GetBurstCurrentCd(CaptureContent content)
// {
// var qRa = content.CaptureRectArea.Crop(AutoFightContext.Instance.FightAssets.QRect);
// var qRa = content.CaptureRectArea.Crop(AutoFightAssets.Instance.QRect);
// var text = OcrFactory.Paddle.Ocr(qRa.SrcGreyMat);
// return StringUtils.TryParseDouble(text);
// }
@@ -510,9 +514,9 @@ public class Avatar
ms = 200;
}
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SprintMouse, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.SprintMouse, KeyType.KeyDown);
Sleep(ms); // 冲刺不能被cts取消
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.SprintMouse, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.SprintMouse, KeyType.KeyUp);
}
public void Walk(string key, int ms)
@@ -545,9 +549,9 @@ public class Avatar
return;
}
AutoFightContext.Instance.Simulator.KeyDown(vk);
Simulation.SendInput.Keyboard.KeyDown(vk);
Sleep(ms); // 行走不能被cts取消
AutoFightContext.Instance.Simulator.KeyUp(vk);
Simulation.SendInput.Keyboard.KeyUp(vk);
}
/// <summary>
@@ -574,7 +578,7 @@ public class Avatar
/// </summary>
public void Jump()
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.Jump);
Simulation.SendInput.SimulateAction(GIActions.Jump);
}
/// <summary>
@@ -590,7 +594,7 @@ public class Avatar
if (Name == "那维莱特")
{
var dpi = TaskContext.Instance().DpiScale;
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
while (ms >= 0)
{
if (Ct is { IsCancellationRequested: true })
@@ -603,13 +607,13 @@ public class Avatar
Sleep(50); // 持续操作不应该被cts取消
}
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
}
else
{
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack, KeyType.KeyDown);
Sleep(ms); // 持续操作不应该被cts取消
AutoFightContext.Instance.Simulator.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
Simulation.SendInput.SimulateAction(GIActions.NormalAttack, KeyType.KeyUp);
}
}
@@ -618,11 +622,11 @@ public class Avatar
key = key.ToLower();
if (key == "left")
{
AutoFightContext.Instance.Simulator.LeftButtonDown();
Simulation.SendInput.Mouse.LeftButtonDown();
}
else if (key == "right")
{
AutoFightContext.Instance.Simulator.RightButtonDown();
Simulation.SendInput.Mouse.RightButtonDown();
}
else if (key == "middle")
{
@@ -635,11 +639,11 @@ public class Avatar
key = key.ToLower();
if (key == "left")
{
AutoFightContext.Instance.Simulator.LeftButtonUp();
Simulation.SendInput.Mouse.LeftButtonUp();
}
else if (key == "right")
{
AutoFightContext.Instance.Simulator.RightButtonUp();
Simulation.SendInput.Mouse.RightButtonUp();
}
else if (key == "middle")
{
@@ -652,11 +656,11 @@ public class Avatar
key = key.ToLower();
if (key == "left")
{
AutoFightContext.Instance.Simulator.LeftButtonClick();
Simulation.SendInput.Mouse.LeftButtonClick();
}
else if (key == "right")
{
AutoFightContext.Instance.Simulator.RightButtonClick();
Simulation.SendInput.Mouse.RightButtonClick();
}
else if (key == "middle")
{
@@ -672,18 +676,18 @@ public class Avatar
public void KeyDown(string key)
{
var vk = User32Helper.ToVk(key);
AutoFightContext.Instance.Simulator.KeyDown(vk);
Simulation.SendInput.Keyboard.KeyDown(vk);
}
public void KeyUp(string key)
{
var vk = User32Helper.ToVk(key);
AutoFightContext.Instance.Simulator.KeyUp(vk);
Simulation.SendInput.Keyboard.KeyUp(vk);
}
public void KeyPress(string key)
{
var vk = User32Helper.ToVk(key);
AutoFightContext.Instance.Simulator.KeyPress(vk);
Simulation.SendInput.Keyboard.KeyPress(vk);
}
}
}
@@ -19,6 +19,7 @@ using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Threading;
using BetterGenshinImpact.Core.Simulator;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight.Model;
@@ -31,7 +32,7 @@ public class CombatScenes : IDisposable
/// <summary>
/// 当前配队
/// </summary>
public Avatar[] Avatars { get; set; } = Array.Empty<Avatar>();
public Avatar[] Avatars { get; set; } = [];
public Dictionary<string, Avatar> AvatarMap { get; set; } = [];
@@ -70,6 +71,7 @@ public class CombatScenes : IDisposable
{
throw new Exception("当前处于联机状态,但是队伍人数超过4人,无法识别");
}
// 联机状态下判断
var onePRa = imageRegion.Find(AutoFightAssets.Instance.OnePRa);
var p = "p";
@@ -167,7 +169,7 @@ public class CombatScenes : IDisposable
if (result.TopClass.Confidence < 0.51)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读了文档中的《快速上手》!");
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
}
}
else
@@ -175,7 +177,7 @@ public class CombatScenes : IDisposable
if (result.TopClass.Confidence < 0.7)
{
Cv2.ImWrite(@"log\avatar_side_classify_error.png", src.ToMat());
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读了文档中的《快速上手》!");
throw new Exception($"无法识别第{index}位角色,置信度{result.TopClass.Confidence:F1},结果:{result.TopClass.Name.Name}。请重新阅读 BetterGI 文档中的《快速上手》!");
}
}
@@ -216,7 +218,7 @@ public class CombatScenes : IDisposable
{
if (avatarIndexRectList == null && ExpectedTeamAvatarNum == 4)
{
avatarIndexRectList = AutoFightContext.Instance.FightAssets.AvatarIndexRectList;
avatarIndexRectList = AutoFightAssets.Instance.AvatarIndexRectList;
}
if (avatarIndexRectList == null)
@@ -246,6 +248,24 @@ public class CombatScenes : IDisposable
}
}
public void AfterTask()
{
// 释放所有按键
Simulation.ReleaseAllKey();
var mwk = SelectAvatar("玛薇卡");
if (mwk != null)
{
foreach (var avatar in Avatars)
{
if (avatar.Name != "玛薇卡")
{
avatar.Switch();
}
}
}
}
public Avatar? SelectAvatar(string name)
{
return AvatarMap.GetValueOrDefault(name);
@@ -268,7 +288,7 @@ public class CombatScenes : IDisposable
}
// 剪裁出队伍区域
var teamRa = content.CaptureRectArea.DeriveCrop(AutoFightContext.Instance.FightAssets.TeamRectNoIndex);
var teamRa = content.CaptureRectArea.DeriveCrop(AutoFightAssets.Instance.TeamRectNoIndex);
// 过滤出白色
var hsvFilterMat = OpenCvCommonHelper.InRangeHsv(teamRa.SrcMat, new Scalar(0, 0, 210), new Scalar(255, 30, 255));
@@ -303,10 +323,10 @@ public class CombatScenes : IDisposable
{
// 流浪者特殊处理
// 4人以上的队伍,不支持流浪者的识别
var wanderer = rectArea.Find(AutoFightContext.Instance.FightAssets.WandererIconRa);
var wanderer = rectArea.Find(AutoFightAssets.Instance.WandererIconRa);
if (wanderer.IsEmpty())
{
wanderer = rectArea.Find(AutoFightContext.Instance.FightAssets.WandererIconNoActiveRa);
wanderer = rectArea.Find(AutoFightAssets.Instance.WandererIconNoActiveRa);
}
if (wanderer.IsEmpty())
@@ -381,4 +401,4 @@ public class CombatScenes : IDisposable
{
_predictor.Dispose();
}
}
}
@@ -67,35 +67,34 @@ public class CombatCommand
public void Execute(CombatScenes combatScenes)
{
// 如果是当前角色
Avatar? avatar;
if (Name == CombatScriptParser.CurrentAvatarName)
{
// 如果是当前角色,不进行角色切换
avatar = combatScenes.Avatars[0]; // 随便取一个角色
}
else
{
// 其余情况要进行角色切换
avatar = combatScenes.SelectAvatar(Name);
if (avatar == null)
{
return;
}
// 非宏类脚本,等待切换角色成功
if (Method != Method.Wait
&& Method != Method.MouseDown
&& Method != Method.MouseUp
&& Method != Method.Click
&& Method != Method.MoveBy
&& Method != Method.KeyDown
&& Method != Method.KeyUp
&& Method != Method.KeyPress)
{
avatar.Switch();
}
}
if (avatar == null)
{
return;
}
// 非宏类脚本,等待切换角色成功
if (Method != Method.Wait
&& Method != Method.MouseDown
&& Method != Method.MouseUp
&& Method != Method.Click
&& Method != Method.MoveBy
&& Method != Method.KeyDown
&& Method != Method.KeyUp
&& Method != Method.KeyPress)
{
avatar.Switch();
}
Execute(avatar);
}
@@ -1,5 +1,7 @@
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation;
@@ -9,9 +11,17 @@ public class AutoGeniusInvokationTask(GeniusInvokationTaskParam taskParam) : ISo
public Task Start(CancellationToken ct)
{
// 读取策略信息
var duel = ScriptParser.Parse(taskParam.StrategyContent);
duel.Run(ct);
try
{
// 读取策略信息
var duel = ScriptParser.Parse(taskParam.StrategyContent);
duel.Run(ct);
}
catch (System.Exception e)
{
TaskControl.Logger.LogDebug(e, "执行自动七圣召唤任务异常");
TaskControl.Logger.LogError("执行自动七圣召唤任务异常:{Exception}", e.Message);
}
return Task.CompletedTask;
}
}
}
@@ -10,6 +10,7 @@ using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Service.Notification.Model.Enum;
namespace BetterGenshinImpact.GameTask.AutoGeniusInvokation.Model;
@@ -60,9 +61,10 @@ public class Duel
LogScreenResolution();
try
{
Notify.Event(NotificationEvent.TcgStart).Success("自动七胜召唤启动");
AutoGeniusInvokationAssets.DestroyInstance();
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Started().Build()); // TODO 需要移动
GeniusInvokationControl.GetInstance().Init(ct);
// 对局准备 选择初始手牌
@@ -288,14 +290,12 @@ public class Duel
}
catch (TaskCanceledException ex)
{
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Cancelled().Build());
throw;
}
catch (NormalEndException ex)
{
_logger.LogInformation("对局结束");
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Success().Build());
throw;
// throw;
}
catch (System.Exception ex)
{
@@ -303,9 +303,10 @@ public class Duel
{
_logger.LogError(ex.StackTrace);
}
NotificationHelper.SendTaskNotificationUsing(b => b.GeniusInvocation().Failure().Build());
throw;
}
Notify.Event(NotificationEvent.TcgEnd).Success("自动七胜召唤结束");
}
private HashSet<ElementalType> PredictionDiceType()
@@ -117,7 +117,7 @@ public class ScriptParser
var characterAndSkill = line.Split('{');
var parts = characterAndSkill[0].Split('=');
character.Index = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(parts[0], ""));
character.Index = int.Parse(RegexHelper.ExcludeNumberRegex().Replace(parts[0].Trim(), ""));
MyAssert(character.Index >= 1 && character.Index <= 3, "角色序号必须在1-3之间");
if (parts[1].Contains('|'))
@@ -1,10 +1,15 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoMusicGame.Assets;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -24,21 +29,38 @@ public class AutoAlbumTask(AutoMusicGameParam taskParam) : ISoloTask
try
{
AutoMusicGameTask.Init();
Notify.Event(NotificationEvent.AlbumStart).Success("自动音游专辑启动");
Logger.LogInformation("开始自动演奏整个专辑未完成的音乐");
await StartOneAlbum(ct);
Notify.Event(NotificationEvent.AlbumEnd).Success("自动音游专辑结束");
}
catch (NormalEndException e)
{
Logger.LogError("手动取消任务 - {Msg}", e.Message);
}
catch (Exception e)
{
Logger.LogError("自动音乐专辑任务异常:{Msg}", e.Message);
Notify.Event(NotificationEvent.AlbumError).Error("自动音游专辑异常", e);
}
}
public async Task StartOneAlbum(CancellationToken ct)
{
using var iconRa = CaptureToRectArea().Find(AutoMusicAssets.Instance.UiLeftTopAlbumIcon);
using var ra1 = CaptureToRectArea();
using var iconRa = ra1.Find(AutoMusicAssets.Instance.UiLeftTopAlbumIcon);
if (!iconRa.IsExist())
{
throw new Exception("当前未处于专辑界面,请在专辑界面运行本任务");
throw new Exception("当前未处于主题专辑界面,请在专辑界面运行本任务。注意全部歌曲列表页面无法运行本任务!");
}
else
{
// OCR 后再次判断,区分是否是全部歌曲页面
var ocrRes = ra1.DeriveCrop(iconRa.Right, iconRa.Top, ra1.Width * 0.16, iconRa.Height).FindMulti(RecognitionObject.OcrThis);
if (ocrRes.Any(region => region.Text.Contains("全部")))
{
throw new Exception("当前在全部歌曲页面,此页面无法运行本任务。请返回到主界面选择专辑列表中以国家为主题的专辑页!");
}
}
var musicLevel = TaskContext.Instance().Config.AutoMusicGameConfig.MusicLevel;
@@ -46,13 +68,14 @@ public class AutoAlbumTask(AutoMusicGameParam taskParam) : ISoloTask
{
musicLevel = "传说";
}
Logger.LogInformation("自动音游乐曲难度等级:{Text}", musicLevel);
// 遍历4个难度等级
var defaultDifficultyLevels = new[]
{
("普通", 480, 600, AutoMusicAssets.Instance.MusicCanorusLevel1),
("困难", 800, 600, AutoMusicAssets.Instance.MusicCanorusLevel2),
("困难", 800, 600, AutoMusicAssets.Instance.MusicCanorusLevel2),
("大师", 1150, 600, AutoMusicAssets.Instance.MusicCanorusLevel3),
("传说", 1400, 600, AutoMusicAssets.Instance.MusicCanorusLevel4)
};
@@ -66,34 +89,51 @@ public class AutoAlbumTask(AutoMusicGameParam taskParam) : ISoloTask
foreach (var (difficultyName, xPos, yPos, canorusAsset) in difficultyLevels)
{
Logger.LogInformation("开始演奏{Difficulty}难度的乐曲", difficultyName);
// 每个难度12首曲子
for (int i = 0; i < 13; i++)
{
using var canoraRa = CaptureToRectArea().Find(canorusAsset);
if (canoraRa.IsExist())
if (TaskContext.Instance().Config.AutoMusicGameConfig.MustCanorusLevel)
{
Logger.LogInformation("乐曲{Num} - {Difficulty}级别:已完成【大音天籁】,切换下一首", i + 1, difficultyName);
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
continue;
using var canoraRa = CaptureToRectArea().Find(canorusAsset);
if (canoraRa.IsExist())
{
Logger.LogInformation("乐曲{Num} - {Difficulty}级别:已完成【大音天籁】,切换下一首", i + 1, difficultyName);
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
continue;
}
Logger.LogInformation("第{Num}首{Difficulty}难度的乐曲:{Message}", i + 1, difficultyName, "没有完成【大音天籁】");
}
else
{
using var doneRa = CaptureToRectArea().Find(AutoMusicAssets.Instance.AlbumMusicComplate);
if (doneRa.IsExist())
{
Logger.LogInformation("当前乐曲{Num}所有奖励已领取,切换下一首", i + 1);
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
continue;
}
Logger.LogInformation("当前乐曲{Num}存在未领取奖励,前往演奏", i + 1);
}
Logger.LogInformation("第{Num}首{Difficulty}难度的乐曲:{Message}", i + 1, difficultyName, "没有完成【大音天籁】");
// 点击确认按钮
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(800, ct);
// 选择难度
GameCaptureRegion.GameRegion1080PPosClick(xPos, yPos);
await Delay(200, ct);
// 开始演奏
Bv.ClickWhiteConfirmButton(CaptureToRectArea());
await Delay(500, ct);
using var cts = new CancellationTokenSource();
var cts = new CancellationTokenSource();
ct.Register(cts.Cancel);
// 演奏结束检查任务
@@ -118,16 +158,16 @@ public class AutoAlbumTask(AutoMusicGameParam taskParam) : ISoloTask
// 等待任意一个任务完成
await Task.WhenAny(checkTask, musicTask);
await cts.CancelAsync();
Logger.LogInformation("第{Num}首{Difficulty}难度乐曲演奏完成", i + 1, difficultyName);
await Delay(2000, ct);
await Bv.WaitUntilFound(AutoMusicAssets.Instance.UiLeftTopAlbumIcon, ct);
Logger.LogDebug("切换到下一首乐曲");
GameCaptureRegion.GameRegion1080PPosClick(310, 220);
await Delay(800, ct);
}
Logger.LogInformation("完成{Difficulty}难度所有乐曲的演奏", difficultyName);
}
@@ -11,6 +11,10 @@ namespace BetterGenshinImpact.GameTask.AutoMusicGame;
[Serializable]
public partial class AutoMusicGameConfig : ObservableObject
{
// 自动达到大音天籁的级别
[ObservableProperty]
private bool _mustCanorusLevel = false;
// 乐曲级别
[ObservableProperty]
private string _musicLevel = "";
@@ -22,6 +22,7 @@ public class ActionFactory
"hydro_collect" => new ElementalCollectHandler(ElementalType.Hydro),
"electro_collect" => new ElementalCollectHandler(ElementalType.Electro),
"anemo_collect" => new ElementalCollectHandler(ElementalType.Anemo),
"pyro_collect" => new ElementalCollectHandler(ElementalType.Pyro),
"combat_script" => new CombatScriptHandler(),
"mining" => new MiningHandler(),
_ => throw new ArgumentException("未知的后置 action 类型")
@@ -112,12 +112,26 @@ public class ElementalCollectAvatarConfigs
new ElementalCollectAvatar("鹿野院平藏", ElementalType.Anemo, true, true),
new ElementalCollectAvatar("流浪者", ElementalType.Anemo, true, false),
new ElementalCollectAvatar("闲云", ElementalType.Anemo, true, false),
new ElementalCollectAvatar("蓝砚", ElementalType.Anemo, true, false),
new ElementalCollectAvatar("枫原万叶", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("珐露珊", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("琳妮特", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("温迪", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("琴", ElementalType.Anemo, false, true),
new ElementalCollectAvatar("早柚", ElementalType.Anemo, false, true),
// 火
new ElementalCollectAvatar("烟绯", ElementalType.Pyro, true, true),
new ElementalCollectAvatar("迪卢克", ElementalType.Pyro, false,true),
new ElementalCollectAvatar("可莉", ElementalType.Pyro, true, true),
new ElementalCollectAvatar("班尼特", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("香菱", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("托马", ElementalType.Pyro,false, true),
new ElementalCollectAvatar("胡桃", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("迪希雅", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("夏沃蕾", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("辛焱", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("林尼", ElementalType.Pyro, false, true),
new ElementalCollectAvatar("宵宫", ElementalType.Pyro, false, true),
];
public static ElementalCollectAvatar? Get(string name, ElementalType type) => Lists.FirstOrDefault(x => x.Name == name && x.ElementalType == type);
@@ -2,23 +2,23 @@
namespace BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
public class ActionEnum(string code, string msg)
public class ActionEnum(string code, string msg, ActionUseWaypointTypeEnum useWaypointTypeEnum)
{
public static readonly ActionEnum StopFlying = new("stop_flying", "下落攻击");
public static readonly ActionEnum ForceTp = new("force_tp", "当前点传送");
public static readonly ActionEnum NahidaCollect = new("nahida_collect", "纳西妲长按E收集");
public static readonly ActionEnum PickAround = new("pick_around", "尝试在周围拾取");
public static readonly ActionEnum Fight = new("fight", "战斗");
public static readonly ActionEnum UpDownGrabLeaf = new("up_down_grab_leaf", "四叶印");
public static readonly ActionEnum StopFlying = new("stop_flying", "下落攻击", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum ForceTp = new("force_tp", "当前点传送", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum NahidaCollect = new("nahida_collect", "纳西妲长按E收集", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum PickAround = new("pick_around", "尝试在周围拾取", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum Fight = new("fight", "战斗", ActionUseWaypointTypeEnum.Path);
public static readonly ActionEnum UpDownGrabLeaf = new("up_down_grab_leaf", "四叶印", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum HydroCollect = new("hydro_collect", "水元素力采集");
public static readonly ActionEnum ElectroCollect = new("electro_collect", "雷元素力采集");
public static readonly ActionEnum AnemoCollect = new("anemo_collect", "风元素力采集");
public static readonly ActionEnum CombatScript = new("combat_script", "战斗策略脚本"); // 这个必须要 action_params 里面有脚本
public static readonly ActionEnum Mining = new("mining", "挖矿");
public static readonly ActionEnum LogOutput = new("log_output", "输出日志");
public static readonly ActionEnum HydroCollect = new("hydro_collect", "水元素力采集", ActionUseWaypointTypeEnum.Target);
public static readonly ActionEnum ElectroCollect = new("electro_collect", "雷元素力采集", ActionUseWaypointTypeEnum.Target);
public static readonly ActionEnum AnemoCollect = new("anemo_collect", "风元素力采集", ActionUseWaypointTypeEnum.Target);
public static readonly ActionEnum CombatScript = new("combat_script", "战斗策略脚本", ActionUseWaypointTypeEnum.Custom); // 这个必须要 action_params 里面有脚本
public static readonly ActionEnum Mining = new("mining", "挖矿", ActionUseWaypointTypeEnum.Custom);
public static readonly ActionEnum LogOutput = new("log_output", "输出日志", ActionUseWaypointTypeEnum.Custom);
// 还有要加入的其他动作
// 滚轮F
@@ -29,15 +29,32 @@ public class ActionEnum(string code, string msg)
public static IEnumerable<ActionEnum> Values
{
get
{
yield return StopFlying;
}
get { yield return StopFlying; }
}
public string Code { get; private set; } = code;
public string Msg { get; private set; } = msg;
public ActionUseWaypointTypeEnum UseWaypointTypeEnum { get; private set; } = useWaypointTypeEnum;
public static ActionEnum? GetEnumByCode(string? code)
{
if (string.IsNullOrEmpty(code))
{
return null;
}
foreach (var item in Values)
{
if (item.Code == code)
{
return item;
}
}
return null;
}
public static string GetMsgByCode(string code)
{
foreach (var item in Values)
@@ -47,6 +64,14 @@ public class ActionEnum(string code, string msg)
return item.Msg;
}
}
return code;
}
}
public enum ActionUseWaypointTypeEnum
{
Custom, // 跟随路径点 Type
Path, // 强制 Path
Target // 强制 Target
}
@@ -6,6 +6,7 @@ public class MoveModeEnum(string code, string msg)
{
public static readonly MoveModeEnum Walk = new("walk", "步行");
public static readonly MoveModeEnum Run = new("run", "奔跑");
public static readonly MoveModeEnum Dash = new("dash", "持续冲刺");
public static readonly MoveModeEnum Climb = new("climb", "攀爬");
public static readonly MoveModeEnum Fly = new("fly", "飞行");
public static readonly MoveModeEnum Jump = new("jump", "跳跃");
@@ -7,6 +7,7 @@ public class WaypointType(string code, string msg)
public static readonly WaypointType Path = new("path", "途径点");
public static readonly WaypointType Target = new("target", "目标点");
public static readonly WaypointType Teleport = new("teleport", "传送点");
public static readonly WaypointType Orientation = new("orientation", "方位点");
public static IEnumerable<WaypointType> Values
{
@@ -15,6 +16,7 @@ public class WaypointType(string code, string msg)
yield return Path;
yield return Target;
yield return Teleport;
yield return Orientation;
}
}
@@ -143,7 +143,7 @@ public class PathExecutor
{
return;
}
InitializePathing(task);
// 转换、按传送点分割路径
var waypointsList = ConvertWaypointsForTrack(task.Positions);
@@ -154,13 +154,13 @@ public class PathExecutor
foreach (var waypoints in waypointsList) // 按传送点分割的路径
{
CurWaypoints = (waypointsList.FindIndex(wps => wps == waypoints), waypoints);
for (var i = 0; i < RetryTimes; i++)
{
try
{
await ResolveAnomalies(); // 异常场景处理
foreach (var waypoint in waypoints) // 一条路径
foreach (var waypoint in waypoints) // 一条路径
{
CurWaypoint = (waypoints.FindIndex(wps => wps == waypoint), waypoint);
TryCloseSkipOtherOperations();
@@ -179,20 +179,22 @@ public class PathExecutor
await BeforeMoveToTarget(waypoint);
// Path不用走得很近,Target需要接近,但都需要先移动到对应位置
await MoveTo(waypoint);
if (waypoint.Type == WaypointType.Target.Code
// 除了 fight mining stop_flying 之外的 action 都需要接近
|| (!string.IsNullOrEmpty(waypoint.Action)
&& waypoint.Action != ActionEnum.NahidaCollect.Code
&& waypoint.Action != ActionEnum.Fight.Code
&& waypoint.Action != ActionEnum.CombatScript.Code
&& waypoint.Action != ActionEnum.Mining.Code))
if (waypoint.Type == WaypointType.Orientation.Code)
{
if (waypoint.Action != ActionEnum.Fight.Code) // 战斗action强制不接近
{
await MoveCloseTo(waypoint);
}
// 方位点,只需要朝向
// 考虑到方位点大概率是作为执行action的最后一个点,所以放在此处处理,不和传送点一样单独处理
await FaceTo(waypoint);
}
else
{
await MoveTo(waypoint);
}
await BeforeMoveCloseToTarget(waypoint);
if (IsTargetPoint(waypoint))
{
await MoveCloseTo(waypoint);
}
//skipOtherOperations如果重试,则跳过相关操作,
@@ -251,6 +253,25 @@ public class PathExecutor
}
}
private bool IsTargetPoint(WaypointForTrack waypoint)
{
// 方位点不需要接近
if (waypoint.Type == WaypointType.Orientation.Code)
{
return false;
}
var action = ActionEnum.GetEnumByCode(waypoint.Action);
if (action is not null && action.UseWaypointTypeEnum != ActionUseWaypointTypeEnum.Custom)
{
// 强制点位类型的 action,以 action 为准
return action.UseWaypointTypeEnum == ActionUseWaypointTypeEnum.Target;
}
// 其余情况和没有action的情况以点位类型为准
return waypoint.Type == WaypointType.Target.Code;
}
private async Task<bool> SwitchPartyBefore(PathingTask task)
{
var ra = CaptureToRectArea();
@@ -564,6 +585,16 @@ public class PathExecutor
await Delay(500, ct); // 多等一会
}
private async Task FaceTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = await GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("朝向点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
await Delay(500, ct);
}
private async Task MoveTo(WaypointForTrack waypoint)
{
// 切人
@@ -680,7 +711,23 @@ public class PathExecutor
// 只有设置为run才会一直疾跑
if (waypoint.MoveMode == MoveModeEnum.Run.Code)
{
if (distance > 25) // 距离大于25时可以使用疾跑
if (distance > 20 != fastMode) // 距离大于20时可以使用疾跑/自由泳
{
if (fastMode)
{
Simulation.SendInput.SimulateAction(GIActions.SprintMouse, KeyType.KeyUp);
}
else
{
Simulation.SendInput.SimulateAction(GIActions.SprintMouse, KeyType.KeyDown);
}
fastMode = !fastMode;
}
}
else if (waypoint.MoveMode == MoveModeEnum.Dash.Code)
{
if (distance > 20) // 距离大于25时可以使用疾跑
{
if (Math.Abs((fastModeColdTime - DateTime.UtcNow).TotalMilliseconds) > 1000) //冷却一会
{
@@ -790,20 +837,11 @@ public class PathExecutor
private async Task MoveCloseTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = await GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
ImageRegion screen;
Point2f position;
int targetOrientation;
Logger.LogInformation("精确接近目标点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
if (waypoint.MoveMode == MoveModeEnum.Fly.Code && waypoint.Action == ActionEnum.StopFlying.Code)
{
//下落攻击接近目的地
Logger.LogInformation("动作:下落攻击");
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1000, ct);
return;
}
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
var stepsTaken = 0;
while (!ct.IsCancellationRequested)
{
@@ -841,6 +879,17 @@ public class PathExecutor
await Delay(1000, ct);
}
private async Task BeforeMoveCloseToTarget(WaypointForTrack waypoint)
{
if (waypoint.MoveMode == MoveModeEnum.Fly.Code && waypoint.Action == ActionEnum.StopFlying.Code)
{
//下落攻击接近目的地
Logger.LogInformation("动作:下落攻击");
Simulation.SendInput.SimulateAction(GIActions.NormalAttack);
await Delay(1000, ct);
}
}
private async Task BeforeMoveToTarget(WaypointForTrack waypoint)
{
if (waypoint.Action == ActionEnum.UpDownGrabLeaf.Code)
@@ -952,6 +1001,8 @@ public class PathExecutor
{
_autoSkipTrigger = new AutoSkipTrigger(new AutoSkipConfig
{
QuicklySkipConversationsEnabled = true, // 快速点击过剧情
ClosePopupPagedEnabled = true,
ClickChatOption = "优先选择最后一个选项",
});
_autoSkipTrigger.Init();
@@ -63,13 +63,11 @@ public class AutoTrackTask(AutoTrackParam param) : BaseIndependentTask
catch (NormalEndException e)
{
Logger.LogInformation("自动追踪中断:" + e.Message);
// NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Cancelled().Build());
}
catch (Exception e)
{
Logger.LogError(e.Message);
Logger.LogDebug(e.StackTrace);
// NotificationHelper.SendTaskNotificationWithScreenshotUsing(b => b.Domain().Failure().Build());
}
finally
{
@@ -0,0 +1,64 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
public partial class TpConfig : ObservableObject
{
[ObservableProperty]
private bool _mapZoomEnabled = true; // 地图缩放开关
[ObservableProperty]
private int _mapZoomOutDistance = 1000; // 地图缩小的最小距离,单位:像素
[ObservableProperty]
private int _mapZoomInDistance = 400; // 地图放大的最大距离,单位:像素
[ObservableProperty]
private int _stepIntervalMilliseconds = 20; // 鼠标移动时间间隔,单位:ms
[ObservableProperty]
private double _maxZoomLevel = 5.0; // 最大缩放等级
[ObservableProperty]
private double _minZoomLevel = 2.0; // 最小缩放等级
[ObservableProperty]
private double _reviveStatueOfTheSevenPointX = 2296.4; // 七天神像点位X坐标
[ObservableProperty]
private double _reviveStatueOfTheSevenPointY = -824.4; // 七天神像点位Y坐标
[ObservableProperty]
[property: JsonIgnore]
private int _zoomOutButtonY = 654; // y-coordinate for zoom-out button
[ObservableProperty]
[property: JsonIgnore]
private int _zoomInButtonY = 428; // y-coordinate for zoom-in button
[ObservableProperty]
[property: JsonIgnore]
private int _zoomButtonX = 49; // x-coordinate for zoom button
[ObservableProperty]
[property: JsonIgnore]
private int _zoomStartY = 453; // y-coordinate for zoom start
[ObservableProperty]
[property: JsonIgnore]
private int _zoomEndY = 628; // y-coordinate for zoom end
[ObservableProperty]
private double _tolerance = 200; // 允许的移动误差
[ObservableProperty]
private int _maxIterations = 30; // 移动最大次数
[ObservableProperty]
private int _maxMouseMove = 300; // 单次移动最大距离
[ObservableProperty]
private double _mapScaleFactor = 2.661; // 游戏坐标和 mapZoomLevel=1 时的像素比例因子。
}
@@ -1,28 +1,29 @@
using BetterGenshinImpact.Core.Recognition;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Core.Simulator.Extensions;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.Core.Script.Dependence;
using Microsoft.Diagnostics.Utilities;
using Log = Serilog.Log;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -34,89 +35,17 @@ public class TpTask(CancellationToken ct)
private readonly QuickTeleportAssets _assets = QuickTeleportAssets.Instance;
private readonly Rect _captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
private readonly double _zoomOutMax1080PRatio = TaskContext.Instance().SystemInfo.ZoomOutMax1080PRatio;
private readonly TpConfig _tpConfig = TaskContext.Instance().Config.TpConfig;
private static double ReviveStatueOfTheSevenPointX = 2296.4;
private static double ReviveStatueOfTheSevenPointY = -824.4;
private static int zoomOutButtonY = 654; // y-coordinate for zoom-out button
private static int zoomInButtonY = 428; // y-coordinate for zoom-in button
private static int zoomButtonX = 49; // x-coordinate for zoom button
private static int zoomStartY = 453; // y-coordinate for zoom start
private static int zoomEndY = 628; // y-coordinate for zoom end
private static bool _mapZoomEnabled = true;
private static int _mapZoomOutDistance = 1000;
private static int _mapZoomInDistance = 400;
private static int _stepIntervalMilliseconds = 20;
public static bool MapZoomEnabled
{
get => _mapZoomEnabled;
set
{
_mapZoomEnabled = value;
if(!value)
{
Logger.LogInformation("禁用了缩放功能,请自行调整合适的缩放,部分脚本可能会因为禁用缩放功能无法使用");
}
}
}
public static int MapZoomOutDistance
{
get => _mapZoomOutDistance;
set
{
if (value < 500 || value > 5000) // 自动设置合理范围
{
_mapZoomOutDistance = 1000;
}
if (value <= _mapZoomInDistance)
{
_mapZoomOutDistance = _mapZoomInDistance * 2;
}
_mapZoomOutDistance = value;
}
}
public static int MapZoomInDistance
{
get => _mapZoomInDistance;
set
{
if (value < 200 || value > 1000) // 自动设置合理范围
{
_mapZoomInDistance = 400;
}
if (value >= _mapZoomOutDistance)
{
_mapZoomInDistance = _mapZoomOutDistance / 2;
}
_mapZoomInDistance = value;
}
}
public static int StepIntervalMilliseconds
{
get => _stepIntervalMilliseconds;
set
{
if (value < 5 || value > 100)
{
_stepIntervalMilliseconds = 20;
}
_stepIntervalMilliseconds = value;
}
}
/// <summary>
/// 传送到须弥七天神像
/// </summary>
public async Task TpToStatueOfTheSeven()
{
await CheckInBigMapUi();
if (_mapZoomEnabled)
if (_tpConfig.MapZoomEnabled)
{
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
bool tempMapZoomEnable = _mapZoomEnabled;
_mapZoomEnabled = false; // 临时禁用缩放功能
if (currentZoomLevel > 4.5)
{
await AdjustMapZoomLevel(currentZoomLevel, 4.5);
@@ -125,52 +54,71 @@ public class TpTask(CancellationToken ct)
{
await AdjustMapZoomLevel(currentZoomLevel, 3);
}
await Tp(ReviveStatueOfTheSevenPointX, ReviveStatueOfTheSevenPointY);
_mapZoomEnabled = tempMapZoomEnable;
}
else
{
await Tp(ReviveStatueOfTheSevenPointX, ReviveStatueOfTheSevenPointY);
}
await Tp(_tpConfig.ReviveStatueOfTheSevenPointX, _tpConfig.ReviveStatueOfTheSevenPointY);
}
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
/// </summary>
/// <param name="tpX"></param>
/// <param name="tpY"></param>
/// <param name="force">强制以当前的tpX,tpY坐标进行自动传送</param>
public async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false)
private async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false)
{
var (x, y) = (tpX, tpY);
string? country = null;
if (!force)
{
// 获取最近的传送点位置
(x, y, country) = GetRecentlyTpPoint(tpX, tpY);
Logger.LogDebug("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", $"{tpX:F1}", $"{tpY:F1}", $"{x:F1}", $"{y:F1}");
}
// 先确认在地图界面
await CheckInBigMapUi();
// 传送前的计算准备
var nTpPoints = GetNearestNTpPoints(tpX, tpY, 2);
var (x, y) = force ? (tpX, tpY) : (nTpPoints[0].x, nTpPoints[0].y);
var country = force ? null : nTpPoints[0].country;
double disBetweenTpPoints = Math.Sqrt((nTpPoints[0].x - nTpPoints[1].x) * (nTpPoints[0].x - nTpPoints[1].x)
+ (nTpPoints[0].y - nTpPoints[1].y) * (nTpPoints[0].y - nTpPoints[1].y));
double minZoomLevel = Math.Max(disBetweenTpPoints / 20, 1);
// 计算传送点位置离哪个地图切换后的中心点最近,切换到该地图
await SwitchRecentlyCountryMap(x, y, country);
// 计算坐标后点击
var bigMapInAllMapRect = GetBigMapRect();
if (_mapZoomEnabled)
double zoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
if (_tpConfig.MapZoomEnabled)
{
double zoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
if (zoomLevel > 4.5)
{
// 显示传送锚点和秘境的缩放等级
await AdjustMapZoomLevel(zoomLevel, 4.5);
Logger.LogInformation("当前缩放等级过大,调整为 {zoomLevel:0.000}", 4.5);
zoomLevel = 4.5;
Logger.LogInformation("当前缩放等级过大,调整为 {zoomLevel:0.00}", 4.5);
}
}
if (zoomLevel > minZoomLevel)
{
if (_tpConfig.MapZoomEnabled)
{
Logger.LogInformation("目标传送点有相近传送点,到目标传送点附近将缩放到{zoomLevel:0.00}", minZoomLevel);
await MoveMapTo(x, y, minZoomLevel);
await Delay(300, ct); // 等待地图移动完成
}
else
{
Logger.LogInformation("目标传送点有相近传送点,可能传送失败。如果失败请到设置-大地图地图传送设置开启地图缩放。");
// TODO 部分无法区分点位强制缩放 即使没有zoomEnabled。
// await AdjustMapZoomLevel(zoomLevel, minZoomLevel); // 临时修改缩放
// await Delay(300, ct); // 等待缩放修改完成
await MoveMapTo(x, y); // 移动地图
await Delay(300, ct); // 等待地图移动完成
// await AdjustMapZoomLevel(minZoomLevel, zoomLevel); // 恢复修改的缩放
}
}
var bigMapInAllMapRect = GetBigMapRect();
while (!IsPointInBigMapWindow(bigMapInAllMapRect, x, y)) // 左上角 350x400也属于禁止点击区域
{
Debug.WriteLine($"({x},{y}) 不在 {bigMapInAllMapRect} 内,继续移动");
Logger.LogInformation("传送点不在当前大地图范围内,继续移动");
await MoveMapTo(x, y, maxMouseMove: 400);
await MoveMapTo(x, y);
await Delay(300, ct); // 等待地图移动完成
bigMapInAllMapRect = GetBigMapRect();
}
@@ -253,25 +201,27 @@ public class TpTask(CancellationToken ct)
}
private async Task CheckInBigMapUi()
{
// 尝试打开地图失败后,先回到主界面后再次尝试打开地图
if (!await TryToOpenBigMapUi())
{
await new ReturnMainUiTask().Start(ct);
if (!await TryToOpenBigMapUi())
{
throw new RetryException("打开大地图失败,请检查按键绑定中「打开地图」按键设置是否和原神游戏中一致!");
}
}
}
/// <summary>
/// 尝试打开地图界面
/// </summary>
private async Task<bool> TryToOpenBigMapUi()
{
// M 打开地图识别当前位置,中心点为当前位置
var ra1 = CaptureToRectArea();
if (!Bv.IsInBigMapUi(ra1))
{
// 不在主界面的情况下,先回到主界面
if (!Bv.IsInMainUi(ra1))
{
for (int i = 0; i < 5; i++)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(1000, ct);
ra1 = CaptureToRectArea();
if (Bv.IsInMainUi(ra1))
{
break;
}
}
}
Simulation.SendInput.SimulateAction(GIActions.OpenMap);
await Delay(1000, ct);
for (int i = 0; i < 3; i++)
@@ -281,12 +231,23 @@ public class TpTask(CancellationToken ct)
{
await Delay(500, ct);
}
else
{
return true;
}
}
return false;
}
else
{
return true;
}
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false)
{
await CheckInBigMapUi();
for (var i = 0; i < 3; i++)
{
try
@@ -303,7 +264,6 @@ public class TpTask(CancellationToken ct)
}
catch (Exception e)
{
await CheckInBigMapUi();
Logger.LogError("传送失败,重试 {I} 次", i + 1);
Logger.LogDebug(e, "传送失败,重试 {I} 次", i + 1);
}
@@ -318,14 +278,13 @@ public class TpTask(CancellationToken ct)
/// </summary>
/// <param name="x">目标x坐标</param>
/// <param name="y">目标y坐标</param>
/// <param name="tolerance">允许误差,默认200</param>
/// <param name="maxIterations">最大尝试次数,默认30</param>
/// <param name="maxMouseMove">单次移动最大距离,默认250</param>
public async Task MoveMapTo(double x, double y, double tolerance = 200, int maxIterations = 30, int maxMouseMove = 250)
/// <param name="minZoomLevel">到达目标点的最小缩放等级,只在 MapZoomEnabled 为 True 生效</param>
private async Task MoveMapTo(double x, double y, double minZoomLevel = 2)
{
// 获取当前地图中心点并计算到目标传送点的初始偏移
// await AdjustMapZoomLevel(mapZoomLevel);
var bigMapCenterPoint = GetPositionFromBigMap(); // 初始中心
minZoomLevel = Math.Min(minZoomLevel, _tpConfig.MinZoomLevel);
var bigMapCenterPoint = GetPositionFromBigMap(); // 初始中心
var newBigMapCenterPoint = bigMapCenterPoint;
var (xOffset, yOffset) = (x - bigMapCenterPoint.X, y - bigMapCenterPoint.Y);
int moveMouseX = 100 * Math.Sign(xOffset);
@@ -333,7 +292,7 @@ public class TpTask(CancellationToken ct)
int moveSteps = 10;
double totalMoveMouseX = Double.MaxValue;
double totalMoveMouseY = Double.MaxValue;
for (int iteration = 0; iteration < maxIterations; iteration++)
for (int iteration = 0; iteration < _tpConfig.MaxIterations; iteration++)
{
// 尝试移动鼠标
await MouseMoveMap(moveMouseX, moveMouseY, moveSteps);
@@ -346,73 +305,93 @@ public class TpTask(CancellationToken ct)
{
Logger.LogWarning("中心点识别失败,尝试预测移动的距离。");
newBigMapCenterPoint = new Point2f(
(float)(bigMapCenterPoint.X + xOffset * moveMouseX / totalMoveMouseX),
(float)(bigMapCenterPoint.Y + yOffset * moveMouseY / totalMoveMouseY)
(float)(bigMapCenterPoint.X + xOffset * moveMouseX / totalMoveMouseX),
(float)(bigMapCenterPoint.Y + yOffset * moveMouseY / totalMoveMouseY)
); // 利用移动鼠标的距离获取新的中心
}
// 本次移动的距离
double diffMapX = Math.Abs(newBigMapCenterPoint.X - bigMapCenterPoint.X);
double diffMapY = Math.Abs(newBigMapCenterPoint.Y - bigMapCenterPoint.Y);
double moveDistance = Math.Sqrt(diffMapX * diffMapX + diffMapY * diffMapY);
if (moveDistance > 10) // 移动距离大于10认为本次移动成功
{
(xOffset, yOffset) = (x - newBigMapCenterPoint.X, y - newBigMapCenterPoint.Y); // 更新目标偏移量
totalMoveMouseX = Math.Abs(moveMouseX * xOffset / diffMapX);
totalMoveMouseY = Math.Abs(moveMouseY * yOffset / diffMapY);
// totalMoveMouseX = Math.Abs(moveMouseX * xOffset / diffMapX);
// totalMoveMouseY = Math.Abs(moveMouseY * yOffset / diffMapY);
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
totalMoveMouseX = _tpConfig.MapScaleFactor * Math.Abs(xOffset) / currentZoomLevel;
totalMoveMouseY = _tpConfig.MapScaleFactor * Math.Abs(yOffset) / currentZoomLevel;
double mouseDistance = Math.Sqrt(totalMoveMouseX * totalMoveMouseX + totalMoveMouseY * totalMoveMouseY);
if (_mapZoomEnabled)
if (_tpConfig.MapZoomEnabled)
{
// 调整地图缩放
// mapZoomLevel<5 才显示传送锚点和秘境; mapZoomLevel>1.7 可以避免点错传送锚点
double currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
double oldZoomLevel = currentZoomLevel;
while (mouseDistance > MapZoomOutDistance || mouseDistance < MapZoomInDistance)
while (mouseDistance > _tpConfig.MapZoomOutDistance || mouseDistance < _tpConfig.MapZoomInDistance)
{
bool zoomOut = mouseDistance > MapZoomOutDistance;
bool zoomIn = mouseDistance < MapZoomInDistance;
if (zoomOut && currentZoomLevel < 4.0 || zoomIn && currentZoomLevel > 2.7)
bool zoomIn = mouseDistance < _tpConfig.MapZoomInDistance;
if (zoomIn)
{
await AdjustMapZoomLevel(zoomIn);
currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
totalMoveMouseX *= oldZoomLevel / currentZoomLevel;
totalMoveMouseY *= oldZoomLevel / currentZoomLevel;
mouseDistance *= oldZoomLevel / currentZoomLevel;
oldZoomLevel = currentZoomLevel;
}
else
{
double targetZoom = zoomIn ? 1.7 : 5.0;
// 考虑调整和识别误差,所以相差0.05就不再调整。
if (currentZoomLevel > 4.95 || currentZoomLevel < 1.75)
if (currentZoomLevel > _tpConfig.MinZoomLevel + 1.0)
{
await AdjustMapZoomLevel(zoomIn);
await Delay(50, ct);
}
else if (currentZoomLevel < minZoomLevel + 0.05)
{
break;
}
await AdjustMapZoomLevel(currentZoomLevel, targetZoom);
break;
else
{
await AdjustMapZoomLevel(currentZoomLevel, minZoomLevel);
break;
}
}
else
{
if (currentZoomLevel < _tpConfig.MaxZoomLevel - 1.0)
{
await AdjustMapZoomLevel(zoomIn);
await Delay(50, ct);
}
else if (currentZoomLevel > _tpConfig.MaxZoomLevel - 0.05)
{
break;
}
else
{
await AdjustMapZoomLevel(currentZoomLevel, _tpConfig.MaxZoomLevel);
break;
}
}
currentZoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
totalMoveMouseX *= oldZoomLevel / currentZoomLevel;
totalMoveMouseY *= oldZoomLevel / currentZoomLevel;
mouseDistance *= oldZoomLevel / currentZoomLevel;
oldZoomLevel = currentZoomLevel;
}
}
// 非常接近目标点,不再进一步调整
if (mouseDistance < tolerance)
if (mouseDistance < _tpConfig.Tolerance)
{
Logger.LogInformation("移动 {I} 次鼠标后,已经接近目标点,不再移动地图。", iteration + 1);
break;
}
// 单次移动最大距离为 maxMouseMove
moveMouseX = (int)Math.Min(totalMoveMouseX, maxMouseMove * totalMoveMouseX / mouseDistance) * Math.Sign(xOffset);
moveMouseY = (int)Math.Min(totalMoveMouseY, maxMouseMove * totalMoveMouseY / mouseDistance) * Math.Sign(yOffset);
moveMouseX = (int)Math.Min(totalMoveMouseX, _tpConfig.MaxMouseMove * totalMoveMouseX / mouseDistance) * Math.Sign(xOffset);
moveMouseY = (int)Math.Min(totalMoveMouseY, _tpConfig.MaxMouseMove * totalMoveMouseY / mouseDistance) * Math.Sign(yOffset);
double moveMouseLength = Math.Sqrt(moveMouseX * moveMouseX + moveMouseY * moveMouseY);
moveSteps = Math.Max((int)moveMouseLength / 10, 3); // 每次移动的步数最小为3,避免除0错误
}
else
{
Logger.LogDebug($"第 {iteration} 次移动鼠标失败,可能是点击了传送点或者其他交互对象。");
Logger.LogDebug($"第 {iteration + 1} 次移动鼠标失败,可能是点击了传送点或者其他交互对象。");
}
}
}
@@ -440,25 +419,26 @@ public class TpTask(CancellationToken ct)
/// 调整地图缩放级别以加速移动
/// </summary>
/// <param name="zoomIn">是否放大地图</param>
public async Task AdjustMapZoomLevel(bool zoomIn)
private async Task AdjustMapZoomLevel(bool zoomIn)
{
if (zoomIn)
{
GameCaptureRegion.GameRegionClick((rect, scale) => (zoomButtonX * scale, zoomInButtonY * scale));
GameCaptureRegion.GameRegionClick((rect, scale) => (_tpConfig.ZoomButtonX * scale, _tpConfig.ZoomInButtonY * scale));
}
else
{
GameCaptureRegion.GameRegionClick((rect, scale) => (zoomButtonX * scale, zoomOutButtonY * scale));
GameCaptureRegion.GameRegionClick((rect, scale) => (_tpConfig.ZoomButtonX * scale, _tpConfig.ZoomOutButtonY * scale));
}
await Delay(50, ct);
}
[Obsolete]
/// <summary>
/// 调整地图的缩放等级(整数缩放级别)。
/// </summary>
/// <param name="zoomLevel">目标等级:1-6。整数。随着数字变大地图越小,细节越少。</param>
[Obsolete]
public async Task AdjustMapZoomLevel(int zoomLevel)
{
for (int i = 0; i < 5; i++)
@@ -478,15 +458,15 @@ public class TpTask(CancellationToken ct)
/// </summary>
/// <param name="zoomLevel">当前缩放等级:1.0-6.0,浮点数。</param>
/// <param name="targetZoomLevel">目标缩放等级:1.0-6.0,浮点数。</param>
public async Task AdjustMapZoomLevel(double zoomLevel, double targetZoomLevel)
private async Task AdjustMapZoomLevel(double zoomLevel, double targetZoomLevel)
{
// Logger.LogInformation("调整地图缩放等级:{zoomLevel:0.000} -> {targetZoomLevel:0.000}", zoomLevel, targetZoomLevel);
int initialY = (int)(zoomStartY + (zoomEndY - zoomStartY) * (zoomLevel - 1) / 5d);
int targetY = (int)(zoomStartY + (zoomEndY - zoomStartY) * (targetZoomLevel - 1) / 5d);
await MouseClickAndMove(zoomButtonX, initialY, zoomButtonX, targetY);
int initialY = (int)(_tpConfig.ZoomStartY + (_tpConfig.ZoomEndY - _tpConfig.ZoomStartY) * (zoomLevel - 1) / 5d);
int targetY = (int)(_tpConfig.ZoomStartY + (_tpConfig.ZoomEndY - _tpConfig.ZoomStartY) * (targetZoomLevel - 1) / 5d);
await MouseClickAndMove(_tpConfig.ZoomButtonX, initialY, _tpConfig.ZoomButtonX, targetY);
}
public async Task MouseMoveMap(int pixelDeltaX, int pixelDeltaY, int steps = 10)
private async Task MouseMoveMap(int pixelDeltaX, int pixelDeltaY, int steps = 10)
{
// 确保不影响总移动距离
int totalX = 0;
@@ -506,8 +486,8 @@ public class TpTask(CancellationToken ct)
}
// 均匀分配多余的部分到前半段
int remainingX = (int)(pixelDeltaX - totalX);
int remainingY = (int)(pixelDeltaY - totalY);
int remainingX = (pixelDeltaX - totalX);
int remainingY = (pixelDeltaY - totalY);
for (int i = 0; i < steps / 2 + 1; i++)
{
stepX[i] += remainingX / (steps / 2 + 1) + ((remainingX % (steps / 2 + 1) > i) ? 0 : 1);
@@ -517,17 +497,17 @@ public class TpTask(CancellationToken ct)
// 随机起点以避免地图移动无效
GameCaptureRegion.GameRegionMove((rect, _) =>
(rect.Width / 2d + Random.Shared.Next(-rect.Width / 6, rect.Width / 6),
rect.Height / 2d + Random.Shared.Next(-rect.Height / 6, rect.Height / 6)));
rect.Height / 2d + Random.Shared.Next(-rect.Height / 6, rect.Height / 6)));
GlobalMethod.LeftButtonDown();
Simulation.SendInput.Mouse.LeftButtonDown();
for (var i = 0; i < steps; i++)
{
GlobalMethod.MoveMouseBy(stepX[i], stepY[i]);
await Delay(StepIntervalMilliseconds, ct);
Simulation.SendInput.Mouse.MoveMouseBy(stepX[i], stepY[i]);
await Delay(_tpConfig.StepIntervalMilliseconds, ct);
}
GlobalMethod.LeftButtonUp();
}
Simulation.SendInput.Mouse.LeftButtonUp();
}
public Point2f GetPositionFromBigMap()
{
@@ -604,11 +584,12 @@ public class TpTask(CancellationToken ct)
}
/// <summary>
/// 获取最近的传送点位置
/// 获取最近的传送点位置和所处区域
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
[Obsolete]
public (double x, double y, string? country) GetRecentlyTpPoint(double x, double y)
{
double recentX = 0;
@@ -626,9 +607,44 @@ public class TpTask(CancellationToken ct)
country = tpPosition.Country;
}
}
return (recentX, recentY, country);
}
/// <summary>
/// 获取最接近的N个传送点坐标和所处区域
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="n">获取最近的 n 个传送点</param>
/// <returns></returns>
public List<(double x, double y, string? country)> GetNearestNTpPoints(double x, double y, int n = 1)
{
// 检查 n 的合法性
if (n < 1)
{
throw new ArgumentException("The value of n must be greater than or equal to 1.", nameof(n));
}
// 按距离排序并选择前 n 个点
var sortedTpPositions = MapLazyAssets.Instance.TpPositions
.Select(tpPosition => new
{
tpPosition.X,
tpPosition.Y,
tpPosition.Country,
Distance = Math.Sqrt(Math.Pow(tpPosition.X - x, 2) + Math.Pow(tpPosition.Y - y, 2))
})
.OrderBy(tp => tp.Distance)
.Take(n) // 取前 n 个点
.ToList();
// 将结果转换为 List<(x, y, country)>
return sortedTpPositions
.Select(tp => (tp.X, tp.Y, tp.Country))
.ToList();
}
public async Task<bool> SwitchRecentlyCountryMap(double x, double y, string? forceCountry = null)
{
// 可能是地下地图,切换到地上地图
@@ -10,6 +10,7 @@ using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoFight;
using Vanara.PInvoke;
using System.Threading;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.AutoSkip.Assets;
using BetterGenshinImpact.GameTask.GameLoading.Assets;
@@ -148,7 +149,7 @@ public static partial class Bv
/// <returns></returns>
public static bool IsInRevivePrompt(ImageRegion region)
{
using var confirmRectArea = region.Find(AutoFightContext.Instance.FightAssets.ConfirmRa);
using var confirmRectArea = region.Find(AutoFightAssets.Instance.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
var list = region.FindMulti(new RecognitionObject
@@ -44,18 +44,28 @@ public partial class ChooseTalkOptionTask
return TalkOptionRes.NotFound;
}
await Task.Delay(200, ct);
await Task.Delay(500, ct);
for (var i = 0; i < skipTimes; i++) // 重试3次
bool firstOcrOption = true;
for (var i = 0; i < skipTimes; i++) // 重试N次
{
var region = CaptureToRectArea();
var optionRegions = RecognizeOption(region, ct);
if (optionRegions == null)
{
TaskContext.Instance().PostMessageSimulator.KeyPressBackground(User32.VK.VK_SPACE);
await Delay(200, ct);
await Delay(500, ct);
continue; // retry
}
else
{
// 首次识别到文字,延迟1s重新识别一次,保证文字已经完全展示
if (firstOcrOption)
{
await Delay(1000, ct);
firstOcrOption = false;
}
}
foreach (var optionRa in optionRegions)
{
@@ -71,7 +81,7 @@ public partial class ChooseTalkOptionTask
}
ClickOcrRegion(optionRa);
await Task.Delay(200, ct);
await Task.Delay(300, ct);
return TalkOptionRes.FoundAndClick;
}
}
@@ -198,16 +208,14 @@ public partial class ChooseTalkOptionTask
private bool IsOrangeOption(Mat textMat)
{
// 只提取橙色
using var bMat = OpenCvCommonHelper.Threshold(textMat, new Scalar(200, 165, 45), new Scalar(255, 205, 55));
var whiteCount = OpenCvCommonHelper.CountGrayMatColor(bMat, 255);
var rate = whiteCount * 1.0 / (bMat.Width * bMat.Height);
Scalar lowerOrange = new Scalar(10, 150, 150);
Scalar upperOrange = new Scalar(25, 255, 255);
var mask = OpenCvCommonHelper.InRangeHsv(textMat, lowerOrange, upperOrange);
int highConfidencePixels = Cv2.CountNonZero(mask);
double rate = highConfidencePixels * 1.0 / (mask.Width * mask.Height);
Debug.WriteLine($"识别到橙色文字区域占比:{rate}");
if (rate > 0.06)
{
return true;
}
return false;
_logger.LogInformation($"识别到橙色文字区域占比:{rate}");
return rate > 0.1;
}
}
@@ -80,7 +80,7 @@ public class GoToAdventurersGuildTask
await new ReturnMainUiTask().Start(ct);
// 结束后重新打开
await Delay(1000, ct);
await Delay(1200, ct);
var ra = CaptureToRectArea();
if (!Bv.FindFAndPress(ra, "凯瑟琳"))
{
@@ -148,7 +148,7 @@ public class SwitchPartyTask
{
if (textRegion.Text == partyName)
{
page.ClickTo(textRegion.Right, textRegion.Bottom + textRegion.Height * 2);
page.ClickTo(textRegion.Right + textRegion.Width, textRegion.Bottom);
await Delay(200, ct);
Logger.LogInformation("切换队伍成功: {Text}", textRegion.Text);
await ConfirmParty(page, ct);
+108 -10
View File
@@ -102,6 +102,33 @@ namespace LogParse
if (configTask != null)
{
//前往七天神像复活
if (logstr.EndsWith("前往七天神像复活"))
{
configTask.Fault.ReviveCount++;
}
//传送失败,重试 n 次
result = parseBgiLine($@"传送失败,重试 (\d+) 次", logstr);
if (result.Item1)
{
configTask.Fault.TeleportFailCount = int.Parse(result.Item2[1]);
}
//战斗超时结束
if (logstr == "战斗超时结束")
{
configTask.Fault.BattleTimeoutCount ++;
}
//重试一次路线或放弃此路线!
if (logstr.EndsWith("重试一次路线或放弃此路线!"))
{
configTask.Fault.RetryCount++;
}
if (logstr.StartsWith("→ 脚本执行结束: \"" + configTask.Name + "\""))
{
configTask.EndDate = parsePreDataTime(logLines, i - 1, logrq);
@@ -182,6 +209,8 @@ namespace LogParse
//配置人物列表xxx.json
public List<ConfigTask> ConfigTaskList { get; } = new();
public class ConfigTask
{
public string Name { get; set; }
@@ -204,6 +233,21 @@ namespace LogParse
Picks[val] = Picks[val] + 1;
}
public FaultScenario Fault { get; set; } = new();
public class FaultScenario
{
//复活次数
public int ReviveCount { get; set; } = 0;
//传送失败次数
public int TeleportFailCount { get; set; } = 0;
//重试次数
public int RetryCount { get; set; } = 0;
//战斗超时
public int BattleTimeoutCount { get; set; } = 0;
}
}
}
@@ -307,7 +351,42 @@ namespace LogParse
return customDayStart;
}
public static string GenerHtmlByConfigGroupEntity(List<ConfigGroupEntity> configGroups, GameInfo gameInfo)
public static string FormatNumberWithStyle(int a, int b=3)
{
if (a== 0)
{
return "";
}
// Determine the style based on the condition
string colorStyle = a >= b ? "color:red;" : string.Empty;
// Return the formatted HTML string
return $"<span style=\"font-weight:bold;{colorStyle}\">{a}</span>";
}
public static string GetNumberOrEmptyString(int number)
{
// 如果数字为0,返回空字符串,否则返回数字的字符串形式
return number == 0 ? string.Empty : number.ToString();
}
public static string SubtractFiveSeconds(string inputTime,int seconds)
{
try
{
// 将输入的字符串解析为 DateTime
DateTime parsedTime = DateTime.ParseExact(inputTime, "yyyy-MM-dd HH:mm:ss", null);
// 减去 5 秒
DateTime resultTime = parsedTime.AddSeconds(-seconds);
// 转换回指定格式的字符串并返回
return resultTime.ToString("yyyy-MM-dd HH:mm:ss");
}
catch (FormatException)
{
return "Invalid input time format. Please use 'yyyy-MM-dd HH:mm:ss'.";
}
}
public static string GenerHtmlByConfigGroupEntity(List<ConfigGroupEntity> configGroups, GameInfo? gameInfo,LogParseConfig.ScriptGroupLogParseConfig scriptGroupLogParseConfig)
{
(string name, Func<ConfigTask, string> value)[] colConfigs =
[
@@ -316,19 +395,28 @@ namespace LogParse
(name: "结束日期", value: task => task.EndDate?.ToString("yyyy-MM-dd HH:mm:ss") ?? ""),
(name: "耗时", value: task => ConvertSecondsToTime((task.EndDate - task.StartDate)?.TotalSeconds ?? 0))
];
List<(string name, Func<ConfigTask, string> value)> colConfigList = new();
colConfigList.AddRange(colConfigs);
if (scriptGroupLogParseConfig.FaultStatsSwitch)
{
colConfigList.Add((name: "复活次数", value: task => FormatNumberWithStyle(task.Fault.ReviveCount)));
colConfigList.Add((name: "重试次数", value: task => FormatNumberWithStyle(task.Fault.RetryCount)));
colConfigList.Add((name: "战斗超时次数", value: task => FormatNumberWithStyle(task.Fault.BattleTimeoutCount)));
colConfigList.Add((name: "传送失败次数", value: task => FormatNumberWithStyle(task.Fault.TeleportFailCount)));
}
(string name, Func<MoraStatistics, string> value)[] msColConfigs =
[
(name: "日期", value: ms => ms.Name), (name: "小怪", value: ms => ms.SmallMonsterStatistics.ToString()),
(name: "日期", value: ms => ms.Name), (name: "小怪", value: ms => GetNumberOrEmptyString(ms.SmallMonsterStatistics)),
(name: "最后小怪日期", value: ms => ms.LastSmallTime),
(name: "精英", value: ms => ms.EliteGameStatistics.ToString()),
(name: "精英", value: ms => GetNumberOrEmptyString(ms.EliteGameStatistics)),
(name: "精英详细", value: ms => ms.EliteDetails), (name: "最后精英日期", value: ms => ms.LastEliteTime),
(name: "总计锄地摩拉", value: ms => ms.TotalMoraKillingMonstersMora.ToString())
(name: "总计锄地摩拉", value: ms => ms.TotalMoraKillingMonstersMora.ToString()),
(name: "突发事件获取摩拉", value: ms => ms.EmergencyBonus)
];
//锄地部分新曾字段
(string name, Func<MoraStatistics, string> value)[] col2Configs=[..msColConfigs.ToList().Where(item=>item.name!="日期" && item.name!="最后小怪日期" && item.name!="最后精英日期"),
(string name, Func<MoraStatistics, string> value)[] col2Configs=[..msColConfigs.ToList().Where(item=>item.name!="日期" && item.name!="最后小怪日期" && item.name!="最后精英日期" && item.name!="突发事件获取摩拉"),
(name: "摩拉(每秒)", value: ms => (ms.TotalMoraKillingMonstersMora/(ms.StatisticsEnd-ms.StatisticsStart)?.TotalSeconds ?? 0).ToString("F2")),
];
@@ -339,11 +427,19 @@ namespace LogParse
List<ActionItem> actionItems = new();
if (gameInfo != null)
{
actionItems = TravelsDiaryDetailManager.loadAllActionItems(gameInfo, configGroups);
int hoeingDelay;
if (int.TryParse(scriptGroupLogParseConfig.HoeingDelay, out hoeingDelay))
{
foreach (var actionItem in actionItems)
{
actionItem.Time = SubtractFiveSeconds(actionItem.Time,hoeingDelay);
}
}
}
return GenerHtmlByConfigGroupEntity(configGroups, "日志分析", colConfigs,col2Configs, actionItems, msColConfigs);
return GenerHtmlByConfigGroupEntity(configGroups, "日志分析", colConfigList.ToArray(),col2Configs, actionItems, msColConfigs);
}
public static string ConcatenateStrings(string a, string b)
{
@@ -372,6 +468,8 @@ namespace LogParse
html.AppendLine(" table { border-collapse: collapse; width: 100%; margin-bottom: 20px; }");
html.AppendLine(" th, td { border: 1px solid black; padding: 8px; text-align: left; }");
html.AppendLine(" th { background-color: #f2f2f2; }");
html.AppendLine(" tr:nth-child(odd) { background-color: #eaeaea; /* 奇数行颜色 */ }");
html.AppendLine(" tr:nth-child(even) { background-color: #f9f9f9; /* 偶数行颜色 */}");
html.AppendLine(" </style>");
html.AppendLine("</head>");
html.AppendLine("<body>");
@@ -386,7 +484,7 @@ namespace LogParse
.OrderBy(group => group.Key)
.Reverse().ToList();
html.AppendLine($"<h2>按日锄地摩拉统计</h2>");
html.AppendLine($"<h2>按日摩拉收益统计</h2>");
html.AppendLine("<table>");
html.AppendLine(" <tr>");
@@ -14,5 +14,7 @@ public partial class LogParseConfig : ObservableObject
[ObservableProperty] private string _rangeValue = "CurrentConfig";
[ObservableProperty] private string _dayRangeValue = "7";
[ObservableProperty] private bool _hoeingStatsSwitch = false;
[ObservableProperty] private bool _faultStatsSwitch = false;
[ObservableProperty] private string _hoeingDelay= "0";
}
}
@@ -25,6 +25,21 @@ namespace LogParse
public List<ActionItem> SmallMonsterActionItems =>
this.MonsterActionItems.Except(EliteMonsterActionItems).ToList();
public string EmergencyBonus
{
get
{
var ls = this.ActionItems.Where(item => item.ActionId == 28).ToList();
var count = ls.Count();
if (count == 0)
{
return "";
}
return ls.Sum(item=>item.Num)+(count>=10?"":$"({count}/10)");
}
}
public string LastEliteTime => EliteMonsterActionItems.MaxBy(item => item?.Time)?.Time ?? null;
public string LastSmallTime => SmallMonsterActionItems.MaxBy(item => item?.Time)?.Time ?? null;
@@ -50,8 +50,8 @@ public class TravelsDiaryDetailManager
var _temp = JsonSerializer.Deserialize<ApiResponse<ActionItem>>(File.ReadAllText(tddfile));
if (_temp != null)
{
//只统计杀怪的
actionItems.AddRange(_temp.Data.List.Where(item => item.ActionId == 37));
//统计杀怪或突发事件奖励
actionItems.AddRange(_temp.Data.List.Where(item => item.ActionId == 37 || item.ActionId == 28));
}
}
}
+8 -13
View File
@@ -11,6 +11,8 @@ using BetterGenshinImpact.Helpers;
using Wpf.Ui.Violeta.Controls;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.Service;
using BetterGenshinImpact.Service.Notification;
using BetterGenshinImpact.Service.Notification.Model.Enum;
namespace BetterGenshinImpact.GameTask;
@@ -48,17 +50,13 @@ public class TaskRunner
_logger.LogError("任务启动失败:当前存在正在运行中的独立任务,请不要重复执行任务!");
return;
}
try
{
_logger.LogInformation("→ {Text}", _name + "任务启动!");
// 初始化
Init();
// 发送运行任务通知
SendNotification();
CancellationContext.Instance.Set();
RunnerContext.Instance.Clear();
@@ -66,8 +64,8 @@ public class TaskRunner
}
catch (NormalEndException e)
{
Notify.Event(NotificationEvent.TaskCancel).Success("任务手动取消,或正常结束");
_logger.LogInformation("任务中断:{Msg}", e.Message);
SendNotification();
if (RunnerContext.Instance.IsContinuousRunGroup)
{
// 连续执行时,抛出异常,终止执行
@@ -76,8 +74,8 @@ public class TaskRunner
}
catch (TaskCanceledException e)
{
Notify.Event(NotificationEvent.TaskCancel).Success("任务被手动取消");
_logger.LogInformation("任务中断:{Msg}", "任务被取消");
SendNotification();
if (RunnerContext.Instance.IsContinuousRunGroup)
{
// 连续执行时,抛出异常,终止执行
@@ -86,15 +84,14 @@ public class TaskRunner
}
catch (Exception e)
{
Notify.Event(NotificationEvent.TaskError).Error("任务执行异常", e);
_logger.LogError(e.Message);
_logger.LogDebug(e.StackTrace);
SendNotification();
}
finally
{
End();
_logger.LogInformation("→ {Text}", _name + "任务结束");
SendNotification();
CancellationContext.Instance.Clear();
RunnerContext.Instance.Clear();
@@ -120,7 +117,8 @@ public class TaskRunner
public async Task RunSoloTaskAsync(ISoloTask soloTask)
{
// 没启动的时候先启动
await ScriptService.StartGameTask();
bool waitForMainUi = soloTask.Name != "自动七圣召唤" && !soloTask.Name.Contains("自动音游");
await ScriptService.StartGameTask(waitForMainUi);
await Task.Run(() => RunCurrentAsync(async () => await soloTask.Start(CancellationContext.Instance.Cts.Token)));
}
@@ -190,7 +188,4 @@ public class TaskRunner
}
}
public void SendNotification()
{
}
}
@@ -0,0 +1,62 @@
using System;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Genshin.Settings;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GameSettingsChecker
{
public static void LoadGameSettingsAndCheck()
{
try
{
var settingStr = GenshinGameSettings.GetStrFromRegistry();
if (settingStr == null)
{
TaskControl.Logger.LogDebug("获取原神游戏设置失败");
return;
}
GenshinGameSettings? settings = GenshinGameSettings.Parse(settingStr);
if (settings == null)
{
TaskControl.Logger.LogDebug("获取原神游戏设置失败");
return;
}
GenshinGameInputSettings? inputSettings = GenshinGameInputSettings.Parse(settings.InputData);
if (inputSettings == null)
{
TaskControl.Logger.LogError("获取原神游戏输入设置失败");
return;
}
if (settings.GammaValue != "2.200000047683716")
{
TaskControl.Logger.LogError("检测到游戏亮度非默认值,将会影响功能正常使用,请在原神 游戏设置——图像——亮度 中恢复默认亮度!");
}
if (inputSettings.MouseSenseIndex != 2
|| inputSettings.MouseSenseIndexY != 2
|| inputSettings.MouseFocusSenseIndex != 2
|| inputSettings.MouseFocusSenseIndexY != 2)
{
TaskControl.Logger.LogInformation("当前:镜头水平灵敏度{X1},镜头垂直灵敏度{Y1},镜头水平灵敏度(瞄准模式){X2},镜头垂直灵敏度(瞄准模式){Y2}",
inputSettings.MouseSenseIndex + 1, inputSettings.MouseSenseIndexY + 1,
inputSettings.MouseFocusSenseIndex + 1, inputSettings.MouseFocusSenseIndexY + 1);
TaskControl.Logger.LogError("检测到镜头灵敏度不是默认值3,将会影响所有视角移动功能的正常使用,请在原神 游戏设置——控制 中恢复默认灵敏度!");
}
var lang = (TextLanguage)settings.DeviceLanguageType;
if (lang != TextLanguage.SimplifiedChinese)
{
TaskControl.Logger.LogWarning("当前游戏语言{Lang}不是简体中文,部分功能可能无法正常使用。The game language is not Simplified Chinese, some functions may not work properly", lang);
}
}
catch (Exception e)
{
TaskControl.Logger.LogDebug(e, "获取原神游戏设置失败");
}
}
}
@@ -0,0 +1,122 @@
using Newtonsoft.Json;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GenshinGameInputSettings
{
[JsonProperty("scriptVersion")]
public string ScriptVersion { get; set; } // 脚本版本
[JsonProperty("mouseSensitivity")]
public string MouseSensitivity { get; set; } // 鼠标灵敏度
[JsonProperty("joypadSenseIndex")]
public int JoypadSenseIndex { get; set; } // 手柄灵敏度索引
[JsonProperty("joypadFocusSenseIndex")]
public int JoypadFocusSenseIndex { get; set; } // 手柄焦点灵敏度索引
[JsonProperty("joypadInvertCameraX")]
public bool JoypadInvertCameraX { get; set; } // 手柄X轴反转摄像头
[JsonProperty("joypadInvertCameraY")]
public bool JoypadInvertCameraY { get; set; } // 手柄Y轴反转摄像头
[JsonProperty("joypadInvertFocusCameraX")]
public bool JoypadInvertFocusCameraX { get; set; } // 手柄X轴反转焦点摄像头
[JsonProperty("joypadInvertFocusCameraY")]
public bool JoypadInvertFocusCameraY { get; set; } // 手柄Y轴反转焦点摄像头
[JsonProperty("mouseSenseIndex")]
public int MouseSenseIndex { get; set; } // 鼠标灵敏度索引
[JsonProperty("mouseFocusSenseIndex")]
public int MouseFocusSenseIndex { get; set; } // 鼠标焦点灵敏度索引
[JsonProperty("touchpadSenseIndex")]
public int TouchpadSenseIndex { get; set; } // 触摸板灵敏度索引
[JsonProperty("touchpadFocusSenseIndex")]
public int TouchpadFocusSenseIndex { get; set; } // 触摸板焦点灵敏度索引
[JsonProperty("enableTouchpadFocusAcceleration")]
public bool EnableTouchpadFocusAcceleration { get; set; } // 启用触摸板焦点加速度
[JsonProperty("lastJoypadDefaultScale")]
public float LastJoypadDefaultScale { get; set; } // 最后一次手柄默认缩放
[JsonProperty("lastJoypadFocusScale")]
public float LastJoypadFocusScale { get; set; } // 最后一次手柄焦点缩放
[JsonProperty("lastPCDefaultScale")]
public float LastPCDefaultScale { get; set; } // 最后一次PC默认缩放
[JsonProperty("lastPCFocusScale")]
public float LastPCFocusScale { get; set; } // 最后一次PC焦点缩放
[JsonProperty("lastTouchDefaultScale")]
public float LastTouchDefaultScale { get; set; } // 最后一次触摸默认缩放
[JsonProperty("lastTouchFcousScale")]
public float LastTouchFocusScale { get; set; } // 最后一次触摸焦点缩放
[JsonProperty("switchWalkRunByBtn")]
public bool SwitchWalkRunByBtn { get; set; } // 通过按钮切换行走和奔跑
[JsonProperty("skiffCameraAutoFix")]
public bool SkiffCameraAutoFix { get; set; } // 小艇摄像头自动修正
[JsonProperty("skiffCameraAutoFixInCombat")]
public bool SkiffCameraAutoFixInCombat { get; set; } // 战斗中小艇摄像头自动修正
[JsonProperty("cameraDistanceRatio")]
public float CameraDistanceRatio { get; set; } // 摄像头距离比率
[JsonProperty("wwiseVibration")]
public bool WwiseVibration { get; set; } // Wwise振动
[JsonProperty("isYInited")]
public bool IsYInited { get; set; } // Y轴是否初始化
[JsonProperty("joypadSenseIndexY")]
public int JoypadSenseIndexY { get; set; } // 手柄Y轴灵敏度索引
[JsonProperty("joypadFocusSenseIndexY")]
public int JoypadFocusSenseIndexY { get; set; } // 手柄Y轴焦点灵敏度索引
[JsonProperty("mouseSenseIndexY")]
public int MouseSenseIndexY { get; set; } // 鼠标Y轴灵敏度索引
[JsonProperty("mouseFocusSenseIndexY")]
public int MouseFocusSenseIndexY { get; set; } // 鼠标Y轴焦点灵敏度索引
[JsonProperty("touchpadSenseIndexY")]
public int TouchpadSenseIndexY { get; set; } // 触摸板Y轴灵敏度索引
[JsonProperty("touchpadFocusSenseIndexY")]
public int TouchpadFocusSenseIndexY { get; set; } // 触摸板Y轴焦点灵敏度索引
[JsonProperty("lastJoypadDefaultScaleY")]
public float LastJoypadDefaultScaleY { get; set; } // 最后一次手柄Y轴默认缩放
[JsonProperty("lastJoypadFocusScaleY")]
public float LastJoypadFocusScaleY { get; set; } // 最后一次手柄Y轴焦点缩放
[JsonProperty("lastPCDefaultScaleY")]
public float LastPCDefaultScaleY { get; set; } // 最后一次PC Y轴默认缩放
[JsonProperty("lastPCFocusScaleY")]
public float LastPCFocusScaleY { get; set; } // 最后一次PC Y轴焦点缩放
[JsonProperty("lastTouchDefaultScaleY")]
public float LastTouchDefaultScaleY { get; set; } // 最后一次触摸Y轴默认缩放
[JsonProperty("lastTouchFcousScaleY")]
public float LastTouchFocusScaleY { get; set; } // 最后一次触摸Y轴焦点缩放
public static GenshinGameInputSettings? Parse(string json)
{
return JsonConvert.DeserializeObject<GenshinGameInputSettings>(json);
}
}
@@ -0,0 +1,360 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json.Serialization;
using BetterGenshinImpact.Genshin.Settings;
using Microsoft.Win32;
using Newtonsoft.Json;
using JsonSerializerOptions = System.Text.Json.JsonSerializerOptions;
namespace BetterGenshinImpact.Genshin.Settings2;
public class GenshinGameSettings
{
[JsonProperty("deviceUUID")]
public string DeviceUUID { get; set; } // 设备唯一标识符
[JsonProperty("userLocalDataVersionId")]
public string UserLocalDataVersionId { get; set; } // 用户本地数据版本ID
[JsonProperty("deviceLanguageType")]
public int DeviceLanguageType { get; set; } // 设备语言类型
[JsonProperty("deviceVoiceLanguageType")]
public int DeviceVoiceLanguageType { get; set; } // 设备语音语言类型
[JsonProperty("selectedServerName")]
public string SelectedServerName { get; set; } // 选择的服务器名称
[JsonProperty("localLevelIndex")]
public int LocalLevelIndex { get; set; } // 本地等级索引
[JsonProperty("deviceID")]
public string DeviceID { get; set; } // 设备ID
[JsonProperty("targetUID")]
public string TargetUID { get; set; } // 目标用户ID
[JsonProperty("curAccountName")]
public string CurAccountName { get; set; } // 当前账户名称
[JsonProperty("uiSaveData")]
public string UiSaveData { get; set; } // UI保存数据
[JsonProperty("inputData")]
public string InputData { get; set; } // 输入设置数据
[JsonProperty("graphicsData")]
public string GraphicsData { get; set; } // 图形设置数据
[JsonProperty("globalPerfData")]
public string GlobalPerfData { get; set; } // 全局性能数据
[JsonProperty("miniMapConfig")]
public int MiniMapConfig { get; set; } // 小地图配置
[JsonProperty("enableCameraSlope")]
public bool EnableCameraSlope { get; set; } // 启用相机坡度
[JsonProperty("enableCameraCombatLock")]
public bool EnableCameraCombatLock { get; set; } // 启用相机战斗锁定
[JsonProperty("completionPkg")]
public bool CompletionPkg { get; set; } // 完成的包
[JsonProperty("completionPlayGoPkg")]
public bool CompletionPlayGoPkg { get; set; } // 完成的PlayGo包
[JsonProperty("onlyPlayWithPSPlayer")]
public bool OnlyPlayWithPSPlayer { get; set; } // 仅与PS玩家一起游戏
[JsonProperty("onlyPlayWithXboxPlayer")]
public bool OnlyPlayWithXboxPlayer { get; set; } // 仅与Xbox玩家一起游戏
[JsonProperty("needPlayGoFullPkgPatch")]
public bool NeedPlayGoFullPkgPatch { get; set; } // 需要PlayGo完整包补丁
[JsonProperty("resinNotification")]
public bool ResinNotification { get; set; } // 树脂通知
[JsonProperty("exploreNotification")]
public bool ExploreNotification { get; set; } // 探索通知
[JsonProperty("volumeGlobal")]
public int VolumeGlobal { get; set; } // 全局音量
[JsonProperty("volumeSFX")]
public int VolumeSFX { get; set; } // 音效音量
[JsonProperty("volumeMusic")]
public int VolumeMusic { get; set; } // 音乐音量
[JsonProperty("volumeVoice")]
public int VolumeVoice { get; set; } // 语音音量
[JsonProperty("audioAPI")]
public int AudioAPI { get; set; } // 音频API
[JsonProperty("audioDynamicRange")]
public int AudioDynamicRange { get; set; } // 音频动态范围
[JsonProperty("audioOutput")]
public int AudioOutput { get; set; } // 音频输出
[JsonProperty("_audioSuccessInit")]
public bool AudioSuccessInit { get; set; } // 音频成功初始化
[JsonProperty("enableAudioChangeAndroidMinimumBufferCapacity")]
public bool EnableAudioChangeAndroidMinimumBufferCapacity { get; set; } // 启用更改Android最小缓冲容量的音频
[JsonProperty("audioAndroidMiniumBufferCapacity")]
public int AudioAndroidMiniumBufferCapacity { get; set; } // Android音频最小缓冲容量
[JsonProperty("vibrationLevel")]
public int VibrationLevel { get; set; } // 震动等级
[JsonProperty("vibrationIntensity")]
public int VibrationIntensity { get; set; } // 震动强度
[JsonProperty("usingNewVibrationSetting")]
public bool UsingNewVibrationSetting { get; set; } // 使用新的震动设置
[JsonProperty("motionBlur")]
public bool MotionBlur { get; set; } // 动态模糊
[JsonProperty("gyroAiming")]
public bool GyroAiming { get; set; } // 陀螺仪瞄准
[JsonProperty("gyroHorMoveSpeedIndex")]
public int GyroHorMoveSpeedIndex { get; set; } // 陀螺仪水平移动速度索引
[JsonProperty("gyroVerMoveSpeedIndex")]
public int GyroVerMoveSpeedIndex { get; set; } // 陀螺仪垂直移动速度索引
[JsonProperty("gyroHorReverse")]
public bool GyroHorReverse { get; set; } // 陀螺仪水平反转
[JsonProperty("gyroVerReverse")]
public bool GyroVerReverse { get; set; } // 陀螺仪垂直反转
[JsonProperty("gyroRotateType")]
public int GyroRotateType { get; set; } // 陀螺仪旋转类型
[JsonProperty("gyroExcludeRightStickVerInput")]
public bool GyroExcludeRightStickVerInput { get; set; } // 陀螺仪排除右摇杆垂直输入
[JsonProperty("firstHDRSetting")]
public bool FirstHDRSetting { get; set; } // 首次HDR设置
[JsonProperty("maxLuminosity")]
public float MaxLuminosity { get; set; } // 最大亮度
[JsonProperty("uiPaperWhite")]
public float UiPaperWhite { get; set; } // UI纸白
[JsonProperty("scenePaperWhite")]
public float ScenePaperWhite { get; set; } // 场景纸白
/// <summary>
/// 2.200000047683716
/// </summary>
[JsonProperty("gammaValue")]
public string GammaValue { get; set; } // 伽马值
[JsonProperty("enableHDR")]
public bool EnableHDR { get; set; } // 启用HDR
[JsonProperty("_overrideControllerMapKeyList")]
public List<string> OverrideControllerMapKeyList { get; set; } // 覆盖控制器映射键列表
[JsonProperty("_overrideControllerMapValueList")]
public List<string> OverrideControllerMapValueList { get; set; } // 覆盖控制器映射值列表
[JsonProperty("rewiredMapMigrateRecord")]
public List<string> RewiredMapMigrateRecord { get; set; } // 重布线映射迁移记录
[JsonProperty("rewiredDisableKeyboard")]
public bool RewiredDisableKeyboard { get; set; } // 重布线禁用键盘
[JsonProperty("rewiredEnableKeyboard")]
public bool RewiredEnableKeyboard { get; set; } // 重布线启用键盘
[JsonProperty("rewiredEnableEDS")]
public bool RewiredEnableEDS { get; set; } // 重布线启用EDS
[JsonProperty("disableRewiredDelayInit")]
public bool DisableRewiredDelayInit { get; set; } // 禁用重布线延迟初始化
[JsonProperty("disableRewiredInitProtection")]
public bool DisableRewiredInitProtection { get; set; } // 禁用重布线初始化保护
[JsonProperty("disableSetJoyInfoForWebViewOnPCMobile")]
public bool DisableSetJoyInfoForWebViewOnPCMobile { get; set; } // 禁用在PC和移动设备上的WebView设置Joy信息
[JsonProperty("conflictKeyBindingElementId")]
public List<int> ConflictKeyBindingElementId { get; set; } // 冲突的按键绑定元素ID
[JsonProperty("conflictKeyBindingActionId")]
public List<int> ConflictKeyBindingActionId { get; set; } // 冲突的按键绑定动作ID
[JsonProperty("lastSeenPreDownloadTime")]
public long LastSeenPreDownloadTime { get; set; } // 上次看到的预下载时间
[JsonProperty("lastSeenSettingResourceTabScriptVersion")]
public string LastSeenSettingResourceTabScriptVersion { get; set; } // 上次看到的设置资源标签脚本版本
[JsonProperty("enableEffectAssembleInEditor")]
public bool EnableEffectAssembleInEditor { get; set; } // 启用在编辑器中组装效果
[JsonProperty("forceDisableQuestResourceManagement")]
public bool ForceDisableQuestResourceManagement { get; set; } // 强制禁用任务资源管理
[JsonProperty("needReportQuestResourceDeleteStatusFiles")]
public bool NeedReportQuestResourceDeleteStatusFiles { get; set; } // 需要报告任务资源删除状态文件
[JsonProperty("disableTeamPageBackgroundSwitch")]
public bool DisableTeamPageBackgroundSwitch { get; set; } // 禁用团队页面背景切换
[JsonProperty("disableHttpDns")]
public bool DisableHttpDns { get; set; } // 禁用HTTP DNS
[JsonProperty("mtrCached")]
public bool MtrCached { get; set; } // MTR缓存
[JsonProperty("mtrIsOpen")]
public bool MtrIsOpen { get; set; } // MTR是否开启
[JsonProperty("mtrMaxTTL")]
public int MtrMaxTTL { get; set; } // MTR最大TTL
[JsonProperty("mtrTimeOut")]
public int MtrTimeOut { get; set; } // MTR超时时间
[JsonProperty("mtrTraceCount")]
public int MtrTraceCount { get; set; } // MTR跟踪次数
[JsonProperty("mtrAbortTimeOutCount")]
public int MtrAbortTimeOutCount { get; set; } // MTR中止超时计数
[JsonProperty("mtrAutoTraceInterval")]
public int MtrAutoTraceInterval { get; set; } // MTR自动跟踪间隔
[JsonProperty("mtrTraceCDEachReason")]
public int MtrTraceCDEachReason { get; set; } // MTR每个原因的冷却时间
[JsonProperty("mtrTimeInterval")]
public int MtrTimeInterval { get; set; } // MTR时间间隔
[JsonProperty("mtrBanReasons")]
public List<string> MtrBanReasons { get; set; } // MTR禁止原因
[JsonProperty("_customDataKeyList")]
public List<string> CustomDataKeyList { get; set; } // 自定义数据键列表
[JsonProperty("_customDataValueList")]
public List<string> CustomDataValueList { get; set; } // 自定义数据值列表
[JsonProperty("_serializedCodeSwitches")]
public List<int> SerializedCodeSwitches { get; set; } // 序列化代码开关
[JsonProperty("urlCheckCached")]
public bool UrlCheckCached { get; set; } // URL检查缓存
[JsonProperty("urlCheckIsOpen")]
public bool UrlCheckIsOpen { get; set; } // URL检查是否开启
[JsonProperty("urlCheckAllIP")]
public bool UrlCheckAllIP { get; set; } // URL检查所有IP
[JsonProperty("urlCheckTimeOut")]
public int UrlCheckTimeOut { get; set; } // URL检查超时时间
[JsonProperty("urlCheckSueecssTraceCount")]
public int UrlCheckSuccessTraceCount { get; set; } // URL检查成功跟踪计数
[JsonProperty("urlCheckErrorTraceCount")]
public int UrlCheckErrorTraceCount { get; set; } // URL检查错误跟踪计数
[JsonProperty("urlCheckAbortTimeOutCount")]
public int UrlCheckAbortTimeOutCount { get; set; } // URL检查中止超时计数
[JsonProperty("urlCheckTimeInterval")]
public int UrlCheckTimeInterval { get; set; } // URL检查时间间隔
[JsonProperty("urlCheckCDEachReason")]
public int UrlCheckCDEachReason { get; set; } // URL检查每个原因的冷却时间
[JsonProperty("urlCheckBanReasons")]
public List<string> UrlCheckBanReasons { get; set; } // URL检查禁止原因
[JsonProperty("mtrUseOldWinVersion")]
public bool MtrUseOldWinVersion { get; set; } // 使用旧版Windows的MTR
[JsonProperty("greyTestDeviceUniqueId")]
public string GreyTestDeviceUniqueId { get; set; } // 灰度测试设备唯一ID
[JsonProperty("muteAudioOnAppMinimized")]
public bool MuteAudioOnAppMinimized { get; set; } // 应用最小化时静音
[JsonProperty("disableFallbackControllerType")]
public bool DisableFallbackControllerType { get; set; } // 禁用回退控制器类型
[JsonProperty("lastShowDoorProgress")]
public float LastShowDoorProgress { get; set; } // 上次显示门进度
[JsonProperty("globalPerfSettingVersion")]
public int GlobalPerfSettingVersion { get; set; } // 全局性能设置版本
public static string? GetStrFromRegistry()
{
if (GenshinRegistry.GetRegistryKey() is not { } hk)
{
return null;
}
using (hk)
{
string value_name = SearchRegistryName(hk);
if (hk.GetValue(value_name) is not byte[] rawBytes)
{
return null;
}
var str = Encoding.UTF8.GetString(rawBytes);
// Debug.WriteLine(str);
return str;
}
}
public static GenshinGameSettings? Parse(string json)
{
return JsonConvert.DeserializeObject<GenshinGameSettings>(json);
}
private static string SearchRegistryName(RegistryKey key)
{
string value_name = string.Empty;
string[] names = key.GetValueNames();
foreach (string name in names)
{
if (name.Contains("GENERAL_DATA"))
{
value_name = name;
break;
}
}
if (value_name == string.Empty)
{
throw new ArgumentException(value_name);
}
return value_name;
}
}
@@ -33,6 +33,15 @@ public class DirectoryHelper
private static void DeleteDirectory(DirectoryInfo directoryInfo)
{
//通过软链接生成的目录,直接删除该链接目录,而不涉及其文件本体
var attributes = directoryInfo.Attributes;
if ((attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint)
{
directoryInfo.Delete();
return;
}
// 递归处理子目录
foreach (var subDirectory in directoryInfo.GetDirectories())
{
@@ -100,4 +109,34 @@ public class DirectoryHelper
CopyDirectory(subDir, destSubDir); // 递归拷贝子目录
}
}
/// <summary>
/// 递归删除指定目录及其所有子目录和文件
/// </summary>
/// <param name="directoryPath">要删除的目录的路径</param>
public static void DeleteDirectoryRecursively(string directoryPath)
{
// 检查目录是否存在
if (Directory.Exists(directoryPath))
{
// 获取目录中的所有子目录
string[] subDirectories = Directory.GetDirectories(directoryPath);
foreach (string subDirectory in subDirectories)
{
// 递归调用删除子目录
DeleteDirectoryRecursively(subDirectory);
}
// 获取目录中的所有文件
string[] files = Directory.GetFiles(directoryPath);
foreach (string file in files)
{
// 删除文件
File.Delete(file);
}
// 删除空目录
Directory.Delete(directoryPath);
}
}
}
@@ -1,24 +1,26 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace BetterGenshinImpact.Helpers.Http;
public class ProxySpeedTester
{
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(5) };
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(15) };
/// <summary>
/// 代理地址已经无法使用在 babalae 的组织下
/// </summary>
public static readonly List<string> ProxyUrls =
[
"{0}",
"https://mirror.ghproxy.com/{0}",
"https://hub.gitmirror.com/{0}",
"https://ghproxy.net/{0}",
"https://ghproxy.cc/{0}",
"https://www.ghproxy.cc/{0}",
"https://ghproxy.cn/{0}",
"https://ghproxy.net/{0}"
];
/// <summary>
@@ -33,8 +35,19 @@ public class ProxySpeedTester
public static async Task<(string, string)> GetFastestProxyAsync(List<string> proxyAddresses, string target)
{
var tasks = new List<Task<(string, string, bool)>>(); // 修改为包含成功标志的元组
var cts = new CancellationTokenSource();
List<string> urlList = [];
foreach (var proxy in proxyAddresses)
{
// 如果目标地址为空且代理地址为默认地址,则跳过
if (string.IsNullOrEmpty(target) && proxy == "{0}")
{
continue;
}
urlList.Add(string.Format(proxy, target));
}
var (fastUrl, resContent) = await GetFastestUrlAsync(urlList);
foreach (var proxy in proxyAddresses)
{
@@ -44,7 +57,23 @@ public class ProxySpeedTester
continue;
}
tasks.Add(TestProxyAsync(proxy, target, cts.Token));
if (fastUrl == string.Format(proxy, target))
{
return (proxy, resContent);
}
}
return (string.Empty, string.Empty); // 如果没有成功的结果,返回空
}
public static async Task<(string, string)> GetFastestUrlAsync(List<string> urlList)
{
var tasks = new List<Task<(string, string, bool)>>(); // 修改为包含成功标志的元组
var cts = new CancellationTokenSource();
foreach (var url in urlList)
{
tasks.Add(TestUrlAsync(url, cts.Token));
}
while (tasks.Count > 0)
@@ -56,25 +85,29 @@ public class ProxySpeedTester
if (result.Item3) // 检查是否成功
{
await cts.CancelAsync(); // 取消所有其他请求
return (result.Item1, result.Item2); // 返回第一个成功的代理地址
return (result.Item1, result.Item2); // 返回第一个成功的地址
}
}
return (string.Empty, string.Empty); // 如果没有成功的结果,返回空
}
private static async Task<(string, string, bool)> TestProxyAsync(string proxyAddress, string target, CancellationToken cancellationToken)
private static async Task<(string, string, bool)> TestUrlAsync(string url, CancellationToken cancellationToken)
{
try
{
// 模拟代理测试请求
var response = await _httpClient.GetAsync(string.Format(proxyAddress, target), cancellationToken);
var response = await _httpClient.GetAsync(url, cancellationToken);
response.EnsureSuccessStatusCode();
return (proxyAddress, await response.Content.ReadAsStringAsync(cancellationToken), true);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
Debug.WriteLine("SpeedTester", $"Info: {url} - {response.StatusCode} - {content.Length} bytes");
var json = JObject.Parse(content);
return (url, content, true);
}
catch (Exception e)
{
return (proxyAddress, e.Message, false);
Debug.WriteLine("SpeedTester", $"Info: {url} - {e.Message}");
return (url, e.Message, false);
}
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.IO;
using System.Security.AccessControl;
using BetterGenshinImpact.GameTask.Common;
using Microsoft.Extensions.Logging;
namespace BetterGenshinImpact.Helpers;
public static class SecurityControlHelper
{
public static void AllowFullFolderSecurity(string dirPath)
{
if (!RuntimeHelper.IsElevated)
{
return;
}
try
{
DirectoryInfo dir = new(dirPath);
DirectorySecurity dirSecurity = dir.GetAccessControl(AccessControlSections.All);
InheritanceFlags inherits = InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit;
FileSystemAccessRule everyoneFileSystemAccessRule = new("Everyone", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
FileSystemAccessRule usersFileSystemAccessRule = new("Users", FileSystemRights.FullControl, inherits, PropagationFlags.None, AccessControlType.Allow);
dirSecurity.ModifyAccessRule(AccessControlModification.Add, everyoneFileSystemAccessRule, out _);
dirSecurity.ModifyAccessRule(AccessControlModification.Add, usersFileSystemAccessRule, out _);
dir.SetAccessControl(dirSecurity);
}
catch (Exception e)
{
TaskControl.Logger.LogError("首次运行自动初始化按键绑定异常:" + e.Source + "\r\n--" + Environment.NewLine + e.StackTrace + "\r\n---" + Environment.NewLine + e.Message);
MessageBox.Show("检测到当前 BetterGI 位于C盘,尝试修改目录权限失败,可能会导致WebView2相关的功能无法使用!" + e.Message);
}
}
}
@@ -0,0 +1,27 @@
using System;
using System.IO;
using BetterGenshinImpact.Core.Config;
namespace BetterGenshinImpact.Helpers;
public class TempManager
{
public static string GetTempDirectory()
{
var tmp = Global.Absolute("User/Temp");
Directory.CreateDirectory(tmp);
return tmp;
}
public static void CleanUp()
{
try
{
DirectoryHelper.DeleteDirectoryRecursively(GetTempDirectory());
}
catch
{
// Suppress any exceptions to avoid exposing errors
}
}
}
@@ -1,4 +1,7 @@
using BetterGenshinImpact.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using BetterGenshinImpact.Model;
using System.IO;
using System.Linq;
@@ -54,4 +57,103 @@ public class FileTreeNodeHelper
parentNode.Children.Add(fileNode);
}
}
/// <summary>
/// 根据路径过滤树形结构,排除指定路径的节点
/// </summary>
/// <typeparam name="T">节点数据类型</typeparam>
/// <param name="nodes">树形结构的根节点集合</param>
/// <param name="folderNames">要排除的路径集合</param>
/// <returns>过滤后的树形结构</returns>
public static ObservableCollection<FileTreeNode<T>> FilterTree<T>(
ObservableCollection<FileTreeNode<T>> nodes,
List<string> folderNames)
{
// 递归过滤节点
ObservableCollection<FileTreeNode<T>> FilterNodes(ObservableCollection<FileTreeNode<T>> inputNodes, List<string> paths)
{
var filteredNodes = new ObservableCollection<FileTreeNode<T>>();
foreach (var node in inputNodes)
{
// 获取当前层需要排除的路径
var matchedPaths = paths
.Where(path => IsPathMatch(node.FileName ??"", path))
.Select(path => GetRemainingPath(node.FileName ?? "" , path))
.Where(remainingPath => remainingPath != null)
.ToList();
// 如果当前路径完全匹配,跳过当前节点
if (matchedPaths.Any(path => path == ""))
{
continue;
}
// 递归对子节点过滤
node.Children = FilterNodes(node.Children, matchedPaths);
// 添加过滤后的节点
filteredNodes.Add(node);
}
return filteredNodes;
}
return FilterNodes(nodes, folderNames);
}
/// <summary>
/// 判断文件路径是否匹配多级路径的前缀
/// </summary>
/// <param name="fileName">当前节点路径</param>
/// <param name="path">目标路径</param>
/// <returns>是否匹配</returns>
private static bool IsPathMatch(string fileName, string path)
{
// 匹配路径是否以指定前缀开始,路径分隔符对齐
return path.StartsWith(fileName, StringComparison.OrdinalIgnoreCase)
&& (path.Length == fileName.Length || path[fileName.Length] == '\\');
}
/// <summary>
/// 获取路径中去掉当前节点后的剩余路径
/// </summary>
/// <param name="fileName">当前节点路径</param>
/// <param name="path">完整路径</param>
/// <returns>剩余路径,如果不匹配返回 null</returns>
private static string? GetRemainingPath(string fileName, string path)
{
if (IsPathMatch(fileName, path))
{
return path.Length > fileName.Length ? path.Substring(fileName.Length + 1) : "";
}
return null;
}
public static ObservableCollection<FileTreeNode<T>> FilterEmptyNodes<T>(ObservableCollection<FileTreeNode<T>> nodes)
{
// 递归过滤节点
ObservableCollection<FileTreeNode<T>> Filter(ObservableCollection<FileTreeNode<T>> inputNodes)
{
var filteredNodes = new ObservableCollection<FileTreeNode<T>>();
foreach (var node in inputNodes)
{
// 递归处理子节点
node.Children = Filter(node.Children);
// 如果是目录并且没有子节点,跳过当前节点
if (node.IsDirectory && !node.Children.Any())
{
continue;
}
// 其他情况保留节点
filteredNodes.Add(node);
}
return filteredNodes;
}
return Filter(nodes);
}
}
+24 -22
View File
@@ -1,4 +1,5 @@
using System.Windows.Media;
using System.Diagnostics;
using System.Windows.Media;
using BetterGenshinImpact.GameTask;
using Wpf.Ui.Controls;
@@ -8,31 +9,32 @@ public class WindowHelper
{
public static void TryApplySystemBackdrop(System.Windows.Window window)
{
window.Background = new SolidColorBrush(Colors.Transparent);
if (WindowBackdrop.IsSupported(TaskContext.Instance().Config.CommonConfig.CurrentBackdropType))
if (OsVersionHelper.IsWindows11_OrGreater)
{
if (TaskContext.Instance().Config.CommonConfig.CurrentBackdropType == WindowBackdropType.Acrylic)
if (WindowBackdrop.IsSupported(TaskContext.Instance().Config.CommonConfig.CurrentBackdropType))
{
if (TaskContext.Instance().Config.CommonConfig.CurrentBackdropType == WindowBackdropType.Acrylic)
{
window.Background = new SolidColorBrush(Color.FromArgb(100, 0, 0, 0));
}
else
{
window.Background = new SolidColorBrush(Colors.Transparent);
}
WindowBackdrop.ApplyBackdrop(window, TaskContext.Instance().Config.CommonConfig.CurrentBackdropType);
return;
}
if (WindowBackdrop.IsSupported(WindowBackdropType.Mica))
{
window.Background = new SolidColorBrush(Colors.Transparent);
WindowBackdrop.ApplyBackdrop(window, WindowBackdropType.Mica);
}
else if (WindowBackdrop.IsSupported(WindowBackdropType.Acrylic))
{
window.Background = new SolidColorBrush(Color.FromArgb(100, 0, 0, 0));
WindowBackdrop.ApplyBackdrop(window, WindowBackdropType.Acrylic);
}
WindowBackdrop.ApplyBackdrop(window, TaskContext.Instance().Config.CommonConfig.CurrentBackdropType);
return;
}
if (WindowBackdrop.IsSupported(WindowBackdropType.Mica))
{
WindowBackdrop.ApplyBackdrop(window, WindowBackdropType.Mica);
}
else if (WindowBackdrop.IsSupported(WindowBackdropType.Tabbed))
{
WindowBackdrop.ApplyBackdrop(window, WindowBackdropType.Tabbed);
}
else if (WindowBackdrop.IsSupported(WindowBackdropType.Acrylic))
{
WindowBackdrop.ApplyBackdrop(window, WindowBackdropType.Acrylic);
}
}
}
@@ -1,8 +0,0 @@
using BetterGenshinImpact.Service.Notification.Model;
namespace BetterGenshinImpact.Service.Notification.Builder;
public interface INotificationDataBuilder<TNotificationData> where TNotificationData : INotificationData
{
TNotificationData Build();
}
@@ -1,13 +0,0 @@
using BetterGenshinImpact.Service.Notification.Model;
namespace BetterGenshinImpact.Service.Notification.Builder;
public class LifecycleNotificationBuilder : INotificationDataBuilder<LifecycleNotificationData>
{
private readonly LifecycleNotificationData _notificationData = new();
public LifecycleNotificationData Build()
{
return _notificationData;
}
}
@@ -1,88 +0,0 @@
using BetterGenshinImpact.Service.Notification.Model;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using System.Drawing;
namespace BetterGenshinImpact.Service.Notification.Builder;
public class TaskNotificationBuilder : INotificationDataBuilder<TaskNotificationData>
{
private readonly TaskNotificationData _notificationData = new();
public TaskNotificationBuilder WithEvent(NotificationEvent notificationEvent)
{
_notificationData.Event = notificationEvent;
return this;
}
public TaskNotificationBuilder WithAction(NotificationAction notificationAction)
{
_notificationData.Action = notificationAction;
return this;
}
public TaskNotificationBuilder WithConclusion(NotificationConclusion? conclusion)
{
_notificationData.Conclusion = conclusion;
return this;
}
public TaskNotificationBuilder GeniusInvocation()
{
return WithEvent(NotificationEvent.GeniusInvocation);
}
public TaskNotificationBuilder Domain()
{
return WithEvent(NotificationEvent.Domain);
}
public TaskNotificationBuilder Started()
{
return WithAction(NotificationAction.Started);
}
public TaskNotificationBuilder Completed()
{
return WithAction(NotificationAction.Completed);
}
public TaskNotificationBuilder Progress()
{
return WithAction(NotificationAction.Progress);
}
public TaskNotificationBuilder Success()
{
return WithAction(NotificationAction.Completed)
.WithConclusion(NotificationConclusion.Success);
}
public TaskNotificationBuilder Failure()
{
return WithAction(NotificationAction.Completed)
.WithConclusion(NotificationConclusion.Failure);
}
public TaskNotificationBuilder Cancelled()
{
return WithAction(NotificationAction.Completed)
.WithConclusion(NotificationConclusion.Cancelled);
}
public TaskNotificationBuilder WithScreenshot(Image? screenshot)
{
_notificationData.Screenshot = screenshot;
return this;
}
public TaskNotificationBuilder AddTask(object task)
{
_notificationData.Task = task;
return this;
}
public TaskNotificationData Build()
{
return _notificationData;
}
}
@@ -0,0 +1,28 @@
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Service.Notification.Converter;
public class BaseDateTimeJsonConverter(string format) : JsonConverter<DateTime>
{
// 反序列化方法
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
if (DateTime.TryParseExact(reader.GetString(), format, null, System.Globalization.DateTimeStyles.None, out DateTime date))
{
return date;
}
}
return reader.GetDateTime();
}
// 序列化方法
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString(format));
}
}
@@ -0,0 +1,7 @@
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Service.Notification.Converter;
public class DateTimeJsonConverter() : BaseDateTimeJsonConverter("yyyy-MM-dd HH:mm:ss")
{
}
@@ -11,11 +11,11 @@ public class ImageToBase64Converter : JsonConverter<Image>
{
public override Image? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.GetString() is string base64)
if (reader.GetString() is { } base64)
{
return Image.FromStream(new MemoryStream(Convert.FromBase64String(base64)));
}
return default;
return null;
}
public override void Write(Utf8JsonWriter writer, Image value, JsonSerializerOptions options)
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.Service.Notification.Model.Base;
// TODO: 需要制定标准 (currently not referenced)
public class DomainDetails
{
public string DomainName { get; set; } = string.Empty;
public int RunCount { get; set; }
public string RewardStatus { get; set; } = string.Empty;
}
@@ -0,0 +1,9 @@
namespace BetterGenshinImpact.Service.Notification.Model.Base;
// TODO: 需要制定标准 (currently not referenced)
public class GeniusInvocationDetails
{
public string GameState { get; set; } = string.Empty;
public int RoundNumber { get; set; }
public string OpponentName { get; set; } = string.Empty;
}
@@ -0,0 +1,8 @@
namespace BetterGenshinImpact.Service.Notification.Model.Base;
// TODO: 需要制定标准 (currently not referenced)
public class ScriptDetails
{
public string ScriptName { get; set; } = string.Empty;
public string ScriptPath { get; set; } = string.Empty;
}
@@ -0,0 +1,90 @@
using System;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using System.Text.Json.Serialization;
using System.Drawing;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.Service.Notification.Converter;
namespace BetterGenshinImpact.Service.Notification.Model;
public class BaseNotificationData
{
/// <summary>
/// NotificationEvent
/// 事件名称
/// </summary>
public string Event { get; set; } = string.Empty;
/// <summary>
/// 事件结果
/// </summary>
[JsonConverter(typeof(JsonStringEnumConverter))]
public NotificationEventResult Result { get; set; }
/// <summary>
/// 事件触发时间
/// </summary>
[JsonConverter(typeof(DateTimeJsonConverter))]
public DateTime Timestamp { get; set; } = DateTime.Now;
/// <summary>
/// 事件触发时的截图
/// </summary>
[JsonConverter(typeof(ImageToBase64Converter))]
public Image? Screenshot { get; set; }
/// <summary>
/// 事件消息
/// </summary>
public string? Message { get; set; }
/// <summary>
/// 额外的事件数据
/// </summary>
public object? Data { get; set; }
public void Send()
{
if (TaskContext.Instance().Config.NotificationConfig.IncludeScreenShot)
{
Screenshot = (Bitmap)TaskControl.CaptureToRectArea().SrcBitmap.Clone();
}
NotificationService.Instance().NotifyAllNotifiers(this);
}
public void Send(string message)
{
Message = message;
Send();
}
public void Success(string message)
{
Message = message;
Result = NotificationEventResult.Success;
Send();
}
public void Fail(string message)
{
Message = message;
Result = NotificationEventResult.Fail;
Send();
}
public void Error(string message)
{
Message = message;
Result = NotificationEventResult.Fail;
Send();
}
public void Error(string message, Exception exception)
{
Message = message + Environment.NewLine + exception.Message + Environment.NewLine + exception.StackTrace;
Result = NotificationEventResult.Fail;
Send();
}
}
@@ -0,0 +1,11 @@
using BetterGenshinImpact.GameTask.AutoDomain;
using BetterGenshinImpact.Service.Notification.Model.Base;
using BetterGenshinImpact.Service.Notification.Model.Enum;
using System.Text.Json.Serialization;
namespace BetterGenshinImpact.Service.Notification.Model;
public class DomainNotificationData : BaseNotificationData
{
public AutoDomainParam? Domain { get; set; }
}
@@ -1,8 +0,0 @@
namespace BetterGenshinImpact.Service.Notification.Model.Enum;
public enum NotificationAction
{
Started,
Completed,
Progress
}
Loaded 100 of 148 files, more files were not shown because too many files have changed in this diff. Show more