Compare commits

..
Author SHA1 Message Date
辉鸭蛋 c4a7823c83 fix js pathingScript 2024-10-13 22:58:42 +08:00
辉鸭蛋 50aac5cea0 auto pathing opt 2024-10-13 22:12:07 +08:00
辉鸭蛋 228d50bb5d Revert "feat: 优化autopath MoveTo逻辑"
This reverts commit 504f853893.
2024-10-13 21:09:41 +08:00
辉鸭蛋 5e16f48cf2 update pating ui 2024-10-13 20:51:02 +08:00
辉鸭蛋 6fb29ddfad Xilonen 5.1 2024-10-13 20:46:56 +08:00
辉鸭蛋 ac4dde6bf0 Merge pull request #685 from gqzcl/main_path
feat: 优化autopath MoveTo逻辑
2024-10-13 18:50:49 +08:00
辉鸭蛋 6c643b2419 删除一些默认用户配置 2024-10-13 18:27:03 +08:00
辉鸭蛋 2f44905c27 rm script 2024-10-13 18:24:06 +08:00
辉鸭蛋 b2cf62a21c add local script repo web
重构了 `AvatarClassifyGen.cs` 中的图像读取逻辑,现在只读取一个图像文件。`AllConfig.cs` 中添加了 `ScriptConfig` 类的配置,并监听其属性变化。`ScriptRepoUpdater.cs` 中引入了多个新命名空间,添加了 `_logger` 和 `_webWindow` 字段,新增了 `AutoUpdate` 方法,修改了 `UpdateCenterRepo` 方法,新增了 `FindCenterRepoPath`、`ImportScriptFromUri` 和 `OpenLocalRepoInWebView` 方法。`WebpagePanel.cs` 中添加了 `OnWebViewInitializedAction` 属性。`WebpageWindow.cs` 中注释掉了背景色设置。`MainWindow.xaml` 中修改了标题栏图标路径。`JsListPage.xaml`、`KeyMouseRecordPage.xaml` 和 `MapPathingPage.xaml` 中修改了按钮命令绑定。`MainWindowViewModel.cs` 中添加了 `AutoUpdate` 方法调用。`JsListViewModel.cs`、`KeyMouseRecordPageViewModel.cs` 和 `MapPathingViewModel.cs` 中添加了 `Config` 属性和 `OnOpenLocalScriptRepo` 命令。新增了 `ScriptConfig.cs` 和 `RepoWebBridge.cs` 文件,定义了 `ScriptConfig` 和 `RepoWebBridge` 类。
2024-10-13 18:13:28 +08:00
辉鸭蛋 245c05b208 1st logo #671 2024-10-13 15:42:49 +08:00
辉鸭蛋 333ad6f0b4 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-13 13:36:10 +08:00
辉鸭蛋 c75dbbc241 add script repo downloader 2024-10-13 13:36:06 +08:00
ema 421b11504f fix: titlebar accent color #442 2024-10-13 03:02:19 +08:00
辉鸭蛋 bb18350457 fix mouse move for js 2024-10-11 03:12:38 +08:00
辉鸭蛋 831f28b2aa WPF-UI.Violeta 3.0.5.18 https://github.com/emako/wpfui.violeta/issues/5 2024-10-10 22:00:30 +08:00
辉鸭蛋 475b9bbd00 update ui text & ProxySpeedTester
删除了 `ClickOffset` 类及其相关代码。
在 `MainWindow.xaml` 中,将导航菜单项的内容从“脚本”更改为“JS 脚本”。
在 `JsListPage.xaml` 和 `KeyMouseRecordPage.xaml` 中,更新了文本内容,并添加了指向相关教程的超链接。
在 `JsListViewModel.cs` 和 `KeyMouseRecordPageViewModel.cs` 中,分别添加了 `OnGoToJsScriptUrl` 和 `OnGoToKmScriptUrl` 方法,用于打开对应的教程 URL。
新增了 `ProxySpeedTester.cs` 文件,包含一个用于测试代理速度的类 `ProxySpeedTester`,提供了获取最快代理地址的方法。
2024-10-10 21:58:35 +08:00
辉鸭蛋 a963a8595a auto pick: add black list
新增黑名单条目至 pick_black_lists.json
2024-10-10 01:20:41 +08:00
辉鸭蛋 5c712c5a31 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-09 23:56:01 +08:00
辉鸭蛋 8651ec74a6 update ui 2024-10-09 23:53:55 +08:00
辉鸭蛋 6fadd528f1 Merge pull request #690 from haokaiyang/main
auto tcg: update character card config to v5.1
2024-10-09 13:32:26 +08:00
haokaiyang f20cf89d5f auto tcg: update character card config to v5.1 2024-10-09 11:25:59 +08:00
辉鸭蛋 c13db0a501 rename 2024-10-08 00:21:56 +08:00
辉鸭蛋 7b80867bd1 update ui 2024-10-06 21:05:42 +08:00
辉鸭蛋 a2f877c455 increase the minimum waiting time for the transmission panel delay to 300 milliseconds
增加传送面板延迟的最小等待时间至 300 毫秒

将 `time` 的最小值从 100 毫秒增加到 300 毫秒。这意味着在等待传送面板延迟时,最小等待时间从 100 毫秒变为 300 毫秒。
2024-10-06 14:50:53 +08:00
gqzcl 504f853893 feat: 优化autopath MoveTo逻辑 2024-10-05 14:04:20 +08:00
辉鸭蛋 b1f6c062fb auto tp: add blocked click area
主要变更:
- 在 `TpTask` 构造函数中添加了两个新的私有只读字段 `_captureRect` 和 `_zoomOutMax1080PRatio`。
- 在 `TpOnce` 方法中,使用新的私有字段 `_zoomOutMax1080PRatio` 替代局部变量 `s`。
- 将 `while` 循环条件改为调用新的私有方法 `IsPointInBigMapWindow`。
- 删除了原来计算点击坐标的代码,改为调用新的私有方法 `ConvertToGameRegionPosition`。
- 添加了新的私有方法 `IsPointInBigMapWindow` 和 `ConvertToGameRegionPosition`。
- 更新了子项目的提交版本。

这些更改通过引入新的私有方法和字段,减少了重复代码,并使逻辑更加清晰,代码变得更加模块化,便于后续的维护和扩展。
2024-10-04 19:57:18 +08:00
辉鸭蛋 876a833590 fix: js script bug 2024-10-04 19:04:32 +08:00
辉鸭蛋 160e45c75a fix JustTp 2024-10-04 14:24:42 +08:00
辉鸭蛋 66f15488e1 add bgi version 2024-10-03 20:14:04 +08:00
辉鸭蛋 389dac879b js: add CaptureGameRegion 2024-10-03 16:24:56 +08:00
辉鸭蛋 8b6351cbd6 update: simulator for js 2024-10-03 00:40:07 +08:00
辉鸭蛋 ca126e0d66 js: +func 2024-10-02 19:20:25 +08:00
辉鸭蛋 6c0b293328 js: add solo task 2024-10-01 21:34:33 +08:00
辉鸭蛋 aee54cc115 js config 2024-10-01 20:25:39 +08:00
辉鸭蛋 2817479d33 Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-10-01 20:10:51 +08:00
辉鸭蛋 8de5bcf987 auto pick: ForceInteraction 2024-10-01 20:10:46 +08:00
辉鸭蛋 a25cc951c9 new banner 2024-10-01 20:10:23 +08:00
辉鸭蛋 50ee1d1a3e Merge pull request #679 from lwh9346/main
添加了一些可靠的路径追踪捡狗粮路线
2024-10-01 19:15:22 +08:00
lwh9346 7f39062f14 添加了一些可靠的路径追踪捡狗粮路线 2024-10-01 16:56:31 +08:00
ema 619cb667cd chore: doc about game cli #665 2024-10-01 14:16:13 +08:00
ema 4da6efd54e fix the all about scrollable 2024-10-01 13:50:59 +08:00
辉鸭蛋 5fe3db52bf fix hotkey bug 2024-10-01 13:36:53 +08:00
辉鸭蛋 d760f2411a Merge pull request #676 from babalae/feat/btn
add TwoStateButton
2024-10-01 12:42:31 +08:00
辉鸭蛋 1706312957 wpfui.violeta 3.0.5.16 2024-10-01 12:35:08 +08:00
辉鸭蛋 d686fdcb5a auto skip black list #677 2024-10-01 12:17:01 +08:00
辉鸭蛋 a93839e0be refactor: hotkey UI to a tree view 2024-10-01 01:58:00 +08:00
辉鸭蛋 6e00e3f91e collect fight screenshots 2024-10-01 01:56:53 +08:00
qhy040404 41c5f4c226 fix wrong state 2024-10-01 00:04:35 +08:00
qhy040404 95f7b76a03 add TwoStateButton 2024-09-30 23:17:10 +08:00
辉鸭蛋 c137daec40 fix ui 2024-09-30 22:04:01 +08:00
辉鸭蛋 c89e2d4e84 upgrade build ps1
在 `upload_1_build_dist.cmd` 文件中:
- 添加了切换到当前脚本目录的命令 `cd /d %~dp0`。
- 添加了删除 `dist` 目录及其子目录的命令 `if exist dist rd /s /q dist`。
- 添加了创建 `dist\BetterGI` 目录的命令 `mkdir dist\BetterGI`。
- 添加了准备编译器的命令,使用 `vswhere.exe` 查找最新的 Visual Studio 安装路径并设置环境变量。
- 添加了准备版本信息的命令,使用 PowerShell 从 `BetterGenshinImpact.csproj` 文件中提取 `AssemblyVersion`。
- 添加了设置临时文件夹和归档文件名的命令。
- 添加了使用 Visual Studio 2022 构建应用程序的命令。
- 添加了使用 7z 打包应用程序的命令。
- 添加了删除特定文件(如 `.lib` 和 `ffmpeg` DLL 文件)的命令。
- 添加了从特定路径复制文件到临时文件夹的命令。
- 添加了暂停命令 `@pause`。

在 `upload_2_zip_dist.ps1` 文件中:
- 添加了导入 `Microsoft.PowerShell.Archive` 模块的命令。
- 添加了设置目录路径、输出 JSON 路径和目标目录路径的命令。
- 添加了将相对路径转换为绝对路径的命令。
- 添加了初始化排除目录列表的命令。
- 添加了初始化一个空的哈希表来存储文件路径和哈希值的命令。
- 添加了获取目录中所有文件的命令。
- 添加了遍历文件列表并计算每个文件的 SHA256 哈希值的命令。
- 添加了将文件路径和哈希值添加到哈希表中的命令。
- 添加了压缩文件并替换原文件的命令。
- 添加了将哈希表转换为 JSON 格式并写入文件的命令。
- 添加了获取所有 `.zip` 文件并复制到目标目录的命令。
- 添加了删除原始目录的命令。
2024-09-30 22:03:55 +08:00
辉鸭蛋 1901246bab Merge branch 'main' of https://github.com/babalae/better-genshin-impact 2024-09-30 14:02:45 +08:00
辉鸭蛋 c15cb33c2c rename variables and properties, refactor code, add new configuration options
重命名变量和属性,重构代码,添加新配置选项

主要更改:
* 将 `AutoFightConfig` 和 `AutoFightParam` 类中的字段和属性重命名,以提高名称的清晰度和一致性。
* 移除不必要的 `using` 语句,并调整顺序。
* 重构 `AutoFightTask` 和 `AutoFightHandler` 类中的条件判断和方法逻辑。
* 调整 `CameraRotateTask` 类中的参数值。
* 在 `PathExecutor` 类中添加 `_rotateTask` 字段,并修改相关方法调用。
* 在 `TaskSettingsPage.xaml` 中添加新的配置选项。
* 在 `HotKeyPageViewModel` 类中添加 `using` 语句,并修改热键回调逻辑。
* 修改 `TaskSettingsPageViewModel` 类中 `AutoFightParam` 的初始化。
2024-09-30 13:42:11 +08:00
ema 377de9e244 update: use embedded pdb 2024-09-30 10:29:19 +08:00
ema 335b053b32 change: moved image assets to new folder 2024-09-30 10:12:13 +08:00
辉鸭蛋 2516f9b248 fix tp task 2024-09-30 00:30:00 +08:00
辉鸭蛋 d9e5f2f1dd add rotate task
在 `BgiYoloV8Predictor.cs` 文件中,添加了 `System.Diagnostics`、`System.Drawing.Imaging` 和 `System.IO` 的引用,并在 YOLOv8 识别结果返回前,添加了调试输出,使用 `JsonSerializer` 序列化识别结果并输出到调试窗口。

在 `AutoFightTask.cs` 文件中,添加了 `System.Collections.Generic` 和 `BetterGenshinImpact.GameTask.AutoPathing` 的引用,修改了 `combatScenes.BeforeTask` 方法的调用,使用新的取消令牌 `cts2`。在战斗操作的 `Task.Run` 中添加了 `try-catch` 块,以捕获并忽略异常。修改了战斗结束检测线程,使用 `async` 和 `await` 关键字,并在检测战斗结束时添加了 `try-catch` 块。修改了 `CheckFightFinish` 方法,改为异步方法 `CheckFightFinish`,并在检测战斗结束时添加了旋转视角的逻辑。

在 `PathExecutor.cs` 文件中,添加了关于 DPI 和分辨率影响转动速度的注释。

在 `TaskSettingsPageViewModel.cs` 文件中,在获取战斗策略后,创建了 `AutoFightParam` 对象,并设置了 `EndDetect` 和 `AutoPickAfterFight` 参数。修改了 `RunSoloTaskAsync` 方法的调用,传入了新的 `AutoFightParam` 对象。

