Compare commits

..
76 Commits
Author SHA1 Message Date
huiyadanli e65c57c486 Update version to 0.46.2 2025-06-22 15:03:17 +00:00
辉鸭蛋 8f2484f336 脚本仓库更新失败时候弹窗 2025-06-22 22:56:37 +08:00
辉鸭蛋 30a774233a fix: 打完秘境后的提示可以直接退出 2025-06-22 22:00:38 +08:00
辉鸭蛋 b97bbd0eee Merge remote-tracking branch 'origin/main' 2025-06-22 21:55:42 +08:00
辉鸭蛋 5e9b78eb55 还原进入秘境的代码 2025-06-22 21:55:33 +08:00
huiyadanli a35fecf579 Update version to 0.46.1-alpha.1 2025-06-22 13:26:21 +00:00
辉鸭蛋 3ca0eb27e3 在无其他树脂,只剩原粹树脂的场景下,利用提示兜底退出秘境 2025-06-22 21:22:58 +08:00
辉鸭蛋 f4fdef9720 Merge remote-tracking branch 'origin/main' 2025-06-22 21:01:36 +08:00
辉鸭蛋 08fbd772b7 修复2K下树脂使用失效的问题,修复无可用树脂的场景 2025-06-22 21:01:28 +08:00
xyToki f937726f86 fix: fix mirrorc 2025-06-22 18:38:00 +08:00
xyToki a7aa62f433 fix: mirrorc release ci 2025-06-22 18:35:46 +08:00
xyToki 0c687840f9 fix: fix mirrorc upload 2025-06-22 18:28:56 +08:00
huiyadanli 36d53a6cb3 Update version to 0.46.0 2025-06-22 09:56:58 +00:00
辉鸭蛋 5e242f2be3 还是水龙王问题,随便点击下 2025-06-22 16:39:06 +08:00
xyToki e0aa5f0821 ci: update mirrorc release pipeline 2025-06-22 16:18:17 +08:00
huiyadanli 64c9f717aa Update version to 0.45.6-alpha.3 2025-06-22 06:58:27 +00:00
辉鸭蛋 f08a53c7cd ci: version for run_name 2025-06-22 14:56:24 +08:00
huiyadanli 1a1141feaa Update version to 0.45.6-alpha.2 2025-06-22 06:12:41 +00:00
辉鸭蛋 b56003fa87 Merge remote-tracking branch 'origin/main' 2025-06-22 13:34:31 +08:00
辉鸭蛋 3b3ac00097 处理刷取次数过多的情况 2025-06-22 13:34:23 +08:00
huiyadanli 82be4d4555 Update version to 0.45.6-alpha.1 2025-06-21 18:34:27 +00:00
辉鸭蛋 8799f34ce8 修复 Yap 无法正常使用的问题 #1459 2025-06-22 02:31:37 +08:00
辉鸭蛋 9284a51ce6 自动秘境支持指定树脂刷取次数 #1440 #1116 #692 #426 2025-06-22 02:15:36 +08:00
xytoki 269869e9d8 Update version to 0.45.5-alpha.10 2025-06-21 15:27:35 +00:00
xyToki 65b5b80a47 ci: fix mirrorc un7z parent folder 2025-06-21 23:25:37 +08:00
xytoki 98ab2089c2 Update version to 0.45.5-alpha.9 2025-06-21 15:04:00 +00:00
xyToki 13a47e64b8 ci: always pass zip to mirrorc 2025-06-21 23:02:04 +08:00
xytoki 71ea62beb6 Update version to 0.45.5-alpha.8 2025-06-21 14:43:16 +00:00
xyToki bc6c0ed3d0 feat(ci): extract metadata from installer 2025-06-21 22:41:26 +08:00
xyToki bd2070b94c ci: fix mirrorc upload exe fail 2025-06-21 22:36:28 +08:00
xytoki 3ed6a04caa Update version to 0.45.5-alpha.7 2025-06-21 14:25:11 +00:00
辉鸭蛋 e7073e5d8a Merge remote-tracking branch 'origin/main' 2025-06-21 22:10:52 +08:00
辉鸭蛋 64b1fa2c2d fix: 七圣召唤元数据加载失败的问题 2025-06-21 22:10:29 +08:00
huiyadanli 93c994570e Update version to 0.45.5-alpha.6 2025-06-21 13:51:28 +00:00
xyToki 255e7bb08e ci: embed dotnet to mirrorc exe 2025-06-21 21:48:51 +08:00
辉鸭蛋 0bb23b9fcc Revert "优化交互界面。 (#1681)" (#1728)
This reverts commit 236c725710.
2025-06-21 21:44:55 +08:00
辉鸭蛋 c04d47f7a7 Merge remote-tracking branch 'origin/main' 2025-06-21 21:40:01 +08:00
辉鸭蛋 0c467d2f97 修复原粹树脂的识别 2025-06-21 21:39:50 +08:00
mfkvfhpdx d2092a6c32 路径追踪增加拾取战斗人次阈值 (#1726)
* 修改调度器任务和部分独立任务失去焦点时,强制切换回游戏窗口,如果用常规的方式无法激活窗口,则第10次会尝试最小化所有窗口后激活游戏。

* 去除未引入的类引用

* 修正战斗结束后,大概率打开队伍界面的问题

* 修复有些电脑上因未知原因,战斗0秒打断

* 把失焦激活放入了设置-通用设置-其他设置中,默认关闭。暂停恢复时,重置移动的起始时间,防止因暂停而导致超时放弃任务。

* 在调度器里面的任务之前,增加月卡处理,解决4点如果未进入任务会卡住的问题。增加了日志分析小怪详细。解决日志分析兜底结束日期不生效的问题。

* 在设置=》其他设置中 增加调度器任务传送过程中自动领取探索奖励功能配置。

* 调整自动派遣后恢复原任务的逻辑

* 自动领取派遣奖励时,跳过异常,防止整个配置组任务被打断。

* 把打开大地图方法从TpTask中抽出为公共方法,自动领取派遣代码调整到了调度器中。

* 去除了未使用的引用

* 暂停恢复逻辑增加恢复中条件和非空判断

* 增加了临时暂停自动拾取的逻辑(RunnerContext.AutoPickTriggerStopCount 为0时不限制,大于0时停止,多次暂停会累加该值,每次恢复-1),支持嵌套情况的暂停,在自动派遣(和结束后5秒)或暂停调度器任务时,同时暂停自动拾取功能。

* 调整暂停拾取方法

* 调整个日志输出

* 路径追踪复苏时,暂停拾取

* 增加根据点位配置,支持能在点位未识别情况下,使用大地图中心点的方式来定位,从而支持像铜锁小岛处这种小地图无法识别的点位。调整了对未识别点位的默认逻辑,未配置点位配置情况下,未识别点位,会取上一个识别的点位,从而支持在某些地方断续小地图能识别情况下的脚本。

* Changes

* 修复暂停后,距离过远,小地图无法识别时,无限取当前一个坐标,导致无法正常恢复的问题。调度器管理增加了按天为单位的周期配置,适用于批量执行时,无需人工判断当天执行哪个任务。

* 调度器配置增加,或开启万叶拾取,并且不存在万叶,但配置了万叶队伍情况下,会切换队伍进行拾取。

* 调度器配置,增加了  只拾取精英掉落模式 ,根据编辑器点位配置,可设定非标记精英或传奇的点位跳过拾取。

* 解决卡换成复活形式的任务卡死

* 判断主界面时,复活界面返回false

* 完全跳过的配置组,不发送通知。给周期配置增加说明。

* 启动参数增加 --no-single ,允许多开,实现特殊需求(重启需要)。增加了一个重启bgi的方法。增加了任务进度的功能,执行调度器任务时,会记录当前任务执行位置,当关闭后(比如F11),下次可以通过继续菜单,选择记录,从上次关闭任务处执行。

* 调整继续执行,最后一次成功的下一个任务执行

* 设置,其他设置,增加了调度器任务,遇到异常时,连续累计一定次数时,重启BGI,和可配置的重启游戏。

* 连续任务支持循环,右键支持从连续的某一个任务开始执行。修改了一些配置变量的写法,使之不会保存到json文件中。

* 修正一条龙,下一个从此执行失效的问题

* 路径追踪增加拾取战斗人次阈值 ,用于配置,战斗次数小于一定次数,会跳过拾取配置,默认不生效。
2025-06-21 11:07:42 +08:00
huiyadanli 3a635524c4 Update version to 0.45.5-alpha.5 2025-06-21 02:23:30 +00:00
辉鸭蛋 5cb032b851 Merge remote-tracking branch 'origin/main' 2025-06-21 10:21:42 +08:00
辉鸭蛋 795c089100 自动秘境:解决水龙王按下左键后没松开,然后后续点击按下就没反应了。使用双击 2025-06-21 10:21:22 +08:00
huiyadanli e81676847c Update version to 0.45.5-alpha.4 2025-06-21 02:20:33 +00:00
辉鸭蛋 d44eaa5312 自动秘境:战斗结束后释放所有按键 2025-06-21 10:18:28 +08:00
辉鸭蛋 008c1b2e03 Merge remote-tracking branch 'origin/main' 2025-06-21 10:16:00 +08:00
辉鸭蛋 26590f7268 自动秘境:解决水龙王按下左键后没松开,然后后续点击按下就没反应了 2025-06-21 10:15:46 +08:00
huiyadanli 909e29f268 Update version to 0.45.5-alpha.3 2025-06-21 01:38:37 +00:00
辉鸭蛋 1ae0db15d3 5.7 model 2025-06-21 09:35:34 +08:00
辉鸭蛋 a520ee8785 修复离线仓库导入不可用的问题 2025-06-21 01:40:00 +08:00
辉鸭蛋 f386b743c3 自动秘境:只剩下原粹树脂,且被刷完的场景 2025-06-21 01:13:03 +08:00
huiyadanli 3575a7274e Update version to 0.45.5-alpha.2 2025-06-20 15:49:38 +00:00
辉鸭蛋 a60229cad2 Update updater command options for stable and alpha channels 2025-06-20 23:47:06 +08:00
huiyadanli 26456bb5ee Update version to 0.45.5-alpha.1 2025-06-20 15:10:28 +00:00
辉鸭蛋 7a41056fc1 适配 5.7 秘境领取奖励 (#1725)
* Improve error message for update failure in ScriptRepoWindow

* 临时提交

* 完成浓缩树脂、原粹树脂的使用兼容
2025-06-20 23:04:46 +08:00
FishmanTheMurloc 32f744538b 用CV的相位相关方法代替旧的方法来检测grid界面是否还能滚动,配有单元测试;封装了一个grid界面的操作类,直接对此类对象进行遍历即可获取所有项 (#1724) 2025-06-20 22:56:21 +08:00
辉鸭蛋 937c86927c 去除轮次判断 2025-06-20 20:55:34 +08:00
huiyadanli abbdfdb710 Update version to 0.45.4-alpha.3 2025-06-20 08:46:36 +00:00
辉鸭蛋 39c1a3155f Update kachina.config.json 2025-06-20 16:15:24 +08:00
huiyadanli 384e05d493 Update version to 0.45.4-alpha.2 2025-06-20 03:35:15 +00:00
kaedelcb e5cc8152f6 尘歌壶进入优化,购买添加重试 (#1722) 2025-06-20 00:34:47 +08:00
辉鸭蛋 01225eda26 Merge remote-tracking branch 'origin/main' 2025-06-19 22:59:19 +08:00
辉鸭蛋 aa43c16d81 5.7 model 2025-06-19 22:59:09 +08:00
辉鸭蛋 a372c93de9 Update README.md 2025-06-19 10:43:57 +08:00
辉鸭蛋 712630acc3 Merge remote-tracking branch 'origin/main' 2025-06-19 00:30:01 +08:00
辉鸭蛋 d7e0af3a57 5.7 角色数据新增 Add new characters Skirk and Dahlia to combat_avatar.json 2025-06-19 00:29:27 +08:00
辉鸭蛋 3408b948b0 5.7 角色数据新增 Add new characters Skirk and Dahlia to combat_avatar.json 2025-06-19 00:12:01 +08:00
郝凯阳 f6540c8e59 auto tcg: update character card config to v5.7 (#1713) 2025-06-18 16:13:53 +08:00
huiyadanli d091bfe7d5 Update version to 0.45.4-alpha.1 2025-06-16 19:17:22 +00:00
辉鸭蛋 6f87a0c4d0 脚本仓库V2 (#1707)
* feat: add custom drawer control and integrate it into the UI

* 更新仓库UI

* feat: implement Git-based repository update mechanism and improve error handling

* feat: add reset repository functionality with confirmation dialog

* 修改打开队伍配置界面的重试次数和日志

* feat: add drawer open/close events and improve drawer closing logic

* feat: enhance WebpagePanel navigation handling and improve initialization logic

* feat: add drawer opened event handling and improve navigation completion logic

* feat: implement dynamic height adjustment for WebpagePanel using Grid container

* feat: update drawer dimensions and apply dynamic sizing based on position

* feat: add CustomDrawer component and integrate with MapPathingViewModel for enhanced navigation

* feat: integrate WebView2 for Markdown file navigation in MapPathingViewModel
2025-06-17 03:13:56 +08:00
FishmanTheMurloc 4787f4f2f9 尝试复现RodNet的训练结果 (#1688)
* 增加RodNet必须支持训练的单元测试;RodNet的torch链路改造成全张量计算,由此把之前忽略的参数dz、h_coeff、offset变得可学习

* 了解到损失函数CrossEntropyLoss内置了softmax,因此从forward方法中移出;offset是手动指定的偏置值,不是学习得到的,因此也移出到单独的PostProcess方法中

* 根据得到的源码整理RodNet;新增在数据集上达到一定准确率的单元测试
2025-06-14 20:03:14 +08:00
Takaranoao dca965e5f0 try to fix IndexOutOfRangeException (#1699) 2025-06-14 14:40:22 +08:00
辉鸭蛋 1d520dc781 Update kachina.config.json 2025-06-14 13:36:04 +08:00
秋云 56d12df1bc add: WaitForElementAppear and WaitForElementDisappear (#1698)
fix: ExitAndRelogin failed in some situation
2025-06-14 10:49:23 +08:00
辉鸭蛋 5bacc495c0 Update mirrorchyan_uploading.yml 2025-06-14 00:54:36 +08:00
辉鸭蛋 9b8aa9e12b Update publish.yml 2025-06-14 00:54:13 +08:00
辉鸭蛋 9664e67d6c Update mirrorchyan_uploading.yml 2025-06-14 00:52:21 +08:00
45 changed files with 2076 additions and 674 deletions

No files matched your search

+47 -21
View File
@@ -6,8 +6,8 @@ on:
types: [released]
jobs:
mirrorchyan_7z:
runs-on: macos-latest
mirrorchyan:
runs-on: windows-latest
steps:
- name: 📥 Download release
uses: robinraju/[email protected]
@@ -15,14 +15,48 @@ jobs:
latest: true
fileName: "*"
- name: Extract 7z
- name: 📥 Download kachina-builder release
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: Embed Dotnet and VCRedist
shell: bash
run: |
# dotnet
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
if [ -z "$VERSION" ]; then
echo "Cannot get the latest version from $VERSION_URL"
exit 1
fi
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
# vcredist
echo "Downloading VCRedist"
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
# embed
echo "Embedding runtimes"
./kachina-builder.exe append -o ./BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
./kachina-builder.exe extract -i ./BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
- name: Extract 7z and create zip
shell: bash
run: |
7z a -tzip BetterGI.Install.zip ./BetterGI.Install.*.exe -mx=1 -r -y
choco install wget --no-progress
7z x BetterGI_v*.7z -oun7z
mv ./BetterGI.Metadata.json ./un7z/BetterGI/.metadata.json
mv ./metadata.json ./un7z/BetterGI/.metadata.json
cd un7z
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
- name: Determine version number
id: get-version
shell: bash
run: |
if [ "${{ github.event_name }}" = "release" ]; then
echo "version=${{ github.event.release.tag_name }}" >> $GITHUB_OUTPUT
@@ -38,25 +72,17 @@ jobs:
with:
filetype: local
mirrorchyan_rid: BGI
working-directory: ./un7z/
pick_files: '["BetterGI"]'
filename: "BetterGI.zip"
version_name: ${{ steps.get-version.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
mirrorchyan_exe:
runs-on: macos-latest
steps:
- uses: MirrorChyan/uploading-action@v1
with:
filetype: latest-release
filename: "BetterGI.Install.*.exe"
extra_zip: true
mirrorchyan_rid: BGI
github_token: ${{ secrets.GITHUB_TOKEN }}
owner: babalae
repo: better-genshin-impact
upload_token: ${{ secrets.MirrorChyanUploadToken }}
os: win
arch: x64
- name: Upload Exe
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
filename: "BetterGI.Install.zip"
version_name: ${{ steps.get-version.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
+56 -19
View File
@@ -1,4 +1,5 @@
name: BetterGI Publish
run-name: "BetterGI ${{ inputs.version }}"
on:
workflow_dispatch:
@@ -299,8 +300,8 @@ jobs:
path: dist/BetterGI.Install.*.exe
- uses: actions/upload-artifact@v4
with:
name: BetterGI_Metadata
path: dist/metadata.json
name: BetterGI_OnlineInst
path: dist/BetterGI/BetterGI.update.exe
build_setup:
runs-on: windows-latest
@@ -349,11 +350,6 @@ jobs:
- uses: actions/download-artifact@v4
with:
path: artifacts
- name: Append Metadata
shell: bash
run: |
mv artifacts/BetterGI_Metadata/metadata.json artifacts/BetterGI_Metadata/BetterGI_Metadata.json
- name: Create Release
uses: softprops/action-gh-release@v1
@@ -366,45 +362,86 @@ jobs:
files: |
artifacts/BetterGI_7z/*.7z
artifacts/BetterGI_Install/*.exe
artifacts/BetterGI_Metadata/*.json
mirrorchyan_uploading:
if: github.repository_owner == 'babalae' && contains(needs.validate.outputs.version, '-')
needs: [validate, build_dist, build_installer]
runs-on: macos-latest
runs-on: windows-latest
steps:
- uses: actions/download-artifact@v4
with:
path: downloads
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: 📥 Download kachina-builder release
if: ${{ github.event.inputs.kachina-channel == 'release' }}
uses: robinraju/[email protected]
with:
repository: "YuehaiTeam/kachina-installer"
latest: true
fileName: "kachina-builder.exe"
- name: 📥 Download kachina-builder dev
if: ${{ github.event.inputs.kachina-channel == 'dev' }}
uses: dawidd6/action-download-artifact@v8
with:
github_token: ${{secrets.GITHUB_TOKEN}}
repo: "YuehaiTeam/kachina-installer"
workflow: "build.yml"
name: artifact
branch: main
event: push
workflow_conclusion: success
- name: Extract 7z
- name: Embed Dotnet and VCRedist
shell: bash
run: |
# dotnet
VERSION_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/8.0/latest.version"
VERSION=$(curl -fsSL "$VERSION_URL" | tr -d '\r\n')
if [ -z "$VERSION" ]; then
echo "Cannot get the latest version from $VERSION_URL"
exit 1
fi
INSTALLER_URL="https://builds.dotnet.microsoft.com/dotnet/WindowsDesktop/${VERSION}/windowsdesktop-runtime-${VERSION}-win-x64.exe"
OUTPUT="windowsdesktop-runtime-${VERSION}-win-x64.exe"
echo "Downloading Windows Desktop Runtime version $VERSION from $INSTALLER_URL"
curl -fSL -o "$OUTPUT" "$INSTALLER_URL"
# vcredist
echo "Downloading VCRedist"
curl -fSL -o "vc_redist.x64.exe" "https://aka.ms/vs/17/release/vc_redist.x64.exe"
# embed
echo "Embedding runtimes"
./kachina-builder.exe append -o ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f "$OUTPUT" -n "Microsoft.DotNet.DesktopRuntime.8" -f "vc_redist.x64.exe" -n "Microsoft.VCRedist.2015+.x64"
./kachina-builder.exe extract -i ./downloads/BetterGI_Install/BetterGI.Install.*.exe -f ./metadata.json -n "\0META"
- name: Extract 7z and create zip
shell: bash
run: |
choco install wget --no-progress
7z a -tzip BetterGI.Install.${{ needs.validate.outputs.version }}.zip ./downloads/BetterGI_Install/BetterGI.Install.${{ needs.validate.outputs.version }}.exe -mx=1 -r -y
cd downloads/BetterGI_7z
7z x BetterGI_v*.7z -oun7z
mv ../BetterGI_Metadata/metadata.json ./un7z/BetterGI/.metadata.json
mv ../../metadata.json ./un7z/BetterGI/.metadata.json
cd un7z
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
- name: Upload Zip
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
working-directory: downloads/BetterGI_7z/un7z/
pick_files: '["BetterGI"]'
filename: "downloads/BetterGI_7z/BetterGI.zip"
version_name: ${{ needs.validate.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
os: win
arch: x64
- name: Upload Install.exe
uses: MirrorChyan/uploading-action@v1
with:
filetype: local
mirrorchyan_rid: BGI
working-directory: downloads/BetterGI_Install/
filename: "BetterGI.Install.*.exe"
extra_zip: true
filename: "BetterGI.Install.${{ needs.validate.outputs.version }}.zip"
version_name: ${{ needs.validate.outputs.version }}
upload_token: ${{ secrets.MirrorChyanUploadToken }}
os: win
arch: x64
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.45.3-alpha.1</Version>
<Version>0.46.2</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -16,32 +16,32 @@ public class TextInferenceFactory
_ => throw new ArgumentOutOfRangeException(nameof(type), type, null),
};
}
public static Mat PreProcessForInference(Mat mat)
{
if (mat.Channels() == 3)
{
mat = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
}
else if (mat.Channels() == 4)
{
mat = mat.CvtColor(ColorConversionCodes.BGRA2GRAY);
}
else if (mat.Channels() != 1)
{
throw new ArgumentException("mat must be 1, 3 or 4 channels");
}
// Yap 已经改用灰度图了 https://github.com/Alex-Beng/Yap/commit/c2ad1e7b1442aaf2d80782a032e00876cd1c6c84
// 二值化
// Cv2.Threshold(mat, mat, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
//Cv2.AdaptiveThreshold(mat, mat, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 31, 3); // 效果不错 但是和模型不搭
//mat = OpenCvCommonHelper.Threshold(mat, Scalar.FromRgb(235, 235, 235), Scalar.FromRgb(255, 255, 255)); // 识别物品不太行
// 不知道为什么要强制拉伸到 221x32
mat = ResizeHelper.ResizeTo(mat, 221, 32);
// 填充到 384x32
var padded = new Mat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
padded[new Rect(0, 0, mat.Width, mat.Height)] = mat;
//Cv2.ImWrite(Global.Absolute("padded.png"), padded);
return padded;
}
// public static Mat PreProcessForInference(Mat mat)
// {
// if (mat.Channels() == 3)
// {
// mat = mat.CvtColor(ColorConversionCodes.BGR2GRAY);
// }
// else if (mat.Channels() == 4)
// {
// mat = mat.CvtColor(ColorConversionCodes.BGRA2GRAY);
// }
// else if (mat.Channels() != 1)
// {
// throw new ArgumentException("mat must be 1, 3 or 4 channels");
// }
//
// // Yap 已经改用灰度图了 https://github.com/Alex-Beng/Yap/commit/c2ad1e7b1442aaf2d80782a032e00876cd1c6c84
// // 二值化
// // Cv2.Threshold(mat, mat, 0, 255, ThresholdTypes.Otsu | ThresholdTypes.Binary);
// //Cv2.AdaptiveThreshold(mat, mat, 255, AdaptiveThresholdTypes.GaussianC, ThresholdTypes.Binary, 31, 3); // 效果不错 但是和模型不搭
// //mat = OpenCvCommonHelper.Threshold(mat, Scalar.FromRgb(235, 235, 235), Scalar.FromRgb(255, 255, 255)); // 识别物品不太行
// // 不知道为什么要强制拉伸到 221x32
// mat = ResizeHelper.ResizeTo(mat, 221, 32);
// // 填充到 384x32
// var padded = new Mat(new Size(384, 32), MatType.CV_8UC1, Scalar.Black);
// padded[new Rect(0, 0, mat.Width, mat.Height)] = mat;
// //Cv2.ImWrite(Global.Absolute("padded.png"), padded);
// return padded;
// }
}
@@ -47,6 +47,8 @@ public class ScriptRepoUpdater : Singleton<ScriptRepoUpdater>
public static readonly string CenterRepoUnzipName = "bettergi-scripts-list-git";
public static readonly string CenterRepoPath = Path.Combine(ReposPath, CenterRepoUnzipName);
public static readonly string CenterRepoPathOld = Path.Combine(ReposPath, "bettergi-scripts-list-main");
public static readonly Dictionary<string, string> PathMapper = new Dictionary<string, string>
{
@@ -24,6 +24,7 @@ using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Job;
using GameTask.Model.GameUI;
namespace BetterGenshinImpact.GameTask.AutoArtifactSalvage;
@@ -210,118 +211,42 @@ public class AutoArtifactSalvageTask : ISoloTask
private async Task Salvage5Star(string regularExpression, int maxNumToCheck)
{
int count = maxNumToCheck;
Queue<string> checkedArtifactAffixesQueue = new Queue<string>();
int duplicateSum = 0;
while (count > 0 && duplicateSum < 3)
using var ra0 = CaptureToRectArea();
Rect gridRoi = new Rect((int)(ra0.Width * 0.025), (int)(ra0.Width * 0.055), (int)(ra0.Width * 0.66), (int)(ra0.Width * 0.4));
GridScreen gridScreen = new GridScreen(gridRoi, 3, 40, 28, 0.018, this.logger, this.ct); // 圣遗物分解Grid有4行9列
await foreach (ImageRegion itemRegion in gridScreen)
{
// VisionContext.Instance().DrawContent.ClearAll();
// await Delay(400, this.ct);
using var ra = CaptureToRectArea();
using ImageRegion grid = ra.DeriveCrop(new Rect((int)(ra.Width * 0.025), (int)(ra.Width * 0.055), (int)(ra.Width * 0.66), (int)(ra.Width * 0.4)));
IEnumerable<Rect> gridItems = GetArtifactGridItems(grid.SrcMat);
//foreach (Rect item in gridItems)
//{
// grid.DrawRect(item, item.GetHashCode().ToString(), new System.Drawing.Pen(System.Drawing.Color.Blue));
//}
bool anyItemChecked = false;
foreach (Rect item in gridItems)
Rect gridRect = itemRegion.ToRect();
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
{
using ImageRegion itemRegion = grid.DeriveCrop(item);
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
itemRegion.Click();
await Delay(300, ct);
using var ra1 = CaptureToRectArea();
using ImageRegion itemRegion1 = ra1.DeriveCrop(gridRect + new Point(gridRoi.X, gridRoi.Y));
if (GetArtifactStatus(itemRegion1.SrcMat) == ArtifactStatus.Selected)
{
anyItemChecked = true;
itemRegion.Click();
await Delay(300, ct);
using ImageRegion card = ra1.DeriveCrop(new Rect((int)(ra1.Width * 0.70), (int)(ra1.Width * 0.055), (int)(ra1.Width * 0.24), (int)(ra1.Width * 0.29)));
string affixes = GetArtifactAffixes(card.SrcMat, OcrFactory.Paddle);
using var ra1 = CaptureToRectArea();
using ImageRegion grid1 = ra1.DeriveCrop(new Rect((int)(ra1.Width * 0.025), (int)(ra1.Width * 0.055), (int)(ra1.Width * 0.66), (int)(ra1.Width * 0.4)));
using ImageRegion itemRegion1 = grid1.DeriveCrop(item);
if (GetArtifactStatus(itemRegion1.SrcMat) == ArtifactStatus.Selected)
if (IsMatchRegularExpression(affixes, regularExpression, out string msg))
{
using ImageRegion card = ra1.DeriveCrop(new Rect((int)(ra1.Width * 0.70), (int)(ra1.Width * 0.055), (int)(ra1.Width * 0.24), (int)(ra1.Width * 0.29)));
string affixes = GetArtifactAffixes(card.SrcMat, OcrFactory.Paddle);
if (checkedArtifactAffixesQueue.Any(c => c == affixes))
{
duplicateSum++;
logger.LogInformation($"重复检查了该圣遗物");
}
if (checkedArtifactAffixesQueue.Count >= 36) // 一个grid最多能看到36个完整的圣遗物
{
checkedArtifactAffixesQueue.Dequeue();
}
checkedArtifactAffixesQueue.Enqueue(affixes);
if (IsMatchRegularExpression(affixes, regularExpression, out string msg))
{
logger.LogInformation(message: msg);
}
else
{
itemRegion.Click();
await Delay(100, ct);
}
if (duplicateSum >= 3)
{
break;
}
}
count--;
if (count <= 0)
{
break;
}
}
}
if (count <= 0 || duplicateSum >= 3)
{
break;
}
if (anyItemChecked)
{
for (int i = 0; i < 32; i++) // 先滚动大约三行半
{
input.Mouse.VerticalScroll(-2);
await Delay(40, ct);
}
DateTimeOffset rollingEndTime = DateTime.Now.AddSeconds(2);
while (DateTime.Now < rollingEndTime)
{
await Delay(60, ct);
using var ra2 = CaptureToRectArea();
using ImageRegion grid2 = ra2.DeriveCrop(new Rect((int)(ra2.Width * 0.025), (int)(ra2.Width * 0.055), (int)(ra2.Width * 0.66), (int)(ra2.Width * 0.4)));
IEnumerable<Rect> gridItems2 = GetArtifactGridItems(grid2.SrcMat);
if (gridItems2.Min(i => i.Y) > (ra2.Width * 0.018)) // 精细滚动,保证完整地显示四行
{
input.Mouse.VerticalScroll(-1);
logger.LogInformation(message: msg);
}
else
{
break;
itemRegion.Click();
await Delay(100, ct);
}
}
grid.MoveTo(grid.Width, grid.Height);
await Delay(500, ct);
count--;
if (count <= 0)
{
logger.LogInformation("检查次数已耗尽");
break;
}
}
else
{
await Delay(400, ct);
logger.LogInformation("找不到可检查的圣遗物了");
break;
}
}
if (count <= 0)
{
logger.LogInformation("检查次数已耗尽");
}
if (duplicateSum >= 3)
{
logger.LogInformation("重复检查次数过多,推断为找不到可检查的了");
}
}
@@ -352,33 +277,6 @@ public class AutoArtifactSalvageTask : ISoloTask
return ocrResult.Text;
}
public static IEnumerable<Rect> GetArtifactGridItems(Mat src)
{
using Mat grey = src.CvtColor(ColorConversionCodes.BGR2GRAY);
using Mat canny = grey.Canny(20, 40);
Cv2.FindContours(canny, out var contours, out _, RetrievalModes.External,
ContourApproximationModes.ApproxSimple, null);
IEnumerable<Rect> boxes = contours.Where(c => Cv2.MinAreaRect(c).Angle % 90 <= 1) // 剔除倾斜
.Select(Cv2.BoundingRect).Where(r =>
{
if (r.Height == 0)
{
return false;
}
return Math.Abs((float)r.Width / r.Height - 0.8) < 0.05; // 按形状筛选
}).ToList();
//src.DrawContours(contours, -1, Scalar.Red);
int biggestRectHeight = boxes.Max(b => b.Height);
boxes = boxes.Where(b => (float)b.Height / biggestRectHeight > 0.88); // 剔除太小的
return boxes.ToArray();
}
public static ArtifactStatus GetArtifactStatus(Mat src)
{
using Mat upperLine = new Mat(src, new Rect(0, 0, src.Width, (int)(src.Height * 0.19)));
@@ -1,5 +1,6 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoDomain;
@@ -51,4 +52,32 @@ public partial class AutoDomainConfig : ObservableObject
// 周日奖励序号
[ObservableProperty]
private string _sundaySelectedValue = string.Empty;
// 指定树脂的使用次数
[ObservableProperty]
private bool _specifyResinUse = false;
// 自定义使用树脂优先级
[ObservableProperty]
private List<string> _resinPriorityList =
[
"浓缩树脂",
"原粹树脂"
];
// 使用原粹树脂刷取副本次数
[ObservableProperty]
private int _originalResinUseCount = 0;
//使用浓缩树脂刷取副本次数
[ObservableProperty]
private int _condensedResinUseCount = 0;
// 使用须臾树脂刷取副本次数
[ObservableProperty]
private int _transientResinUseCount = 0;
// 使用脆弱树脂刷取副本次数
[ObservableProperty]
private int _fragileResinUseCount = 0;
}
@@ -1,4 +1,5 @@
using BetterGenshinImpact.GameTask.Model;
using System.Collections.Generic;
using BetterGenshinImpact.GameTask.Model;
using System.Threading;
namespace BetterGenshinImpact.GameTask.AutoDomain;
@@ -25,6 +26,27 @@ public class AutoDomainParam : BaseTaskParam
// 1~4
public string MaxArtifactStar { get; set; } = "4";
public bool SpecifyResinUse { get; set; } = false;
// 使用树脂优先级
public List<string> ResinPriorityList { get; set; } =
[
"浓缩树脂",
"原粹树脂"
];
// 使用原粹树脂刷取副本次数
public int OriginalResinUseCount { get; set; } = 0;
// 使用浓缩树脂刷取副本次数
public int CondensedResinUseCount { get; set; } = 0;
// 使用须臾树脂刷取副本次数
public int TransientResinUseCount { get; set; } = 0;
// 使用脆弱树脂刷取副本次数
public int FragileResinUseCount { get; set; } = 0;
public AutoDomainParam(int domainRoundNum, string path)
{
DomainRoundNum = domainRoundNum;
@@ -45,5 +67,11 @@ public class AutoDomainParam : BaseTaskParam
SundaySelectedValue = config.SundaySelectedValue;
AutoArtifactSalvage = config.AutoArtifactSalvage;
MaxArtifactStar = TaskContext.Instance().Config.AutoArtifactSalvageConfig.MaxArtifactStar;
ResinPriorityList = config.ResinPriorityList;
OriginalResinUseCount = config.OriginalResinUseCount;
CondensedResinUseCount = config.CondensedResinUseCount;
TransientResinUseCount = config.TransientResinUseCount;
FragileResinUseCount = config.FragileResinUseCount;
SpecifyResinUse = config.SpecifyResinUse;
}
}
@@ -39,6 +39,8 @@ using System.Text.RegularExpressions;
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using System.Collections.ObjectModel;
using BetterGenshinImpact.Core.Script.Dependence;
using BetterGenshinImpact.GameTask.AutoDomain.Model;
using BetterGenshinImpact.GameTask.Common;
using Compunet.YoloSharp;
using Microsoft.Extensions.DependencyInjection;
@@ -69,6 +71,8 @@ public class AutoDomainTask : ISoloTask
private readonly string matchingChallengeString;
private readonly string rapidformationString;
private List<ResinUseRecord> _resinPriorityListWhenSpecifyUse;
public AutoDomainTask(AutoDomainParam taskParam)
{
AutoFightAssets.DestroyInstance();
@@ -79,6 +83,8 @@ public class AutoDomainTask : ISoloTask
_combatScriptBag = CombatScriptParser.ReadAndParse(_taskParam.CombatStrategyPath);
_resinPriorityListWhenSpecifyUse = ResinUseRecord.BuildFromDomainParam(taskParam);
IStringLocalizer<AutoDomainTask> stringLocalizer =
App.GetService<IStringLocalizer<AutoDomainTask>>() ?? throw new NullReferenceException();
CultureInfo cultureInfo = new CultureInfo(TaskContext.Instance().Config.OtherConfig.GameCultureInfoName);
@@ -182,17 +188,9 @@ public class AutoDomainTask : ISoloTask
// 5. 快速领取奖励并判断是否有下一轮
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
if (!await GettingTreasure())
{
if (i == _taskParam.DomainRoundNum - 1)
{
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
}
else
{
Logger.LogInformation("体力已经耗尽,结束自动秘境");
}
Logger.LogInformation("体力耗尽或者设置轮次已达标,结束自动秘境");
break;
}
@@ -400,84 +398,58 @@ public class AutoDomainTask : ISoloTask
Logger.LogInformation("周日未设置秘境奖励序号,不进行奖励选择");
}
}
else
{
Logger.LogWarning("周日设置秘境奖励序号错误,请检查配置页面");
}
}
else
{
Logger.LogWarning("周日奖励选择:圣遗物副本无需选择奖励");
Logger.LogDebug("周日奖励选择:圣遗物副本无需选择奖励");
}
await Delay(300, _ct);
//await Delay(100000, _ct);//调试延时=========
}
// 点击单人挑战,增加容错,点击失败则继续尝试
// 点击单人挑战
int retryTimes = 0;
while (retryTimes < 40)
while (retryTimes < 20)
{
retryTimes++;
using var confirmRectArea = CaptureToRectArea().Find(fightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
await Delay(500, _ct);
confirmRectArea.Click();
await Delay(500, _ct);
var ra = CaptureToRectArea();
var matchingChallengeArea = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.64, ra.Height * 0.91,
ra.Width * 0.13, ra.Height * 0.06));
var done = matchingChallengeArea.LastOrDefault(t =>
Regex.IsMatch(t.Text, this.matchingChallengeString));
if (done != null)
{
continue;
}
else
{
break;
}
}
await Delay(500, _ct);
}
//如果卡顿,可能会错过"是否仍要挑战该秘境"判断弹框,改为判断"快速编队"后进行点击进入
retryTimes = 0;
while (retryTimes < 30)
{
await Delay(600, _ct);
var ra = CaptureToRectArea();
var rapidformationStringArea = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.64, ra.Height * 0.91,
ra.Width * 0.13, ra.Height * 0.06));
var done = rapidformationStringArea.LastOrDefault(t =>
Regex.IsMatch(t.Text, this.rapidformationString));
if (done != null)
{
using var confirmRectArea = CaptureToRectArea().Find(fightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
confirmRectArea.Click();
await Delay(500, _ct);
}
}
else
{
break;
}
using var confirmRectArea2 = ra.Find(RecognitionObject.Ocr(ra.Width * 0.263, ra.Height * 0.32,
ra.Width - ra.Width * 0.263 * 2, ra.Height - ra.Height * 0.32 - ra.Height * 0.353));
if (confirmRectArea2.IsExist() && confirmRectArea2.Text.Contains("是否仍要挑战该秘境"))
await Delay(1500, _ct);
}
// 判断弹框
await Delay(600, _ct);
var ra = CaptureToRectArea();
using var confirmRectArea2 = ra.Find(RecognitionObject.Ocr(ra.Width * 0.263, ra.Height * 0.32,
ra.Width - ra.Width * 0.263 * 2, ra.Height - ra.Height * 0.32 - ra.Height * 0.353));
if (confirmRectArea2.IsExist() && confirmRectArea2.Text.Contains("是否仍要挑战该秘境"))
{
Logger.LogWarning("自动秘境:检测到树脂不足提示:{Text}", confirmRectArea2.Text);
throw new Exception("当前树脂不足,自动秘境停止运行。");
}
// 点击进入
retryTimes = 0;
while (retryTimes < 20)
{
retryTimes++;
using var confirmRectArea = CaptureToRectArea().Find(fightAssets.ConfirmRa);
if (!confirmRectArea.IsEmpty())
{
Logger.LogWarning("自动秘境:检测到树脂不足提示:{Text}", confirmRectArea2.Text);
throw new Exception("当前树脂不足,自动秘境停止运行。");
confirmRectArea.Click();
break;
}
retryTimes++;
await Delay(1200, _ct);
}
// 载入动画
await Delay(3000, _ct);
}
@@ -615,6 +587,7 @@ public class AutoDomainTask : ISoloTask
finally
{
Logger.LogInformation("自动战斗线程结束");
Simulation.ReleaseAllKey();
}
}, cts.Token);
@@ -997,7 +970,7 @@ public class AutoDomainTask : ISoloTask
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
}
Sleep(100);
Sleep(100, _ct);
}
Logger.LogInformation("锁定东方向视角线程结束");
@@ -1008,64 +981,131 @@ public class AutoDomainTask : ISoloTask
/// <summary>
/// 领取奖励
/// </summary>
/// <param name="recognizeResin">是否识别树脂</param>
/// <param name="isLastTurn">是否最后一轮</param>
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
private async Task<bool> GettingTreasure()
{
bool isLastTurn = false;
// 等待窗口弹出
Sleep(1500, _ct);
await Delay(300, _ct);
// 优先使用浓缩树脂
var retryTimes = 0;
while (true)
// 1. OCR 直到确认弹出框弹出
bool chooseResinPrompt = await NewRetry.WaitForAction(() =>
{
retryTimes++;
if (retryTimes > 3)
using var ra = CaptureToRectArea();
var regionList = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.25, ra.Height * 0.2, ra.Width * 0.5, ra.Height * 0.6));
var res = regionList.FirstOrDefault(t => t.Text.Contains("石化古树"));
if (res != null)
{
Logger.LogInformation("没有浓缩树脂了");
break;
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了,界面上点一下
res.Click();
return true;
}
var useCondensedResinRa = CaptureToRectArea().Find(AutoFightAssets.Instance.UseCondensedResinRa);
if (!useCondensedResinRa.IsEmpty())
{
useCondensedResinRa.Click();
// 点两下 #224 #218
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
Sleep(400, _ct);
useCondensedResinRa.Click();
break;
}
return false;
}, _ct, 10, 500);
Debug.WriteLine("识别到选择树脂页");
await Delay(800, _ct);
Sleep(800, _ct);
// 再 OCR 一次,弹出框,确认当前是否有原粹树脂
using var ra2 = CaptureToRectArea();
var textListInPrompt = ra2.FindMulti(RecognitionObject.Ocr(ra2.Width * 0.25, ra2.Height * 0.2, ra2.Width * 0.5, ra2.Height * 0.6));
if (textListInPrompt.Any(t => t.Text.Contains("数量不足") || t.Text.Contains("补充原粹树脂")))
{
// 没有原粹树脂,直接退出秘境
Logger.LogInformation("自动秘境:原粹树脂已用尽,退出秘境");
await ExitDomain();
return false;
}
if (chooseResinPrompt)
{
using var ra3 = CaptureToRectArea();
if (!_taskParam.SpecifyResinUse)
{
// 自动刷干树脂
// 识别树脂状况
var resinStatus = ResinStatus.RecogniseFromRegion(ra3);
resinStatus.Print(Logger);
if (resinStatus is { CondensedResinCount: <= 0, OriginalResinCount: < 20 })
{
Logger.LogWarning("树脂不足");
await ExitDomain();
return false;
}
bool resinUsed = false;
if (resinStatus.CondensedResinCount > 0)
{
resinUsed = PressUseResin(ra3, "浓缩树脂");
resinStatus.CondensedResinCount -= 1;
}
else if (resinStatus.OriginalResinCount >= 20)
{
resinUsed = PressUseResin(ra3, "原粹树脂");
resinStatus.OriginalResinCount -= 20;
}
if (!resinUsed)
{
Logger.LogWarning("自动秘境:未找到可用的树脂,可能是{Msg1} 或者 {Msg2}。", "树脂不足", "OCR 识别失败");
await ExitDomain();
return false;
}
if (resinStatus is { CondensedResinCount: <= 0, OriginalResinCount: < 20 })
{
// 没树脂了就是最后一回合了
isLastTurn = true;
}
}
else
{
// 指定使用树脂
var textListInPrompt2 = ra3.FindMulti(RecognitionObject.Ocr(ra3.Width * 0.25, ra3.Height * 0.2, ra3.Width * 0.5, ra3.Height * 0.6));
// 按优先级使用
var failCount = 0;
foreach (var record in _resinPriorityListWhenSpecifyUse)
{
if (record.RemainCount > 0 && PressUseResin(textListInPrompt2, record.Name))
{
record.RemainCount -= 1;
Logger.LogInformation("自动秘境:{Name} 刷取 {Re}/{Max}", record.Name, record.MaxCount - record.RemainCount, record.MaxCount);
break;
}
else
{
failCount++;
}
}
if (_resinPriorityListWhenSpecifyUse.Sum(o => o.RemainCount) <= 0)
{
// 全部刷完
isLastTurn = true;
}
if (failCount == _resinPriorityListWhenSpecifyUse.Count)
{
// 没有找到对应的树脂
Logger.LogWarning("自动秘境:指定树脂领取次数时,当前可用树脂选项无法满足配置。你可能设置的刷取次数过多!退出秘境。");
Logger.LogInformation("当前刷取情况:{ResinList}", string.Join(", ", _resinPriorityListWhenSpecifyUse.Select(o => $"{o.Name}({o.MaxCount - o.RemainCount}/{o.MaxCount})")));
await ExitDomain();
return false;
}
}
}
else
{
// 如果没有选择树脂的提示,说明只有原粹树脂
// 继续向下执行
}
Sleep(1000, _ct);
var hasSkip = false;
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
for (var i = 0; i < 30; i++)
{
// 跳过领取动画
if (!hasSkip)
{
TaskContext.Instance().PostMessageSimulator.LeftButtonClick(); // 先随便点一个地方使得跳过出现
}
using var ra = CaptureToRectArea();
// OCR识别是否有跳过
var ocrList = ra.FindMulti(RecognitionObject.Ocr(captureArea.Width - 230 * assetScale, 0,
230 * assetScale - 5, 80 * assetScale));
var skipTextRa = ocrList.FirstOrDefault(t => Regex.IsMatch(t.Text, this.skipLocalizedString));
if (skipTextRa != null)
{
hasSkip = true;
skipTextRa.Click(); // 有则点击
}
// 优先点击继续
using var confirmRectArea = ra.Find(AutoFightAssets.Instance.ConfirmRa);
if (!confirmRectArea.IsEmpty())
@@ -1080,28 +1120,33 @@ public class AutoDomainTask : ISoloTask
return false;
}
}
if (!recognizeResin)
{
confirmRectArea.Click();
return true;
}
var (condensedResinCount, fragileResinCount) = GetRemainResinStatus();
if (condensedResinCount == 0 && fragileResinCount < 20)
{
// 没有体力了退出
var exitRectArea = ra.Find(AutoFightAssets.Instance.ExitRa);
if (!exitRectArea.IsEmpty())
{
exitRectArea.Click();
return false;
}
}
else
{
if (!chooseResinPrompt)
{
// TODO 前面没有弹框的情况下,意味着只有原粹树脂,要再识别一次右上角确认树脂余量,没有余量直接退出
}
// 有体力继续
confirmRectArea.Click();
await Delay(60, _ct); // 双击
confirmRectArea.Click();
if (!chooseResinPrompt)
{
// 真没树脂了还有提示兜底
await Delay(900, _ct);
var textListInNoResinPrompt = CaptureToRectArea().FindMulti(RecognitionObject.Ocr(ra2.Width * 0.25, ra2.Height * 0.2, ra2.Width * 0.5, ra2.Height * 0.6));
if (textListInNoResinPrompt.Any(t => t.Text.Contains("是否仍要") && t.Text.Contains("挑战") && t.Text.Contains("秘境")))
{
var cancelBtn = textListInNoResinPrompt.FirstOrDefault(t => t.Text.Contains("取消"));
if (cancelBtn != null)
{
cancelBtn.Click();
return false;
}
}
}
return true;
}
}
@@ -1112,41 +1157,69 @@ public class AutoDomainTask : ISoloTask
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
}
/// <summary>
/// 获取剩余树脂状态
/// </summary>
private (int, int) GetRemainResinStatus()
private async Task ExitDomain()
{
var condensedResinCount = 0;
var fragileResinCount = 0;
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
await Delay(500, _ct);
Simulation.SendInput.Keyboard.KeyPress(VK.VK_ESCAPE);
await Delay(800, _ct);
Bv.ClickBlackConfirmButton(CaptureToRectArea());
}
var ra = CaptureToRectArea();
// 浓缩树脂
var condensedResinCountRa = ra.Find(AutoFightAssets.Instance.CondensedResinCountRa);
if (!condensedResinCountRa.IsEmpty())
private bool PressUseResin(ImageRegion ra, string resinName)
{
var regionList = ra.FindMulti(RecognitionObject.Ocr(ra.Width * 0.25, ra.Height * 0.2, ra.Width * 0.5, ra.Height * 0.6));
return PressUseResin(regionList, resinName);
}
private bool PressUseResin(List<Region> regionList, string resinName)
{
var resinKey = regionList.FirstOrDefault(t => t.Text.Contains(resinName));
if (resinKey != null)
{
// 图像右侧就是浓缩树脂数量
var countArea = ra.DeriveCrop(condensedResinCountRa.X + condensedResinCountRa.Width,
condensedResinCountRa.Y, condensedResinCountRa.Width, condensedResinCountRa.Height);
// Cv2.ImWrite($"log/resin_{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffff")}.png", countArea.SrcGreyMat);
var count = OcrFactory.Paddle.OcrWithoutDetector(countArea.CacheGreyMat);
condensedResinCount = StringUtils.TryParseInt(count);
// 找到树脂名称对应的按键,关键词为使用,是同一行的(高度相交)
var useList = regionList.Where(t => t.Text.Contains("使用")).ToList();
if (useList.Count != 0)
{
// 找到使用按键
var useKey = useList.FirstOrDefault(t => t.X > TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect.Width / 2
&& IsHeightOverlap(t, resinKey));
if (useKey != null)
{
// 点击使用
useKey.Click();
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了。使用双击
Sleep(60, _ct);
useKey.Click();
Logger.LogInformation("自动秘境:使用 {ResinName}", resinName);
return true;
}
else
{
Logger.LogWarning("自动秘境:未找到 {ResinName} 的使用按键", resinName);
}
}
else
{
Logger.LogWarning("自动秘境:未找到 {ResinName} 的使用按键", resinName);
}
}
// 脆弱树脂
var fragileResinCountRa = ra.Find(AutoFightAssets.Instance.FragileResinCountRa);
if (!fragileResinCountRa.IsEmpty())
{
// 图像右侧就是脆弱树脂数量
var countArea = ra.DeriveCrop(fragileResinCountRa.X + fragileResinCountRa.Width, fragileResinCountRa.Y,
(int)(fragileResinCountRa.Width * 3), fragileResinCountRa.Height);
var count = OcrFactory.Paddle.Ocr(countArea.SrcMat);
fragileResinCount = StringUtils.TryParseInt(count);
}
return false;
}
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 原粹树脂 {FragileResinCount}", condensedResinCount,
fragileResinCount);
return (condensedResinCount, fragileResinCount);
/// <summary>
/// 判断两个区域在垂直方向上是否有重叠
/// </summary>
private bool IsHeightOverlap(Region region1, Region region2)
{
int region1Top = region1.Y;
int region1Bottom = region1.Y + region1.Height;
int region2Top = region2.Y;
int region2Bottom = region2.Y + region2.Height;
// 检查区域是否在垂直方向上重叠
return (region1Top <= region2Bottom && region1Bottom >= region2Top);
}
private async Task ArtifactSalvage()
@@ -0,0 +1,73 @@
using System;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.Helpers;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.AutoDomain.Model;
public class ResinStatus
{
/// <summary>
/// 原粹树脂(1自回体)
/// </summary>
public int OriginalResinCount { get; set; } = 0;
/// <summary>
/// 脆弱树脂(60)
/// </summary>
public int FragileResinCount { get; set; } = 0;
/// <summary>
/// 浓缩树脂(40)
/// </summary>
public int CondensedResinCount { get; set; } = 0;
/// <summary>
/// 须臾树脂(60壶内购买)
/// </summary>
public int TransientResinCount { get; set; } = 0;
public static ResinStatus RecogniseFromRegion(ImageRegion region)
{
var status = new ResinStatus();
// 1. 原粹树脂 起点 w-(256+100) ~ w-256
var captureArea = TaskContext.Instance().SystemInfo.ScaleMax1080PCaptureRect;
var assetScale = TaskContext.Instance().SystemInfo.AssetScale;
var originalResinTopIconRa = AutoFightAssets.Instance.OriginalResinTopIconRa;
var originalResinRes = region.Find(originalResinTopIconRa);
if (originalResinRes.IsEmpty())
{
throw new Exception("未找到原粹树脂图标");
}
// 找出 icon 的位置 + 30 ~ w-267 就是原粹树脂的数字
var originalResinCountRect = new Rect(originalResinRes.Right + 30, (int)(37 * assetScale),
captureArea.Width - (originalResinRes.Right + 30) - (int)(267 * assetScale), (int)(21 * assetScale));
string cnt1 = OcrFactory.Paddle.OcrWithoutDetector(region.DeriveCrop(originalResinCountRect).SrcMat);
status.OriginalResinCount = StringUtils.TryExtractPositiveInt(cnt1, 0);
// 2. 浓缩树脂
var condensedResinRes = region.Find(AutoFightAssets.Instance.CondensedResinTopIconRa);
if (condensedResinRes.IsExist())
{
// 找出 icon 的位置 + 25 ~ icon 的位置+45 就是浓缩树脂的数字,数字宽20
var condensedResinCountRect = new Rect(condensedResinRes.Right + (int)(25 * assetScale), condensedResinRes.Y, (int)(20 * assetScale), condensedResinRes.Height);
string cnt40 = OcrFactory.Paddle.OcrWithoutDetector(region.DeriveCrop(condensedResinCountRect).SrcMat);
status.CondensedResinCount = StringUtils.TryExtractPositiveInt(cnt40, 0);
}
return status;
}
public void Print(ILogger logger)
{
// logger.LogInformation("原粹树脂:{Cnt1},浓缩树脂:{Cnt2},须臾树脂:{Cnt3},脆弱树脂:{Cnt4}",
// OriginalResinCount, CondensedResinCount, FragileResinCount, TransientResinCount);
logger.LogInformation("原粹树脂:{Cnt1},浓缩树脂:{Cnt2}",
OriginalResinCount, CondensedResinCount);
}
}
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoDomain.Model;
/// <summary>
/// 树脂使用记录
/// 用于自动秘境指定树脂刷取次数时候,计算剩余刷取次数
/// </summary>
public class ResinUseRecord
{
public string Name { get; set; }
public int RemainCount { get; set; }
public int MaxCount { get; set; }
public ResinUseRecord(string name, int maxCount)
{
Name = name;
RemainCount = maxCount;
MaxCount = maxCount;
}
public static List<ResinUseRecord> BuildFromDomainParam(AutoDomainParam taskParam)
{
List<ResinUseRecord> list = [];
if (taskParam.SpecifyResinUse)
{
if (taskParam.CondensedResinUseCount > 0)
{
list.Add(new ResinUseRecord("浓缩树脂", taskParam.CondensedResinUseCount));
}
if (taskParam.OriginalResinUseCount > 0)
{
list.Add(new ResinUseRecord("原粹树脂", taskParam.OriginalResinUseCount));
}
if (taskParam.TransientResinUseCount > 0)
{
list.Add(new ResinUseRecord("须臾树脂", taskParam.TransientResinUseCount));
}
if (taskParam.FragileResinUseCount > 0)
{
list.Add(new ResinUseRecord("脆弱树脂", taskParam.FragileResinUseCount));
}
if (list.Count == 0)
{
throw new Exception("你选择了指定树脂刷取次数,请至少配置一种树脂的刷取次数!");
}
}
return list;
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 456 B

@@ -26,8 +26,11 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
// 树脂状态
public RecognitionObject CondensedResinCountRa;
public RecognitionObject FragileResinCountRa;
// 自动秘境
// public RecognitionObject LockIconRa; // 锁定辅助图标
public RecognitionObject CondensedResinTopIconRa;
public RecognitionObject OriginalResinTopIconRa;
public Dictionary<string, string> AvatarCostumeMap;
@@ -245,5 +248,31 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 3 * 2, CaptureRect.Width / 2, CaptureRect.Height / 3),
DrawOnWindow = false
}.InitTemplate();
// 自动秘境
// LockIconRa = new RecognitionObject
// {
// Name = "LockIcon",
// RecognitionType = RecognitionTypes.TemplateMatch,
// TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "lock_icon.png"),
// RegionOfInterest = new Rect(CaptureRect.Width - (int)(215 * AssetScale), 0, (int)(215 * AssetScale), (int)(80 * AssetScale)),
// DrawOnWindow = false
// }.InitTemplate();
CondensedResinTopIconRa = new RecognitionObject
{
Name = "CondensedResinTopIcon",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "condensed_resin_top_icon.png"),
RegionOfInterest = new Rect((int)(1270 * AssetScale), (int)(25 * AssetScale), (int)(520 * AssetScale), (int)(45 * AssetScale)),
DrawOnWindow = false
}.InitTemplate();
OriginalResinTopIconRa = new RecognitionObject
{
Name = "OriginalResinTopIcon",
RecognitionType = RecognitionTypes.TemplateMatch,
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "original_resin_top_icon.png"),
RegionOfInterest = new Rect(CaptureRect.Width - (int)(450 * AssetScale), (int)(25 * AssetScale), (int)(265 * AssetScale), (int)(45 * AssetScale)),
DrawOnWindow = false
}.InitTemplate();
}
}
@@ -1868,5 +1868,35 @@
"nameEn": "Ifa",
"skillCD": 7.5,
"weapon": "10"
},
{
"alias": [
"丝柯克",
"Skirk",
"丝柯可",
"斯柯克"
],
"burstCD": 15,
"id": "10000114",
"name": "丝柯克",
"nameEn": "SkirkNew",
"skillCD": 8,
"weapon": "1"
},
{
"alias": [
"塔利雅",
"Dahlia",
"塔利亚",
"塔丽雅",
"主祭",
"助祭"
],
"burstCD": 15,
"id": "10000115",
"name": "塔利雅",
"nameEn": "Dahlia",
"skillCD": 9,
"weapon": "1"
}
]
@@ -96,6 +96,11 @@ public partial class AutoFightConfig : ObservableObject
[ObservableProperty]
private int _pickDropsAfterFightSeconds = 15;
/// <summary>
/// 拾取战斗人次阈值,当战斗人次小于一定次数,就结束战斗情况下,不触发拾取掉落物和万叶拾取后拾取,只有不小于2时才生效。
/// </summary>
[ObservableProperty]
private int? _battleThresholdForLoot;
/// <summary>
/// 战斗结束后,如果存在枫原万叶,则使用该角色捡材料
/// </summary>
@@ -36,6 +36,7 @@ public class AutoFightParam : BaseTaskParam
FinishDetectConfig.BeforeDetectDelay = autoFightConfig.FinishDetectConfig.BeforeDetectDelay;
KazuhaPartyName = autoFightConfig.KazuhaPartyName;
OnlyPickEliteDropsMode = autoFightConfig.OnlyPickEliteDropsMode;
BattleThresholdForLoot = autoFightConfig.BattleThresholdForLoot ?? BattleThresholdForLoot;
//下面参数固定,只取自动战斗里面的
FinishDetectConfig.BattleEndProgressBarColor = TaskContext.Instance().Config.AutoFightConfig.FinishDetectConfig.BattleEndProgressBarColor;
FinishDetectConfig.BattleEndProgressBarColorTolerance = TaskContext.Instance().Config.AutoFightConfig.FinishDetectConfig.BattleEndProgressBarColorTolerance;
@@ -48,7 +49,7 @@ public class AutoFightParam : BaseTaskParam
public bool FightFinishDetectEnabled { get; set; } = false;
public bool PickDropsAfterFightEnabled { get; set; } = false;
public int PickDropsAfterFightSeconds { get; set; } = 15;
public int BattleThresholdForLoot { get; set; } = -1;
public int Timeout { get; set; } = 120;
public bool KazuhaPickupEnabled = true;
@@ -417,44 +417,12 @@ public class AutoFightTask : ISoloTask
}, cts2.Token);
await fightTask;
// 战斗结束检测线程
// 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.Token);
// }
// }
// catch (Exception e)
// {
// Debug.WriteLine(e.Message);
// Debug.WriteLine(e.StackTrace);
// }
// }, cts2.Token);
//
// await Task.WhenAll(fightTask, endTask);
//战斗人次少于2时(通常无怪物情况下),跳过拾取
if (countFight < 2)
if (_taskParam.BattleThresholdForLoot>=2 && countFight < _taskParam.BattleThresholdForLoot)
{
Logger.LogInformation($"战斗人次({countFight})低于配置人次({_taskParam.BattleThresholdForLoot}),跳过此次拾取!");
return;
}
if (_taskParam.KazuhaPickupEnabled)
{
// 队伍中存在万叶的时候使用一次长E
@@ -505,7 +473,7 @@ public class AutoFightTask : ISoloTask
}
else
{
Logger.LogInformation((countFight < 2 ? "首个人出招就结束战斗,应该无怪物" : "距最近一次万叶出招,时间过短") + ",跳过此次万叶拾取!");
Logger.LogInformation("距最近一次万叶出招,时间过短,跳过此次万叶拾取!");
}
}
//切换过队伍的,需要再切回来
@@ -21,15 +21,15 @@ public class BigFishType
// public static readonly BigFishType FormaloRay = new("formalo ray", "fake fly bait", "佛玛洛鳐");
// public static readonly BigFishType DivdaRay = new("divda ray", "fake fly bait", "迪芙妲鳐");
public static readonly BigFishType Angler = new("angler", "sugardew bait", "角鲀", 8);
public static readonly BigFishType AxeMarlin = new("axe marlin", "sugardew bait", "斧枪鱼", 9);
public static readonly BigFishType HeartfeatherBass = new("heartfeather bass", "sour bait", "心羽鲈", 10);
public static readonly BigFishType MaintenanceMek = new("maintenance mek", "flashing maintenance mek bait", "维护机关", 11);
public static readonly BigFishType Unihornfish = new("unihornfish", "spinelgrain bait", "独角鱼", 11);
public static readonly BigFishType Sunfish = new("sunfish", "spinelgrain bait", "翻车鲀", 8);
public static readonly BigFishType Rapidfish = new("rapidfish", "spinelgrain bait", "斗士急流鱼", 10);
public static readonly BigFishType PhonyUnihornfish = new("phony unihornfish", "emberglow bait", "燃素独角鱼", 11);
public static readonly BigFishType MagmaRapidfish = new("magma rapidfish", "emberglow bait", "炽岩斗士急流鱼", 10);
public static readonly BigFishType Angler = new("angler", "sugardew bait", "角鲀", 7);
public static readonly BigFishType AxeMarlin = new("axe marlin", "sugardew bait", "斧枪鱼", 8);
public static readonly BigFishType HeartfeatherBass = new("heartfeather bass", "sour bait", "心羽鲈", 9);
public static readonly BigFishType MaintenanceMek = new("maintenance mek", "flashing maintenance mek bait", "维护机关", 10);
public static readonly BigFishType Unihornfish = new("unihornfish", "spinelgrain bait", "独角鱼", 10);
public static readonly BigFishType Sunfish = new("sunfish", "spinelgrain bait", "翻车鲀", 7);
public static readonly BigFishType Rapidfish = new("rapidfish", "spinelgrain bait", "斗士急流鱼", 9);
public static readonly BigFishType PhonyUnihornfish = new("phony unihornfish", "emberglow bait", "燃素独角鱼", 10);
public static readonly BigFishType MagmaRapidfish = new("magma rapidfish", "emberglow bait", "炽岩斗士急流鱼", 9);
public static IEnumerable<BigFishType> Values
@@ -1,4 +1,6 @@
namespace BetterGenshinImpact.GameTask.AutoFishing;
using static TorchSharp.torch;
namespace BetterGenshinImpact.GameTask.AutoFishing;
public record RodInput
{
+113 -101
View File
@@ -37,8 +37,14 @@ namespace BetterGenshinImpact.GameTask.AutoFishing;
/// tmd 今天我意识到 XXXX可不就是XXXX
///
/// 哦 到这一步以后剩下的就很弱智了 远了挪近一点 近了挪远一点 调调参差不多得了
///
/// *后来又新增了一些访谈内容:
///
/// 额 总之就是要求不能把不咬钩的识别成咬钩的 但是咬钩的可以识别成不咬钩的
///
/// 然后就可视化一下onehot在不同距离的结果 加一个offset使得模型输出的结果在保证可以predict距离正好的结果的同时距离范围尽可能小
/// </summary>
public class RodNet : Module<Tensor, Tensor>
public class RodNet : Module<Tensor, Tensor, Tensor, Tensor, Tensor>
{
const double alpha = 1734.34 / 2.5;
// fitted parameters
@@ -75,23 +81,21 @@ public class RodNet : Module<Tensor, Tensor>
static readonly double[] offset = { 0.8, 0.4, 0.35, 0.35, 0.6, 0.3, 0.3, 0.8, 0.8, 0.8, 0.8 };
private readonly Module<Tensor, Tensor> layers;
private Parameter thetaParameter;
private Parameter bParameter;
private Parameter dzParameter;
private Parameter hCoeffParameter;
public RodNet() : base("RodNet")
{
var weight = tensor(RodNet.weight, ScalarType.Float64);
var bias = tensor(RodNet.bias, ScalarType.Float64);
long num_embeddings = RodNet.weight.GetLength(0);
long embedding_dim = 3;
RodLayer1 rodLayer1 = new RodLayer1(num_embeddings: weight.shape[0], embedding_dim: weight.shape[1], input_dim: 3, output_dim: 3);
rodLayer1.SetWeightsManually(weight, bias);
this.thetaParameter = new Parameter(torch.randn(num_embeddings, embedding_dim, dtype: ScalarType.Float64));
this.bParameter = new Parameter(torch.randn(num_embeddings, embedding_dim, dtype: ScalarType.Float64));
var modules = new List<(string, Module<Tensor, Tensor>)>
{
($"rodLayer1", rodLayer1),
($"softmax", nn.Softmax(1))
};
layers = Sequential(modules);
this.dzParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
this.hCoeffParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
RegisterComponents();
}
@@ -109,58 +113,26 @@ public class RodNet : Module<Tensor, Tensor>
dst[i] /= sum;
}
}
public record NetInput(double dist, int fish_label);
public static NetInput? GeometryProcessing(RodInput input)
internal static int GetRodState(RodInput input)
{
double a, b, v0, u, v, h;
double[] pred = ComputeScores(input);
a = (input.rod_x2 - input.rod_x1) / 2 / alpha;
b = (input.rod_y2 - input.rod_y1) / 2 / alpha;
h = (input.fish_y2 - input.fish_y1) / 2 / alpha;
return Array.IndexOf(pred, pred.Max());
}
if (a < b)
{
b = Math.Sqrt(a * b);
a = b + 1e-6;
}
public static double[] ComputeScores(RodInput input)
{
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
v0 = (288 - (input.rod_y1 + input.rod_y2) / 2) / alpha;
u = (input.fish_x1 + input.fish_x2 - input.rod_x1 - input.rod_x2) / 2 / alpha;
v = (288 - (input.fish_y1 + input.fish_y2) / 2) / alpha;
v -= h * h_coeff[input.fish_label];
double y0, z0, t;
double x, y, dist;
y0 = Math.Sqrt(Math.Pow(a, 4) - b * b + a * a * (1 - b * b + v0 * v0)) / (a * a);
z0 = b / (a * a);
t = a * a * (y0 * b + v0) / (a * a - b * b);
x = u * (z0 + dz[input.fish_label]) * Math.Sqrt(1 + t * t) / (t - v);
y = (z0 + dz[input.fish_label]) * (1 + t * v) / (t - v);
dist = Math.Sqrt(x * x + (y - y0) * (y - y0));
return new NetInput(dist, input.fish_label);
}
internal static int GetRodState(RodInput input)
{
NetInput? netInput = GeometryProcessing(input);
if (netInput is null)
{
return -1;
}
double[] pred = ComputeScores(netInput);
return Array.IndexOf(pred, pred.Max());
}
public static double[] ComputeScores(NetInput netInput)
{
double dist = netInput.dist;
int fish_label = netInput.fish_label;
int fish_label = input.fish_label;
double[] logits = new double[3];
for (int i = 0; i < 3; i++)
@@ -177,73 +149,113 @@ public class RodNet : Module<Tensor, Tensor>
internal int GetRodState_Torch(RodInput input)
{
NetInput? netInput = GeometryProcessing(input);
if (netInput is null)
{
return -1;
}
Tensor outputTensor = ComputeScores_Torch(netInput);
using var _ = no_grad();
Tensor outputTensor = ComputeScores_Torch(input);
var max = argmax(outputTensor);
return (int)max.item<long>();
}
public Tensor ComputeScores_Torch(NetInput netInput)
public Tensor ComputeScores_Torch(RodInput input)
{
double dist = netInput.dist;
int fish_label = netInput.fish_label;
using var _ = no_grad();
this.SetWeightsManually();
Tensor inputTensor = cat([tensor(new double[,] { { dist } }, dtype: ScalarType.Float64),
tensor(new int[,] { {fish_label } }, dtype: ScalarType.Int32)]).T;
var outputTensor = forward(inputTensor);
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
outputTensor[0][0] = outputTensor[0][0] - RodNet.offset[fish_label];
Tensor fishLabel = tensor(new double[] { input.fish_label }, dtype: ScalarType.Int32);
Tensor uv = tensor(new double[,] { { u, v } }, dtype: ScalarType.Float64);
Tensor y0z0t = tensor(new double[,] { { y0, z0, t } }, dtype: ScalarType.Float64);
Tensor h_ = tensor(new double[,] { { h } }, dtype: ScalarType.Float64);
return outputTensor;
var logits = forward(fishLabel, uv, y0z0t, h_);
var output = PostProcess(logits, fishLabel);
return output;
}
public override Tensor forward(Tensor input)
/// <summary>
/// 使用时直接赋值已知权重
/// </summary>
public void SetWeightsManually()
{
return layers.forward(input);
}
}
public class RodLayer1 : Module<Tensor, Tensor>
{
private readonly Embedding embedding1;
private readonly Embedding embedding2;
private readonly Linear linear;
public RodLayer1(long num_embeddings, long embedding_dim, long input_dim, long output_dim)
: base("RodLinear")
{
embedding1 = torch.nn.Embedding(num_embeddings, embedding_dim);
embedding2 = torch.nn.Embedding(num_embeddings, embedding_dim);
linear = torch.nn.Linear(input_dim, output_dim);
RegisterComponents();
var weightTensor = tensor(RodNet.weight, ScalarType.Float64);
var biasTensor = tensor(RodNet.bias, ScalarType.Float64);
var dzTensor = tensor(RodNet.dz, ScalarType.Float64).reshape([RodNet.dz.Length, 1]);
var h_coeffTensor = tensor(RodNet.h_coeff, ScalarType.Float64).reshape([RodNet.h_coeff.Length, 1]);
this.thetaParameter = new Parameter(weightTensor);
this.bParameter = new Parameter(biasTensor);
this.dzParameter = new Parameter(dzTensor);
this.hCoeffParameter = new Parameter(h_coeffTensor);
}
public void SetWeightsManually(Tensor weight, Tensor bias)
public override Tensor forward(Tensor fishLabel, Tensor uv, Tensor y0z0t, Tensor h)
{
embedding1.weight = new Parameter(weight);
embedding2.weight = new Parameter(bias);
var uvSplit = uv.split([1, 1], dim: 1);
Tensor u = uvSplit[0];
Tensor v = uvSplit[1];
var y0z0tSplit = y0z0t.split([1, 1, 1], dim: 1);
Tensor y0 = y0z0tSplit[0];
Tensor z0 = y0z0tSplit[1];
Tensor t = y0z0tSplit[2];
v = v - h * hCoeffParameter[fishLabel];
Tensor x, y, dist;
var dz = dzParameter[fishLabel];
x = u * (z0 + dz) * torch.sqrt(1 + t * t) / (t - v);
y = (z0 + dz) * (1 + t * v) / (t - v);
dist = torch.sqrt(x * x + (y - y0) * (y - y0));
Tensor logits = this.thetaParameter[fishLabel] * dist + this.bParameter[fishLabel];
return logits;
}
public override Tensor forward(Tensor input)
public Tensor PostProcess(Tensor logits, Tensor fishLabel)
{
var splitInput = input.split([1, 1], dim: 1);
var dist = splitInput[0];
var fish_label = splitInput[1].to(ScalarType.Int32).flatten();
var x_softmax = torch.nn.functional.softmax(logits, 1);
var embed1 = embedding1.forward(fish_label);
//Console.WriteLine(String.Join(",", embed1.data<double>()));
var embed2 = embedding2.forward(fish_label);
//Console.WriteLine(String.Join(",", embed2.data<double>()));
Tensor x_offset = tensor(fishLabel.data<int>().Select(l => RodNet.offset[l]).ToArray());
linear.weight = new Parameter(embed1.T);
linear.bias = new Parameter(embed2);
x_softmax[torch.arange(x_offset.shape[0]), 0] -= x_offset;
return x_softmax;
}
return linear.forward(dist);
/// <summary>
/// 根据rod和fish的坐标计算y0z0t、uv、h
/// </summary>
/// <param name="input"></param>
/// <returns>y0, z0, t, u, v, h</returns>
public static (double, double, double, double, double, double) GetRodStatePreProcess(RodInput input)
{
/*
* 以下为hutaofisher代码中关于部分变量的意义的注释
# uv: screen coordinate of bbox center of the fish
# abv0: rod shape and center coordinate in screen
*/
double a, b, v0, u, v, h;
a = (input.rod_x2 - input.rod_x1) / 2 / alpha;
b = (input.rod_y2 - input.rod_y1) / 2 / alpha;
h = (input.fish_y2 - input.fish_y1) / 2 / alpha;
if (a < b)
{
b = Math.Sqrt(a * b);
a = b + 1e-6;
}
v0 = (288 - (input.rod_y1 + input.rod_y2) / 2) / alpha;
u = (input.fish_x1 + input.fish_x2 - input.rod_x1 - input.rod_x2) / 2 / alpha;
v = (288 - (input.fish_y1 + input.fish_y2) / 2) / alpha;
double y0, z0, t;
y0 = Math.Sqrt(Math.Pow(a, 4) - b * b + a * a * (1 - b * b + v0 * v0)) / (a * a);
z0 = b / (a * a);
t = a * a * (y0 * b + v0) / (a * a - b * b);
return (y0, z0, t, u, v, h);
}
}
@@ -919,6 +919,83 @@
}
]
},
{
"id": 1114,
"nameEn": "citlali",
"type": "character",
"name": "茜特菈莉",
"hp": 10,
"energy": 2,
"element": "冰元素",
"weapon": "法器",
"skills": [
{
"nameEn": "shadowstealing_spirit_vessel",
"name": "宿灵捕影",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "dawnfrost_darkstar",
"name": "霜昼黑星",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 3
}
]
},
{
"nameEn": "edict_of_entwined_splendor",
"name": "诸曜饬令",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1101,
"nameEn": "cryo",
"type": "冰元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "songs_of_profound_mystery",
"name": "奥秘传唱",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1201,
"nameEn": "barbara",
@@ -1354,7 +1431,7 @@
"nameEn": "candace",
"type": "character",
"name": "坎蒂丝",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "水元素",
"weapon": "长柄武器",
@@ -1569,7 +1646,7 @@
"nameEn": "neuvillette",
"type": "character",
"name": "那维莱特",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "水元素",
"weapon": "法器",
@@ -2853,6 +2930,77 @@
}
]
},
{
"id": 1315,
"nameEn": "mavuika",
"type": "character",
"name": "玛薇卡",
"hp": 10,
"energy": 0,
"element": "火元素",
"weapon": "双手剑",
"skills": [
{
"nameEn": "flames_weave_life",
"name": "以火织命",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "the_named_moment",
"name": "称名之刻",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 2
}
]
},
{
"nameEn": "hour_of_burning_skies",
"name": "燔天之时",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1103,
"nameEn": "pyro",
"type": "火元素",
"count": 4
}
]
},
{
"nameEn": "fighting_spirit",
"name": "战意",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1401,
"nameEn": "fischl",
@@ -3142,7 +3290,7 @@
"nameEn": "beidou",
"type": "character",
"name": "北斗",
"hp": 10,
"hp": 11,
"energy": 3,
"element": "雷元素",
"weapon": "双手剑",
@@ -3332,7 +3480,7 @@
"id": 1104,
"nameEn": "electro",
"type": "雷元素",
"count": 4
"count": 3
},
{
"id": 1110,
@@ -4464,6 +4612,83 @@
}
]
},
{
"id": 1511,
"nameEn": "chasca",
"type": "character",
"name": "恰斯卡",
"hp": 10,
"energy": 2,
"element": "风元素",
"weapon": "弓",
"skills": [
{
"nameEn": "phantom_feather_flurry",
"name": "迷羽流击",
"skillTag": [
"普通攻击"
],
"cost": [
{
"id": 1105,
"nameEn": "anemo",
"type": "风元素",
"count": 1
},
{
"id": 1109,
"nameEn": "unaligned_element",
"type": "无色元素",
"count": 2
}
]
},
{
"nameEn": "spirit_reins_shadow_hunt",
"name": "灵缰追影",
"skillTag": [
"元素战技"
],
"cost": [
{
"id": 1105,
"nameEn": "anemo",
"type": "风元素",
"count": 3
}
]
},
{
"nameEn": "soul_reapers_fatal_round",
"name": "索魂命袭",
"skillTag": [
"元素爆发"
],
"cost": [
{
"id": 1105,
"nameEn": "anemo",
"type": "风元素",
"count": 3
},
{
"id": 1110,
"nameEn": "energy",
"type": "充能",
"count": 2
}
]
},
{
"nameEn": "shadowhunt_shell",
"name": "追影弹",
"skillTag": [
"被动技能"
],
"cost": []
}
]
},
{
"id": 1601,
"nameEn": "ningguang",
@@ -4691,7 +4916,7 @@
"nameEn": "albedo",
"type": "character",
"name": "阿贝多",
"hp": 10,
"hp": 12,
"energy": 2,
"element": "岩元素",
"weapon": "单手剑",
@@ -5550,7 +5775,7 @@
"nameEn": "baizhu",
"type": "character",
"name": "白术",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "草元素",
"weapon": "法器",
@@ -6579,7 +6804,7 @@
"nameEn": "hydro_hilichurl_rogue",
"type": "character",
"name": "丘丘水行游侠",
"hp": 10,
"hp": 11,
"energy": 2,
"element": "水元素",
"weapon": "其他武器",
@@ -198,7 +198,7 @@ public partial class AutoPickTrigger : ITaskTrigger
if (config.OcrEngine == PickOcrEngineEnum.Yap.ToString())
{
var textMat = new Mat(content.CaptureRectArea.CacheGreyMat, textRect);
text = _pickTextInference.Inference(TextInferenceFactory.PreProcessForInference(textMat));
text = _pickTextInference.Inference(textMat);
}
else
{
@@ -6,6 +6,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
using BetterGenshinImpact.GameTask.AutoWood.Assets;
using BetterGenshinImpact.GameTask.AutoWood.Utils;
using BetterGenshinImpact.GameTask.Common.BgiVision;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Model.Area;
using Microsoft.Extensions.Logging;
using Vanara.PInvoke;
@@ -15,54 +16,46 @@ namespace BetterGenshinImpact.GameTask.Common.Job;
public class ExitAndReloginJob
{
private AutoWoodAssets _assets;
private AutoWoodAssets _assets = AutoWoodAssets.Instance;
private readonly Login3rdParty _login3rdParty = new();
public async Task Start(CancellationToken ct)
{
//============== 退出游戏流程 ==============
Logger.LogInformation("退出至登录页面");
_assets = AutoWoodAssets.Instance;
SystemControl.FocusWindow(TaskContext.Instance().GameHandle);
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(800, ct);
// 菜单界面验证(带重试机制)
try
{
NewRetry.Do(() =>
{
using var contentRegion = CaptureToRectArea();
using var ra = contentRegion.Find(_assets.MenuBagRo);
if (ra.IsEmpty())
{
// 未检测到菜单时再次发送ESC
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
throw new RetryException("菜单界面验证失败");
}
}, TimeSpan.FromSeconds(1.2), 5); // 1.2秒内重试5次
}
catch
{
// 即使失败也继续退出流程
}
// 点击退出按钮
GameCaptureRegion.GameRegionClick((size, scale) => (50 * scale, size.Height - 50 * scale));
await Delay(500, ct);
// 等待菜单界面出现
await NewRetry.WaitForElementAppear(
_assets.MenuBagRo,
() => Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE),
ct,
5,
1200
);
// 点击退出按钮并等待确认弹窗出现
await NewRetry.WaitForElementAppear(
_assets.ConfirmRo,
() => GameCaptureRegion.GameRegionClick((size, scale) => (50 * scale, size.Height - 50 * scale)),
ct,
5,
800
);
// 点击确认退出并等待确认弹窗消失
await NewRetry.WaitForElementDisappear(
_assets.ConfirmRo,
() => {
using var cr = CaptureToRectArea();
cr.Find(_assets.ConfirmRo, ra => { ra.Click(); ra.Dispose(); });
},
ct,
5,
1000
);
await Delay(1000, ct);
// 确认退出
using var cr = CaptureToRectArea();
cr.Find(_assets.ConfirmRo, ra =>
{
ra.Click();
ra.Dispose();
});
await Delay(1000, ct); // 等待退出完成
//============== 重新登录流程 ==============
// 第三方登录(如果启用)
Logger.LogInformation("点击登录");
_login3rdParty.RefreshAvailabled();
if (_login3rdParty is { Type: Login3rdParty.The3rdPartyType.Bilibili, IsAvailabled: true })
@@ -72,45 +65,48 @@ public class ExitAndReloginJob
Logger.LogInformation("退出重登启用 B 服模式");
}
// 进入游戏检测
var clickCnt = 0;
for (var i = 0; i < 50; i++)
// 等待进入游戏按钮出现并点击
var enterGameAppear = await NewRetry.WaitForElementAppear(
_assets.EnterGameRo,
() => { },
ct,
50,
1000
);
if (enterGameAppear)
{
await Delay(1, ct);
using var contentRegion = CaptureToRectArea();
using var ra = contentRegion.Find(_assets.EnterGameRo);
if (!ra.IsEmpty())
{
clickCnt++;
GameCaptureRegion.GameRegion1080PPosClick(955, 666);
}
else
{
if (clickCnt > 2)
{
await Delay(5000, ct);
break;
}
}
await Delay(1000, ct);
// 点击进入游戏按钮直到它消失
await NewRetry.WaitForElementDisappear(
_assets.EnterGameRo,
() => GameCaptureRegion.GameRegion1080PPosClick(955, 666),
ct,
10,
1000
);
}
if (clickCnt == 0)
else
{
throw new RetryException("未检测进入游戏界面");
}
for (var i = 0; i < 50; i++)
// 等待主界面出现
var mainUiFound = await NewRetry.WaitForElementAppear(
ElementAssets.Instance.PaimonMenuRo,
() => { },
ct,
50,
1000
);
if (mainUiFound)
{
if (Bv.IsInMainUi(CaptureToRectArea()))
{
Logger.LogInformation("退出重新登录结束!");
break;
}
await Delay(1000, ct);
Logger.LogInformation("退出重新登录结束!");
}
else
{
Logger.LogWarning("未检测到主界面,登录可能未完成");
}
await Delay(500, ct);
}
}
}
@@ -82,35 +82,40 @@ internal class GoToSereniteaPotTask
// 进入 壶
await ChangeCountryForce("尘歌壶", ct);
// 若未找到 ElementAssets.Instance.SereniteaPotRo 就是已经在尘歌壶了
var ra = CaptureToRectArea();
//确定洞天名称
var list = ra.FindMulti(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect((int)(ra.Width * 0.86), ra.Height*9/10, (int)(ra.Width * 0.073), (int)(ra.Height*0.04))
});
if (list.Count > 0)
{
dongTianName = list[0].Text;
Logger.LogInformation("领取尘歌壶奖励:{text}", "洞天名称:" + dongTianName);
var ra = CaptureToRectArea();
for (int i = 0; i < 5; i++){
ra = CaptureToRectArea();
//确定洞天名称
var list = ra.FindMulti(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect((int)(ra.Width * 0.86), ra.Height*9/10, (int)(ra.Width * 0.073), (int)(ra.Height*0.04))
});
if (list.Count > 0)
{
dongTianName = list[0].Text;
Logger.LogInformation("领取尘歌壶奖励:{text}", "洞天名称:" + dongTianName);
await Task.Delay(100, ct);
break;
}
else
{
dongTianName = "";
Logger.LogInformation("领取尘歌壶奖励:{text}", "未识别到洞天名称");
}
await Task.Delay(100, ct);
}
else
{
dongTianName = "";
Logger.LogInformation("领取尘歌壶奖励:{text}", "未识别到洞天名称");
}
for (int i = 0; i < 3; i++)
for (int i = 0; i < 5; i++)
{
var sereniteaPotHomeIcon = ra.Find(ElementAssets.Instance.SereniteaPotHomeRo);
if (!sereniteaPotHomeIcon.IsExist())
{
Logger.LogInformation("领取尘歌壶奖励:{text}", "住宅图标未找到,调整地图缩放至3.0。");
await new Core.Script.Dependence.Genshin().SetBigMapZoomLevel(3.0);
Logger.LogInformation("领取尘歌壶奖励:{text}", "住宅图标未找到,调整地图缩放至2。");
await Task.Delay(1000, ct);
await new Core.Script.Dependence.Genshin().SetBigMapZoomLevel(2.5-i*0.2);//尝试缩放地图
await Task.Delay(1000, ct);
}
else
{
@@ -141,8 +146,6 @@ internal class GoToSereniteaPotTask
await NewRetry.WaitForAction(() => Bv.IsInMainUi(CaptureToRectArea()), ct);
}
// 寻找阿圆并靠近
private async Task FindAYuan(CancellationToken ct)
{
@@ -297,18 +300,18 @@ internal class GoToSereniteaPotTask
if (numberBtn.IsExist())
{
numberBtn.Move();
await Delay(300, ct);
await Delay(600, ct);//减慢速度,设备差异导致的延迟
Simulation.SendInput.Mouse.LeftButtonDown();
await Delay(300, ct);
await Delay(600, ct);
numberBtn.MoveTo(ra.Width/7,0);//moveby会超出边界,改用MoveTo
await Delay(300, ct);
await Delay(600, ct);
Simulation.SendInput.Mouse.LeftButtonUp();
}
await Delay(300, ct);
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
await Delay(500, ct);
await Delay(600, ct);
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
await Delay(600, ct);
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenPaimonMenu); // ESC
}
private async Task GetReward(CancellationToken ct)
@@ -371,7 +374,6 @@ internal class GoToSereniteaPotTask
if (shopOption == TalkOptionRes.FoundAndClick)
{
Logger.LogInformation("领取尘歌壶奖励:{text}", "购买商店物品");
await Delay(500, ct);
// 购买的物品清单
var buy = new List<RecognitionObject>();
@@ -410,18 +412,39 @@ internal class GoToSereniteaPotTask
break;
}
}
//对比购买成功和buy的数量,如果不等,重试一次
var buyCount = 0;
var retryBuy= 0;
// 直接购买最大数量
foreach (var item in buy)
while (retryBuy < 2)
{
var itemRo = CaptureToRectArea().Find(item);
if (itemRo.IsExist())
foreach (var item in buy)
{
Logger.LogInformation("领取尘歌壶奖励:购买 {text} ", item.Name);
itemRo.Click();
await Delay(600, ct);
await BuyMaxNumber(ct);
await Delay(1200, ct);//等待购买动画结束
var itemRo = CaptureToRectArea().Find(item);
if (itemRo.IsExist())
{
buyCount++;
Logger.LogInformation("领取尘歌壶奖励:购买 {text} ", item.Name);
itemRo.Click();
await Delay(600, ct);
await BuyMaxNumber(ct);
await Delay(1000, ct);//等待购买动画结束
}
else
{
await Delay(700, ct);
Logger.LogInformation("领取尘歌壶奖励: {text} 未找到", item.Name);
}
await Delay(700, ct);
}
if (buyCount < buy.Count)
{
retryBuy++;
await Delay(500, ct);
}else
{
break;
}
}
await Delay(900, ct);
@@ -4,6 +4,8 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.Common;
@@ -12,6 +14,12 @@ namespace BetterGenshinImpact.GameTask.Common;
/// </summary>
public static class NewRetry
{
/// <summary>
/// 重试指定操作,若抛出 RetryException 则在指定间隔后重试,最多尝试 maxAttemptCount 次。
/// </summary>
/// <param name="action">要执行的操作</param>
/// <param name="retryInterval">重试间隔</param>
/// <param name="maxAttemptCount">最大尝试次数</param>
public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
_ = Do<object?>(() =>
@@ -21,6 +29,14 @@ public static class NewRetry
}, retryInterval, maxAttemptCount);
}
/// <summary>
/// 重试指定操作,若抛出 RetryException 则在指定间隔后重试,最多尝试 maxAttemptCount 次,返回操作结果。
/// </summary>
/// <typeparam name="T">返回值类型</typeparam>
/// <param name="action">要执行的操作</param>
/// <param name="retryInterval">重试间隔</param>
/// <param name="maxAttemptCount">最大尝试次数</param>
/// <returns>操作结果</returns>
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)
{
List<System.Exception> exceptions = [];
@@ -49,6 +65,14 @@ public static class NewRetry
throw new AggregateException(exceptions);
}
/// <summary>
/// 重试执行 action,直到返回 true 或达到最大重试次数。
/// </summary>
/// <param name="action">判断条件</param>
/// <param name="ct">取消令牌</param>
/// <param name="retryTimes">最大重试次数</param>
/// <param name="delayMs">每次重试间隔(毫秒)</param>
/// <returns>是否成功</returns>
public static async Task<bool> WaitForAction(Func<bool> action, CancellationToken ct, int retryTimes = 10, int delayMs = 1000)
{
for (var i = 0; i < retryTimes; i++)
@@ -61,4 +85,84 @@ public static class NewRetry
}
return false;
}
/// <summary>
/// 重试直到某个元素出现,可执行键盘或鼠标操作。
/// </summary>
/// <param name="recognitionObject">要识别的目标对象</param>
/// <param name="retryAction">每次重试时执行的操作</param>
/// <param name="ct">取消令牌</param>
/// <param name="maxAttemptCount">最大尝试次数</param>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns>是否成功找到元素</returns>
public static async Task<bool> WaitForElementAppear(
RecognitionObject recognitionObject,
Action retryAction,
CancellationToken ct,
int maxAttemptCount = 10,
int retryInterval = 1000
)
{
for (int i = 0; i < maxAttemptCount; i++)
{
if (ct.IsCancellationRequested) return false;
// 执行重试操作(如按键)
retryAction?.Invoke();
// 等待指定时间
await TaskControl.Delay(retryInterval, ct);
// 截图并查找元素
using var screen = CaptureToRectArea();
using var result = screen.Find(recognitionObject);
// 元素已出现
if (!result.IsEmpty())
{
return true;
}
}
return false;
}
/// <summary>
/// 重试直到某个元素消失,可执行键盘或鼠标操作。
/// </summary>
/// <param name="recognitionObject">要识别的目标对象</param>
/// <param name="retryAction">每次重试时执行的操作</param>
/// <param name="ct">取消令牌</param>
/// <param name="maxAttemptCount">最大尝试次数</param>
/// <param name="retryInterval">重试间隔(毫秒)</param>
/// <returns>是否成功等待元素消失</returns>
public static async Task<bool> WaitForElementDisappear(
RecognitionObject recognitionObject,
Action retryAction,
CancellationToken ct,
int maxAttemptCount = 10,
int retryInterval = 1000)
{
for (int i = 0; i < maxAttemptCount; i++)
{
if (ct.IsCancellationRequested) return false;
// 执行重试操作(如按键)
retryAction?.Invoke();
// 等待指定时间
await TaskControl.Delay(retryInterval, ct);
// 截图并查找元素
using var screen = CaptureToRectArea();
using var result = screen.Find(recognitionObject);
// 元素已消失
if (result.IsEmpty())
{
return true;
}
}
return false;
}
}
@@ -0,0 +1,232 @@
using BetterGenshinImpact.Core.Simulator;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Model.Area;
using Fischless.WindowsInput;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace GameTask.Model.GameUI
{
public class GridScreen : IAsyncEnumerable<ImageRegion>
{
private readonly Rect gridRoi;
private readonly CancellationToken ct;
private readonly ILogger logger;
private readonly InputSimulator input = Simulation.SendInput;
private readonly int s1Round;
private readonly int roundMilliseconds;
private readonly int s2Round;
private readonly double s3Scale;
/// <summary>
/// 对Gird类型界面的操作封装类
/// 直接对此类对象进行遍历即可获取所有项
/// 每次的截图是上次滚动后的,如果实时性要求高,应每次迭代自行截图
/// 在末页可能重复返回GridItem,须自行处理
/// </summary>
/// <param name="gridRoi">Grid所在位置</param>
/// <param name="logger"></param>
/// <param name="ct"></param>
public GridScreen(Rect gridRoi, int s1Round, int roundMilliseconds, int s2Round, double s3Scale, ILogger logger, CancellationToken ct)
{
this.gridRoi = gridRoi;
this.ct = ct;
this.logger = logger;
this.s1Round = s1Round;
this.roundMilliseconds = roundMilliseconds;
this.s2Round = s2Round;
this.s3Scale = s3Scale;
}
public IAsyncEnumerator<ImageRegion> GetAsyncEnumerator(CancellationToken cancellationToken = default)
{
return new GridEnumerator(this.gridRoi, this.s1Round, this.roundMilliseconds, this.s2Round, this.s3Scale, this.logger, this.input, this.ct);
}
public class GridEnumerator : IAsyncEnumerator<ImageRegion>
{
private readonly Rect roi;
private readonly CancellationToken ct;
private readonly ILogger logger;
private readonly InputSimulator input = Simulation.SendInput;
private readonly int s1Round;
private readonly int roundMilliseconds;
private readonly int s2Round;
private readonly double s3Scale;
private record Page(ImageRegion ImageRegion, Stack<Rect> Rects);
private Page? currentPage;
private ImageRegion current;
ImageRegion IAsyncEnumerator<ImageRegion>.Current => current;
/// <summary>
/// 滚动操作枚举器
/// </summary>
/// <param name="roi"></param>
/// <param name="s1Round">测试是否能滚动时发出的滚动命令次数</param>
/// <param name="roundMilliseconds">滚动命令间隔毫秒</param>
/// <param name="s2Round">滚过一整页时发出的滚动命令次数</param>
/// <param name="s3Scale">微调滚动时控制首行距离上边界的参数</param>
/// <param name="logger"></param>
/// <param name="input"></param>
/// <param name="ct"></param>
public GridEnumerator(Rect roi, int s1Round, int roundMilliseconds, int s2Round, double s3Scale, ILogger logger, InputSimulator input, CancellationToken ct)
{
this.roi = roi;
this.ct = ct;
this.logger = logger;
this.input = input;
this.s1Round = s1Round;
this.roundMilliseconds = roundMilliseconds;
this.s2Round = s2Round;
this.s3Scale = s3Scale;
}
public async Task<bool> TryVerticalScollDown()
{
using var ra = TaskControl.CaptureToRectArea();
using ImageRegion prevGrid = ra.DeriveCrop(roi);
for (int i = 0; i < this.s1Round; i++)
{
this.input.Mouse.VerticalScroll(-2);
await TaskControl.Delay(this.roundMilliseconds, this.ct);
}
await TaskControl.Delay(300, this.ct);
using var ra2 = TaskControl.CaptureToRectArea();
using ImageRegion scrolledGrid = ra2.DeriveCrop(this.roi);
bool isScrolling = IsScrolling(prevGrid.CacheGreyMat, scrolledGrid.CacheGreyMat, out Point2d shift, logger: this.logger);
return isScrolling;
}
/// <summary>
/// 判断是否还能继续滚动,如果到底了则只能滚动一丝并很快地回弹
/// </summary>
/// <param name="prevGray">先前的灰度图</param>
/// <param name="nextGray">尝试滚动并等待可能的回弹后的灰度图</param>
/// <param name="shift">估计的位移</param>
/// <param name="lowerThreshold">低于下限则可能不存在平移</param>
/// <param name="upperThreshold">上限用于抵消微小的其他差异</param>
/// <param name="logger"></param>
/// <returns></returns>
public static bool IsScrolling(Mat prevGray, Mat nextGray, out Point2d shift, double lowerThreshold = 0.5, double upperThreshold = 0.95, ILogger? logger = null)
{
using Mat prev = new Mat();
prevGray.ConvertTo(prev, MatType.CV_32FC1);
using Mat next = new Mat();
nextGray.ConvertTo(next, MatType.CV_32FC1);
using Mat window = new Mat();
shift = Cv2.PhaseCorrelate(prev, next, window, out double response); // 相位相关性
logger?.LogInformation($"response={response:F3}, shift=({shift.X:F2}, {shift.Y:F2})");
return response > lowerThreshold && response < upperThreshold;
}
public static IEnumerable<Rect> GetGridItems(Mat src)
{
using Mat grey = src.CvtColor(ColorConversionCodes.BGR2GRAY);
using Mat canny = grey.Canny(20, 40);
Cv2.FindContours(canny, out var contours, out _, RetrievalModes.External, ContourApproximationModes.ApproxSimple, null);
IEnumerable<Rect> boxes = contours.Where(c => Cv2.MinAreaRect(c).Angle % 90 <= 1) // 剔除倾斜
.Select(Cv2.BoundingRect).Where(r =>
{
if (r.Height == 0)
{
return false;
}
return Math.Abs((float)r.Width / r.Height - 0.8) < 0.05; // 按形状筛选
}).ToList();
//src.DrawContours(contours, -1, Scalar.Red);
int biggestRectHeight = boxes.Max(b => b.Height);
boxes = boxes.Where(b => (float)b.Height / biggestRectHeight > 0.88); // 剔除太小的
return boxes.ToArray();
}
public async ValueTask<bool> MoveNextAsync()
{
if (this.currentPage == null || this.currentPage.Rects.Count < 1)
{
if (this.currentPage != null)
{
//BetterGenshinImpact.View.Drawable.VisionContext.Instance().DrawContent.ClearAll();
using var ra4 = TaskControl.CaptureToRectArea();
ra4.MoveTo(this.roi.X + this.roi.Width / 2, this.roi.Y + this.roi.Height / 2);
await TaskControl.Delay(300, ct);
bool canScoll = await TryVerticalScollDown();
if (canScoll)
{
for (int i = 0; i < this.s2Round; i++) // 再滚动差不多(最多行数-1)行
{
input.Mouse.VerticalScroll(-2);
await TaskControl.Delay(this.roundMilliseconds, ct);
}
DateTimeOffset rollingEndTime = DateTime.Now.AddSeconds(2);
while (DateTime.Now < rollingEndTime)
{
await TaskControl.Delay(60, ct);
using var ra2 = TaskControl.CaptureToRectArea();
using ImageRegion grid2 = ra2.DeriveCrop(this.roi);
IEnumerable<Rect> gridItems2 = GetGridItems(grid2.SrcMat);
if (gridItems2.Min(i => i.Y) > (ra2.Width * this.s3Scale)) // 最后精细滚动,保证完整地显示最多行
{
input.Mouse.VerticalScroll(-1);
}
else
{
break;
}
}
using var ra3 = TaskControl.CaptureToRectArea();
using ImageRegion grid3 = ra3.DeriveCrop(this.roi);
grid3.MoveTo(grid3.Width, grid3.Height);
await TaskControl.Delay(300, ct);
}
else
{
await TaskControl.Delay(300, ct);
this.logger.LogInformation("滚动到底部了");
return false;
}
}
using var ra = TaskControl.CaptureToRectArea();
var imageRegion = ra.DeriveCrop(this.roi);
IEnumerable<Rect> gridItems = GetGridItems(imageRegion.SrcMat);
this.currentPage = new Page(imageRegion, new Stack<Rect>(gridItems));
//foreach (Rect item in gridItems)
//{
// imageRegion.DrawRect(item, item.GetHashCode().ToString(), new System.Drawing.Pen(System.Drawing.Color.Blue));
//}
}
this.current = this.currentPage.ImageRegion.DeriveCrop(this.currentPage.Rects.Pop());
return true;
}
public ValueTask DisposeAsync()
{
return ValueTask.CompletedTask;
}
}
}
}
+4 -4
View File
@@ -88,21 +88,21 @@ public partial class StringUtils
return int.TryParse(text, out int result) ? result : defaultValue;
}
public static int TryExtractPositiveInt(string text)
public static int TryExtractPositiveInt(string text, int defaultValue = -1)
{
if (string.IsNullOrEmpty(text))
{
return -1;
return defaultValue;
}
try
{
text = RegexHelper.ExcludeNumberRegex().Replace(text, "");
return int.Parse(text);
return TryParseInt(text, defaultValue);
}
catch
{
return -1;
return defaultValue;
}
}
@@ -335,13 +335,18 @@
<!-- 自动秘境 -->
<TextBlock Margin="4,0,0,4"
FontSize="14"
Foreground="{DynamicResource SystemAccentColorPrimaryBrush}"
Text="自动秘境" />
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" Margin="4,0,0,4">
<TextBlock FontSize="14"
Foreground="{DynamicResource SystemAccentColorPrimaryBrush}"
Text="自动秘境" />
<TextBlock Margin="4,0,0,0"
VerticalAlignment="Center"
FontSize="11"
Text="(此处未覆盖的配置可在 独立任务-自动秘境 中配置)" />
</StackPanel>
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="{Binding SelectedConfig.WeeklyDomainEnabled, Converter={StaticResource InverseBooleanConverter}, Mode=TwoWay}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf073;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
@@ -470,7 +475,8 @@
</Grid>
</StackPanel>
</ui:CardExpander>
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="{Binding SelectedConfig.WeeklyDomainEnabled, Mode=TwoWay}">
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="True">
<ui:CardExpander.Icon>
<ui:FontIcon Glyph="&#xf784;" Style="{StaticResource FaFontIconStyle}" />
</ui:CardExpander.Icon>
@@ -502,7 +508,7 @@
</Grid>
</ui:CardExpander.Header>
<StackPanel>
<Grid Margin="52,16,16,8">
<Grid Margin="52,16,16,16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
@@ -9,6 +9,7 @@
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"
xmlns:emoji="clr-namespace:Emoji.Wpf;assembly=Emoji.Wpf"
Title="TaskSettingsPage"
d:DataContext="{d:DesignInstance Type=pages:TaskSettingsPageViewModel}"
d:DesignHeight="1150"
@@ -954,20 +955,113 @@
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="循环次数"
Text="刷取至树脂耗尽"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="循环秘境多少次,输入 0 则为用光所有树脂为止,优先使用浓缩树脂"
Text="优先使用浓缩树脂,然后使用原粹树脂,其余树脂不使用"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
MinWidth="90"
Margin="0,0,36,0"
Text="{Binding AutoDomainRoundNum, Mode=TwoWay}" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.AutoDomainConfig.SpecifyResinUse,Converter={StaticResource InverseBooleanConverter}, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<!-- 指定树脂使用开关 -->
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="指定每种树脂刷取次数"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="开启后会根据配置的次数使用对应的树脂"
TextWrapping="Wrap" />
<ui:ToggleSwitch Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
Margin="0,0,36,0"
IsChecked="{Binding Config.AutoDomainConfig.SpecifyResinUse, Mode=TwoWay}" />
</Grid>
<!-- 树脂设置组 -->
<Border Margin="16,8,16,16"
BorderThickness="1"
BorderBrush="{ui:ThemeResource CardStrokeColorDefaultBrush}"
Background="{ui:ThemeResource ControlFillColorSecondaryBrush}"
CornerRadius="8"
IsEnabled="{Binding Config.AutoDomainConfig.SpecifyResinUse, Mode=OneWay}">
<StackPanel Margin="12">
<!-- 原粹树脂设置 -->
<StackPanel Orientation="Horizontal"
Margin="0,8,0,12">
<ui:TextBlock Text="原粹树脂刷取次数:"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<ui:NumberBox Value="{Binding Config.AutoDomainConfig.OriginalResinUseCount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0"
SmallChange="1"
LargeChange="5"
SpinButtonPlacementMode="Inline"
Width="120"/>
</StackPanel>
<!-- 浓缩树脂设置 -->
<StackPanel Orientation="Horizontal"
Margin="0,0,0,12">
<ui:TextBlock Text="浓缩树脂刷取次数:"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<ui:NumberBox Value="{Binding Config.AutoDomainConfig.CondensedResinUseCount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0"
SmallChange="1"
LargeChange="5"
SpinButtonPlacementMode="Inline"
Width="120" />
</StackPanel>
<!-- 须臾树脂设置 -->
<StackPanel Orientation="Horizontal"
Margin="0,0,0,12">
<ui:TextBlock Text="须臾树脂刷取次数:"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<ui:NumberBox Value="{Binding Config.AutoDomainConfig.TransientResinUseCount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0"
SmallChange="1"
LargeChange="5"
SpinButtonPlacementMode="Inline"
Width="120" />
</StackPanel>
<!-- 脆弱树脂设置 -->
<StackPanel Orientation="Horizontal"
Margin="0,0,0,0">
<ui:TextBlock Text="脆弱树脂刷取次数:"
VerticalAlignment="Center"
Margin="0,0,8,0" />
<ui:NumberBox Value="{Binding Config.AutoDomainConfig.FragileResinUseCount, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Minimum="0"
SmallChange="1"
LargeChange="5"
SpinButtonPlacementMode="Inline"
Width="120" />
</StackPanel>
</StackPanel>
</Border>
<Grid Margin="16">
<Grid.RowDefinitions>
@@ -878,6 +878,32 @@
Margin="0,0,36,0"
IsChecked="{Binding PathingConfig.AutoFightConfig.KazuhaPickupEnabled, Mode=TwoWay}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:TextBlock Grid.Row="0"
Grid.Column="0"
FontTypography="Body"
Text="拾取战斗人次阈值"
TextWrapping="Wrap" />
<ui:TextBlock Grid.Row="1"
Grid.Column="0"
Foreground="{ui:ThemeResource TextFillColorTertiaryBrush}"
Text="拾取战斗人次阈值,当战斗人次小于一定次数,就结束战斗情况下,不触发拾取掉落物和万叶拾取配置,只有不小于2时才生效。"
TextWrapping="Wrap" />
<ui:TextBox Grid.Row="0"
Grid.RowSpan="2"
Grid.Column="1"
MinWidth="120"
Margin="0,0,36,0"
Text="{Binding PathingConfig.AutoFightConfig.BattleThresholdForLoot}" />
</Grid>
<Grid Margin="16">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
@@ -135,11 +135,11 @@ public partial class CheckUpdateWindow : FluentWindow
if (_option.Channel == UpdateChannel.Stable)
{
await RunUpdaterAsync("--source mirrorc");
await RunUpdaterAsync("-I --source mirrorc");
}
else
{
await RunUpdaterAsync("--source mirrorc-alpha");
await RunUpdaterAsync("-I --source mirrorc-alpha");
}
}
@@ -81,7 +81,7 @@ public partial class ScriptRepoWindow
}
catch (Exception ex)
{
Toast.Error($"更新失败: {ex.Message}");
await MessageBox.ErrorAsync($"更新失败,可尝试重置仓库后重新更新。失败原因:: {ex.Message}");
}
}
@@ -226,15 +226,16 @@ public partial class CommonSettingsPageViewModel : ViewModel
{
var zipPath = dialog.FileName;
// 删除旧文件夹
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPathOld))
{
DirectoryHelper.DeleteReadOnlyDirectory(ScriptRepoUpdater.CenterRepoPath);
DirectoryHelper.DeleteReadOnlyDirectory(ScriptRepoUpdater.CenterRepoPathOld);
}
ZipFile.ExtractToDirectory(zipPath, ScriptRepoUpdater.ReposPath, true);
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPathOld))
{
DirectoryHelper.CopyDirectory(ScriptRepoUpdater.CenterRepoPathOld, ScriptRepoUpdater.CenterRepoPath);
MessageBox.Information("脚本仓库离线包导入成功!");
}
else
@@ -31,6 +31,7 @@ using BetterGenshinImpact.ViewModel.Pages.View;
using System.Linq;
using System.Reflection;
using System.Collections.Frozen;
using System.Diagnostics;
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.View.Windows;
+2 -2
View File
@@ -8,12 +8,12 @@
{
"id": "mirrorc",
"name": "Mirror酱",
"uri": "mirrorc://BGI"
"uri": "mirrorc://BGI?os=win&arch=x64"
},
{
"id": "mirrorc-alpha",
"name": "Mirror酱 Alpha",
"uri": "mirrorc://BGI?channel=alpha",
"uri": "mirrorc://BGI?channel=alpha&os=win&arch=x64",
"hidden": true
}
],
+1 -1
View File
@@ -130,4 +130,4 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
## 问题反馈
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1036100501](https://qm.qq.com/q/fvRNqEbFyo)
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1053273766](https://qm.qq.com/q/qtocsOXnIQ)
@@ -16,6 +16,8 @@ public class AvatarClassifyGen
private static readonly string BackgroundDir = @"E:\HuiTask\更好的原神\数据源\background";
private static readonly Random Rd = new Random();
public static readonly List<string> ImgNames = ["UI_AvatarIcon_Side_Ambor.png","UI_AvatarIcon_Side_AmborCostumeWic.png"];
public static void GenAll()
{
@@ -23,9 +25,8 @@ public class AvatarClassifyGen
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
// 只用一个图像
List<string> sideImageFiles = [];
List<string> imgNames = ["UI_AvatarIcon_Side_Escoffier.png","UI_AvatarIcon_Side_Ifa.png",
"UI_AvatarIcon_Side_Flamingo.png","UI_AvatarIcon_Side_Hookwalker.png","UI_AvatarIcon_Side_Mosasaurus.png","UI_AvatarIcon_Side_Shamansaurus.png","UI_AvatarIcon_Side_Drillhead.png"];
foreach (string imgName in imgNames)
foreach (string imgName in ImgNames)
{
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
}
@@ -23,12 +23,7 @@ public class AvatarClassifyTransparentGen
public static void GenAll()
{
List<string> sideImageFiles = [];
List<string> imgNames =
[
"UI_AvatarIcon_Side_Escoffier.png", "UI_AvatarIcon_Side_Ifa.png",
"UI_AvatarIcon_Side_Flamingo.png", "UI_AvatarIcon_Side_Hookwalker.png", "UI_AvatarIcon_Side_Mosasaurus.png",
"UI_AvatarIcon_Side_Shamansaurus.png", "UI_AvatarIcon_Side_Drillhead.png"
];
List<string> imgNames = AvatarClassifyGen.ImgNames;
foreach (string imgName in imgNames)
{
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
@@ -10,13 +10,13 @@ public class OcrTest
{
public static void TestYap()
{
Mat mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png");
var text = TextInferenceFactory.Pick.Inference(TextInferenceFactory.PreProcessForInference(mat));
Debug.WriteLine(text);
Mat mat2 = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png");
var text2 = OcrFactory.Paddle.Ocr(mat2);
Debug.WriteLine(text2);
// Mat mat = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png");
// var text = TextInferenceFactory.Pick.Inference(TextInferenceFactory.PreProcessForInference(mat));
// Debug.WriteLine(text);
//
// Mat mat2 = Cv2.ImRead(@"E:\HuiTask\更好的原神\临时文件\fuben_jueyuan.png");
// var text2 = OcrFactory.Paddle.Ocr(mat2);
// Debug.WriteLine(text2);
}
@@ -1,5 +1,6 @@
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
using BetterGenshinImpact.UnitTest.CoreTests.RecognitionTests.OCRTests;
using GameTask.Model.GameUI;
using OpenCvSharp;
using System;
using System.Collections.Concurrent;
@@ -52,7 +53,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoArtifactSalvageTests
using Mat mat = new Mat(@$"..\..\..\Assets\AutoArtifactSalvage\{screenshot}");
//
var result = AutoArtifactSalvageTask.GetArtifactGridItems(mat);
var result = GridScreen.GridEnumerator.GetGridItems(mat);
//
Assert.Equal(4, result.Count());
@@ -69,7 +70,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoArtifactSalvageTests
using Mat mat = new Mat(@$"..\..\..\Assets\AutoArtifactSalvage\ArtifactGrid.png");
//
var result = AutoArtifactSalvageTask.GetArtifactGridItems(mat);
var result = GridScreen.GridEnumerator.GetGridItems(mat);
using Mat leftTopOne = new Mat(mat, result.Single(r => r.X + r.Width / 2 < mat.Width / 2 && r.Y + r.Height / 2 < mat.Height / 2));
using Mat rightTopOne = new Mat(mat, result.Single(r => r.X + r.Width / 2 > mat.Width / 2 && r.Y + r.Height / 2 < mat.Height / 2));
using Mat leftBottomOne = new Mat(mat, result.Single(r => r.X + r.Width / 2 < mat.Width / 2 && r.Y + r.Height / 2 > mat.Height / 2));
@@ -0,0 +1,392 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static TorchSharp.torch.nn;
using static TorchSharp.torch;
using TorchSharp;
using System.Diagnostics;
using System.Collections;
using BetterGenshinImpact.GameTask.AutoFishing;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
public partial class RodNetTests
{
/// <summary>
/// RodNet验证,应在数据集上达到一定准确率
/// </summary>
[Theory]
[InlineData(@"..\..\..\Assets\AutoFishing\data_selected.csv")]
public void Training_AccuracyShouldBeOK(string dataLocation)
{
//
using var _ = no_grad();
var device =
torch.cuda.is_available() ? torch.CUDA :
torch.mps_is_available() ? torch.MPS :
torch.CPU;
var loss = CrossEntropyLoss();
var sut = new RodNet().to((Device)device);
sut.SetWeightsManually();
using var test_reader = new CSVReader(Enumerable.Repeat(false, 8).Concat(Enumerable.Repeat(true, 2)), Path.GetFullPath(dataLocation), (Device)device);
//
var accuracy = evaluate(test_reader.GetBatches(eval_batch_size), sut, loss);
//
Assert.True(accuracy > 0.8);
}
/// <summary>
/// RodNet必须粗略地支持训练
/// </summary>
[Fact]
public void Training_ShouldBeDifferentiable()
{
//
RodInput input = new RodInput();
var (y0, z0, t, u, v, h) = RodNet.GetRodStatePreProcess(input);
Tensor fishLabel = tensor(new double[] { input.fish_label }, dtype: ScalarType.Int32);
Tensor uv = tensor(new double[,] { { u, v } }, dtype: ScalarType.Float64);
Tensor y0z0t = tensor(new double[,] { { y0, z0, t } }, dtype: ScalarType.Float64);
Tensor h_ = tensor(new double[,] { { h } }, dtype: ScalarType.Float64);
RodNet sut = new RodNet();
//
Tensor output = sut.forward(fishLabel, uv, y0z0t, h_);
output.backward([torch.ones_like(output)]);
//
}
#region 训练相关代码
// 这部分代码改编自TorchSharpExamples的CSharpExamples.TextClassification
private const long batch_size = 32;
private const long eval_batch_size = 32;
internal static RodNet Run(int epochs, int timeout, string dataLocation)
{
torch.random.manual_seed(1);
var device =
torch.cuda.is_available() ? torch.CUDA :
torch.mps_is_available() ? torch.MPS :
torch.CPU;
Console.WriteLine();
Console.WriteLine($"\tRunning TextClassification on {device.type.ToString()} for {epochs} epochs, terminating after {TimeSpan.FromSeconds(timeout)}.");
Console.WriteLine();
Console.WriteLine($"\tPreparing training and test data...");
using (var reader = new CSVReader(Enumerable.Repeat(true, 8).Concat(Enumerable.Repeat(false, 2)), dataLocation, (Device)device))
{
Console.WriteLine($"\tCreating the model...");
Console.WriteLine();
var model = new RodNet().to((Device)device);
var loss = CrossEntropyLoss();
var lr = 1e-2;
var optimizer = torch.optim.SGD(model.parameters(), learningRate: lr);
var scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs, eta_min: 0);
var totalTime = new Stopwatch();
totalTime.Start();
foreach (var epoch in Enumerable.Range(1, epochs))
{
var sw = new Stopwatch();
sw.Start();
train(epoch, reader.GetBatches(batch_size), model, loss, optimizer);
sw.Stop();
Console.WriteLine($"\nEnd of epoch: {epoch} | lr: {optimizer.ParamGroups.First().LearningRate:0.0000} | time: {sw.Elapsed.TotalSeconds:0.0}s\n");
scheduler.step();
if (totalTime.Elapsed.TotalSeconds > timeout) break;
}
totalTime.Stop();
using (var test_reader = new CSVReader(Enumerable.Repeat(false, 8).Concat(Enumerable.Repeat(true, 2)), dataLocation, (Device)device))
{
var sw = new Stopwatch();
sw.Start();
var accuracy = evaluate(test_reader.GetBatches(eval_batch_size), model, loss);
sw.Stop();
Console.WriteLine($"\nEnd of training: test accuracy: {accuracy:0.00} | eval time: {sw.Elapsed.TotalSeconds:0.0}s\n");
scheduler.step();
}
foreach (var (name, param) in model.named_parameters())
{
switch (param.dtype)
{
case ScalarType.Int64:
Console.WriteLine($"参数{name}={String.Join(", ", param.data<long>())}");
break;
case ScalarType.Float32:
Console.WriteLine($"参数{name}={String.Join(", ", param.data<float>())}");
break;
case ScalarType.Float64:
Console.WriteLine($"参数{name}={String.Join(", ", param.data<double>())}");
break;
}
}
return model;
}
}
static void train(int epoch, IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> train_data, RodNet model, Loss<Tensor, Tensor, Tensor> criterion, torch.optim.Optimizer optimizer)
{
model.train();
double total_acc = 0.0;
long total_count = 0;
long log_interval = 1;
var batch = 0;
var batch_count = train_data.Count();
using (var d = torch.NewDisposeScope())
{
foreach (var (y0z0t, uv, h, fish_label, success) in train_data)
{
optimizer.zero_grad();
using (var predicted_labels = model.forward(fish_label, uv, y0z0t, h))
{
var loss = criterion.forward(predicted_labels, success.to(ScalarType.Int64));
loss.backward();
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1);
optimizer.step();
total_acc += (predicted_labels.argmax(1) == success).sum().to(torch.CPU).item<long>();
total_count += success.size(0);
}
batch += 1;
if (batch % log_interval == 0)
{
var accuracy = total_acc / total_count;
Console.WriteLine($"epoch: {epoch} | batch: {batch} / {batch_count} | accuracy: {accuracy:0.00}");
}
}
}
}
static double evaluate(IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> test_data, RodNet model, Loss<Tensor, Tensor, Tensor> criterion)
{
model.eval();
double total_acc = 0.0;
long total_count = 0;
using (var d = torch.NewDisposeScope())
{
foreach (var (y0z0t, uv, h, fish_label, success) in test_data)
{
using (var predicted_labels = model.forward(fish_label, uv, y0z0t, h))
{
var loss = criterion.forward(predicted_labels, success.to(ScalarType.Int64));
total_acc += (predicted_labels.argmax(1) == success).sum().to(torch.CPU).item<long>();
total_count += success.size(0);
}
}
return total_acc / total_count;
}
}
#endregion
}
internal class CSVReader : IDisposable
{
/// <summary>
///
/// </summary>
/// <param name="takeMask">按长度分组,布尔值代表每组内此序号元素是否被读取。例如8个true2个false就是将近80%进入训练集</param>
/// <param name="path"></param>
/// <param name="device"></param>
public CSVReader(IEnumerable<bool> takeMask, string path, Device device)
{
this.takeMask = takeMask.ToArray();
_path = path;
_device = device;
}
private readonly bool[] takeMask;
private readonly string _path;
private readonly Device _device;
public IEnumerable<Data> Enumerate()
{
var all = File.ReadLines(_path).Skip(1); // 跳过首行列名
int count = takeMask.Length;
int maskCount = all.Count() / count;
for (int i = 0; i < maskCount + 1; i++)
{
int lastGroupCount = (i == maskCount) ? (all.Count() % count) : count;
for (int j = 0; j < lastGroupCount; j++)
{
if (takeMask[j])
{
yield return ParseLine(all.Skip(i * count + j).First());
}
}
}
}
public IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> GetBatches(long batch_size)
{
// This data set fits in memory, so we will simply load it all and cache it between epochs.
var inputs = new List<Data>();
if (_data == null)
{
_data = new List<(Tensor, Tensor, Tensor, Tensor, Tensor)>();
var counter = 0;
var lines = Enumerate().ToList();
var left = lines.Count;
foreach (var line in lines)
{
inputs.Add(line);
left -= 1;
if (++counter == batch_size || left == 0)
{
_data.Add(Batchifier(inputs));
inputs.Clear();
counter = 0;
}
}
}
return _data;
}
private List<(Tensor, Tensor, Tensor, Tensor, Tensor)> _data;
private bool disposedValue;
/// <summary>
/// 将csv中的数据进行初步转换
/// </summary>
/// <param name="input"></param>
/// <returns>y0z0t、uv、h、fish_label、success张量</returns>
private (Tensor, Tensor, Tensor, Tensor, Tensor) Batchifier(IEnumerable<Data> input)
{
var y0List = new List<double>();
var z0List = new List<double>();
var tList = new List<double>();
var uList = new List<double>();
var vList = new List<double>();
var hList = new List<double>();
var labelList = new List<int>();
var successList = new List<int>();
foreach (var line in input)
{
int fish_label = line.fish_label;
int success = line.success;
RodInput rodInput = new RodInput()
{
rod_x1 = line.rod_x1,
rod_x2 = line.rod_x2,
rod_y1 = line.rod_y1,
rod_y2 = line.rod_y2,
fish_x1 = line.fish_x1,
fish_x2 = line.fish_x2,
fish_y1 = line.fish_y1,
fish_y2 = line.fish_y2
};
var (y0, z0, t, u, v, h) = RodNet.GetRodStatePreProcess(rodInput);
y0List.Add(y0);
z0List.Add(z0);
tList.Add(t);
uList.Add(u);
vList.Add(v);
hList.Add(h);
labelList.Add(fish_label);
successList.Add(success);
}
Tensor y0Tensor = tensor(y0List, dtype: ScalarType.Float64).to(_device);
Tensor z0Tensor = tensor(z0List, dtype: ScalarType.Float64).to(_device);
Tensor tTensor = tensor(tList, dtype: ScalarType.Float64).to(_device);
Tensor uTensor = tensor(uList, dtype: ScalarType.Float64).to(_device);
Tensor vTensor = tensor(vList, dtype: ScalarType.Float64).to(_device);
Tensor hTensor = tensor(hList, dtype: ScalarType.Float64).to(_device);
Tensor fish_labelTensor = tensor(labelList, dtype: ScalarType.Int32).to(_device);
Tensor successTensor = tensor(successList, dtype: ScalarType.Int32).to(_device);
return (torch.stack([y0Tensor, z0Tensor, tTensor], dim: 1), torch.stack([uTensor, vTensor], dim: 1), hTensor.unsqueeze(1), fish_labelTensor, successTensor);
}
/// <summary>
/// csv的列定义默认为time,bite_time,rod_x1,rod_x2,rod_y1,rod_y2,fish_x1,fish_x2,fish_y1,fish_y2,fish_label,success
/// </summary>
/// <param name="line"></param>
/// <returns></returns>
public Data ParseLine(string line)
{
var columns = line.Split(",").ToArray();
return new Data(float.Parse(columns[2]), float.Parse(columns[3]), float.Parse(columns[4]), float.Parse(columns[5]),
float.Parse(columns[6]), float.Parse(columns[7]), float.Parse(columns[8]), float.Parse(columns[9]),
int.Parse(columns[10]), int.Parse(columns[11]));
}
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing && _data != null)
{
foreach (var (y0z0t, uv, h, label, success) in _data)
{
y0z0t.Dispose();
uv.Dispose();
h.Dispose();
label.Dispose();
success.Dispose();
}
}
disposedValue = true;
}
}
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
internal record Data(float rod_x1, float rod_x2, float rod_y1, float rod_y2, float fish_x1, float fish_x2, float fish_y1, float fish_y2, int fish_label, int success);
}
@@ -1,17 +1,16 @@
using BetterGenshinImpact.GameTask.AutoFishing;
using BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static BetterGenshinImpact.GameTask.AutoFishing.RodNet;
using TorchSharp;
using static TorchSharp.torch;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
{
[Collection("Init Collection")]
public class RodNetTests
public partial class RodNetTests
{
public RodNetTests(TorchFixture torch)
{
@@ -42,9 +41,8 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
RodNet sut = new RodNet();
//
NetInput netInput = GeometryProcessing(rodInput) ?? throw new NullReferenceException();
Tensor outputTensor = sut.ComputeScores_Torch(netInput);
double[] pred = ComputeScores(netInput);
Tensor outputTensor = sut.ComputeScores_Torch(rodInput);
double[] pred = RodNet.ComputeScores(rodInput);
//
Assert.Equal((float)pred[0], (float)outputTensor.data<double>()[0]); // 对比时降低精度,差不多就行
@@ -0,0 +1,39 @@
using GameTask.Model.GameUI;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BetterGenshinImpact.UnitTest.GameTaskTests.Model.GameUI
{
public class GridScreenTests
{
[Fact]
/// <summary>
/// 测试判断前后两张图是否属于滚动,结果应正确
/// </summary>
public void IsScrolling_ResultShouldBeRight()
{
//
using Mat mat = new Mat(@$"..\..\..\Assets\AutoArtifactSalvage\ArtifactGrid.png", flags: ImreadModes.Grayscale);
using Mat cropped = mat[new Rect(0, 0, mat.Width, mat.Height - 10)];
using Mat black = new Mat(mat.Size(), mat.Type(), Scalar.Black);
using Mat scrolled = black.Clone(); // 一个向下平移了10像素的图
using Mat pos = scrolled[new Rect(0, 10, mat.Width, mat.Height - 10)];
cropped.CopyTo(pos);
//
bool result1 = GridScreen.GridEnumerator.IsScrolling(mat, scrolled, out Point2d shift);
bool result2 = GridScreen.GridEnumerator.IsScrolling(mat, mat, out Point2d _);
bool result3 = GridScreen.GridEnumerator.IsScrolling(mat, black, out Point2d _);
//
Assert.True(result1);
Assert.True(shift.Y <= 10 && shift.Y > 9.9);
Assert.False(result2);
Assert.False(result3);
}
}
}