Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fbde10cc0 | ||
|
|
2562567715 | ||
|
|
5e6e18ca96 | ||
|
|
a4db8b4a90 | ||
|
|
43bbb409f8 | ||
|
|
29cbdd7ab2 | ||
|
|
1845475018 | ||
|
|
54e9a01a9d | ||
|
|
cc3d8fc2ef | ||
|
|
b1efd2d3f7 | ||
|
|
833638a758 | ||
|
|
99f4f1da20 |
No files matched your search
@@ -6,8 +6,8 @@ on:
|
||||
types: [released]
|
||||
|
||||
jobs:
|
||||
mirrorchyan:
|
||||
runs-on: windows-latest
|
||||
mirrorchyan_7z:
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- name: 📥 Download release
|
||||
uses: robinraju/[email protected]
|
||||
@@ -15,45 +15,11 @@ jobs:
|
||||
latest: true
|
||||
fileName: "*"
|
||||
|
||||
- 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: Embed Dotnet and VCRedist
|
||||
- name: Extract 7z
|
||||
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 ./metadata.json ./un7z/BetterGI/.metadata.json
|
||||
cd un7z
|
||||
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
|
||||
mv ./BetterGI.Metadata.json ./un7z/BetterGI/.metadata.json
|
||||
|
||||
- name: Determine version number
|
||||
id: get-version
|
||||
@@ -72,17 +38,25 @@ jobs:
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "downloads/BetterGI_7z/BetterGI.zip"
|
||||
version_name: ${{ steps.get-version.outputs.version }}
|
||||
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"
|
||||
working-directory: ./un7z/
|
||||
pick_files: '["BetterGI"]'
|
||||
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
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
name: BetterGI Publish
|
||||
run-name: "BetterGI ${{ inputs.version }}"
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
@@ -300,8 +299,8 @@ jobs:
|
||||
path: dist/BetterGI.Install.*.exe
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: BetterGI_OnlineInst
|
||||
path: dist/BetterGI/BetterGI.update.exe
|
||||
name: BetterGI_Metadata
|
||||
path: dist/metadata.json
|
||||
|
||||
build_setup:
|
||||
runs-on: windows-latest
|
||||
@@ -350,6 +349,11 @@ 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
|
||||
@@ -362,86 +366,45 @@ 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: windows-latest
|
||||
runs-on: macos-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: Embed Dotnet and VCRedist
|
||||
- name: Extract 7z
|
||||
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 ../../metadata.json ./un7z/BetterGI/.metadata.json
|
||||
cd un7z
|
||||
7z a -tzip ../BetterGI.zip ./BetterGI -mx=5 -r -y
|
||||
mv ../BetterGI_Metadata/metadata.json ./un7z/BetterGI/.metadata.json
|
||||
|
||||
- name: Upload Zip
|
||||
uses: MirrorChyan/uploading-action@v1
|
||||
with:
|
||||
filetype: local
|
||||
mirrorchyan_rid: BGI
|
||||
filename: "downloads/BetterGI_7z/BetterGI.zip"
|
||||
working-directory: downloads/BetterGI_7z/un7z/
|
||||
pick_files: '["BetterGI"]'
|
||||
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
|
||||
filename: "BetterGI.Install.${{ needs.validate.outputs.version }}.zip"
|
||||
working-directory: downloads/BetterGI_Install/
|
||||
filename: "BetterGI.Install.*.exe"
|
||||
extra_zip: true
|
||||
version_name: ${{ needs.validate.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
|
||||
os: win
|
||||
arch: x64
|
||||
Binary file not shown.
@@ -2,7 +2,7 @@
|
||||
|
||||
<PropertyGroup>
|
||||
<AssemblyName>BetterGI</AssemblyName>
|
||||
<Version>0.46.0</Version>
|
||||
<Version>0.45.3-alpha.1</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,8 +47,6 @@ 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,7 +24,6 @@ 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;
|
||||
|
||||
@@ -211,42 +210,118 @@ public class AutoArtifactSalvageTask : ISoloTask
|
||||
private async Task Salvage5Star(string regularExpression, int maxNumToCheck)
|
||||
{
|
||||
int count = maxNumToCheck;
|
||||
|
||||
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)
|
||||
Queue<string> checkedArtifactAffixesQueue = new Queue<string>();
|
||||
int duplicateSum = 0;
|
||||
while (count > 0 && duplicateSum < 3)
|
||||
{
|
||||
Rect gridRect = itemRegion.ToRect();
|
||||
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
|
||||
// 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)
|
||||
{
|
||||
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)
|
||||
using ImageRegion itemRegion = grid.DeriveCrop(item);
|
||||
if (GetArtifactStatus(itemRegion.SrcMat) == ArtifactStatus.None)
|
||||
{
|
||||
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);
|
||||
anyItemChecked = true;
|
||||
itemRegion.Click();
|
||||
await Delay(300, ct);
|
||||
|
||||
if (IsMatchRegularExpression(affixes, regularExpression, out string msg))
|
||||
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)
|
||||
{
|
||||
logger.LogInformation(message: 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);
|
||||
}
|
||||
else
|
||||
{
|
||||
itemRegion.Click();
|
||||
await Delay(100, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
count--;
|
||||
if (count <= 0)
|
||||
{
|
||||
logger.LogInformation("检查次数已耗尽");
|
||||
break;
|
||||
}
|
||||
|
||||
grid.MoveTo(grid.Width, grid.Height);
|
||||
await Delay(500, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
await Delay(400, ct);
|
||||
logger.LogInformation("找不到可检查的圣遗物了");
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (count <= 0)
|
||||
{
|
||||
logger.LogInformation("检查次数已耗尽");
|
||||
}
|
||||
if (duplicateSum >= 3)
|
||||
{
|
||||
logger.LogInformation("重复检查次数过多,推断为找不到可检查的了");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -277,6 +352,33 @@ 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,6 +1,5 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
|
||||
@@ -52,32 +51,4 @@ 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,5 +1,4 @@
|
||||
using System.Collections.Generic;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using BetterGenshinImpact.GameTask.Model;
|
||||
using System.Threading;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoDomain;
|
||||
@@ -26,27 +25,6 @@ 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;
|
||||
@@ -67,11 +45,5 @@ 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,8 +39,6 @@ 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;
|
||||
|
||||
@@ -71,8 +69,6 @@ public class AutoDomainTask : ISoloTask
|
||||
private readonly string matchingChallengeString;
|
||||
private readonly string rapidformationString;
|
||||
|
||||
private List<ResinUseRecord> _resinPriorityListWhenSpecifyUse;
|
||||
|
||||
public AutoDomainTask(AutoDomainParam taskParam)
|
||||
{
|
||||
AutoFightAssets.DestroyInstance();
|
||||
@@ -83,8 +79,6 @@ 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);
|
||||
@@ -188,9 +182,17 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
// 5. 快速领取奖励并判断是否有下一轮
|
||||
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
|
||||
if (!await GettingTreasure())
|
||||
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
|
||||
{
|
||||
Logger.LogInformation("体力耗尽或者设置轮次已达标,结束自动秘境");
|
||||
if (i == _taskParam.DomainRoundNum - 1)
|
||||
{
|
||||
Logger.LogInformation("配置的{Cnt}轮秘境已经完成,结束自动秘境", _taskParam.DomainRoundNum);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("体力已经耗尽,结束自动秘境");
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
@@ -613,7 +615,6 @@ public class AutoDomainTask : ISoloTask
|
||||
finally
|
||||
{
|
||||
Logger.LogInformation("自动战斗线程结束");
|
||||
Simulation.ReleaseAllKey();
|
||||
}
|
||||
}, cts.Token);
|
||||
|
||||
@@ -996,7 +997,7 @@ public class AutoDomainTask : ISoloTask
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
|
||||
}
|
||||
|
||||
Sleep(100, _ct);
|
||||
Sleep(100);
|
||||
}
|
||||
|
||||
Logger.LogInformation("锁定东方向视角线程结束");
|
||||
@@ -1007,116 +1008,64 @@ public class AutoDomainTask : ISoloTask
|
||||
/// <summary>
|
||||
/// 领取奖励
|
||||
/// </summary>
|
||||
private async Task<bool> GettingTreasure()
|
||||
/// <param name="recognizeResin">是否识别树脂</param>
|
||||
/// <param name="isLastTurn">是否最后一轮</param>
|
||||
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
|
||||
{
|
||||
bool isLastTurn = false;
|
||||
// 等待窗口弹出
|
||||
await Delay(300, _ct);
|
||||
Sleep(1500, _ct);
|
||||
|
||||
// 1. OCR 直到确认弹出框弹出
|
||||
bool chooseResinPrompt = await NewRetry.WaitForAction(() =>
|
||||
// 优先使用浓缩树脂
|
||||
var retryTimes = 0;
|
||||
while (true)
|
||||
{
|
||||
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)
|
||||
retryTimes++;
|
||||
if (retryTimes > 3)
|
||||
{
|
||||
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了,界面上点一下
|
||||
res.Click();
|
||||
return true;
|
||||
Logger.LogInformation("没有浓缩树脂了");
|
||||
break;
|
||||
}
|
||||
|
||||
return false;
|
||||
}, _ct, 10, 500);
|
||||
Debug.WriteLine("识别到选择树脂页");
|
||||
await Delay(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 useCondensedResinRa = CaptureToRectArea().Find(AutoFightAssets.Instance.UseCondensedResinRa);
|
||||
if (!useCondensedResinRa.IsEmpty())
|
||||
{
|
||||
// 自动刷干树脂
|
||||
// 识别树脂状况
|
||||
var resinStatus = ResinStatus.RecogniseFromRegion(ra3);
|
||||
resinStatus.Print(Logger);
|
||||
|
||||
if (resinStatus.CondensedResinCount > 0)
|
||||
{
|
||||
PressUseResin(ra3, "浓缩树脂");
|
||||
resinStatus.CondensedResinCount -= 1;
|
||||
}
|
||||
else if (resinStatus.OriginalResinCount >= 20)
|
||||
{
|
||||
PressUseResin(ra3, "原粹树脂");
|
||||
resinStatus.OriginalResinCount -= 20;
|
||||
}
|
||||
|
||||
if (resinStatus is { CondensedResinCount: <= 0, OriginalResinCount: < 20 })
|
||||
{
|
||||
// 没树脂了就是最后一回合了
|
||||
isLastTurn = true;
|
||||
}
|
||||
useCondensedResinRa.Click();
|
||||
// 点两下 #224 #218
|
||||
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
|
||||
Sleep(400, _ct);
|
||||
useCondensedResinRa.Click();
|
||||
break;
|
||||
}
|
||||
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(800, _ct);
|
||||
}
|
||||
|
||||
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())
|
||||
@@ -1131,13 +1080,26 @@ 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();
|
||||
return true;
|
||||
@@ -1150,69 +1112,41 @@ public class AutoDomainTask : ISoloTask
|
||||
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
|
||||
}
|
||||
|
||||
private async Task ExitDomain()
|
||||
/// <summary>
|
||||
/// 获取剩余树脂状态
|
||||
/// </summary>
|
||||
private (int, int) GetRemainResinStatus()
|
||||
{
|
||||
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 condensedResinCount = 0;
|
||||
var fragileResinCount = 0;
|
||||
|
||||
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 ra = CaptureToRectArea();
|
||||
// 浓缩树脂
|
||||
var condensedResinCountRa = ra.Find(AutoFightAssets.Instance.CondensedResinCountRa);
|
||||
if (!condensedResinCountRa.IsEmpty())
|
||||
{
|
||||
// 找到树脂名称对应的按键,关键词为使用,是同一行的(高度相交)
|
||||
var useList = regionList.Where(t => t.Text.Contains("使用")).ToList();
|
||||
if (useList.Count != 0)
|
||||
{
|
||||
// 找到使用按键
|
||||
var useKey = useList.FirstOrDefault(t => t.X > TaskContext.Instance().SystemInfo.CaptureAreaRect.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 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);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
// 脆弱树脂
|
||||
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);
|
||||
}
|
||||
|
||||
/// <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);
|
||||
Logger.LogInformation("剩余:浓缩树脂 {CondensedResinCount} 原粹树脂 {FragileResinCount}", condensedResinCount,
|
||||
fragileResinCount);
|
||||
return (condensedResinCount, fragileResinCount);
|
||||
}
|
||||
|
||||
private async Task ArtifactSalvage()
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
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.
|
Before Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 456 B |
@@ -26,11 +26,8 @@ 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;
|
||||
|
||||
@@ -248,31 +245,5 @@ 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,35 +1868,5 @@
|
||||
"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,11 +96,6 @@ public partial class AutoFightConfig : ObservableObject
|
||||
[ObservableProperty]
|
||||
private int _pickDropsAfterFightSeconds = 15;
|
||||
|
||||
/// <summary>
|
||||
/// 拾取战斗人次阈值,当战斗人次小于一定次数,就结束战斗情况下,不触发拾取掉落物和万叶拾取后拾取,只有不小于2时才生效。
|
||||
/// </summary>
|
||||
[ObservableProperty]
|
||||
private int? _battleThresholdForLoot;
|
||||
/// <summary>
|
||||
/// 战斗结束后,如果存在枫原万叶,则使用该角色捡材料
|
||||
/// </summary>
|
||||
|
||||
@@ -36,7 +36,6 @@ 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;
|
||||
@@ -49,7 +48,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,12 +417,44 @@ public class AutoFightTask : ISoloTask
|
||||
}, cts2.Token);
|
||||
|
||||
await fightTask;
|
||||
if (_taskParam.BattleThresholdForLoot>=2 && countFight < _taskParam.BattleThresholdForLoot)
|
||||
|
||||
// 战斗结束检测线程
|
||||
// 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)
|
||||
{
|
||||
Logger.LogInformation($"战斗人次({countFight})低于配置人次({_taskParam.BattleThresholdForLoot}),跳过此次拾取!");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
if (_taskParam.KazuhaPickupEnabled)
|
||||
{
|
||||
// 队伍中存在万叶的时候使用一次长E
|
||||
@@ -473,7 +505,7 @@ public class AutoFightTask : ISoloTask
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogInformation("距最近一次万叶出招,时间过短,跳过此次万叶拾取!");
|
||||
Logger.LogInformation((countFight < 2 ? "首个人出招就结束战斗,应该无怪物" : "距最近一次万叶出招,时间过短") + ",跳过此次万叶拾取!");
|
||||
}
|
||||
}
|
||||
//切换过队伍的,需要再切回来
|
||||
|
||||
@@ -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", "角鲀", 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 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 IEnumerable<BigFishType> Values
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using static TorchSharp.torch;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
|
||||
public record RodInput
|
||||
{
|
||||
|
||||
@@ -37,14 +37,8 @@ namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
/// tmd 今天我意识到 XXXX可不就是XXXX
|
||||
///
|
||||
/// 哦 到这一步以后剩下的就很弱智了 远了挪近一点 近了挪远一点 调调参差不多得了
|
||||
///
|
||||
/// *后来又新增了一些访谈内容:
|
||||
///
|
||||
/// 额 总之就是要求不能把不咬钩的识别成咬钩的 但是咬钩的可以识别成不咬钩的
|
||||
///
|
||||
/// 然后就可视化一下onehot在不同距离的结果 加一个offset使得模型输出的结果在保证可以predict距离正好的结果的同时距离范围尽可能小
|
||||
/// </summary>
|
||||
public class RodNet : Module<Tensor, Tensor, Tensor, Tensor, Tensor>
|
||||
public class RodNet : Module<Tensor, Tensor>
|
||||
{
|
||||
const double alpha = 1734.34 / 2.5;
|
||||
// fitted parameters
|
||||
@@ -81,21 +75,23 @@ public class RodNet : Module<Tensor, Tensor, Tensor, 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 Parameter thetaParameter;
|
||||
private Parameter bParameter;
|
||||
private Parameter dzParameter;
|
||||
private Parameter hCoeffParameter;
|
||||
private readonly Module<Tensor, Tensor> layers;
|
||||
|
||||
public RodNet() : base("RodNet")
|
||||
{
|
||||
long num_embeddings = RodNet.weight.GetLength(0);
|
||||
long embedding_dim = 3;
|
||||
var weight = tensor(RodNet.weight, ScalarType.Float64);
|
||||
var bias = tensor(RodNet.bias, ScalarType.Float64);
|
||||
|
||||
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));
|
||||
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.dzParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
|
||||
this.hCoeffParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
|
||||
var modules = new List<(string, Module<Tensor, Tensor>)>
|
||||
{
|
||||
($"rodLayer1", rodLayer1),
|
||||
($"softmax", nn.Softmax(1))
|
||||
};
|
||||
|
||||
layers = Sequential(modules);
|
||||
|
||||
RegisterComponents();
|
||||
}
|
||||
@@ -113,26 +109,58 @@ public class RodNet : Module<Tensor, Tensor, Tensor, Tensor, Tensor>
|
||||
dst[i] /= sum;
|
||||
}
|
||||
}
|
||||
|
||||
internal static int GetRodState(RodInput input)
|
||||
public record NetInput(double dist, int fish_label);
|
||||
public static NetInput? GeometryProcessing(RodInput input)
|
||||
{
|
||||
double[] pred = ComputeScores(input);
|
||||
double a, b, v0, u, v, h;
|
||||
|
||||
return Array.IndexOf(pred, pred.Max());
|
||||
}
|
||||
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;
|
||||
|
||||
public static double[] ComputeScores(RodInput input)
|
||||
{
|
||||
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
|
||||
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;
|
||||
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));
|
||||
|
||||
int fish_label = input.fish_label;
|
||||
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;
|
||||
|
||||
double[] logits = new double[3];
|
||||
for (int i = 0; i < 3; i++)
|
||||
@@ -149,113 +177,73 @@ public class RodNet : Module<Tensor, Tensor, Tensor, Tensor, Tensor>
|
||||
|
||||
internal int GetRodState_Torch(RodInput input)
|
||||
{
|
||||
using var _ = no_grad();
|
||||
Tensor outputTensor = ComputeScores_Torch(input);
|
||||
NetInput? netInput = GeometryProcessing(input);
|
||||
if (netInput is null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
Tensor outputTensor = ComputeScores_Torch(netInput);
|
||||
|
||||
var max = argmax(outputTensor);
|
||||
return (int)max.item<long>();
|
||||
}
|
||||
|
||||
public Tensor ComputeScores_Torch(RodInput input)
|
||||
public Tensor ComputeScores_Torch(NetInput netInput)
|
||||
{
|
||||
using var _ = no_grad();
|
||||
this.SetWeightsManually();
|
||||
double dist = netInput.dist;
|
||||
int fish_label = netInput.fish_label;
|
||||
|
||||
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
|
||||
Tensor inputTensor = cat([tensor(new double[,] { { dist } }, dtype: ScalarType.Float64),
|
||||
tensor(new int[,] { {fish_label } }, dtype: ScalarType.Int32)]).T;
|
||||
var outputTensor = forward(inputTensor);
|
||||
|
||||
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);
|
||||
outputTensor[0][0] = outputTensor[0][0] - RodNet.offset[fish_label];
|
||||
|
||||
var logits = forward(fishLabel, uv, y0z0t, h_);
|
||||
var output = PostProcess(logits, fishLabel);
|
||||
|
||||
return output;
|
||||
return outputTensor;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用时直接赋值已知权重
|
||||
/// </summary>
|
||||
public void SetWeightsManually()
|
||||
public override Tensor forward(Tensor input)
|
||||
{
|
||||
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);
|
||||
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();
|
||||
}
|
||||
|
||||
public override Tensor forward(Tensor fishLabel, Tensor uv, Tensor y0z0t, Tensor h)
|
||||
public void SetWeightsManually(Tensor weight, Tensor 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;
|
||||
embedding1.weight = new Parameter(weight);
|
||||
embedding2.weight = new Parameter(bias);
|
||||
}
|
||||
|
||||
public Tensor PostProcess(Tensor logits, Tensor fishLabel)
|
||||
public override Tensor forward(Tensor input)
|
||||
{
|
||||
var x_softmax = torch.nn.functional.softmax(logits, 1);
|
||||
var splitInput = input.split([1, 1], dim: 1);
|
||||
var dist = splitInput[0];
|
||||
var fish_label = splitInput[1].to(ScalarType.Int32).flatten();
|
||||
|
||||
Tensor x_offset = tensor(fishLabel.data<int>().Select(l => RodNet.offset[l]).ToArray());
|
||||
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>()));
|
||||
|
||||
x_softmax[torch.arange(x_offset.shape[0]), 0] -= x_offset;
|
||||
return x_softmax;
|
||||
}
|
||||
linear.weight = new Parameter(embed1.T);
|
||||
linear.bias = new Parameter(embed2);
|
||||
|
||||
/// <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);
|
||||
return linear.forward(dist);
|
||||
}
|
||||
}
|
||||
@@ -919,83 +919,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
@@ -1431,7 +1354,7 @@
|
||||
"nameEn": "candace",
|
||||
"type": "character",
|
||||
"name": "坎蒂丝",
|
||||
"hp": 11,
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "水元素",
|
||||
"weapon": "长柄武器",
|
||||
@@ -1646,7 +1569,7 @@
|
||||
"nameEn": "neuvillette",
|
||||
"type": "character",
|
||||
"name": "那维莱特",
|
||||
"hp": 11,
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "水元素",
|
||||
"weapon": "法器",
|
||||
@@ -2930,77 +2853,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
@@ -3290,7 +3142,7 @@
|
||||
"nameEn": "beidou",
|
||||
"type": "character",
|
||||
"name": "北斗",
|
||||
"hp": 11,
|
||||
"hp": 10,
|
||||
"energy": 3,
|
||||
"element": "雷元素",
|
||||
"weapon": "双手剑",
|
||||
@@ -3480,7 +3332,7 @@
|
||||
"id": 1104,
|
||||
"nameEn": "electro",
|
||||
"type": "雷元素",
|
||||
"count": 3
|
||||
"count": 4
|
||||
},
|
||||
{
|
||||
"id": 1110,
|
||||
@@ -4612,83 +4464,6 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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",
|
||||
@@ -4916,7 +4691,7 @@
|
||||
"nameEn": "albedo",
|
||||
"type": "character",
|
||||
"name": "阿贝多",
|
||||
"hp": 12,
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "岩元素",
|
||||
"weapon": "单手剑",
|
||||
@@ -5775,7 +5550,7 @@
|
||||
"nameEn": "baizhu",
|
||||
"type": "character",
|
||||
"name": "白术",
|
||||
"hp": 11,
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "草元素",
|
||||
"weapon": "法器",
|
||||
@@ -6804,7 +6579,7 @@
|
||||
"nameEn": "hydro_hilichurl_rogue",
|
||||
"type": "character",
|
||||
"name": "丘丘水行游侠",
|
||||
"hp": 11,
|
||||
"hp": 10,
|
||||
"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(textMat);
|
||||
text = _pickTextInference.Inference(TextInferenceFactory.PreProcessForInference(textMat));
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
@@ -6,7 +6,6 @@ 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;
|
||||
@@ -16,46 +15,54 @@ namespace BetterGenshinImpact.GameTask.Common.Job;
|
||||
|
||||
public class ExitAndReloginJob
|
||||
{
|
||||
private AutoWoodAssets _assets = AutoWoodAssets.Instance;
|
||||
private AutoWoodAssets _assets;
|
||||
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
|
||||
{
|
||||
// 即使失败也继续退出流程
|
||||
}
|
||||
|
||||
// 等待菜单界面出现
|
||||
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);
|
||||
// 点击退出按钮
|
||||
GameCaptureRegion.GameRegionClick((size, scale) => (50 * scale, size.Height - 50 * scale));
|
||||
await Delay(500, 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 })
|
||||
@@ -65,48 +72,45 @@ public class ExitAndReloginJob
|
||||
Logger.LogInformation("退出重登启用 B 服模式");
|
||||
}
|
||||
|
||||
// 等待进入游戏按钮出现并点击
|
||||
var enterGameAppear = await NewRetry.WaitForElementAppear(
|
||||
_assets.EnterGameRo,
|
||||
() => { },
|
||||
ct,
|
||||
50,
|
||||
1000
|
||||
);
|
||||
if (enterGameAppear)
|
||||
// 进入游戏检测
|
||||
var clickCnt = 0;
|
||||
for (var i = 0; i < 50; i++)
|
||||
{
|
||||
// 点击进入游戏按钮直到它消失
|
||||
await NewRetry.WaitForElementDisappear(
|
||||
_assets.EnterGameRo,
|
||||
() => GameCaptureRegion.GameRegion1080PPosClick(955, 666),
|
||||
ct,
|
||||
10,
|
||||
1000
|
||||
);
|
||||
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);
|
||||
}
|
||||
else
|
||||
|
||||
if (clickCnt == 0)
|
||||
{
|
||||
throw new RetryException("未检测进入游戏界面");
|
||||
}
|
||||
|
||||
// 等待主界面出现
|
||||
var mainUiFound = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PaimonMenuRo,
|
||||
() => { },
|
||||
ct,
|
||||
50,
|
||||
1000
|
||||
);
|
||||
|
||||
if (mainUiFound)
|
||||
for (var i = 0; i < 50; i++)
|
||||
{
|
||||
Logger.LogInformation("退出重新登录结束!");
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("未检测到主界面,登录可能未完成");
|
||||
if (Bv.IsInMainUi(CaptureToRectArea()))
|
||||
{
|
||||
Logger.LogInformation("退出重新登录结束!");
|
||||
break;
|
||||
}
|
||||
await Delay(1000, ct);
|
||||
}
|
||||
await Delay(500, ct);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -82,40 +82,35 @@ internal class GoToSereniteaPotTask
|
||||
// 进入 壶
|
||||
await ChangeCountryForce("尘歌壶", ct);
|
||||
|
||||
// 若未找到 ElementAssets.Instance.SereniteaPotRo 就是已经在尘歌壶了
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
|
||||
// 若未找到 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);
|
||||
}
|
||||
else
|
||||
{
|
||||
dongTianName = "";
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "未识别到洞天名称");
|
||||
}
|
||||
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
var sereniteaPotHomeIcon = ra.Find(ElementAssets.Instance.SereniteaPotHomeRo);
|
||||
if (!sereniteaPotHomeIcon.IsExist())
|
||||
{
|
||||
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);
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "住宅图标未找到,调整地图缩放至3.0。");
|
||||
await new Core.Script.Dependence.Genshin().SetBigMapZoomLevel(3.0);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -146,6 +141,8 @@ internal class GoToSereniteaPotTask
|
||||
await NewRetry.WaitForAction(() => Bv.IsInMainUi(CaptureToRectArea()), ct);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 寻找阿圆并靠近
|
||||
private async Task FindAYuan(CancellationToken ct)
|
||||
{
|
||||
@@ -300,18 +297,18 @@ internal class GoToSereniteaPotTask
|
||||
if (numberBtn.IsExist())
|
||||
{
|
||||
numberBtn.Move();
|
||||
await Delay(600, ct);//减慢速度,设备差异导致的延迟
|
||||
await Delay(300, ct);
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
await Delay(600, ct);
|
||||
await Delay(300, ct);
|
||||
numberBtn.MoveTo(ra.Width/7,0);//moveby会超出边界,改用MoveTo
|
||||
await Delay(600, ct);
|
||||
await Delay(300, ct);
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
}
|
||||
|
||||
await Delay(600, ct);
|
||||
await Delay(300, ct);
|
||||
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
|
||||
await Delay(500, ct);
|
||||
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
|
||||
await Delay(600, ct);
|
||||
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenPaimonMenu); // ESC
|
||||
}
|
||||
|
||||
private async Task GetReward(CancellationToken ct)
|
||||
@@ -374,6 +371,7 @@ internal class GoToSereniteaPotTask
|
||||
if (shopOption == TalkOptionRes.FoundAndClick)
|
||||
{
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "购买商店物品");
|
||||
|
||||
await Delay(500, ct);
|
||||
// 购买的物品清单
|
||||
var buy = new List<RecognitionObject>();
|
||||
@@ -412,39 +410,18 @@ internal class GoToSereniteaPotTask
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//对比购买成功和buy的数量,如果不等,重试一次
|
||||
var buyCount = 0;
|
||||
var retryBuy= 0;
|
||||
|
||||
// 直接购买最大数量
|
||||
while (retryBuy < 2)
|
||||
foreach (var item in buy)
|
||||
{
|
||||
foreach (var item in buy)
|
||||
var itemRo = CaptureToRectArea().Find(item);
|
||||
if (itemRo.IsExist())
|
||||
{
|
||||
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;
|
||||
Logger.LogInformation("领取尘歌壶奖励:购买 {text} ", item.Name);
|
||||
itemRo.Click();
|
||||
await Delay(600, ct);
|
||||
await BuyMaxNumber(ct);
|
||||
await Delay(1200, ct);//等待购买动画结束
|
||||
}
|
||||
}
|
||||
await Delay(900, ct);
|
||||
|
||||
@@ -4,8 +4,6 @@ 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;
|
||||
|
||||
@@ -14,12 +12,6 @@ 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?>(() =>
|
||||
@@ -29,14 +21,6 @@ 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 = [];
|
||||
@@ -65,14 +49,6 @@ 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++)
|
||||
@@ -85,84 +61,4 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,232 +0,0 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -88,21 +88,21 @@ public partial class StringUtils
|
||||
return int.TryParse(text, out int result) ? result : defaultValue;
|
||||
}
|
||||
|
||||
public static int TryExtractPositiveInt(string text, int defaultValue = -1)
|
||||
public static int TryExtractPositiveInt(string text)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return defaultValue;
|
||||
return -1;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
text = RegexHelper.ExcludeNumberRegex().Replace(text, "");
|
||||
return TryParseInt(text, defaultValue);
|
||||
return int.Parse(text);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return defaultValue;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -335,18 +335,13 @@
|
||||
|
||||
|
||||
<!-- 自动秘境 -->
|
||||
<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>
|
||||
|
||||
<TextBlock Margin="4,0,0,4"
|
||||
FontSize="14"
|
||||
Foreground="{DynamicResource SystemAccentColorPrimaryBrush}"
|
||||
Text="自动秘境" />
|
||||
|
||||
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0">
|
||||
|
||||
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="{Binding SelectedConfig.WeeklyDomainEnabled, Converter={StaticResource InverseBooleanConverter}, Mode=TwoWay}">
|
||||
<ui:CardExpander.Icon>
|
||||
<ui:FontIcon Glyph="" Style="{StaticResource FaFontIconStyle}" />
|
||||
</ui:CardExpander.Icon>
|
||||
@@ -475,8 +470,7 @@
|
||||
</Grid>
|
||||
</StackPanel>
|
||||
</ui:CardExpander>
|
||||
|
||||
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="True">
|
||||
<ui:CardExpander Margin="0,0,0,12" ContentPadding="0" IsExpanded="{Binding SelectedConfig.WeeklyDomainEnabled, Mode=TwoWay}">
|
||||
<ui:CardExpander.Icon>
|
||||
<ui:FontIcon Glyph="" Style="{StaticResource FaFontIconStyle}" />
|
||||
</ui:CardExpander.Icon>
|
||||
@@ -508,7 +502,7 @@
|
||||
</Grid>
|
||||
</ui:CardExpander.Header>
|
||||
<StackPanel>
|
||||
<Grid Margin="52,16,16,16">
|
||||
<Grid Margin="52,16,16,8">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
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"
|
||||
@@ -955,113 +954,20 @@
|
||||
<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="优先使用浓缩树脂,然后使用原粹树脂,其余树脂不使用"
|
||||
Text="循环秘境多少次,输入 0 则为用光所有树脂为止,优先使用浓缩树脂"
|
||||
TextWrapping="Wrap" />
|
||||
<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}" />
|
||||
<ui:TextBox Grid.Row="0"
|
||||
Grid.RowSpan="2"
|
||||
Grid.Column="1"
|
||||
MinWidth="90"
|
||||
Margin="0,0,36,0"
|
||||
Text="{Binding AutoDomainRoundNum, 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,32 +878,6 @@
|
||||
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("-I --source mirrorc");
|
||||
await RunUpdaterAsync("--source mirrorc");
|
||||
}
|
||||
else
|
||||
{
|
||||
await RunUpdaterAsync("-I --source mirrorc-alpha");
|
||||
await RunUpdaterAsync("--source mirrorc-alpha");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ public partial class ScriptRepoWindow
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Toast.Error($"更新失败,可尝试重置仓库后重新更新。失败原因:: {ex.Message}");
|
||||
Toast.Error($"更新失败: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -226,16 +226,15 @@ public partial class CommonSettingsPageViewModel : ViewModel
|
||||
{
|
||||
var zipPath = dialog.FileName;
|
||||
// 删除旧文件夹
|
||||
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPathOld))
|
||||
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
|
||||
{
|
||||
DirectoryHelper.DeleteReadOnlyDirectory(ScriptRepoUpdater.CenterRepoPathOld);
|
||||
DirectoryHelper.DeleteReadOnlyDirectory(ScriptRepoUpdater.CenterRepoPath);
|
||||
}
|
||||
|
||||
ZipFile.ExtractToDirectory(zipPath, ScriptRepoUpdater.ReposPath, true);
|
||||
|
||||
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPathOld))
|
||||
if (Directory.Exists(ScriptRepoUpdater.CenterRepoPath))
|
||||
{
|
||||
DirectoryHelper.CopyDirectory(ScriptRepoUpdater.CenterRepoPathOld, ScriptRepoUpdater.CenterRepoPath);
|
||||
MessageBox.Information("脚本仓库离线包导入成功!");
|
||||
}
|
||||
else
|
||||
|
||||
@@ -31,7 +31,6 @@ 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;
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
{
|
||||
"id": "mirrorc",
|
||||
"name": "Mirror酱",
|
||||
"uri": "mirrorc://BGI?os=win&arch=x64"
|
||||
"uri": "mirrorc://BGI"
|
||||
},
|
||||
{
|
||||
"id": "mirrorc-alpha",
|
||||
"name": "Mirror酱 Alpha",
|
||||
"uri": "mirrorc://BGI?channel=alpha&os=win&arch=x64",
|
||||
"uri": "mirrorc://BGI?channel=alpha",
|
||||
"hidden": true
|
||||
}
|
||||
],
|
||||
|
||||
@@ -130,4 +130,4 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
|
||||
|
||||
## 问题反馈
|
||||
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1053273766](https://qm.qq.com/q/qtocsOXnIQ)
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1036100501](https://qm.qq.com/q/fvRNqEbFyo)
|
||||
@@ -16,8 +16,6 @@ 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()
|
||||
{
|
||||
@@ -25,8 +23,9 @@ public class AvatarClassifyGen
|
||||
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// 只用一个图像
|
||||
List<string> sideImageFiles = [];
|
||||
|
||||
foreach (string imgName in ImgNames)
|
||||
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)
|
||||
{
|
||||
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
|
||||
}
|
||||
|
||||
@@ -23,7 +23,12 @@ public class AvatarClassifyTransparentGen
|
||||
public static void GenAll()
|
||||
{
|
||||
List<string> sideImageFiles = [];
|
||||
List<string> imgNames = AvatarClassifyGen.ImgNames;
|
||||
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)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
|
||||
+2
-3
@@ -1,6 +1,5 @@
|
||||
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
using BetterGenshinImpact.UnitTest.CoreTests.RecognitionTests.OCRTests;
|
||||
using GameTask.Model.GameUI;
|
||||
using OpenCvSharp;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
@@ -53,7 +52,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoArtifactSalvageTests
|
||||
using Mat mat = new Mat(@$"..\..\..\Assets\AutoArtifactSalvage\{screenshot}");
|
||||
|
||||
//
|
||||
var result = GridScreen.GridEnumerator.GetGridItems(mat);
|
||||
var result = AutoArtifactSalvageTask.GetArtifactGridItems(mat);
|
||||
|
||||
//
|
||||
Assert.Equal(4, result.Count());
|
||||
@@ -70,7 +69,7 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoArtifactSalvageTests
|
||||
using Mat mat = new Mat(@$"..\..\..\Assets\AutoArtifactSalvage\ArtifactGrid.png");
|
||||
|
||||
//
|
||||
var result = GridScreen.GridEnumerator.GetGridItems(mat);
|
||||
var result = AutoArtifactSalvageTask.GetArtifactGridItems(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));
|
||||
|
||||
-392
@@ -1,392 +0,0 @@
|
||||
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,16 +1,17 @@
|
||||
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 TorchSharp;
|
||||
using static BetterGenshinImpact.GameTask.AutoFishing.RodNet;
|
||||
using static TorchSharp.torch;
|
||||
|
||||
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
{
|
||||
[Collection("Init Collection")]
|
||||
public partial class RodNetTests
|
||||
public class RodNetTests
|
||||
{
|
||||
public RodNetTests(TorchFixture torch)
|
||||
{
|
||||
@@ -41,8 +42,9 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
RodNet sut = new RodNet();
|
||||
|
||||
//
|
||||
Tensor outputTensor = sut.ComputeScores_Torch(rodInput);
|
||||
double[] pred = RodNet.ComputeScores(rodInput);
|
||||
NetInput netInput = GeometryProcessing(rodInput) ?? throw new NullReferenceException();
|
||||
Tensor outputTensor = sut.ComputeScores_Torch(netInput);
|
||||
double[] pred = ComputeScores(netInput);
|
||||
|
||||
//
|
||||
Assert.Equal((float)pred[0], (float)outputTensor.data<double>()[0]); // 对比时降低精度,差不多就行
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user