在 `CameraRotateTask.cs` 文件中,添加了新的 `CameraRotateTask` 类,用于处理相机视角的旋转,实现了 `RotateToApproach` 方法,用于将视角旋转到接近目标角度,实现了 `WaitUntilRotatedTo` 异步方法,用于等待视角旋转到目标角度。
2024-09-30 00:10:08 +08:00
辉鸭蛋 0549df75b6 auto fight: init end detect
在 `BetterGenshinImpact.csproj` 文件中,删除了 `Assets\Model\World\` 和 `Script\JustTp\` 文件夹的包含项。

在 `AutoFightConfig.cs` 文件中,`AutoFightConfig` 类新增了两个属性:`_endDetect` 和 `_autoPickAfterFight`,并且默认值分别为 `true`。

在 `AutoFightParam.cs` 文件中,`AutoFightParam` 类新增了两个属性:`EndDetect` 和 `AutoPickAfterFight`,并且默认值分别为 `false`。

在 `AutoFightTask.cs` 文件中:
  * 修改了 `using` 引用,添加了 `BetterGenshinImpact.Core.Config` 和 `BetterGenshinImpact.GameTask.Model.Area`,删除了 `BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception`。
  * 在 `AutoFightTask` 类中,新增了 `_predictor` 和 `_lastFightFlagTime` 字段。
  * 在 `AutoFightTask` 构造函数中,增加了对 `EndDetect` 和 `AutoPickAfterFight` 属性的检查,并在满足条件时初始化 `_predictor`。
  * 修改了 `Start` 方法,增加了战斗结束检测线程和自动拾取掉落物的功能。
  * 新增了 `CheckFightFinish` 和 `HasFightFlag` 方法,用于检测战斗是否结束。

在 `BetterGenshinImpact.Core.Recognition.ONNX` 命名空间下新增了 `BgiYoloV8Predictor` 类,并实现了 `IDisposable` 接口。
  * 添加了一个只读字段 `_predictor`,并通过 `YoloV8Builder` 创建了一个默认的 YoloV8 预测器。
  * 添加了一个 `Predictor` 属性,用于获取 `_predictor`。
  * 添加了一个 `Detect` 方法,该方法接受一个 `ImageRegion` 对象作为参数,并返回一个包含类别和矩形框的字典。
  * 添加了 `Dispose` 方法,用于释放 `_predictor` 的资源。
2024-09-29 23:01:29 +08:00
辉鸭蛋 35264bc855 auto tp: throwing an exception when the tp point is not activated
在 `TpTask.cs` 文件中,添加了 `using BetterGenshinImpact.GameTask.Common.Exceptions;` 引用,并在 `TpTask` 类中添加了对 `TpPointNotActivate` 异常的处理逻辑,当传送点未激活或不存在时,按下 ESC 键返回大地图界面,并抛出异常。同时在 `ClickTpPoint` 方法中,修改了判断逻辑,增加了对传送点未激活或不存在的异常处理。

在 `MapAssets.cs`、`NewRetry.cs`、`TaskControl.cs` 文件中,将 `Exception` 修改为 `System.Exception`。

在 `NormalEndException.cs` 和 `RetryException.cs` 文件中,删除了旧的异常类定义,并重新添加了新的异常类定义。

在 `TpPointNotActivate.cs` 文件中,添加了新的异常类 `TpPointNotActivate`。
2024-09-29 21:37:54 +08:00
辉鸭蛋 5167ce0ba8 Merge pull request #658 from iris10086/iris-dev
在路径追踪中添加了一个AutoFightAction实现
2024-09-25 10:58:16 +08:00
辉鸭蛋 7df330a9fb 低分辨率缩放 2024-09-24 01:18:26 +08:00
辉鸭蛋 24c2d2cbf0 直接调用重构后的自动战斗独立任务
移除了 `AutoFightHandler` 类中的 `_combatScriptBag` 相关代码,并替换为新的 `AutoFightTask` 任务。
添加了新的命名空间引用,包括 `BetterGenshinImpact.GameTask.AutoFight`、`BetterGenshinImpact.GameTask.Common.TaskControl`、`System.IO` 和 `Wpf.Ui.Violeta.Controls`。
在 `StartFight` 方法中,替换了原有的战斗操作逻辑,使用 `AutoFightTask` 类来处理战斗任务。
添加了新的 `GetFightStrategy` 方法,用于获取战斗策略文件路径。
修改了战斗结束检测逻辑,将 `checkFightFinish` 方法重命名为 `CheckFightFinish`,并调整了检测逻辑。
调整了任务取消的逻辑,使用新的 `CancellationTokenSource` 实例 `cts2` 来管理任务取消。
将原有的 `Task` 实例替换为 `Task.Run` 方法来启动任务。
调整了任务等待逻辑,使用 `Task.WhenAll` 方法等待战斗任务和结束检测任务的完成。
2024-09-23 22:24:58 +08:00
辉鸭蛋 d51139025b 便携营养袋 的判断进行前置,减少无意义的性能损耗 2024-09-23 22:21:12 +08:00
辉鸭蛋 e7148f827d Merge branch 'iris-dev' of https://github.com/iris10086/better-genshin-impact into pr/658 2024-09-23 21:59:59 +08:00
辉鸭蛋 3d5d918d24 Merge branch 'main' into pr/658 2024-09-23 21:59:16 +08:00
何杰泽 ff969abbc7 自动吃药 添加了是否携带食物的检测 2024-09-23 21:18:24 +08:00
iris10086 541e9331c0 Merge branch 'babalae:main' into iris-dev 2024-09-23 20:44:10 +08:00
辉鸭蛋 89340c42b0 code cleanup 2024-09-22 00:01:10 +08:00
iris10086 6cf96c71f3 Merge branch 'babalae:main' into iris-dev 2024-09-21 16:02:40 +08:00
何杰泽 997059dd4b 添加fight action。战斗结束策略比较low。 2024-09-21 15:56:37 +08:00
128 changed files with 3286 additions and 1318 deletions

No files matched your search

@@ -19,17 +19,17 @@ public class AvatarClassifyGen
// 读取基础图像
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Emilie.png", SearchOption.TopDirectoryOnly).ToList();
List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_MomokaCostumeErrantry.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles2);
List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_NilouCostumeFairy.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles3);
List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kachina.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles4);
List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mualani.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles5);
List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kinich.png", SearchOption.TopDirectoryOnly).ToList();
sideImageFiles.AddRange(sideImageFiles6);
List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Xilonen.png", SearchOption.TopDirectoryOnly).ToList();
// List<string> sideImageFiles2 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_MomokaCostumeErrantry.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles2);
// List<string> sideImageFiles3 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_NilouCostumeFairy.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles3);
// List<string> sideImageFiles4 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kachina.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles4);
// List<string> sideImageFiles5 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Mualani.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles5);
// List<string> sideImageFiles6 = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "UI_AvatarIcon_Side_Kinich.png", SearchOption.TopDirectoryOnly).ToList();
// sideImageFiles.AddRange(sideImageFiles6);
// 生成训练集
GenTo(sideImageFiles, Path.Combine(BaseDir, @"dateset\train"), 200);
+2 -6
View File
@@ -1,17 +1,13 @@
using System.Windows;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Test.Dataset;
using BetterGenshinImpact.Test.Simple;
using BetterGenshinImpact.Test.Simple.AllMap;
using BetterGenshinImpact.Test.Simple.Track;
using BetterGenshinImpact.Test.View;
using System.Windows;
namespace BetterGenshinImpact.Test;
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 199 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 114 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 197 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 198 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 108 KiB

@@ -0,0 +1,21 @@
# 启动参数说明
启动参数本质是 Unity 独立平台播放器命令行参数 ,测试下来有用的参数大概如下:
- `-window-mode exclusive` 参数
- **独占全屏**,即选择游戏进程以独占全屏模式运行
- **该功能与游戏内浏览器功能不兼容,你应仅在能独立描述独占全屏的技术原理和效果的情况下开启本项**
- `-screen-fullscreen` 参数
- **全屏**,即选择启动游戏后的游戏界面是否设置为全屏
- `-popupwindow` 参数
- **无边框**,即选择启动游戏后的游戏界面是否设置为无边框窗口
- `-platform_type CLOUD_THIRD_PARTY_MOBILE` 参数
- **触摸屏模式**,即启用原神内置的触摸屏操作模式(键鼠输入将被忽略)
- 分辨率
- 该功能可以快速设置下方的覆盖屏幕宽度和高度选项,有一些常见的预设项可供选择
- `-screen-width` 参数
- **宽度**,即选择启动游戏后的游戏界面的宽度,例如 `1920`
- `-screen-height` 参数
- **高度**,即选择启动游戏后的游戏界面的高度,例如 `1080`
- `-monitor` 参数
- **显示器**,允许多显示器用户选择指定的显示器来运行游戏
Binary file not shown.

Before

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 76 KiB

+15 -19
View File
@@ -8,29 +8,34 @@
<UseWindowsForms>true</UseWindowsForms>
<LangVersion>12.0</LangVersion>
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<ApplicationIcon>Assets\logo.ico</ApplicationIcon>
<ApplicationIcon>Assets\Images\Anniversary\logo_1st.ico</ApplicationIcon>
<AssemblyName>BetterGI</AssemblyName>
<AssemblyVersion>0.34.4</AssemblyVersion>
<AssemblyVersion>0.34.6</AssemblyVersion>
<Platforms>x64</Platforms>
<DebugType>embedded</DebugType>
</PropertyGroup>
<ItemGroup>
<None Remove="Assets\*.jpg" />
<None Remove="Assets\*.png" />
<None Remove="Assets\*.ico" />
<None Remove="Assets\Images\*.jpg" />
<None Remove="Assets\Images\*" />
<None Remove="Assets\Images\*.png" />
<None Remove="Assets\Images\*.ico" />
<None Remove="Assets\Fonts\*.ttf" />
<None Remove="Assets\Highlighting\*.xshd" />
<None Remove="Assets\Strings\*.html" />
<None Remove="Assets\Strings\*.md" />
<None Remove="Assets\Audios\*.mp3" />
</ItemGroup>
<ItemGroup>
<Resource Include="Assets\*.jpg" />
<Resource Include="Assets\*.png" />
<Resource Include="Assets\*.ico" />
<Resource Include="Assets\Images\*.jpg" />
<Resource Include="Assets\Images\Anniversary\*" />
<Resource Include="Assets\Images\*.png" />
<Resource Include="Assets\Images\*.ico" />
<Resource Include="Assets\Fonts\*.ttf" />
<Resource Include="Assets\Highlighting\*.xshd" />
<Resource Include="Assets\Strings\*.html" />
<Resource Include="Assets\Strings\*.md" />
<Resource Include="Assets\Audios\*.mp3" />
</ItemGroup>
@@ -64,7 +69,7 @@
<PackageReference Include="Vanara.PInvoke.User32" Version="4.0.2" />
<PackageReference Include="WPF-UI" Version="3.0.5" />
<PackageReference Include="WPF-UI.Tray" Version="3.0.5" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.12" />
<PackageReference Include="WPF-UI.Violeta" Version="3.0.5.18" />
<PackageReference Include="YoloV8" Version="4.1.7" />
<PackageReference Include="gong-wpf-dragdrop" Version="3.2.1" />
</ItemGroup>
@@ -130,19 +135,10 @@
<None Update="User\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="Script\**">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Script\JustTp\" />
</ItemGroup>
<ItemGroup>
<Compile Update="View\Pages\MapPathingPage.xaml.cs">
<SubType>Code</SubType>
</Compile>
<Folder Include="User\AutoPathing\" />
</ItemGroup>
</Project>
+8 -1
View File
@@ -122,12 +122,17 @@ public partial class AllConfig : ObservableObject
public AutoDomainConfig AutoDomainConfig { get; set; } = new();
/// <summary>
/// 脚本类配置
/// 宏配置
/// </summary>
public MacroConfig MacroConfig { get; set; } = new();
public RecordConfig RecordConfig { get; set; } = new();
/// <summary>
/// 脚本配置
/// </summary>
public ScriptConfig ScriptConfig { get; set; } = new();
/// <summary>
/// 快捷键配置
/// </summary>
@@ -160,6 +165,8 @@ public partial class AllConfig : ObservableObject
AutoWoodConfig.PropertyChanged += OnAnyPropertyChanged;
AutoFightConfig.PropertyChanged += OnAnyPropertyChanged;
AutoDomainConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
+1 -6
View File
@@ -29,12 +29,7 @@ public class Global
public static string ScriptPath()
{
return Absolute("Script");
}
public static string ScriptPath(string folderName)
{
return Path.Combine(Absolute("Script"), folderName);
return Absolute("User\\JsScript");
}
public static string? ReadAllTextIfExist(string relativePath)
@@ -0,0 +1,28 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.Core.Config;
/// <summary>
/// 脚本配置
/// </summary>
[Serializable]
public partial class ScriptConfig : ObservableObject
{
// 自动更新脚本仓库周期(天)
[ObservableProperty]
private int _autoUpdateScriptRepoPeriod = 1;
// 上次更新脚本仓库时间
[ObservableProperty]
private DateTime _lastUpdateScriptRepoTime = DateTime.MinValue;
// 脚本仓库按钮红点是否展示
[ObservableProperty]
private bool _scriptRepoHintDotVisible = false;
// 已订阅的脚本路径列表
[ObservableProperty]
private List<string> _subscribedScriptPaths = [];
}
@@ -23,7 +23,7 @@ public class PaddleOcrService : IOcrService
public PaddleOcrService()
{
var path = Global.Absolute("Assets\\Model\\PaddleOcr");
var path = Global.Absolute(@"Assets\Model\PaddleOcr");
var localDetModel = DetectionModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_det"), ModelVersion.V4);
var localClsModel = ClassificationModel.FromDirectory(Path.Combine(path, "ch_ppocr_mobile_v2.0_cls"));
var localRecModel = RecognizationModel.FromDirectory(Path.Combine(path, "ch_PP-OCRv4_rec"), Path.Combine(path, "ppocr_keys_v1.txt"), ModelVersion.V4);
@@ -0,0 +1,55 @@
using System;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Model.Area;
using Compunet.YoloV8;
using OpenCvSharp;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing.Imaging;
using System.IO;
using System.Text.Json;
namespace BetterGenshinImpact.Core.Recognition.ONNX;
public class BgiYoloV8Predictor(string modelRelativePath) : IDisposable
{
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute(modelRelativePath))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
public YoloV8Predictor Predictor => _predictor;
/// <summary>
/// 检测
/// </summary>
/// <param name="region">图像</param>
/// <returns>类别-矩形框</returns>
public Dictionary<string, List<Rect>> Detect(ImageRegion region)
{
using var memoryStream = new MemoryStream();
region.SrcBitmap.Save(memoryStream, ImageFormat.Bmp);
memoryStream.Seek(0, SeekOrigin.Begin);
var result = _predictor.Detect(memoryStream);
var dict = new Dictionary<string, List<Rect>>();
foreach (var box in result.Boxes)
{
if (!dict.ContainsKey(box.Class.Name))
{
dict[box.Class.Name] = [new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height)];
}
else
{
dict[box.Class.Name].Add(new Rect(box.Bounds.X, box.Bounds.Y, box.Bounds.Width, box.Bounds.Height));
}
}
Debug.WriteLine("YOLOv8识别结果:" + JsonSerializer.Serialize(dict));
return dict;
}
public void Dispose()
{
_predictor.Dispose();
}
}
@@ -23,12 +23,12 @@ public class PickTextInference : ITextInference
public PickTextInference()
{
var modelPath = Global.Absolute("Assets\\Model\\Yap\\model_training.onnx");
var modelPath = Global.Absolute(@"Assets\Model\Yap\model_training.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("Yap模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, BgiSessionOption.Instance.Options);
var wordJsonPath = Global.Absolute("Assets\\Model\\Yap\\index_2_word.json");
var wordJsonPath = Global.Absolute(@"Assets\Model\Yap\index_2_word.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("Yap字典文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -15,12 +15,12 @@ public class Predictor
public Predictor()
{
var options = new SessionOptions();
var modelPath = Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx");
var modelPath = Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx");
if (!File.Exists(modelPath)) throw new FileNotFoundException("自动钓鱼模型文件不存在", modelPath);
_session = new InferenceSession(modelPath, options);
var wordJsonPath = Global.Absolute("Assets\\Model\\Fish\\label.json");
var wordJsonPath = Global.Absolute(@"Assets\Model\Fish\label.json");
if (!File.Exists(wordJsonPath)) throw new FileNotFoundException("自动钓鱼模型分类文件不存在", wordJsonPath);
var json = File.ReadAllText(wordJsonPath);
@@ -9,6 +9,15 @@ public class KeyMouseScriptInfo
public string Description { get; set; } = string.Empty;
public string? Author { get; set; }
public string? Version { get; set; }
/// <summary>
/// 制作时 BetterGI 的版本,用于兼容性检查
/// </summary>
public string? BgiVersion { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
@@ -1,19 +1,14 @@
using System.Threading.Tasks;
using System.Text.Json;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Core.Script.Dependence;
internal class AutoPathing(string rootPath)
public class AutoPathingScript(string rootPath)
{
public async Task Run(string json)
{
var task = JsonSerializer.Deserialize<PathingTask>(json);
if (task == null)
{
return;
}
var task = PathingTask.BuildFromJson(json);
await new PathExecutor(CancellationContext.Instance.Cts).Pathing(task);
}
@@ -1,6 +1,9 @@
using BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.ViewModel.Pages;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoDomain;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -29,4 +32,60 @@ public class Dispatcher
TaskTriggerDispatcher.Instance().AddTrigger(realtimeTimer.Name, realtimeTimer.Config);
}
/// <summary>
/// 运行独立任务
/// </summary>
/// <param name="soloTask">
/// 支持的任务名称:
/// - AutoGeniusInvokation: 启动自动七圣召唤任务
/// - AutoWood: 启动自动伐木任务
/// - AutoFight: 启动自动战斗任务
/// - AutoDomain: 启动自动秘境任务
/// </param>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
public async Task RunTask(SoloTask soloTask)
{
if (soloTask == null)
{
throw new ArgumentNullException(nameof(soloTask), "独立任务对象不能为空");
}
var taskSettingsPageViewModel = App.GetService<TaskSettingsPageViewModel>();
if (taskSettingsPageViewModel == null)
{
throw new ArgumentNullException(nameof(taskSettingsPageViewModel), "内部视图模型对象为空");
}
// 根据名称执行任务
switch (soloTask.Name)
{
case "AutoGeniusInvokation":
taskSettingsPageViewModel.SwitchAutoGeniusInvokationCommand.Execute(null);
break;
case "AutoWood":
taskSettingsPageViewModel.SwitchAutoWoodCommand.Execute(null);
break;
case "AutoFight":
taskSettingsPageViewModel.SwitchAutoFightCommand.Execute(null);
break;
case "AutoDomain":
if (taskSettingsPageViewModel.GetFightStrategy(out var path))
{
return;
}
await new AutoDomainTask(new AutoDomainParam(0, path)).Start(CancellationContext.Instance.Cts);
break;
case "AutoMusicGame":
taskSettingsPageViewModel.SwitchAutoMusicGameCommand.Execute(null);
break;
default:
throw new ArgumentException($"未知的任务名称: {soloTask.Name}", nameof(soloTask.Name));
}
}
}
@@ -1,15 +1,51 @@
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using System.Threading.Tasks;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
{
private RECT captureAreaRect = TaskContext.Instance().SystemInfo.CaptureAreaRect;
/// <summary>
/// 游戏宽度
/// </summary>
public int Width => captureAreaRect.Width;
/// <summary>
/// 游戏高度
/// </summary>
public int Height => captureAreaRect.Height;
/// <summary>
/// 游戏窗口大小相比1080P的缩放比例
/// </summary>
public double ScaleTo1080PRatio { get; } = TaskContext.Instance().SystemInfo.ScaleTo1080PRatio;
/// <summary>
/// 系统屏幕的DPI缩放比例
/// </summary>
public double ScreenDpiScale => TaskContext.Instance().DpiScale;
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(double x, double y)
{
await new TpTask(CancellationContext.Instance.Cts).Tp(x, y);
}
/// <summary>
/// 传送到指定位置
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
public async Task Tp(string x, string y)
{
double.TryParse(x, out var dx);
@@ -1,4 +1,11 @@
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using System;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence;
@@ -8,4 +15,138 @@ public class GlobalMethod
{
await Task.Delay(millisecondsTimeout, CancellationContext.Instance.Cts.Token);
}
#region 键盘操作
public static void KeyDown(string key)
{
Simulation.SendInput.Keyboard.KeyDown(ToVk(key));
}
public static void KeyUp(string key)
{
Simulation.SendInput.Keyboard.KeyUp(ToVk(key));
}
public static void KeyPress(string key)
{
Simulation.SendInput.Keyboard.KeyPress(ToVk(key));
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
#endregion 键盘操作
#region 鼠标操作
private static int _gameWidth = 1920;
private static int _gameHeight = 1080;
private static double _dpi = 1;
public static void SetGameMetrics(int width, int height, double dpi = 1)
{
// 必须16:9 的分辨率
if (width * 9 != height * 16)
{
throw new ArgumentException("游戏分辨率必须是16:9的分辨率");
}
_gameWidth = width;
_gameHeight = height;
_dpi = dpi;
}
public static void MoveMouseBy(int x, int y)
{
var realDpi = TaskContext.Instance().DpiScale;
x = (int)(x * realDpi / _dpi);
y = (int)(y * realDpi / _dpi);
Simulation.SendInput.Mouse.MoveMouseBy(x, y);
}
public static void MoveMouseTo(int x, int y)
{
if (x < 0 || x > _gameWidth || y < 0 || y > _gameHeight)
{
throw new ArgumentException("鼠标坐标超出游戏窗口范围");
}
GameCaptureRegion.GameRegionMove((size, s2) =>
{
var scale = 1920.0 / _gameWidth;
return (x * scale * s2, y * scale * s2);
});
}
public static void Click(int x, int y)
{
MoveMouseTo(x, y);
Simulation.SendInput.Mouse.LeftButtonClick();
}
public static void LeftButtonClick()
{
Simulation.SendInput.Mouse.LeftButtonClick();
}
public static void LeftButtonDown()
{
Simulation.SendInput.Mouse.LeftButtonDown();
}
public static void LeftButtonUp()
{
Simulation.SendInput.Mouse.LeftButtonUp();
}
public static void RightButtonClick()
{
Simulation.SendInput.Mouse.RightButtonClick();
}
public static void RightButtonDown()
{
Simulation.SendInput.Mouse.RightButtonDown();
}
public static void RightButtonUp()
{
Simulation.SendInput.Mouse.RightButtonUp();
}
public static void MiddleButtonClick()
{
Simulation.SendInput.Mouse.MiddleButtonClick();
}
public static void MiddleButtonDown()
{
Simulation.SendInput.Mouse.MiddleButtonDown();
}
public static void MiddleButtonUp()
{
Simulation.SendInput.Mouse.MiddleButtonUp();
}
#endregion 鼠标操作
#region 识图操作
public static ImageRegion CaptureGameRegion()
{
return TaskControl.CaptureToRectArea();
}
#endregion 识图操作
}
@@ -1,4 +1,7 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
using BetterGenshinImpact.Core.Script.Dependence.Model.TimerConfig;
using BetterGenshinImpact.Helpers;
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 实时任务触发器
@@ -29,4 +32,13 @@ public class RealtimeTimer
{
Name = name;
}
public RealtimeTimer(string name, dynamic config)
{
Name = name;
if (Name == "AutoPick")
{
Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
}
}
}
@@ -0,0 +1,31 @@
namespace BetterGenshinImpact.Core.Script.Dependence.Model;
/// <summary>
/// 独立任务
/// </summary>
public class SoloTask
{
/// <summary>
/// 独立任务名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 独立任务配置
/// </summary>
public object? Config;
public SoloTask(string name)
{
Name = name;
}
public SoloTask(string name, dynamic config)
{
Name = name;
// if (Name == "AutoPick")
// {
// Config = ScriptObjectConverter.ConvertTo<AutoPickExternalConfig>(config);
// }
}
}
@@ -0,0 +1,44 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.Helpers;
using System;
using BetterGenshinImpact.GameTask;
using Vanara.PInvoke;
namespace BetterGenshinImpact.Core.Script.Dependence.Simulator;
public class PostMessage
{
private readonly PostMessageSimulator _postMessageSimulator = TaskContext.Instance().PostMessageSimulator;
public void KeyDown(string key)
{
_postMessageSimulator.KeyDownBackground(ToVk(key));
}
public void KeyUp(string key)
{
_postMessageSimulator.KeyUpBackground(ToVk(key));
}
public void KeyPress(string key)
{
_postMessageSimulator.KeyPressBackground(ToVk(key));
}
public void Click()
{
_postMessageSimulator.LeftButtonClick();
}
private static User32.VK ToVk(string key)
{
try
{
return User32Helper.ToVk(key);
}
catch
{
throw new ArgumentException($"键盘编码必须是VirtualKeyCodes枚举中的值,当前传入的 {key} 不合法");
}
}
}
@@ -1,31 +1,51 @@
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.Core.Script.Dependence.Model;
using Microsoft.ClearScript;
using System.Reflection;
using System.Threading.Tasks;
using OpenCvSharp;
using BetterGenshinImpact.Core.Recognition;
using BetterGenshinImpact.GameTask.Model.Area;
namespace BetterGenshinImpact.Core.Script;
public class EngineExtend
{
/// <summary>
/// !!! 注意:这个方法会添加一些全局方法和对象,不要随便添加,以免安全风险!!!
/// </summary>
/// <param name="engine"></param>
/// <param name="workDir"></param>
/// <param name="searchPaths"></param>
public static void InitHost(IScriptEngine engine, string workDir, string[]? searchPaths = null)
{
// engine.AddHostObject("xHost", new ExtendedHostFunctions()); // 有越权的安全风险
// 添加我的自定义实例化对象
engine.AddHostObject("keyMouseScript", new KeyMouseScript(workDir));
engine.AddHostObject("autoPathing", new AutoPathing(workDir));
engine.AddHostObject("pathingScript", new AutoPathingScript(workDir));
engine.AddHostObject("genshin", new Dependence.Genshin());
engine.AddHostObject("log", new Log());
engine.AddHostObject("file", new LimitedFile(workDir)); // 限制文件访问
// 实时任务调度器
// 任务调度器
engine.AddHostObject("dispatcher", new Dispatcher());
engine.AddHostType("RealtimeTimer", typeof(RealtimeTimer));
engine.AddHostType("SoloTask", typeof(SoloTask));
// PostMessage 作为类型实例化
engine.AddHostType("PostMessage", typeof(Dependence.Simulator.PostMessage));
// 直接添加方法
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
#pragma warning restore CS8974 // Converting method group to non-delegate type
AddAllGlobalMethod(engine);
// 识图模块相关
engine.AddHostType("Mat", typeof(Mat));
engine.AddHostType("RecognitionObject", typeof(RecognitionObject));
engine.AddHostType("DesktopRegion", typeof(DesktopRegion));
engine.AddHostType("GameCaptureRegion", typeof(GameCaptureRegion));
engine.AddHostType("ImageRegion", typeof(ImageRegion));
engine.AddHostType("Region", typeof(Region));
// 添加C#的类型
engine.AddHostType(typeof(Task));
@@ -39,4 +59,38 @@ public class EngineExtend
engine.DocumentSettings.SearchPath = string.Join(';', searchPaths);
}
}
public static void AddAllGlobalMethod(IScriptEngine engine)
{
// // 获取GlobalMethod类的所有静态方法
// var methods = typeof(GlobalMethod).GetMethods(BindingFlags.Static | BindingFlags.Public);
//
// foreach (var method in methods)
// {
// // 使用方法名首字母小写作为HostObject的名称
// var methodName = char.ToLowerInvariant(method.Name[0]) + method.Name[1..];
// engine.AddHostObject(methodName, method);
// }
#pragma warning disable CS8974 // Converting method group to non-delegate type
engine.AddHostObject("sleep", GlobalMethod.Sleep);
engine.AddHostObject("keyDown", GlobalMethod.KeyDown);
engine.AddHostObject("keyUp", GlobalMethod.KeyUp);
engine.AddHostObject("keyPress", GlobalMethod.KeyPress);
engine.AddHostObject("setGameMetrics", GlobalMethod.SetGameMetrics);
engine.AddHostObject("moveMouseBy", GlobalMethod.MoveMouseBy);
engine.AddHostObject("moveMouseTo", GlobalMethod.MoveMouseTo);
engine.AddHostObject("click", GlobalMethod.Click);
engine.AddHostObject("leftButtonClick", GlobalMethod.LeftButtonClick);
engine.AddHostObject("leftButtonDown", GlobalMethod.LeftButtonDown);
engine.AddHostObject("leftButtonUp", GlobalMethod.LeftButtonUp);
engine.AddHostObject("rightButtonClick", GlobalMethod.RightButtonClick);
engine.AddHostObject("rightButtonDown", GlobalMethod.RightButtonDown);
engine.AddHostObject("rightButtonUp", GlobalMethod.RightButtonUp);
engine.AddHostObject("middleButtonClick", GlobalMethod.MiddleButtonClick);
engine.AddHostObject("middleButtonDown", GlobalMethod.MiddleButtonDown);
engine.AddHostObject("middleButtonUp", GlobalMethod.MiddleButtonUp);
engine.AddHostObject("captureGameRegion", GlobalMethod.CaptureGameRegion);
#pragma warning restore CS8974 // Converting method group to non-delegate type
}
}
@@ -34,6 +34,6 @@ public partial class ScriptGroup : ObservableObject
public static ScriptGroup FromJson(string json)
{
return JsonSerializer.Deserialize<ScriptGroup>(json, ConfigService.JsonOptions) ?? throw new Exception("解析配置组JSON配置失败");
return Newtonsoft.Json.JsonConvert.DeserializeObject<ScriptGroup>(json) ?? throw new Exception("解析配置组JSON配置失败");
}
}
@@ -14,6 +14,7 @@ public class Manifest
public int ManifestVersion { get; set; } = 1;
public string Name { get; set; } = string.Empty;
public string Version { get; set; } = string.Empty;
public string? BgiVersion { get; set; }
public string Description { get; set; } = string.Empty;
public List<Author> Authors { get; set; } = [];
public string Main { get; set; } = string.Empty;
@@ -0,0 +1,423 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Script.WebView;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.Helpers.Http;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Controls.Webview;
using BetterGenshinImpact.ViewModel.Pages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.Core.Script;
public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
{
private readonly ILogger<ScriptRepoUpdater> _logger = App.GetLogger<ScriptRepoUpdater>();
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(30) };
// 仓储位置
public static readonly string ReposPath = Global.Absolute("Repos");
// 仓储临时目录 用于下载与解压
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 string CenterRepoUnzipName = "bettergi-scripts-list-main";
public static readonly string CenterRepoPath = Path.Combine(ReposPath, CenterRepoUnzipName);
public static readonly Dictionary<string, string> PathMapper = new Dictionary<string, string>
{
{ "pathing", Global.Absolute("User\\AutoPathing") },
{ "js", Global.Absolute("User\\JsScript") },
{ "combat", Global.Absolute("User\\AutoFight") },
{ "tcg", Global.Absolute("User\\AutoGeniusInvokation") },
};
private WebpageWindow? _webWindow;
public void AutoUpdate()
{
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
// 判断更新周期是否到达
if (DateTime.Now - scriptConfig.LastUpdateScriptRepoTime >= TimeSpan.FromDays(scriptConfig.AutoUpdateScriptRepoPeriod))
{
// 更新仓库
Task.Run(async () =>
{
try
{
var (repoPath, updated) = await UpdateCenterRepo();
Debug.WriteLine($"脚本仓库更新完成,路径:{repoPath}");
scriptConfig.LastUpdateScriptRepoTime = DateTime.Now;
if (updated)
{
scriptConfig.ScriptRepoHintDotVisible = true;
}
}
catch (Exception e)
{
_logger.LogDebug(e, $"脚本仓库更新失败:{e.Message}");
}
});
}
}
public async Task<(string, bool)> UpdateCenterRepo()
{
// 测速并获取信息
var res = await ProxySpeedTester.GetFastestProxyAsync(CenterRepoInfoUrl);
// 解析信息
var fastProxyUrl = res.Item1;
var jsonString = res.Item2;
var (time, url, file) = ParseJson(jsonString);
var updated = false;
// 检查仓库是否存在,不存在则下载
if (!Directory.Exists(CenterRepoPath))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url));
updated = true;
}
// 搜索本地的 repo.json
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, file, SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
var (time2, url2, file2) = ParseJson(await File.ReadAllTextAsync(localRepoJsonPath));
// 检查是否需要更新
if (long.Parse(time) > long.Parse(time2))
{
await DownloadRepoAndUnzip(string.Format(fastProxyUrl, url2));
updated = true;
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return (folderPath, updated);
}
public string FindCenterRepoPath()
{
var localRepoJsonPath = Directory.GetFiles(CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
// 获取与 localRepoJsonPath 同名(无扩展名)的文件夹路径
var folderName = Path.GetFileNameWithoutExtension(localRepoJsonPath);
var folderPath = Path.Combine(Path.GetDirectoryName(localRepoJsonPath)!, folderName);
if (!Directory.Exists(folderPath))
{
throw new Exception("本地仓库文件夹不存在");
}
return folderPath;
}
private (string time, string url, string file) ParseJson(string jsonString)
{
var json = JObject.Parse(jsonString);
var time = json["time"]?.ToString();
var url = json["url"]?.ToString();
var file = json["file"]?.ToString();
// 检查是否有空值
if (time is null || url is null || file is null)
{
throw new Exception("repo.json 解析失败");
}
return (time, url, file);
}
public async Task DownloadRepoAndUnzip(string url)
{
// 下载
var res = await _httpClient.GetAsync(url);
if (!res.IsSuccessStatusCode)
{
throw new Exception("下载失败");
}
var bytes = await res.Content.ReadAsByteArrayAsync();
// 获取文件名
var contentDisposition = res.Content.Headers.ContentDisposition;
var fileName = contentDisposition is { FileName: not null } ? contentDisposition.FileName.Trim('"') : "temp.zip";
// 创建临时目录
if (!Directory.Exists(ReposTempPath))
{
Directory.CreateDirectory(ReposTempPath);
}
// 保存下载的文件
var zipPath = Path.Combine(ReposTempPath, fileName);
await File.WriteAllBytesAsync(zipPath, bytes);
// 删除旧文件夹
if (Directory.Exists(CenterRepoPath))
{
Directory.Delete(CenterRepoPath, true);
}
// 使用 System.IO.Compression 解压
ZipFile.ExtractToDirectory(zipPath, ReposPath, true);
}
public async Task ImportScriptFromClipboard()
{
// 获取剪切板内容
if (Clipboard.ContainsText())
{
string clipboardText = Clipboard.GetText();
await ImportScriptFromUri(clipboardText, true);
}
}
public async Task ImportScriptFromUri(string uri, bool formClipboard)
{
// 检查剪切板内容是否符合特定的URL格式
if (!string.IsNullOrEmpty(uri) && uri.Trim().ToLower().StartsWith("bettergi://script?import="))
{
Debug.WriteLine($"脚本订购内容:{uri}");
// 执行相关操作
var pathJson = ParseUri(uri);
if (!string.IsNullOrEmpty(pathJson))
{
var uiMessageBox = new Wpf.Ui.Controls.MessageBox
{
Title = "脚本订阅",
Content = $"检测到{(formClipboard ? "剪切板上存在" : "")}脚本订阅链接,解析后需要导入的脚本为:{pathJson}。\n是否导入并覆盖此文件或者文件夹下的脚本?",
CloseButtonText = "关闭",
PrimaryButtonText = "确认导入",
WindowStartupLocation = WindowStartupLocation.CenterOwner,
Owner = Application.Current.MainWindow,
};
var result = await uiMessageBox.ShowDialogAsync();
if (result == Wpf.Ui.Controls.MessageBoxResult.Primary)
{
await ImportScriptFromPathJson(pathJson);
}
}
if (formClipboard)
{
// 清空剪切板内容
Clipboard.Clear();
}
}
}
private string? ParseUri(string uriString)
{
var uri = new Uri(uriString);
// 获取 query 参数
string query = uri.Query;
Debug.WriteLine($"Query: {query}");
// 解析 query 参数
var queryParams = System.Web.HttpUtility.ParseQueryString(query);
var import = queryParams["import"];
if (string.IsNullOrEmpty(import))
{
Debug.WriteLine("未找到 import 参数");
return null;
}
// Base64 解码后再使用url解码
byte[] data = Convert.FromBase64String(import);
return System.Web.HttpUtility.UrlDecode(System.Text.Encoding.UTF8.GetString(data));
}
public async Task ImportScriptFromPathJson(string pathJson)
{
var paths = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(pathJson);
if (paths is null || paths.Count == 0)
{
Toast.Warning("订阅脚本路径为空");
return;
}
// 保存订阅信息
var scriptConfig = TaskContext.Instance().Config.ScriptConfig;
scriptConfig.SubscribedScriptPaths.AddRange(paths);
Toast.Information("获取最新仓库信息中...");
// 更新仓库
var (repoPath, _) = await Task.Run(UpdateCenterRepo);
// // 收集将被覆盖的文件和文件夹
// var filesToOverwrite = new List<string>();
// foreach (var path in paths)
// {
// var first = GetFirstFolder(path);
// if (PathMapper.TryGetValue(first, out var userPath))
// {
// var scriptPath = Path.Combine(repoPath, path);
// var destPath = Path.Combine(userPath, path.Replace(first, ""));
// if (Directory.Exists(scriptPath))
// {
// if (Directory.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// else if (File.Exists(scriptPath))
// {
// if (File.Exists(destPath))
// {
// filesToOverwrite.Add(destPath);
// }
// }
// }
// else
// {
// Toast.Warning($"未知的脚本路径:{path}");
// }
// }
//
// // 提示用户确认
// if (filesToOverwrite.Count > 0)
// {
// var message = "以下文件和文件夹将被覆盖:\n" + string.Join("\n", filesToOverwrite) + "\n是否覆盖所有文件和文件夹?";
// var uiMessageBox = new Wpf.Ui.Controls.MessageBox
// {
// Title = "确认覆盖",
// Content = message,
// CloseButtonText = "取消",
// PrimaryButtonText = "确认覆盖",
// WindowStartupLocation = WindowStartupLocation.CenterOwner,
// Owner = Application.Current.MainWindow,
// };
//
// var result = await uiMessageBox.ShowDialogAsync();
// if (result != Wpf.Ui.Controls.MessageBoxResult.Primary)
// {
// return;
// }
// }
// 拷贝文件
foreach (var path in paths)
{
var (first, remainingPath) = GetFirstFolderAndRemainingPath(path);
if (PathMapper.TryGetValue(first, out var userPath))
{
var scriptPath = Path.Combine(repoPath, path);
var destPath = Path.Combine(userPath, remainingPath);
if (Directory.Exists(scriptPath))
{
if (Directory.Exists(destPath))
{
Directory.Delete(destPath, true);
}
CopyDirectory(scriptPath, destPath);
}
else if (File.Exists(scriptPath))
{
if (File.Exists(destPath))
{
File.Delete(destPath);
}
File.Copy(scriptPath, destPath, true);
}
Toast.Success("脚本订阅链接导入完成");
}
else
{
Toast.Warning($"未知的脚本路径:{path}");
}
}
}
private void CopyDirectory(string sourceDir, string destDir)
{
// 创建目标目录
Directory.CreateDirectory(destDir);
// 拷贝文件
foreach (var file in Directory.GetFiles(sourceDir))
{
var destFile = Path.Combine(destDir, Path.GetFileName(file));
File.Copy(file, destFile, true);
}
// 拷贝子目录
foreach (var dir in Directory.GetDirectories(sourceDir))
{
var destSubDir = Path.Combine(destDir, Path.GetFileName(dir));
CopyDirectory(dir, destSubDir);
}
}
private static (string firstFolder, string remainingPath) GetFirstFolderAndRemainingPath(string path)
{
// 检查路径是否为空或仅包含部分字符
if (string.IsNullOrEmpty(path))
{
return (string.Empty, string.Empty);
}
// 使用路径分隔符分割路径
string[] parts = path.Split(new char[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries);
// 返回第一个文件夹和剩余路径
return parts.Length > 0 ? (parts[0], string.Join(Path.DirectorySeparatorChar, parts.Skip(1))) : (string.Empty, string.Empty);
}
public void OpenLocalRepoInWebView()
{
if (_webWindow is not { IsVisible: true })
{
_webWindow = new WebpageWindow
{
Title = "enshin Copilot Scripts | BetterGI 脚本本地中央仓库",
Width = 1366,
Height = 768,
// Owner = Application.Current.MainWindow,
WindowState = WindowState.Maximized
};
_webWindow.Closed += (s, e) => _webWindow = null;
_webWindow.Panel!.DownloadFolderPath = MapPathingViewModel.PathJsonPath;
_webWindow.NavigateToFile(Global.Absolute(@"Assets\Web\ScriptRepo\index.html"));
_webWindow.Panel!.OnWebViewInitializedAction = () => _webWindow.Panel!.WebView.CoreWebView2.AddHostObjectToScript("repoWebBridge", new RepoWebBridge());
_webWindow.Show();
}
else
{
_webWindow.Activate();
}
}
}
@@ -0,0 +1,52 @@
using System;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
namespace BetterGenshinImpact.Core.Script.WebView;
/// <summary>
/// 给 WebView 提供的桥接类
/// 用于调用 C# 方法
/// </summary>
[ClassInterface(ClassInterfaceType.AutoDual)]
[ComVisible(true)]
public class RepoWebBridge
{
public string GetRepoJson()
{
try
{
var localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
_ = ScriptRepoUpdater.Instance.UpdateCenterRepo().ConfigureAwait(false);
localRepoJsonPath = Directory.GetFiles(ScriptRepoUpdater.CenterRepoPath, "repo.json", SearchOption.AllDirectories).FirstOrDefault();
if (localRepoJsonPath is null)
{
throw new Exception("本地仓库缺少 repo.json");
}
}
var json = File.ReadAllText(localRepoJsonPath);
return json;
}
catch (Exception e)
{
MessageBox.Show(e.Message, "获取仓库信息失败!");
return "";
}
}
public void ImportUri(string url)
{
try
{
ScriptRepoUpdater.Instance.ImportScriptFromUri(url, false).ConfigureAwait(false);
}
catch (Exception e)
{
MessageBox.Show(e.Message, "订阅脚本链接失败!");
}
}
}
@@ -51,7 +51,7 @@ public class AutoDomainTask : ISoloTask
_simulator = AutoFightContext.Instance.Simulator;
_predictor = YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute("Assets\\Model\\Domain\\bgi_tree.onnx"))
.UseOnnxModel(Global.Absolute(@"Assets\Model\Domain\bgi_tree.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
@@ -386,6 +386,11 @@ public class AutoDomainTask : ISoloTask
{
return;
}
if (!IsTakeFood())
{
Logger.LogInformation("未装备 “{Tool}”,不启用红血自动吃药功能", "便携营养袋");
return;
}
try
{
@@ -420,6 +425,17 @@ public class AutoDomainTask : ISoloTask
return pixelColor is { Item2: 255, Item1: 90, Item0: 90 };
}
private bool IsTakeFood()
{
// 获取图像
using var ra = CaptureToRectArea();
// 识别道具图标下是否是数字
var s = TaskContext.Instance().SystemInfo.AssetScale;
var countArea = ra.DeriveCrop(1800 * s, 845 * s, 40 * s, 20 * s);
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.SrcGreyMat);
return int.TryParse(count, out _);
}
/// <summary>
/// 旋转视角后寻找石化古树
/// </summary>
@@ -800,7 +800,7 @@
"weapon": "13"
},
{
"alias": [ "基尼奇", "Kinich", "基哥" ],
"alias": [ "基尼奇", "Kinich", "基哥", "基尼齐" ],
"burstCD": 18.0,
"id": "10000101",
"name": "基尼奇",
@@ -817,5 +817,14 @@
"skillCD": 1.8,
"skillHoldCD": 6.0,
"weapon": "10"
},
{
"alias": [ "希诺宁", "Xilonen", "豹女", "岩大猫", "大岩猫", "岩猫", "岩猫猫", "西诺宁" ],
"burstCD": 15.0,
"id": "10000103",
"name": "希诺宁",
"nameEn": "Xilonen",
"skillCD": 7.0,
"weapon": "1"
}
]
@@ -15,4 +15,16 @@ public partial class AutoFightConfig : ObservableObject
/// 英文逗号分割 强制指定队伍角色
/// </summary>
[ObservableProperty] private string _teamNames = "";
}
/// <summary>
/// 检测战斗结束
/// </summary>
[ObservableProperty]
private bool _fightFinishDetectEnabled = true;
/// <summary>
/// 检测战斗结束
/// </summary>
[ObservableProperty]
private bool _pickDropsAfterFightEnabled = true;
}
@@ -5,4 +5,8 @@ namespace BetterGenshinImpact.GameTask.AutoFight;
public class AutoFightParam(string path) : BaseTaskParam
{
public string CombatStrategyPath { get; set; } = path;
public bool FightFinishDetectEnabled { get; set; } = false;
public bool PickDropsAfterFightEnabled { get; set; } = false;
}
@@ -1,11 +1,16 @@
using BetterGenshinImpact.Core.Script;
using BetterGenshinImpact.Core.Recognition.ONNX;
using BetterGenshinImpact.GameTask.AutoFight.Model;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Helpers;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoFight;
@@ -18,13 +23,22 @@ public class AutoFightTask : ISoloTask
private CancellationTokenSource? _cts;
private readonly BgiYoloV8Predictor _predictor;
private DateTime _lastFightFlagTime = DateTime.Now; // 战斗标志最近一次出现的时间
public AutoFightTask(AutoFightParam taskParam)
{
_taskParam = taskParam;
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
if (_taskParam.FightFinishDetectEnabled)
{
_predictor = new BgiYoloV8Predictor(@"Assets\Model\World\bgi_world.onnx");
}
}
public Task Start(CancellationTokenSource cts)
public async Task Start(CancellationTokenSource cts)
{
_cts = cts;
@@ -34,33 +48,71 @@ public class AutoFightTask : ISoloTask
{
throw new Exception("识别队伍角色失败");
}
var combatCommands = _combatScriptBag.FindCombatScript(combatScenes.Avatars);
combatScenes.BeforeTask(_cts);
// 新的取消token
var cts2 = new CancellationTokenSource();
cts.Token.Register(cts2.Cancel);
combatScenes.BeforeTask(cts2);
// 战斗操作
try
var fightTask = Task.Run(() =>
{
while (!_cts.Token.IsCancellationRequested)
try
{
// 通用化战斗策略
foreach (var command in combatCommands)
while (!cts2.Token.IsCancellationRequested)
{
command.Execute(combatScenes);
// 通用化战斗策略
foreach (var command in combatCommands)
{
command.Execute(combatScenes);
}
}
}
}
catch (NormalEndException)
{
Logger.LogInformation("战斗操作结束");
}
catch (Exception e)
{
Logger.LogWarning(e.Message);
throw;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
}, cts2.Token);
return Task.CompletedTask;
// 战斗结束检测线程
var endTask = Task.Run(async () =>
{
if (!_taskParam.FightFinishDetectEnabled)
{
return;
}
try
{
while (!cts2.IsCancellationRequested)
{
var finish = await CheckFightFinish();
if (finish)
{
await cts2.CancelAsync();
break;
}
Sleep(1000, cts2);
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
Debug.WriteLine(e.StackTrace);
}
}, cts2.Token);
await Task.WhenAll(fightTask, endTask);
if (_taskParam is { FightFinishDetectEnabled: true, PickDropsAfterFightEnabled: true })
{
// 执行自动拾取掉落物的功能
}
}
private void LogScreenResolution()
@@ -71,4 +123,47 @@ public class AutoFightTask : ISoloTask
Logger.LogWarning("游戏窗口分辨率不是 16:9 !当前分辨率为 {Width}x{Height} , 非 16:9 分辨率的游戏可能无法正常使用自动战斗功能 !", gameScreenSize.Width, gameScreenSize.Height);
}
}
private async Task<bool> CheckFightFinish()
{
// YOLO 判断血条和怪物位置
if (HasFightFlag(CaptureToRectArea()))
{
_lastFightFlagTime = DateTime.Now;
return false;
}
// 几秒内没有检测到血条和怪物位置,则开始旋转视角重新检测
if ((DateTime.Now - _lastFightFlagTime).TotalSeconds > 5)
{
// 旋转完毕后都没有检测到血条和怪物位置,则按L键确认战斗结束
List<int> angles = [0, 90, 180, 270];
var rotateTask = new CameraRotateTask(_cts!);
foreach (var a in angles)
{
await rotateTask.WaitUntilRotatedTo(a, 5, 30);
await Delay(1000, _cts!); // 等待视角稳定
if (HasFightFlag(CaptureToRectArea()))
{
return false;
}
}
// 最终方案确认战斗结束
Logger.LogInformation("识别到战斗结束");
return true;
}
return false;
}
private bool HasFightFlag(ImageRegion imageRegion)
{
if (RuntimeHelper.IsDebug)
{
imageRegion.SrcMat.SaveImage(Global.Absolute(@"log\fight\" + $"{DateTime.Now:yyyyMMdd_HHmmss_ffff}.png"));
}
var dict = _predictor.Detect(imageRegion);
return dict.ContainsKey("health_bar") || dict.ContainsKey("enemy_identify");
}
}
@@ -39,7 +39,7 @@ public class CombatScenes : IDisposable
private readonly YoloV8Predictor _predictor =
YoloV8Builder.CreateDefaultBuilder()
.UseOnnxModel(Global.Absolute("Assets\\Model\\Common\\avatar_side_classify_sim.onnx"))
.UseOnnxModel(Global.Absolute(@"Assets\Model\Common\avatar_side_classify_sim.onnx"))
.WithSessionOptions(BgiSessionOption.Instance.Options)
.Build();
@@ -32,7 +32,7 @@ namespace BetterGenshinImpact.GameTask.AutoFishing
{
private readonly ILogger<AutoFishingTrigger> _logger = App.GetLogger<AutoFishingTrigger>();
private readonly IOcrService _ocrService = OcrFactory.Paddle;
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute("Assets\\Model\\Fish\\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
private readonly YoloV8Predictor _predictor = YoloV8Builder.CreateDefaultBuilder().UseOnnxModel(Global.Absolute(@"Assets\Model\Fish\bgi_fish.onnx")).WithSessionOptions(BgiSessionOption.Instance.Options).Build();
public string Name => "自动钓鱼";
public bool IsEnabled { get; set; }
@@ -4601,6 +4601,75 @@
}
]
},
{
"id": 1609,
"nameEn": "chiori",
"type": "character",
"name": "千织",
"hp": 10,
"energy": 2,
"element": "岩元素",
"weapon": "单手剑",
"skills": [
{
"nameEn": "weaving_blade",
"name": "心织刀流",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "fluttering_hasode",
"name": "羽袖一触",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
}
]
},
{
"nameEn": "hiyoku_twin_blades",
"name": "二刀之形·比翼",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1106,
"nameEn": "geo",
"type": "岩元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
}
]
},
{
"id": 1701,
"nameEn": "collei",
@@ -6529,6 +6598,83 @@
}
]
},
{
"id": 2406,
"nameEn": "abyss_lector_violet_lightning",
"type": "character",
"name": "深渊咏者·紫电",
"hp": 6,
"energy": 2,
"element": "雷元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "den_of_thunder",
"name": "渊薮落雷",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "shock_of_the_enigmatic_abyss",
"name": "秘渊虚霆",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
}
]
},
{
"nameEn": "wild_thunderburst",
"name": "狂迸骇雷",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "electric_rebirth",
"name": "雷之新生",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 2501,
"nameEn": "maguu_kenki",
@@ -7081,5 +7227,82 @@
"cost": []
}
]
},
{
"id": 2703,
"nameEn": "eremite_floral_ringdancer",
"type": "character",
"name": "镀金旅团·叶轮舞者",
"hp": 10,
"energy": 2,
"element": "草元素",
"weapon": "其他武器",
"skills": [
{
"nameEn": "floralring_caress",
"name": "叶轮轻扫",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "spiraling_whirl",
"name": "蔓延旋舞",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
}
]
},
{
"nameEn": "spirit_of_omens_awakening_dendro_spiritserpent",
"name": "厄灵苏醒·草之灵蛇",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1107,
"nameEn": "dendro",
"type": "草元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "spirit_of_omens_power",
"name": "厄灵之能",
"skillTag": [
"被动技能"
],
"cost": []
}
]
}
]
@@ -0,0 +1,76 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoPathing;
public class CameraRotateTask(CancellationTokenSource cts)
{
private readonly double _dpi = TaskContext.Instance().DpiScale;
/// <summary>
/// 向目标角度旋转
/// </summary>
/// <param name="targetOrientation"></param>
/// <param name="imageRegion"></param>
/// <returns></returns>
public int RotateToApproach(int targetOrientation, ImageRegion imageRegion)
{
var cao = CameraOrientation.Compute(imageRegion.SrcGreyMat);
var diff = (cao - targetOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
if (diff == 0)
{
return diff;
}
// 平滑的旋转视角
// todo dpi 和分辨率都会影响转动速度
double controlRatio = 1;
if (Math.Abs(diff) > 90)
{
controlRatio = 4;
}
else if (Math.Abs(diff) > 30)
{
controlRatio = 3;
}
else if (Math.Abs(diff) > 5)
{
controlRatio = 2;
}
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(-controlRatio * diff * _dpi), 0);
return diff;
}
/// <summary>
/// 转动视角到目标角度
/// </summary>
/// <param name="targetOrientation">目标角度</param>
/// <param name="maxDiff">最大误差</param>
/// <param name="maxTryTimes">最大尝试次数(超时时间)</param>
/// <returns></returns>
public async Task WaitUntilRotatedTo(int targetOrientation, int maxDiff, int maxTryTimes = 50)
{
int count = 0;
while (!cts.IsCancellationRequested)
{
var screen = CaptureToRectArea();
if (Math.Abs(RotateToApproach(targetOrientation, screen)) < maxDiff)
{
break;
}
if (count > maxTryTimes)
{
Logger.LogWarning("视角转动到目标角度超时,停止转动");
break;
}
await Delay(50, cts);
count++;
}
}
}
@@ -15,6 +15,7 @@ public class ActionFactory
{
"nahida_collect" => new NahidaCollectHandler(),
"pick_around" => new PickAroundHandler(),
"fight" => new AutoFightHandler(),
_ => throw new ArgumentException("未知的 action 类型")
};
});
@@ -0,0 +1,43 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.AutoFight;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.GameTask.AutoPathing.Handler;
internal class AutoFightHandler : IActionHandler
{
public async Task RunAsync(CancellationTokenSource cts)
{
await StartFight(cts);
}
private async Task StartFight(CancellationTokenSource cts)
{
// 爷们要战斗
var taskParams = new AutoFightParam(GetFightStrategy())
{
FightFinishDetectEnabled = true,
PickDropsAfterFightEnabled = true
};
var fightSoloTask = new AutoFightTask(taskParams);
await fightSoloTask.Start(cts);
}
private string GetFightStrategy()
{
var path = Global.Absolute(@"User\AutoFight\" + TaskContext.Instance().Config.AutoFightConfig.StrategyName + ".txt");
if ("根据队伍自动选择".Equals(TaskContext.Instance().Config.AutoFightConfig.StrategyName))
{
path = Global.Absolute(@"User\AutoFight\");
}
if (!File.Exists(path) && !Directory.Exists(path))
{
throw new Exception("战斗策略文件不存在");
}
return path;
}
}
@@ -8,6 +8,7 @@ public class ActionEnum(string code, string msg)
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", "战斗");
// 还有要加入的其他动作
// 滚轮F
@@ -5,6 +5,8 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
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 Climb = new("climb", "攀爬");
public static readonly MoveModeEnum Fly = new("fly", "飞行");
public static readonly MoveModeEnum Jump = new("jump", "跳跃");
public static readonly MoveModeEnum Swim = new("swim", "游泳");
@@ -34,6 +34,12 @@ public class PathingTask
return task;
}
public static PathingTask BuildFromJson(string json)
{
var task = JsonSerializer.Deserialize<PathingTask>(json, PathRecorder.JsonOptions) ?? throw new Exception("Failed to deserialize PathingTask");
return task;
}
public void SaveToFile(string filePath)
{
var json = JsonSerializer.Serialize(this, PathRecorder.JsonOptions);
@@ -8,7 +8,16 @@ namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
public class PathingTaskInfo
{
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string? Description { get; set; }
public string? Author { get; set; }
public string? Version { get; set; }
/// <summary>
/// 制作时 BetterGI 的版本,用于兼容性检查
/// </summary>
public string? BgiVersion { get; set; }
/// <summary>
/// 任务类型
@@ -0,0 +1,31 @@
using BetterGenshinImpact.GameTask.Common.Map;
using System;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
[Serializable]
public class WaypointForTrack : Waypoint
{
// 原神坐标系
public double GameX { get; set; }
public double GameY { get; set; }
// 全地图图像坐标系
public double MatX { get; set; }
public double MatY { get; set; }
public WaypointForTrack(Waypoint waypoint)
{
Type = waypoint.Type;
MoveMode = waypoint.MoveMode;
Action = waypoint.Action;
GameX = waypoint.X;
GameY = waypoint.Y;
// 坐标系转换
(MatX, MatY) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
X = MatX;
Y = MatY;
}
}
@@ -1,10 +1,10 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.GameTask.AutoTrackPath;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Extensions.Logging;
@@ -15,7 +15,6 @@ using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.AutoPathing.Handler;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -23,11 +22,10 @@ namespace BetterGenshinImpact.GameTask.AutoPathing;
public class PathExecutor(CancellationTokenSource cts)
{
private double _dpi = 1;
private readonly CameraRotateTask _rotateTask = new(cts);
public async Task Pathing(PathingTask task)
{
_dpi = TaskContext.Instance().DpiScale;
if (!task.Positions.Any())
{
Logger.LogWarning("没有路径点,寻路结束");
@@ -36,7 +34,7 @@ public class PathExecutor(CancellationTokenSource cts)
InitializePathing(task);
var waypoints = ConvertWaypoints(task.Positions);
var waypoints = ConvertWaypointsForTrack(task.Positions);
await Delay(100, cts);
Navigation.WarmUp(); // 提前加载地图特征点
@@ -78,43 +76,27 @@ public class PathExecutor(CancellationTokenSource cts)
"UpdateCurrentPathing", new object(), task));
}
private List<Waypoint> ConvertWaypoints(List<Waypoint> positions)
private List<WaypointForTrack> ConvertWaypointsForTrack(List<Waypoint> positions)
{
var waypoints = new List<Waypoint>();
foreach (var waypoint in positions)
{
if (waypoint.Type == WaypointType.Teleport.Code)
{
waypoints.Add(waypoint);
continue;
}
var waypointCopy = new Waypoint
{
Action = waypoint.Action,
Type = waypoint.Type,
MoveMode = waypoint.MoveMode
};
(waypointCopy.X, waypointCopy.Y) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
waypoints.Add(waypointCopy);
}
return waypoints;
// 把 X Y 转换为 MatX MatY
return positions.Select(waypoint => new WaypointForTrack(waypoint)).ToList();
}
private async Task HandleTeleportWaypoint(Waypoint waypoint)
private async Task HandleTeleportWaypoint(WaypointForTrack waypoint)
{
var forceTp = waypoint.Action == ActionEnum.ForceTp.Code;
var (tpX, tpY) = await new TpTask(cts).Tp(waypoint.X, waypoint.Y, forceTp);
var (tpX, tpY) = await new TpTask(cts).Tp(waypoint.GameX, waypoint.GameY, forceTp);
var (tprX, tprY) = MapCoordinate.GameToMain2048(tpX, tpY);
EntireMap.Instance.SetPrevPosition((float)tprX, (float)tprY); // 通过上一个位置直接进行局部特征匹配
}
private async Task MoveTo(Waypoint waypoint)
private async Task MoveTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = Navigation.GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("粗略接近途经点,位置({x2},{y2})", $"{waypoint.X:F1}", $"{waypoint.Y:F1}");
await WaitUntilRotatedTo(targetOrientation, 5);
Logger.LogInformation("粗略接近途经点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
var startTime = DateTime.UtcNow;
var lastPositionRecord = DateTime.UtcNow;
var fastMode = false;
@@ -124,11 +106,12 @@ public class PathExecutor(CancellationTokenSource cts)
while (!cts.IsCancellationRequested)
{
var now = DateTime.UtcNow;
if ((now - startTime).TotalSeconds > 60)
if ((now - startTime).TotalSeconds > 240)
{
Logger.LogWarning("执行超时,跳过路径点");
break;
}
screen = CaptureToRectArea();
position = Navigation.GetPosition(screen);
var distance = Navigation.GetDistance(waypoint, position);
@@ -138,38 +121,36 @@ public class PathExecutor(CancellationTokenSource cts)
Logger.LogInformation("到达路径点附近");
break;
}
if (distance > 500)
{
Logger.LogWarning("距离过远,跳过路径点");
break;
}
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
// 非爬行状态下,检测是否卡死
if (waypoint.MoveMode != MoveModeEnum.Climb.Code)
{
lastPositionRecord = now;
prevPositions.Add(position);
if (prevPositions.Count > 8)
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
{
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
lastPositionRecord = now;
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
Logger.LogWarning("疑似卡死,尝试脱离并跳过路径点");
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
await Delay(1500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_S);
await Delay(1500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_A);
await Delay(1500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_D);
await Delay(500, cts);
return;
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
{
Logger.LogWarning("疑似卡死,尝试脱离并跳过路径点");
await EscapeTrap();
return;
}
}
}
}
// 旋转视角
targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
RotateTo(targetOrientation, screen);
_rotateTask.RotateToApproach(targetOrientation, screen);
// 根据指定方式进行移动
if (waypoint.MoveMode == MoveModeEnum.Fly.Code)
{
@@ -180,45 +161,97 @@ public class PathExecutor(CancellationTokenSource cts)
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Delay(200, cts);
}
continue;
}
// if (isFlying)
// {
// Simulation.SendInput.Mouse.LeftButtonClick();
// await Delay(1000, cts);
// continue;
// }
if (waypoint.MoveMode == MoveModeEnum.Jump.Code)
{
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Delay(200, cts);
continue;
}
// 跑步或者游泳
if (distance > 20 != fastMode)// 距离大于20时可以使用疾跑/自由泳
// 只有设置为run才会疾跑
if (waypoint.MoveMode == MoveModeEnum.Run.Code)
{
if (fastMode)
if (distance > 20 != fastMode) // 距离大于20时可以使用疾跑/自由泳
{
Simulation.SendInput.Mouse.RightButtonUp();
if (fastMode)
{
Simulation.SendInput.Mouse.RightButtonUp();
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
else
{
Simulation.SendInput.Mouse.RightButtonDown();
}
fastMode = !fastMode;
}
await Delay(100, cts);
}
// 抬起w键
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
private async Task MoveCloseTo(Waypoint waypoint)
private bool IsStuck(DateTime now, DateTime lastPositionRecord, List<Point2f> prevPositions, Point2f position)
{
if ((now - lastPositionRecord).TotalMilliseconds > 1000)
{
prevPositions.Add(position);
if (prevPositions.Count > 8)
{
var delta = prevPositions[^1] - prevPositions[^8];
if (Math.Abs(delta.X) + Math.Abs(delta.Y) < 3)
{
return true;
}
}
}
return false;
}
private async Task EscapeTrap()
{
// 脱离攀爬状态
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
await Delay(1500, cts);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 向后移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_S);
await Task.Delay(1500);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_S);
// 向左移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_A);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(1000);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_A);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 向右移动
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_D);
await Task.Delay(300);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(700);
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_D);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_X);
await Delay(500, cts);
// 跳跃
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_SPACE);
await Task.Delay(200); // 等待跳跃动作
}
private async Task MoveCloseTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = Navigation.GetPosition(screen);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("精确接近目标点,位置({x2},{y2})", $"{waypoint.X:F1}", $"{waypoint.Y:F1}");
Logger.LogInformation("精确接近目标点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
if (waypoint.MoveMode == MoveModeEnum.Fly.Code && waypoint.Action == ActionEnum.StopFlying.Code)
{
//下落攻击接近目的地
@@ -226,17 +259,19 @@ public class PathExecutor(CancellationTokenSource cts)
Simulation.SendInput.Mouse.LeftButtonClick();
await Delay(1000, cts);
}
await WaitUntilRotatedTo(targetOrientation, 2);
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
var wPressed = false;
var stepsTaken = 0;
while (!cts.IsCancellationRequested)
{
stepsTaken++;
if (stepsTaken > 8)
if (stepsTaken > 12)
{
Logger.LogWarning("精确接近超时");
break;
}
screen = CaptureToRectArea();
position = Navigation.GetPosition(screen);
if (Navigation.GetDistance(waypoint, position) < 2)
@@ -244,7 +279,8 @@ public class PathExecutor(CancellationTokenSource cts)
Logger.LogInformation("已到达路径点");
break;
}
RotateTo(targetOrientation, screen); //不再改变视角
_rotateTask.RotateToApproach(targetOrientation, screen); //不再改变视角
if (waypoint.MoveMode == MoveModeEnum.Walk.Code)
{
// 小碎步接近
@@ -252,67 +288,26 @@ public class PathExecutor(CancellationTokenSource cts)
await Delay(200, cts);
continue;
}
if (!wPressed)
{
Simulation.SendInput.Keyboard.KeyDown(User32.VK.VK_W);
}
await Delay(100, cts);
}
if (wPressed)
{
Simulation.SendInput.Keyboard.KeyUp(User32.VK.VK_W);
}
}
private int RotateTo(int targetOrientation, ImageRegion imageRegion, double controlRatio = 1)
{
var cao = CameraOrientation.Compute(imageRegion.SrcGreyMat);
var diff = (cao - targetOrientation + 180) % 360 - 180;
diff += diff < -180 ? 360 : 0;
if (diff == 0)
{
return diff;
}
// 平滑的旋转视角
if (Math.Abs(diff) > 90)
{
controlRatio = 5;
}
else if (Math.Abs(diff) > 30)
{
controlRatio = 3;
}
else if (Math.Abs(diff) > 5)
{
controlRatio = 2;
}
Simulation.SendInput.Mouse.MoveMouseBy((int)Math.Round(-controlRatio * diff * _dpi), 0);
return diff;
}
private async Task WaitUntilRotatedTo(int targetOrientation, int maxDiff)
{
int count = 0;
while (!cts.IsCancellationRequested)
{
var screen = CaptureToRectArea();
if (Math.Abs(RotateTo(targetOrientation, screen)) < maxDiff)
{
break;
}
if (count > 50)
{
break;
}
await Delay(50, cts);
count++;
}
}
private async Task AfterMoveToTarget(Waypoint waypoint)
{
if (waypoint.Action == ActionEnum.NahidaCollect.Code
|| waypoint.Action == ActionEnum.PickAround.Code)
|| waypoint.Action == ActionEnum.PickAround.Code
|| waypoint.Action == ActionEnum.Fight.Code)
{
var handler = ActionFactory.GetHandler(waypoint.Action);
await handler.RunAsync(cts);
@@ -134,6 +134,14 @@ public partial class AutoPickTrigger : ITaskTrigger
content.CaptureRectArea.Find(_pickRo, foundRectArea =>
{
speedTimer.Record($"识别到 {_pickKeyName} 拾取键");
if (_externalConfig is { ForceInteraction: true })
{
LogPick(content, "直接拾取");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_F);
return;
}
var scale = TaskContext.Instance().SystemInfo.AssetScale;
var config = TaskContext.Instance().Config.AutoPickConfig;
@@ -16,6 +16,7 @@ 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;
@@ -28,6 +29,10 @@ public class TpTask(CancellationTokenSource cts)
{
private readonly QuickTeleportAssets _assets = QuickTeleportAssets.Instance;
private readonly Rect _captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
private readonly double _zoomOutMax1080PRatio = TaskContext.Instance().SystemInfo.ZoomOutMax1080PRatio;
/// <summary>
/// 通过大地图传送到指定坐标最近的传送点,然后移动到指定坐标
/// </summary>
@@ -42,7 +47,7 @@ public class TpTask(CancellationTokenSource cts)
{
// 获取最近的传送点位置
(x, y) = GetRecentlyTpPoint(tpX, tpY);
Logger.LogInformation("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", $"{tpX:F1}", $"{tpY:F1}", $"{x:F1}", $"{y:F1}");
Logger.LogDebug("({TpX},{TpY}) 最近的传送点位置 ({X},{Y})", $"{tpX:F1}", $"{tpY:F1}", $"{x:F1}", $"{y:F1}");
}
// M 打开地图识别当前位置,中心点为当前位置
@@ -58,7 +63,7 @@ public class TpTask(CancellationTokenSource cts)
// 计算坐标后点击
var bigMapInAllMapRect = GetBigMapRect();
while (!bigMapInAllMapRect.Shrink(115).Contains(x, y))
while (!IsPointInBigMapWindow(bigMapInAllMapRect, x, y)) // 左上角 350x400也属于禁止点击区域
{
Debug.WriteLine($"({x},{y}) 不在 {bigMapInAllMapRect} 内,继续移动");
Logger.LogInformation("传送点不在当前大地图范围内,继续移动");
@@ -68,15 +73,10 @@ public class TpTask(CancellationTokenSource cts)
// Debug.WriteLine($"({x},{y}) 在 {bigMapInAllMapRect} 内,计算它在窗体内的位置");
// 注意这个坐标的原点是中心区域某个点,所以要转换一下点击坐标(点击坐标是左上角为原点的坐标系),不能只是缩放
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var captureRect = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var clickX = (int)((picX - picRect.X) / picRect.Width * captureRect.Width);
var clickY = (int)((picY - picRect.Y) / picRect.Height * captureRect.Height);
Logger.LogInformation("点击传送点:({X},{Y})", clickX, clickY);
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
Logger.LogInformation("点击传送点");
using var ra = CaptureToRectArea();
ra.ClickTo(clickX, clickY);
ra.ClickTo((int)clickX, (int)clickY);
// 触发一次快速传送功能
await Delay(500, cts);
@@ -97,6 +97,57 @@ public class TpTask(CancellationTokenSource cts)
return (x, y);
}
/// <summary>
/// 传送点是否在大地图窗口内
/// </summary>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private bool IsPointInBigMapWindow(Rect bigMapInAllMapRect, double x, double y)
{
// 坐标不包含直接返回
if (!bigMapInAllMapRect.Contains(x, y))
{
return false;
}
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
// 屏蔽左上角350x400区域
if (clickX < 250 * _zoomOutMax1080PRatio && clickY < 400 * _zoomOutMax1080PRatio)
{
return false;
}
// 屏蔽周围 115 一圈的区域
if (clickX < 115 * _zoomOutMax1080PRatio
|| clickY < 115 * _zoomOutMax1080PRatio
|| clickX > _captureRect.Width - 115 * _zoomOutMax1080PRatio
|| clickY > _captureRect.Height - 115 * _zoomOutMax1080PRatio)
{
return false;
}
return true;
}
/// <summary>
/// 转换传送点坐标到窗体内需要点击的坐标
/// </summary>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private (double clickX, double clickY) ConvertToGameRegionPosition(Rect bigMapInAllMapRect, double x, double y)
{
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var clickX = (picX - picRect.X) / picRect.Width * _captureRect.Width;
var clickY = (picY - picRect.Y) / picRect.Height * _captureRect.Height;
return (clickX, clickY);
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false)
{
// 重试3次
@@ -106,11 +157,19 @@ public class TpTask(CancellationTokenSource cts)
{
return await TpOnce(tpX, tpY, force);
}
catch (TpPointNotActivate)
{
// 传送点未激活或不存在 按ESC回到大地图界面
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(300, cts);
throw;
}
catch (Exception e)
{
Logger.LogError(e, "传送失败,重试 {I} 次", i + 1);
}
}
throw new InvalidOperationException("传送失败");
}
@@ -313,7 +372,7 @@ public class TpTask(CancellationTokenSource cts)
if (bigMapCenterPointNullable != null)
{
var bigMapCenterPoint = bigMapCenterPointNullable.Value;
Logger.LogInformation("识别当前大地图位置:{Pos}", bigMapCenterPoint);
Logger.LogDebug("识别当前大地图位置:{Pos}", bigMapCenterPoint);
minDistance = Math.Sqrt(Math.Pow(bigMapCenterPoint.X - x, 2) + Math.Pow(bigMapCenterPoint.Y - y, 2));
}
@@ -328,7 +387,7 @@ public class TpTask(CancellationTokenSource cts)
}
}
Logger.LogInformation("离目标传送点最近的区域是:{Country}", minCountry);
Logger.LogDebug("离目标传送点最近的区域是:{Country}", minCountry);
if (minCountry != "当前位置")
{
GameCaptureRegion.GameRegionClick((rect, scale) => (rect.Width - 160 * scale, rect.Height - 60 * scale));
@@ -363,33 +422,37 @@ public class TpTask(CancellationTokenSource cts)
// 1.判断是否在地图界面
if (Bv.IsInBigMapUi(imageRegion))
{
// 2. 判断是否有传送按钮
// 2. 判断是否已经点出传送按钮
var hasTeleportButton = CheckTeleportButton(imageRegion);
if (!hasTeleportButton)
{
// 存在地图关闭按钮,说明未选中传送点,直接返回
var mapCloseRa = imageRegion.Find(_assets.MapCloseButtonRo);
if (!mapCloseRa.IsEmpty())
// 3. 没点出传送按钮,且不存在外部地图关闭按钮
// 说明只有两种可能,a. 点出来的是未激活传送点或者标点 b. 选择传送点选项列表
var mapCloseRa1 = imageRegion.Find(_assets.MapCloseButtonRo);
if (!mapCloseRa1.IsEmpty())
{
return;
throw new TpPointNotActivate("传送点未激活或不存在");
}
// 存在地图选择按钮,说明未选中传送点,直接返回
var mapChooseRa = imageRegion.Find(_assets.MapChooseRo);
if (!mapChooseRa.IsEmpty())
else
{
return;
}
// 3. 循环判断选项列表是否有传送点
var hasMapChooseIcon = CheckMapChooseIcon(imageRegion);
if (hasMapChooseIcon)
{
var time = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
time = time < 100 ? 100 : time;
await Delay(time, cts);
CheckTeleportButton(CaptureToRectArea());
// 3. 循环判断选项列表是否有传送点(未激活点位也在里面)
var hasMapChooseIcon = CheckMapChooseIcon(imageRegion);
if (hasMapChooseIcon)
{
var time = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
time = time < 300 ? 300 : time;
await Delay(time, cts);
if (!CheckTeleportButton(CaptureToRectArea()))
{
// 没传送确认图标说明点开的是未激活传送锚点
throw new TpPointNotActivate("传送点未激活或不存在");
}
}
else
{
// 没有传送点说明不是传送点
throw new TpPointNotActivate("传送点未激活或不存在");
}
}
}
}
@@ -440,7 +503,7 @@ public class TpTask(CancellationTokenSource cts)
Logger.LogInformation("传送:点击 {Option}", textRegion.Text);
var time = TaskContext.Instance().Config.QuickTeleportConfig.TeleportListClickDelay;
time = time < 200 ? 200 : time;
time = time < 500 ? 500 : time;
Thread.Sleep(time);
ra.Click();
hasMapChooseIcon = true;
@@ -36,6 +36,6 @@ public class MapAssets : BaseAssets<MapAssets>
public MapAssets()
{
var json = File.ReadAllText(Global.Absolute(@"GameTask\AutoTrackPath\Assets\tp.json"));
TpPositions = JsonSerializer.Deserialize<List<GiWorldPosition>>(json, ConfigService.JsonOptions) ?? throw new Exception("tp.json deserialize failed");
TpPositions = JsonSerializer.Deserialize<List<GiWorldPosition>>(json, ConfigService.JsonOptions) ?? throw new System.Exception("tp.json deserialize failed");
}
}
@@ -0,0 +1,5 @@
namespace BetterGenshinImpact.GameTask.Common.Exceptions;
public class TpPointNotActivate(string message) : System.Exception(message)
{
}
@@ -22,7 +22,7 @@ public static class NewRetry
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
List<Exception> exceptions = [];
List<System.Exception> exceptions = [];
for (int attempted = 0; attempted < maxAttemptCount; attempted++)
{
@@ -131,7 +131,7 @@ public class TaskControl
Sleep(30);
}
throw new Exception("尝试多次后,截图失败!");
throw new System.Exception("尝试多次后,截图失败!");
}
else
{
@@ -99,6 +99,15 @@ public class ImageRegion : Region
return new ImageRegion(new Mat(SrcMat, new Rect(x, y, w, h)), x, y, this, new TranslationConverter(x, y));
}
public ImageRegion DeriveCrop(double dx, double dy, double dw, double dh)
{
var x = (int)Math.Round(dx);
var y = (int)Math.Round(dy);
var w = (int)Math.Round(dw);
var h = (int)Math.Round(dh);
return new ImageRegion(new Mat(SrcMat, new Rect(x, y, w, h)), x, y, this, new TranslationConverter(x, y));
}
public ImageRegion DeriveCrop(Rect rect)
{
return DeriveCrop(rect.X, rect.Y, rect.Width, rect.Height);
@@ -191,48 +191,6 @@ namespace BetterGenshinImpact.GameTask
return _timer;
}
/// <summary>
/// 启动独立任务
/// </summary>
public void StartIndependentTask(IndependentTaskEnum taskType, BaseTaskParam param)
{
// if (!_timer.Enabled)
// {
// throw new Exception("请先在启动页启动BetterGI,如果已经启动请重启");
// }
//
// var maskWindow = MaskWindow.Instance();
// maskWindow.Invoke(() => { maskWindow.Show(); });
// if (taskType == IndependentTaskEnum.AutoGeniusInvokation)
// {
// AutoGeniusInvokationTask.Start((GeniusInvokationTaskParam)param);
// }
// else if (taskType == IndependentTaskEnum.AutoWood)
// {
// Task.Run(() => { new AutoWoodTask().Start((WoodTaskParam)param); });
// }
// else if (taskType == IndependentTaskEnum.AutoFight)
// {
// Task.Run(() => { new AutoFightTask((AutoFightParam)param).Start(); });
// }
// else if (taskType == IndependentTaskEnum.AutoDomain)
// {
// Task.Run(() => { new AutoDomainTask((AutoDomainParam)param).Start(); });
// }
// else if (taskType == IndependentTaskEnum.AutoTrack)
// {
// Task.Run(() => { new AutoTrackTask((AutoTrackParam)param).Start(); });
// }
// else if (taskType == IndependentTaskEnum.AutoTrackPath)
// {
// Task.Run(() => { new AutoTrackPathTask((AutoTrackPathParam)param).Start(); });
// }
// else if (taskType == IndependentTaskEnum.AutoMusicGame)
// {
// Task.Run(() => { new AutoMusicGameTask((AutoMusicGameParam)param).Start(); });
// }
}
public void Dispose()
{
Stop();
@@ -1,66 +0,0 @@
// using BetterGenshinImpact.GameTask;
// using BetterGenshinImpact.Helpers.Extensions;
// using System;
//
// namespace BetterGenshinImpact.Helpers;
//
// /// <summary>
// /// 不推荐使用
// /// 请使用 GameCaptureRegion.GameRegionClick 或 GameCaptureRegion.GameRegion1080PPosClick 替代
// /// </summary>
// [Obsolete]
// public class ClickOffset
// {
// public int OffsetX { get; set; }
// public int OffsetY { get; set; }
// public double AssetScale { get; set; }
//
// // public double CaptureAreaScale { get; set; }
//
// public ClickOffset()
// {
// if (!TaskContext.Instance().IsInitialized)
// {
// throw new Exception("请先启动");
// }
// var captureArea = TaskContext.Instance().SystemInfo.CaptureAreaRect;
// var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
// OffsetX = captureArea.X;
// OffsetY = captureArea.Y;
// AssetScale = assetScale;
// // CaptureAreaScale = TaskContext.Instance().SystemInfo.CaptureAreaScale;
// }
//
// public ClickOffset(int offsetX, int offsetY, double assetScale)
// {
// if (!TaskContext.Instance().IsInitialized)
// {
// throw new Exception("请先启动");
// }
// // CaptureAreaScale = TaskContext.Instance().SystemInfo.CaptureAreaScale;
//
// OffsetX = offsetX;
// OffsetY = offsetY;
// AssetScale = assetScale;
// }
//
// public void Click(int x, int y)
// {
// ClickExtension.Click(OffsetX + (int)(x * AssetScale), OffsetY + (int)(y * AssetScale));
// }
//
// /// <summary>
// /// 输入的x,y 注意处理缩放
// /// </summary>
// /// <param name="x"></param>
// /// <param name="y"></param>
// public void ClickWithoutScale(int x, int y)
// {
// ClickExtension.Click(OffsetX + x, OffsetY + y);
// }
//
// public void Move(int x, int y)
// {
// ClickExtension.Move(OffsetX + (int)(x * AssetScale), OffsetY + (int)(y * AssetScale));
// }
// }
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;
using System.Text.Json;
namespace BetterGenshinImpact.Helpers;
public class ExpandoObjectConverter
{
private static readonly JsonSerializerOptions _options = new()
{
NumberHandling = JsonNumberHandling.AllowNamedFloatingPointLiterals,
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
AllowTrailingCommas = true,
ReadCommentHandling = JsonCommentHandling.Skip,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static T ConvertTo<T>(dynamic source)
{
var json = JsonSerializer.Serialize(source, _options);
return JsonSerializer.Deserialize<T>(json, _options);
}
}
@@ -1,5 +1,6 @@
using BetterGenshinImpact.ViewModel;
using Microsoft.Extensions.DependencyInjection;
using System.Windows;
using System.Windows.Controls;
namespace BetterGenshinImpact.Helpers.Extensions;
@@ -17,11 +18,11 @@ internal static class DependencyInjectionExtensions
}
public static IServiceCollection AddView<TPage, TViewModel>(this IServiceCollection services)
where TPage : Page
where TPage : FrameworkElement
where TViewModel : class, IViewModel
{
return services
.AddSingleton<TPage>()
.AddSingleton<TViewModel>();
}
}
}
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
namespace BetterGenshinImpact.Helpers.Http;
public class ProxySpeedTester
{
private static readonly HttpClient _httpClient = new() { Timeout = TimeSpan.FromSeconds(5) };
public static readonly List<string> ProxyUrls =
[
"{0}",
"https://mirror.ghproxy.com/{0}",
"https://hub.gitmirror.com/{0}",
"https://ghproxy.cc/{0}",
"https://www.ghproxy.cc/{0}",
"https://ghproxy.cn/{0}",
"https://ghproxy.net/{0}"
];
/// <summary>
/// 获得最快的代理地址
/// </summary>
/// <param name="target"></param>
/// <returns>最快的代理地址,结果</returns>
public static async Task<(string, string)> GetFastestProxyAsync(string target)
{
return await GetFastestProxyAsync(ProxyUrls, target);
}
public static async Task<(string, string)> GetFastestProxyAsync(List<string> proxyAddresses, string target)
{
var tasks = new List<Task<(string, string, bool)>>(); // 修改为包含成功标志的元组
var cts = new CancellationTokenSource();
foreach (var proxy in proxyAddresses)
{
// 如果目标地址为空且代理地址为默认地址,则跳过
if (string.IsNullOrEmpty(target) && proxy == "{0}")
{
continue;
}
tasks.Add(TestProxyAsync(proxy, target, cts.Token));
}
while (tasks.Count > 0)
{
var firstCompletedTask = await Task.WhenAny(tasks);
tasks.Remove(firstCompletedTask);
var result = await firstCompletedTask;
if (result.Item3) // 检查是否成功
{
await cts.CancelAsync(); // 取消所有其他请求
return (result.Item1, result.Item2); // 返回第一个成功的代理地址
}
}
return (string.Empty, string.Empty); // 如果没有成功的结果,返回空
}
private static async Task<(string, string, bool)> TestProxyAsync(string proxyAddress, string target, CancellationToken cancellationToken)
{
try
{
// 模拟代理测试请求
var response = await _httpClient.GetAsync(string.Format(proxyAddress, target), cancellationToken);
response.EnsureSuccessStatusCode();
return (proxyAddress, await response.Content.ReadAsStringAsync(cancellationToken), true);
}
catch (Exception e)
{
return (proxyAddress, e.Message, false);
}
}
}
@@ -0,0 +1,42 @@
using Microsoft.ClearScript;
using System;
using System.Reflection;
namespace BetterGenshinImpact.Helpers;
public class ScriptObjectConverter
{
public static T ConvertTo<T>(ScriptObject source)
{
T result = Activator.CreateInstance<T>();
Type type = typeof(T);
foreach (PropertyInfo property in type.GetProperties())
{
// 支持 PascalCase 和 camelCase
DealWithProperty(source, property, char.ToLower(property.Name[0]) + property.Name[1..], result);
DealWithProperty(source, property, char.ToUpper(property.Name[0]) + property.Name[1..], result);
}
return result;
}
private static void DealWithProperty<T>(ScriptObject source, PropertyInfo property, string propertyName, T result)
{
if (source[propertyName] is not Undefined && source[propertyName] != null)
{
object value = source.GetProperty(propertyName);
if (property.PropertyType.IsPrimitive || property.PropertyType == typeof(string))
{
property.SetValue(result, Convert.ChangeType(value, property.PropertyType));
}
else
{
MethodInfo method = typeof(ScriptObjectConverter).GetMethod("ConvertTo")!.MakeGenericMethod(property.PropertyType);
object? nestedValue = method.Invoke(null, [value]);
property.SetValue(result, nestedValue);
}
}
}
}
@@ -0,0 +1,54 @@
using BetterGenshinImpact.Model;
using System.IO;
namespace BetterGenshinImpact.Helpers.Ui;
public class FileTreeNodeHelper
{
public static FileTreeNode<T> LoadDirectory<T>(string directoryPath)
{
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
var rootDirectoryInfo = new DirectoryInfo(directoryPath);
var rootNode = new FileTreeNode<T>
{
FileName = rootDirectoryInfo.Name,
IsDirectory = true,
FilePath = rootDirectoryInfo.FullName
};
LoadSubDirectories(rootDirectoryInfo, rootNode);
return rootNode;
}
public static void LoadSubDirectories<T>(DirectoryInfo directoryInfo, FileTreeNode<T> parentNode)
{
foreach (var directory in directoryInfo.GetDirectories())
{
var directoryNode = new FileTreeNode<T>
{
FileName = directory.Name,
IsDirectory = true,
FilePath = directory.FullName
};
parentNode.Children.Add(directoryNode);
LoadSubDirectories(directory, directoryNode);
}
foreach (var file in directoryInfo.GetFiles())
{
var fileNode = new FileTreeNode<T>
{
FileName = Path.GetFileNameWithoutExtension(file.Name),
IsDirectory = false,
FilePath = file.FullName
};
parentNode.Children.Add(fileNode);
}
}
}
@@ -1,79 +0,0 @@
using System;
using System.Collections;
using System.Drawing;
using System.IO;
using System.Linq;
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using Wpf.Ui.Controls;
using static Vanara.PInvoke.Gdi32;
namespace BetterGenshinImpact.Model;
public class FileTreeModel<T>(string rootPath) : ITreeModel where T : class
{
public string? Name { get; set; }
public DirectoryInfo? Directory { get; set; }
public T? Data { get; set; }
public IEnumerable GetChildren(object? parent)
{
parent ??= new FileTreeModel<T>(rootPath)
{
Directory = new DirectoryInfo(rootPath)
};
if (parent is FileTreeModel<T> { Directory: not null } model)
{
// 返回子目录
foreach (var dir in model.Directory.GetDirectories())
{
yield return new FileTreeModel<T>(rootPath)
{
Name = dir.Name,
Directory = dir
};
}
// 返回文件
foreach (var file in model.Directory.GetFiles())
{
var m = new FileTreeModel<T>(rootPath)
{
Name = file.Name,
};
if (typeof(T) == typeof(PathingTask))
{
m.Data = PathingTask.BuildFromFilePath(file.FullName) as T;
}
yield return m;
}
}
}
public bool HasChildren(object parent)
{
if (parent is FileTreeModel<T> { Directory: not null } model)
{
try
{
// 检查是否有子目录或文件
return model.Directory.GetDirectories().Any() || model.Directory.GetFiles().Any();
}
catch (UnauthorizedAccessException)
{
// 捕获没有权限的异常并返回 false
return false;
}
catch (Exception ex)
{
// 处理其他可能的异常
Console.WriteLine($"An error occurred: {ex.Message}");
return false;
}
}
return false;
}
}
@@ -0,0 +1,52 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
namespace BetterGenshinImpact.Model;
public partial class FileTreeNode<T> : ObservableObject
{
// 统一展示的属性
[ObservableProperty]
private string? _name;
[ObservableProperty]
private string? _version;
[ObservableProperty]
private string? _author;
[ObservableProperty]
private bool _isExpanded = false;
/// <summary>
/// 界面上显示是文件夹
/// </summary>
[ObservableProperty]
private bool _isDirectory;
/// <summary>
/// 文件名
/// </summary>
[ObservableProperty]
private string? _fileName;
/// <summary>
/// 完整路径
/// </summary>
[ObservableProperty]
private string? _filePath;
// 节点的值
[ObservableProperty]
private T? _value;
// 子节点列表
[ObservableProperty]
private ObservableCollection<FileTreeNode<T>> _children = [];
public T BuildValue()
{
Value = default!;
return Value;
}
}
@@ -2,6 +2,7 @@
using CommunityToolkit.Mvvm.Input;
using Fischless.HotkeyCapture;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows.Forms;
using System.Windows.Input;
@@ -22,8 +23,19 @@ public partial class HotKeySettingModel : ObservableObject
[ObservableProperty] private string _hotKeyTypeName;
[ObservableProperty]
private ObservableCollection<HotKeySettingModel> _children = [];
public string FunctionName { get; set; }
public bool IsExpanded => true;
/// <summary>
/// 界面上显示是文件夹而不是快捷键
/// </summary>
[ObservableProperty]
private bool _isDirectory;
public string ConfigPropertyName { get; set; }
public Action<object?, KeyPressedEventArgs>? OnKeyPressAction { get; set; }
@@ -49,6 +61,12 @@ public partial class HotKeySettingModel : ObservableObject
/// </summary>
public MouseHook? MouseMonitorHook { get; set; }
public HotKeySettingModel(string functionName)
{
FunctionName = functionName;
IsDirectory = true;
}
public HotKeySettingModel(string functionName, string configPropertyName, string hotkey, string hotKeyTypeCode, Action<object?, KeyPressedEventArgs>? onKeyPressAction, bool isHold = false)
{
FunctionName = functionName;
@@ -1,18 +0,0 @@
using BetterGenshinImpact.GameTask.AutoPathing.Model;
using CommunityToolkit.Mvvm.ComponentModel;
using Wpf.Ui.Controls;
namespace BetterGenshinImpact.Model;
[ObservableObject]
public partial class PathingTaskTreeObject : TreeObject<PathingTaskTreeObject>
{
[ObservableProperty]
private string? _name;
[ObservableProperty]
private bool _isFolder;
[ObservableProperty]
private PathingTask? _task;
}
+2 -2
View File
@@ -68,11 +68,11 @@ public class SettingItem
{
comboBox.SelectedItem = Default;
}
BindingOperations.SetBinding(comboBox, ItemsControl.ItemsSourceProperty, binding);
BindingOperations.SetBinding(comboBox, Selector.SelectedItemProperty, binding);
list.Add(comboBox);
break;
case "checkBox":
case "checkbox":
var checkBox = new CheckBox
{
Name = Name,
@@ -1,21 +0,0 @@
角色定义:
角色1=林尼
角色2=琳妮特
角色3=珊瑚宫心海
---
策略定义:
林尼 使用 技能3
林尼 使用 技能3
琳妮特 使用 技能2
林尼 使用 技能1
林尼 使用 技能2
琳妮特 使用 技能2
琳妮特 使用 技能1
林尼 使用 技能2
琳妮特 使用 技能2
// from: https://www.bilibili.com/video/av793443702/?p=2
@@ -1,20 +0,0 @@
角色定义:
角色1=雷电将军|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=4雷骰子}
角色2=香菱|火{技能3消耗=1火骰子+2任意,技能2消耗=3火骰子,技能1消耗=4火骰子}
角色3=柯莱|草{技能3消耗=1草骰子+2任意,技能2消耗=3草骰子,技能1消耗=3草骰子}
---
策略定义:
柯莱 使用 技能2
柯莱 使用 技能3
柯莱 使用 技能1
香菱 使用 技能2
雷电将军 使用 技能2
雷电将军 使用 技能3
雷电将军 使用 技能1
柯莱 使用 技能1
// from: https://www.bilibili.com/video/av271572530/?p=13
@@ -1,25 +0,0 @@
角色定义:
角色1=钟离|岩{技能4消耗=1岩骰子+2任意,技能3消耗=3岩骰子,技能2消耗=5岩骰子,技能1消耗=3岩骰子}
角色2=胡桃|火{技能3消耗=1火骰子+2任意,技能2消耗=2火骰子,技能1消耗=3火骰子}
角色3=行秋|水{技能3消耗=1水骰子+2任意,技能2消耗=3水骰子,技能1消耗=3水骰子}
---
策略定义:
行秋 使用 技能2
行秋 使用 技能3
行秋 使用 技能1
胡桃 使用 技能2
胡桃 使用 技能3
钟离 使用 技能3
胡桃 使用 技能3
钟离 使用 技能2
钟离 使用 技能4
钟离 使用 技能3
钟离 使用 技能1
// from: https://www.bilibili.com/video/av271572530/?p=4
@@ -1,17 +0,0 @@
角色定义:
角色1=温迪|风{技能3消耗=1风骰子+2任意,技能2消耗=3风骰子,技能1消耗=3风骰子}
角色2=菲谢尔|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=3雷骰子}
角色3=莫娜|水{技能3消耗=1水骰子+2任意,技能2消耗=3水骰子,技能1消耗=3水骰子}
---
策略定义:
菲谢尔 使用 技能2
温迪 使用 技能2
温迪 使用 技能2
温迪 使用 技能1
菲谢尔 使用 技能2
菲谢尔 使用 技能3
// from: https://www.bilibili.com/video/av271572530/?p=17
@@ -1,20 +0,0 @@
角色定义:
角色1=纳西妲|草{技能4消耗=1草骰子+2任意,技能3消耗=3草骰子,技能2消耗=5草骰子,技能1消耗=3草骰子}
角色2=九条裟罗|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=4雷骰子}
角色3=莫娜|水{技能3消耗=1水骰子+2任意,技能2消耗=3水骰子,技能1消耗=3水骰子}
---
策略定义:
纳西妲 使用 技能2
纳西妲 使用 技能4
纳西妲 使用 技能1
九条裟罗 使用 技能2
莫娜 使用 技能2
九条裟罗 使用 技能2
纳西妲 使用 技能3
九条裟罗 使用 技能1
// from: https://www.bilibili.com/video/av271572530/?p=7
@@ -1,16 +0,0 @@
角色定义:
角色1=特瓦林|风{技能4消耗=1风骰子+2任意,技能3消耗=3风骰子,技能2消耗=5风骰子,技能1消耗=4风骰子}
角色2=凯亚|冰{技能3消耗=1冰骰子+2任意,技能2消耗=3冰骰子,技能1消耗=4冰骰子}
角色3=无相之雷|雷{技能3消耗=1雷骰子+2任意,技能2消耗=5雷骰子,技能1消耗=3雷骰子}
---
策略定义:
特瓦林 使用 技能2
无相之雷 使用 技能3
无相之雷 使用 技能3
凯亚 使用 技能3
凯亚 使用 技能3
// from: https://www.bilibili.com/video/av880726236/
@@ -1,20 +0,0 @@
角色定义:
角色1=若陀龙王|岩{技能3消耗=3岩骰子,技能2消耗=3岩骰子,技能1消耗=3岩骰子}
角色2=菲谢尔|雷{技能3消耗=1雷骰子+2任意,技能2消耗=3雷骰子,技能1消耗=3雷骰子}
角色3=纯水精灵|水{技能4消耗=1水骰子+2任意,技能3消耗=3水骰子,技能2消耗=5水骰子,技能1消耗=3水骰子}
---
策略定义:
纯水精灵 使用 技能3
纯水精灵 使用 技能3
菲谢尔 使用 技能2
若陀龙王 使用 技能2
若陀龙王 使用 技能3
若陀龙王 使用 技能1
菲谢尔 使用 技能2
// from: https://www.bilibili.com/video/av880726236/?p=2
// 肥陀的定义是暂时缓解一个问题锁做的特殊定义,请勿直接复制使用
@@ -65,5 +65,6 @@
"买点东西",
"买新鲜的鱼",
"我想装饰一下场地",
"能交换什么呢"
"能交换什么呢",
"助力好友加速制作"
]
@@ -1,4 +1,5 @@
[
"调整序列",
"石之轮",
"幻想真境剧诗",
"开始演奏",
@@ -8,82 +8,76 @@ using System.Windows;
using System.Windows.Media;
using Wpf.Ui.Violeta.Controls;
namespace BetterGenshinImpact.View
namespace BetterGenshinImpact.View;
public partial class CaptureTestWindow : Window
{
/// <summary>
/// CaptureTestWindow.xaml 的交互逻辑
/// </summary>
public partial class CaptureTestWindow : Window
private IGameCapture? _capture;
private long _captureTime;
private long _transferTime;
private long _captureCount;
public CaptureTestWindow()
{
private IGameCapture? _capture;
private long _captureTime;
private long _transferTime;
private long _captureCount;
public CaptureTestWindow()
_captureTime = 0;
_transferTime = 0;
_captureCount = 0;
InitializeComponent();
Closed += (sender, args) =>
{
_captureTime = 0;
_transferTime = 0;
_captureCount = 0;
InitializeComponent();
Closed += (sender, args) =>
{
CompositionTarget.Rendering -= Loop;
_capture?.Stop();
CompositionTarget.Rendering -= Loop;
_capture?.Stop();
Debug.WriteLine("平均截图耗时:" + _captureTime * 1.0 / _captureCount);
Debug.WriteLine("平均转换耗时:" + _transferTime * 1.0 / _captureCount);
Debug.WriteLine("平均总耗时:" + (_captureTime + _transferTime) * 1.0 / _captureCount);
};
Debug.WriteLine("平均截图耗时:" + _captureTime * 1.0 / _captureCount);
Debug.WriteLine("平均转换耗时:" + _transferTime * 1.0 / _captureCount);
Debug.WriteLine("平均总耗时:" + (_captureTime + _transferTime) * 1.0 / _captureCount);
};
}
public void StartCapture(IntPtr hWnd, CaptureModes captureMode)
{
if (hWnd == IntPtr.Zero)
{
Toast.Warning("请选择窗口");
return;
}
public void StartCapture(IntPtr hWnd, CaptureModes captureMode)
{
if (hWnd == IntPtr.Zero)
_capture = GameCaptureFactory.Create(captureMode);
//_capture.IsClientEnabled = true;
_capture.Start(hWnd,
new Dictionary<string, object>()
{
Toast.Warning("请选择窗口");
return;
{ "useBitmapCache", TaskContext.Instance().Config.WgcUseBitmapCache }
}
);
CompositionTarget.Rendering += Loop;
}
_capture = GameCaptureFactory.Create(captureMode);
//_capture.IsClientEnabled = true;
_capture.Start(hWnd,
new Dictionary<string, object>()
{
{ "useBitmapCache", TaskContext.Instance().Config.WgcUseBitmapCache }
}
);
private void Loop(object? sender, EventArgs e)
{
var sw = new Stopwatch();
sw.Start();
var bitmap = _capture?.Capture();
sw.Stop();
Debug.WriteLine("截图耗时:" + sw.ElapsedMilliseconds);
_captureTime += sw.ElapsedMilliseconds;
CompositionTarget.Rendering += Loop;
}
private void Loop(object? sender, EventArgs e)
if (bitmap != null)
{
var sw = new Stopwatch();
Debug.WriteLine($"Bitmap:{bitmap.Width}x{bitmap.Height}");
_captureCount++;
sw.Reset();
sw.Start();
var bitmap = _capture?.Capture();
DisplayCaptureResultImage.Source = bitmap.ToBitmapImage();
sw.Stop();
Debug.WriteLine("截图耗时:" + sw.ElapsedMilliseconds);
_captureTime += sw.ElapsedMilliseconds;
if (bitmap != null)
{
Debug.WriteLine($"Bitmap:{bitmap.Width}x{bitmap.Height}");
_captureCount++;
sw.Reset();
sw.Start();
DisplayCaptureResultImage.Source = bitmap.ToBitmapImage();
sw.Stop();
Debug.WriteLine("转换耗时:" + sw.ElapsedMilliseconds);
_transferTime += sw.ElapsedMilliseconds;
}
else
{
Debug.WriteLine("截图失败");
}
Debug.WriteLine("转换耗时:" + sw.ElapsedMilliseconds);
_transferTime += sw.ElapsedMilliseconds;
}
else
{
Debug.WriteLine("截图失败");
}
}
}
}
@@ -3,12 +3,12 @@
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls">
<ResourceDictionary.MergedDictionaries>
<!-- SizeChrome 显示宽高的 -->
<!-- SizeChrome 显示宽高的 -->
<!-- <ResourceDictionary Source="SizeChrome.xaml"/> -->
<ResourceDictionary Source="ResizeRotateChrome.xaml" />
</ResourceDictionary.MergedDictionaries>
<!-- 可以拖拽调整大小的 -->
<!-- 可以拖拽调整大小的 -->
<ControlTemplate x:Key="MoveThumbTemplate" TargetType="{x:Type controls:MoveThumb}">
<Rectangle Fill="Transparent" />
</ControlTemplate>
@@ -23,8 +23,7 @@
<ControlTemplate TargetType="ContentControl">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<controls:MoveThumb Cursor="SizeAll" Template="{StaticResource MoveThumbTemplate}" />
<ContentPresenter Content="{TemplateBinding ContentControl.Content}"
Margin="{TemplateBinding Padding}" />
<ContentPresenter Margin="{TemplateBinding Padding}" Content="{TemplateBinding ContentControl.Content}" />
<controls:DesignerItemDecorator x:Name="ItemDecorator" />
</Grid>
<ControlTemplate.Triggers>
@@ -37,12 +36,12 @@
</Setter>
</Style>
<!-- 可以拖拽调整大小的 拖拽按钮在外面 -->
<!-- 可以拖拽调整大小的 拖拽按钮在外面 -->
<ControlTemplate x:Key="OuterMoveThumbTemplate" TargetType="{x:Type controls:MoveThumb}">
<!--<Rectangle x:Name="DragHandle" Fill="Blue" >
</Rectangle>-->
<Image x:Name="DragHandle" Source="pack://application:,,,/BetterGenshinImpact;component/Assets/drag.png" />
<Image x:Name="DragHandle" Source="pack://application:,,,/BetterGenshinImpact;component/Assets/Images/drag.png" />
<!--<ControlTemplate.Triggers>
<Trigger Property="Selector.IsSelected" Value="False">
@@ -60,11 +59,14 @@
<Setter.Value>
<ControlTemplate TargetType="ContentControl">
<Grid DataContext="{Binding RelativeSource={RelativeSource TemplatedParent}}">
<controls:MoveThumb Width="20" Height="20" Margin="0,-23,0,0"
VerticalAlignment="Top" HorizontalAlignment="Left"
Cursor="SizeAll" Template="{StaticResource OuterMoveThumbTemplate}" />
<ContentPresenter Content="{TemplateBinding ContentControl.Content}"
Margin="{TemplateBinding Padding}" />
<controls:MoveThumb Width="20"
Height="20"
Margin="0,-23,0,0"
HorizontalAlignment="Left"
VerticalAlignment="Top"
Cursor="SizeAll"
Template="{StaticResource OuterMoveThumbTemplate}" />
<ContentPresenter Margin="{TemplateBinding Padding}" Content="{TemplateBinding ContentControl.Content}" />
<controls:DesignerItemDecorator x:Name="ItemDecorator" />
</Grid>
<ControlTemplate.Triggers>
@@ -0,0 +1,103 @@
using System.Windows;
using System.Windows.Input;
using Wpf.Ui.Controls;
namespace BetterGenshinImpact.View.Controls;
public class TwoStateButton : Button
{
public TwoStateButton()
{
if (TryFindResource(typeof(Button)) is Style style)
{
Style = style;
}
Loaded += OnLoaded;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
UpdateButton();
}
private static void OnIsCheckedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is TwoStateButton button)
{
button.UpdateButton();
}
}
private static readonly DependencyProperty IsCheckedProperty = DependencyProperty.Register(nameof(IsChecked), typeof(bool), typeof(TwoStateButton), new PropertyMetadata(false, OnIsCheckedChanged));
public bool IsChecked
{
get => (bool)GetValue(IsCheckedProperty);
set => SetValue(IsCheckedProperty, value);
}
private static readonly DependencyProperty EnableContentProperty = DependencyProperty.Register(nameof(EnableContent), typeof(object), typeof(TwoStateButton), new PropertyMetadata("启动"));
public object EnableContent
{
get => (string)GetValue(EnableContentProperty);
set => SetValue(EnableContentProperty, value);
}
private static readonly DependencyProperty EnableIconProperty = DependencyProperty.Register(nameof(EnableIcon), typeof(IconElement), typeof(TwoStateButton), new PropertyMetadata(null));
public IconElement EnableIcon
{
get => (IconElement)GetValue(EnableIconProperty);
set => SetValue(EnableIconProperty, value);
}
private static readonly DependencyProperty EnableCommandProperty = DependencyProperty.Register(nameof(EnableCommand), typeof(ICommand), typeof(TwoStateButton), new PropertyMetadata(null));
public ICommand EnableCommand
{
get => (ICommand)GetValue(EnableCommandProperty);
set => SetValue(EnableCommandProperty, value);
}
private static readonly DependencyProperty DisableContentProperty = DependencyProperty.Register(nameof(DisableContent), typeof(object), typeof(TwoStateButton), new PropertyMetadata("停止"));
public object DisableContent
{
get => (string)GetValue(DisableContentProperty);
set => SetValue(DisableContentProperty, value);
}
private static readonly DependencyProperty DisableIconProperty = DependencyProperty.Register(nameof(DisableIcon), typeof(IconElement), typeof(TwoStateButton), new PropertyMetadata(null));
public IconElement DisableIcon
{
get => (IconElement)GetValue(DisableIconProperty);
set => SetValue(DisableIconProperty, value);
}
private static readonly DependencyProperty DisableCommandProperty = DependencyProperty.Register(nameof(DisableCommand), typeof(ICommand), typeof(TwoStateButton), new PropertyMetadata(null));
public ICommand DisableCommand
{
get => (ICommand)GetValue(DisableCommandProperty);
set => SetValue(DisableCommandProperty, value);
}
private void UpdateButton()
{
if (IsChecked)
{
Command = DisableCommand;
Content = DisableContent;
Icon = DisableIcon;
}
else
{
Command = EnableCommand;
Content = EnableContent;
Icon = EnableIcon;
}
}
}
@@ -21,6 +21,8 @@ public class WebpagePanel : UserControl
public string? DownloadFolderPath { get; set; }
public Action? OnWebViewInitializedAction { get; set; }
public WebpagePanel()
{
if (!IsWebView2Available())
@@ -34,7 +36,9 @@ public class WebpagePanel : UserControl
CreationProperties = new CoreWebView2CreationProperties
{
UserDataFolder = Path.Combine(new FileInfo(Environment.ProcessPath!).DirectoryName!, @"WebView2Data\\"),
AdditionalBrowserArguments = "--enable-features=WebContentsForceDark"
// TODO: change the theme from `md2html.html` to fit it firstly.
// AdditionalBrowserArguments = "--enable-features=WebContentsForceDark"
}
};
_webView.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
@@ -52,6 +56,8 @@ public class WebpagePanel : UserControl
{
WebView.CoreWebView2.Profile.DefaultDownloadFolderPath = DownloadFolderPath;
}
// 调用外部设置的 Action
OnWebViewInitializedAction?.Invoke();
}
else
{
@@ -20,7 +20,7 @@ public class WebpageWindow : Window
};
Content = wp;
Background = new SolidColorBrush(Color.FromRgb(0x20, 0x20, 0x20));
// Background = new SolidColorBrush(Color.FromRgb(0x20, 0x20, 0x20));
}
protected override void OnSourceInitialized(EventArgs e)
+7 -3
View File
@@ -20,6 +20,7 @@
ExtendsContentIntoTitleBar="True"
FontFamily="{StaticResource TextThemeFontFamily}"
Visibility="{Binding IsVisible, Mode=TwoWay, Converter={StaticResource BooleanToVisibilityConverter}}"
WindowBackdropType="Auto"
WindowStartupLocation="CenterScreen"
WindowState="{Binding WindowState, Mode=TwoWay}"
mc:Ignorable="d">
@@ -27,6 +28,9 @@
<BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
</Window.Resources>
<b:Interaction.Triggers>
<b:EventTrigger EventName="Activated">
<b:InvokeCommandAction Command="{Binding ActivatedCommand}" />
</b:EventTrigger>
<b:EventTrigger EventName="Loaded">
<b:InvokeCommandAction Command="{Binding LoadedCommand}" CommandParameter="{Binding}" />
</b:EventTrigger>
@@ -94,7 +98,7 @@
</ui:NavigationViewItem.Icon>
</ui:NavigationViewItem>
<!-- WebAsset24 | DocumentJs16 | Script16 -->
<ui:NavigationViewItem Content="脚本"
<ui:NavigationViewItem Content="JS 脚本"
NavigationCacheMode="Enabled"
TargetPageType="{x:Type pages:JsListPage}">
<ui:NavigationViewItem.Icon>
@@ -154,7 +158,7 @@
<ui:TitleBar Title="{Binding Title, Mode=OneWay}" Grid.Row="0">
<ui:TitleBar.Icon>
<ui:ImageIcon Source="pack://application:,,,/Assets/Kirara.png" />
<ui:ImageIcon Source="pack://application:,,,/Assets/Images/Anniversary/logo_1st.png" />
</ui:TitleBar.Icon>
<ui:TitleBar.Header>
<StackPanel>
@@ -172,7 +176,7 @@
<tray:NotifyIcon Grid.Row="0"
FocusOnLeftClick="False"
Icon="pack://application:,,,/Assets/logo.ico"
Icon="pack://application:,,,/Assets/Images/logo.ico"
LeftDoubleClick="OnNotifyIconLeftDoubleClick"
MenuOnRightClick="True"
TooltipText="BetterGI">
@@ -1,18 +1,15 @@
using BetterGenshinImpact.ViewModel.Pages;
using System.Windows.Controls;
namespace BetterGenshinImpact.View.Pages
namespace BetterGenshinImpact.View.Pages;
public partial class CommonSettingsPage : Page
{
/// <summary>
/// CommonSettingsPage.xaml 的交互逻辑
/// </summary>
public partial class CommonSettingsPage : Page
private CommonSettingsPageViewModel ViewModel { get; }
public CommonSettingsPage(CommonSettingsPageViewModel viewModel)
{
CommonSettingsPageViewModel ViewModel { get; }
public CommonSettingsPage(CommonSettingsPageViewModel viewModel)
{
DataContext = ViewModel = viewModel;
InitializeComponent();
}
DataContext = ViewModel = viewModel;
InitializeComponent();
}
}
+33 -12
View File
@@ -2,8 +2,8 @@
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BetterGenshinImpact.View.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
@@ -29,7 +29,7 @@
<Grid>
<Border ClipToBounds="True" CornerRadius="8">
<Border.Background>
<ImageBrush ImageSource="pack://application:,,,/Assets/keqing.jpg"
<ImageBrush ImageSource="pack://application:,,,/Assets/Images/banner_4th.jpg"
RenderOptions.BitmapScalingMode="HighQuality"
Stretch="UniformToFill" />
</Border.Background>
@@ -95,14 +95,21 @@
Grid.Column="1"
Margin="0,0,24,0"
Orientation="Horizontal">
<ui:Button Command="{Binding StartTriggerCommand}"
Content="启动"
Icon="{ui:SymbolIcon Play24}"
Visibility="{Binding TaskDispatcherEnabled, Converter={StaticResource BooleanToVisibilityRevertConverter}, Mode=OneWay}" />
<ui:Button Command="{Binding StopTriggerCommand}"
Content="停止"
Icon="{ui:SymbolIcon Dismiss24}"
Visibility="{Binding TaskDispatcherEnabled, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}" />
<controls:TwoStateButton DisableCommand="{Binding StopTriggerCommand}"
DisableContent="停止"
DisableIcon="{ui:SymbolIcon Dismiss24}"
EnableCommand="{Binding StartTriggerCommand}"
EnableContent="启动"
EnableIcon="{ui:SymbolIcon Play24}"
IsChecked="{Binding TaskDispatcherEnabled, Mode=OneWay}" />
<!-- <ui:Button Command="{Binding StartTriggerCommand}" -->
<!-- Content="启动" -->
<!-- Icon="{ui:SymbolIcon Play24}" -->
<!-- Visibility="{Binding TaskDispatcherEnabled, Converter={StaticResource BooleanToVisibilityRevertConverter}, Mode=OneWay}" /> -->
<!-- <ui:Button Command="{Binding StopTriggerCommand}" -->
<!-- Content="停止" -->
<!-- Icon="{ui:SymbolIcon Dismiss24}" -->
<!-- Visibility="{Binding TaskDispatcherEnabled, Converter={StaticResource BooleanToVisibilityConverter}, Mode=OneWay}" /> -->
</StackPanel>
</Grid>
</ui:CardExpander.Header>
@@ -378,12 +385,25 @@
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="启动参数"
TextWrapping="Wrap" />
TextWrapping="Wrap">
<ui:TextBlock.Inlines>
<Run Text="启动参数" />
<ui:HyperlinkButton Grid.Row="1"
Margin="0,0,0,0"
Command="{Binding OpenGameCommandLineDocumentCommand}"
Padding="0"
Cursor="Hand">
<ui:HyperlinkButton.Content>
<TextBlock FontSize="11" Text="打开文档" />
</ui:HyperlinkButton.Content>
</ui:HyperlinkButton>
</ui:TextBlock.Inlines>
</ui:TextBlock>
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
@@ -396,6 +416,7 @@
MinWidth="300"
MaxWidth="800"
Margin="0,0,36,0"
PlaceholderText="示例:-screen-width 1920"
Text="{Binding Config.GenshinStartConfig.GenshinStartArgs, Mode=TwoWay}"
TextWrapping="Wrap" />
</Grid>
+77 -23
View File
@@ -1,28 +1,28 @@
<Page x:Class="BetterGenshinImpact.View.Pages.HotKeyPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hotKey="clr-namespace:BetterGenshinImpact.View.Controls.HotKey"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:model="clr-namespace:BetterGenshinImpact.Model"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="HotkeyPage"
d:DataContext="{d:DesignInstance Type=pages:HotKeyPageViewModel}"
d:DesignHeight="850"
d:DesignWidth="600"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<UserControl x:Class="BetterGenshinImpact.View.Pages.HotKeyPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:controls="clr-namespace:BetterGenshinImpact.View.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:hotKey="clr-namespace:BetterGenshinImpact.View.Controls.HotKey"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:model="clr-namespace:BetterGenshinImpact.Model"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
d:DataContext="{d:DesignInstance Type=pages:HotKeyPageViewModel}"
d:DesignHeight="850"
d:DesignWidth="600"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<Grid Margin="42,16,42,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0"
Margin="0,0,0,8"
@@ -33,7 +33,8 @@
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="全局热键:只支持组合键和功能键,软件启动直接生效。键鼠监听:支持任意键盘单键、鼠标侧键,功能启动后才生效(推荐)。点击类型按钮可以切换快捷键类型。其中存在长按需求的功能不能使用全局热键。"
TextWrapping="Wrap" />
<ItemsControl Grid.Row="2" ItemsSource="{Binding HotKeySettingModels}">
<!--<ItemsControl Grid.Row="2" ItemsSource="{Binding HotKeySettingModels}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type model:HotKeySettingModel}">
<Grid Margin="0,8">
@@ -59,6 +60,59 @@
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</ItemsControl>-->
<ui:Border Grid.Row="2"
Background="{DynamicResource CardBackground}"
BorderBrush="{DynamicResource CardBorderBrush}"
BorderThickness="1"
CornerRadius="{DynamicResource ControlCornerRadius}">
<Grid Margin="4">
<ui:Grid ColumnDefinitions="*,235" Visibility="Hidden">
<Grid x:Name="TreeColumnStar" Grid.Column="0" />
</ui:Grid>
<ui:TreeListView BorderThickness="0" ItemsSource="{Binding HotKeySettingModels}">
<ui:TreeListView.Columns>
<GridViewColumnCollection>
<ui:GridViewColumn Width="{Binding ActualWidth, ElementName=TreeColumnStar}" Header="功能">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:TreeRowExpander Content="{Binding FunctionName}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="100" Header="快捷键类型">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<ui:Button Height="33"
VerticalAlignment="Center"
Command="{Binding SwitchHotKeyTypeCommand}"
Content="{Binding HotKeyTypeName, Mode=OneWay}"
IsEnabled="{Binding SwitchHotkeyTypeEnabled, Mode=OneWay}"
Visibility="{Binding IsDirectory, Converter={StaticResource BooleanToVisibilityRevertConverter}, Mode=OneWay}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
<ui:GridViewColumn Width="120" Header="配置快捷键">
<ui:GridViewColumn.CellTemplate>
<DataTemplate>
<hotKey:HotKeyTextBox Padding="16,6,16,6"
VerticalAlignment="Center"
HotKeyTypeName="{Binding HotKeyTypeName, Mode=OneWay}"
Hotkey="{Binding HotKey}"
Style="{StaticResource DefaultTextBoxStyle}"
TextAlignment="Center"
Visibility="{Binding IsDirectory, Converter={StaticResource BooleanToVisibilityRevertConverter}, Mode=OneWay}" />
</DataTemplate>
</ui:GridViewColumn.CellTemplate>
</ui:GridViewColumn>
</GridViewColumnCollection>
</ui:TreeListView.Columns>
<ui:TreeListView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" />
</ui:TreeListView.ItemTemplate>
</ui:TreeListView>
</Grid>
</ui:Border>
</Grid>
</Page>
</UserControl>
@@ -3,10 +3,7 @@ using System.Windows.Controls;
namespace BetterGenshinImpact.View.Pages;
/// <summary>
/// TaskSettingsPage.xaml 的交互逻辑
/// </summary>
public partial class HotKeyPage : Page
public partial class HotKeyPage : UserControl
{
private HotKeyPageViewModel ViewModel { get; }
+39 -25
View File
@@ -1,28 +1,27 @@
<Page x:Class="BetterGenshinImpact.View.Pages.JsListPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BetterGenshinImpact.View.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
Title="JsListPage"
d:DataContext="{d:DesignInstance Type=pages:JsListViewModel}"
d:DesignHeight="600"
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<Page.Resources>
<UserControl x:Class="BetterGenshinImpact.View.Pages.JsListPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:BetterGenshinImpact.View.Pages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:pages="clr-namespace:BetterGenshinImpact.ViewModel.Pages"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
d:DataContext="{d:DesignInstance Type=pages:JsListViewModel}"
d:DesignHeight="600"
d:DesignWidth="800"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
FontFamily="{StaticResource TextThemeFontFamily}"
Foreground="{DynamicResource TextFillColorPrimaryBrush}"
mc:Ignorable="d">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="/View/Controls/Style/ListViewEx.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Page.Resources>
</UserControl.Resources>
<Grid Margin="42,16,42,12">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -30,23 +29,38 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="400" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ui:TextBlock Grid.Row="0"
Margin="0,0,0,8"
FontTypography="BodyStrong"
Text="自定义 Javascript 脚本(开发中功能)" />
Text="自定义 Javascript 脚本(实验功能)" />
<ui:TextBlock Grid.Row="1"
Margin="0,0,0,8"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="可以通过 Javascript 调用 BetterGI 在原神中的各项能力,右键可以直接执行脚本。建议在调度器中使用!"
TextWrapping="Wrap" />
TextWrapping="Wrap">
可以通过 Javascript 调用 BetterGI 在原神中的各项能力。请在调度器中使用!<Hyperlink Command="{Binding GoToJsScriptUrlCommand}" Foreground="{ui:ThemeResource TextFillColorSecondaryBrush}">
点击查看 Javascript 脚本使用与编写教程
</Hyperlink>
</ui:TextBlock>
<StackPanel Grid.Row="2" Orientation="Horizontal">
<ui:Button Command="{Binding OpenScriptsFolderCommand}"
Content="打开脚本目录"
Icon="{ui:SymbolIcon FolderOpen24}" />
<Separator Width="10" Opacity="0" />
<ui:Button Command="{Binding OpenLocalScriptRepoCommand}" Icon="{ui:SymbolIcon Archive24}">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ui:TextBlock>脚本仓库</ui:TextBlock>
<ui:InfoBadge Margin="0,-8,-14,0"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Severity="Attention"
Style="{DynamicResource DotInfoBadgeStyle}"
Visibility="{Binding Config.ScriptConfig.ScriptRepoHintDotVisible, Converter={StaticResource BooleanToVisibilityConverter}}" />
</Grid>
</ui:Button>
</StackPanel>
<Separator Grid.Row="3"
@@ -119,4 +133,4 @@
</ListView.Style>
</ui:ListView>
</Grid>
</Page>
</UserControl>
@@ -1,13 +1,9 @@
using BetterGenshinImpact.ViewModel;
using BetterGenshinImpact.ViewModel.Pages;
using BetterGenshinImpact.ViewModel.Pages;
using System.Windows.Controls;
namespace BetterGenshinImpact.View.Pages;
/// <summary>
/// JsListPage.xaml 的交互逻辑
/// </summary>
public partial class JsListPage : Page
public partial class JsListPage : UserControl
{
private JsListViewModel ViewModel { get; }
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff. Show more