Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8a4f7c62e0 | ||
|
|
60eb3c0574 | ||
|
|
dec4d5ac7a | ||
|
|
abbdfdb710 | ||
|
|
39c1a3155f | ||
|
|
384e05d493 | ||
|
|
e5cc8152f6 | ||
|
|
01225eda26 | ||
|
|
aa43c16d81 | ||
|
|
a372c93de9 | ||
|
|
712630acc3 | ||
|
|
d7e0af3a57 | ||
|
|
3408b948b0 | ||
|
|
f6540c8e59 | ||
|
|
d091bfe7d5 | ||
|
|
6f87a0c4d0 | ||
|
|
4787f4f2f9 | ||
|
|
dca965e5f0 | ||
|
|
1d520dc781 | ||
|
|
56d12df1bc | ||
|
|
5bacc495c0 | ||
|
|
9b8aa9e12b | ||
|
|
9664e67d6c |
No files matched your search
@@ -42,6 +42,8 @@ jobs:
|
||||
pick_files: '["BetterGI"]'
|
||||
version_name: ${{ steps.get-version.outputs.version }}
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
os: win
|
||||
arch: x64
|
||||
|
||||
mirrorchyan_exe:
|
||||
runs-on: macos-latest
|
||||
@@ -57,6 +59,4 @@ jobs:
|
||||
owner: babalae
|
||||
repo: better-genshin-impact
|
||||
upload_token: ${{ secrets.MirrorChyanUploadToken }}
|
||||
os: win
|
||||
arch: x64
|
||||
|
||||
@@ -395,6 +395,8 @@ jobs:
|
||||
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
|
||||
@@ -406,5 +408,4 @@ jobs:
|
||||
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.45.3-alpha.1</Version>
|
||||
<Version>0.45.4-alpha.3</Version>
|
||||
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
|
||||
|
||||
@@ -39,6 +39,8 @@ using System.Text.RegularExpressions;
|
||||
using BetterGenshinImpact.GameTask.AutoArtifactSalvage;
|
||||
using System.Collections.ObjectModel;
|
||||
using BetterGenshinImpact.Core.Script.Dependence;
|
||||
using BetterGenshinImpact.GameTask.AutoDomain.Model;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using Compunet.YoloSharp;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
@@ -182,7 +184,7 @@ public class AutoDomainTask : ISoloTask
|
||||
|
||||
// 5. 快速领取奖励并判断是否有下一轮
|
||||
Logger.LogInformation("自动秘境:{Text}", "5. 领取奖励");
|
||||
if (!GettingTreasure(_taskParam.DomainRoundNum == 9999, i == _taskParam.DomainRoundNum - 1))
|
||||
if (!await GettingTreasure(i == _taskParam.DomainRoundNum - 1))
|
||||
{
|
||||
if (i == _taskParam.DomainRoundNum - 1)
|
||||
{
|
||||
@@ -997,7 +999,7 @@ public class AutoDomainTask : ISoloTask
|
||||
Simulation.SendInput.Mouse.MoveMouseBy(moveAngle, 0);
|
||||
}
|
||||
|
||||
Sleep(100);
|
||||
Sleep(100, _ct);
|
||||
}
|
||||
|
||||
Logger.LogInformation("锁定东方向视角线程结束");
|
||||
@@ -1008,64 +1010,51 @@ public class AutoDomainTask : ISoloTask
|
||||
/// <summary>
|
||||
/// 领取奖励
|
||||
/// </summary>
|
||||
/// <param name="recognizeResin">是否识别树脂</param>
|
||||
/// <param name="isLastTurn">是否最后一轮</param>
|
||||
private bool GettingTreasure(bool recognizeResin, bool isLastTurn)
|
||||
private async Task<bool> GettingTreasure(bool isLastTurn)
|
||||
{
|
||||
// 等待窗口弹出
|
||||
Sleep(1500, _ct);
|
||||
await Delay(300, _ct);
|
||||
|
||||
// 优先使用浓缩树脂
|
||||
var retryTimes = 0;
|
||||
while (true)
|
||||
// OCR 弹出框
|
||||
bool chooseResinPrompt = await NewRetry.WaitForAction(() =>
|
||||
{
|
||||
retryTimes++;
|
||||
if (retryTimes > 3)
|
||||
{
|
||||
Logger.LogInformation("没有浓缩树脂了");
|
||||
break;
|
||||
}
|
||||
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));
|
||||
return regionList.Any(t => t.Text.Contains("石化古树"));
|
||||
}, _ct, 10, 500);
|
||||
Debug.WriteLine("识别到选择树脂页");
|
||||
|
||||
var useCondensedResinRa = CaptureToRectArea().Find(AutoFightAssets.Instance.UseCondensedResinRa);
|
||||
if (!useCondensedResinRa.IsEmpty())
|
||||
{
|
||||
useCondensedResinRa.Click();
|
||||
// 点两下 #224 #218
|
||||
// 解决水龙王按下左键后没松开,然后后续点击按下就没反应了
|
||||
Sleep(400, _ct);
|
||||
useCondensedResinRa.Click();
|
||||
break;
|
||||
}
|
||||
|
||||
Sleep(800, _ct);
|
||||
if (!chooseResinPrompt)
|
||||
{
|
||||
throw new NormalEndException("未检测到选取树脂界面,可能是背包物品已满。");
|
||||
}
|
||||
|
||||
|
||||
await Delay(800, _ct);
|
||||
// 弹出框
|
||||
using var ra2 = CaptureToRectArea();
|
||||
// 识别树脂状况
|
||||
var resinStatus = ResinStatus.RecogniseFromRegion(ra2);
|
||||
resinStatus.Print(Logger);
|
||||
|
||||
if (resinStatus.CondensedResinCount > 0)
|
||||
{
|
||||
PressUseResin(ra2, "浓缩树脂");
|
||||
resinStatus.CondensedResinCount -= 1;
|
||||
}
|
||||
else if (resinStatus.OriginalResinCount >= 20)
|
||||
{
|
||||
PressUseResin(ra2, "原粹树脂");
|
||||
resinStatus.OriginalResinCount -= 20;
|
||||
}
|
||||
|
||||
|
||||
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())
|
||||
@@ -1081,14 +1070,7 @@ public class AutoDomainTask : ISoloTask
|
||||
}
|
||||
}
|
||||
|
||||
if (!recognizeResin)
|
||||
{
|
||||
confirmRectArea.Click();
|
||||
return true;
|
||||
}
|
||||
|
||||
var (condensedResinCount, fragileResinCount) = GetRemainResinStatus();
|
||||
if (condensedResinCount == 0 && fragileResinCount < 20)
|
||||
if (resinStatus.CondensedResinCount <= 0 && resinStatus.OriginalResinCount < 20)
|
||||
{
|
||||
// 没有体力了退出
|
||||
var exitRectArea = ra.Find(AutoFightAssets.Instance.ExitRa);
|
||||
@@ -1112,6 +1094,50 @@ public class AutoDomainTask : ISoloTask
|
||||
throw new NormalEndException("未检测到秘境结束,可能是背包物品已满。");
|
||||
}
|
||||
|
||||
private void 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));
|
||||
var resinKey = regionList.FirstOrDefault(t => t.Text.Contains(resinName));
|
||||
if (resinKey != null)
|
||||
{
|
||||
// 找到树脂名称对应的按键,关键词为使用,是同一行的(高度相交)
|
||||
var useList = regionList.Where(t => t.Text.Contains("使用")).ToList();
|
||||
if (useList.Count != 0)
|
||||
{
|
||||
// 找到使用按键
|
||||
var useKey = useList.FirstOrDefault(t => t.X > ra.Width / 2 && IsHeightOverlap(t, resinKey));
|
||||
if (useKey != null)
|
||||
{
|
||||
// 点击使用
|
||||
useKey.Click();
|
||||
Logger.LogInformation("自动秘境:使用 {ResinName}", resinName);
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("自动秘境:未找到 {ResinName} 的使用按键", resinName);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("自动秘境:未找到 {ResinName} 的使用按键", resinName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取剩余树脂状态
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
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;
|
||||
originalResinTopIconRa.RegionOfInterest = new Rect(captureArea.Width - (int)(356 * assetScale), (int)(37 * assetScale), (int)(100 * assetScale), (int)(21 * assetScale));
|
||||
var originalResinRes = region.Find(originalResinTopIconRa);
|
||||
if (originalResinRes.IsEmpty())
|
||||
{
|
||||
throw new Exception("未找到原粹树脂图标");
|
||||
}
|
||||
|
||||
// 找出 icon 的位置 + 30 ~ w-267 就是原粹树脂的数字
|
||||
var originalResinCountRect = new Rect(originalResinRes.X + 30, originalResinTopIconRa.RegionOfInterest.Y,
|
||||
captureArea.Width - (originalResinRes.X + 30) - (int)(267 * assetScale), originalResinTopIconRa.RegionOfInterest.Height);
|
||||
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);
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.0 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 456 B |
@@ -26,8 +26,11 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
|
||||
// 树脂状态
|
||||
public RecognitionObject CondensedResinCountRa;
|
||||
|
||||
public RecognitionObject FragileResinCountRa;
|
||||
// 自动秘境
|
||||
// public RecognitionObject LockIconRa; // 锁定辅助图标
|
||||
public RecognitionObject CondensedResinTopIconRa;
|
||||
public RecognitionObject OriginalResinTopIconRa;
|
||||
|
||||
public Dictionary<string, string> AvatarCostumeMap;
|
||||
|
||||
@@ -245,5 +248,31 @@ public class AutoFightAssets : BaseAssets<AutoFightAssets>
|
||||
RegionOfInterest = new Rect(CaptureRect.Width / 2, CaptureRect.Height / 3 * 2, CaptureRect.Width / 2, CaptureRect.Height / 3),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
|
||||
// 自动秘境
|
||||
// LockIconRa = new RecognitionObject
|
||||
// {
|
||||
// Name = "LockIcon",
|
||||
// RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
// TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "lock_icon.png"),
|
||||
// RegionOfInterest = new Rect(CaptureRect.Width - (int)(215 * AssetScale), 0, (int)(215 * AssetScale), (int)(80 * AssetScale)),
|
||||
// DrawOnWindow = false
|
||||
// }.InitTemplate();
|
||||
CondensedResinTopIconRa = new RecognitionObject
|
||||
{
|
||||
Name = "CondensedResinTopIcon",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "condensed_resin_top_icon.png"),
|
||||
RegionOfInterest = new Rect((int)(1270 * AssetScale), (int)(25 * AssetScale), (int)(520 * AssetScale), (int)(45 * AssetScale)),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
OriginalResinTopIconRa = new RecognitionObject
|
||||
{
|
||||
Name = "OriginalResinTopIcon",
|
||||
RecognitionType = RecognitionTypes.TemplateMatch,
|
||||
TemplateImageMat = GameTaskManager.LoadAssetImage("AutoFight", "original_resin_top_icon.png"),
|
||||
RegionOfInterest = new Rect(0, (int)(37 * AssetScale), CaptureRect.Width, (int)(21 * AssetScale)),
|
||||
DrawOnWindow = false
|
||||
}.InitTemplate();
|
||||
}
|
||||
}
|
||||
@@ -1868,5 +1868,35 @@
|
||||
"nameEn": "Ifa",
|
||||
"skillCD": 7.5,
|
||||
"weapon": "10"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"丝柯克",
|
||||
"Skirk",
|
||||
"丝柯可",
|
||||
"斯柯克"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000114",
|
||||
"name": "丝柯克",
|
||||
"nameEn": "SkirkNew",
|
||||
"skillCD": 8,
|
||||
"weapon": "1"
|
||||
},
|
||||
{
|
||||
"alias": [
|
||||
"塔利雅",
|
||||
"Dahlia",
|
||||
"塔利亚",
|
||||
"塔丽雅",
|
||||
"主祭",
|
||||
"助祭"
|
||||
],
|
||||
"burstCD": 15,
|
||||
"id": "10000115",
|
||||
"name": "塔利雅",
|
||||
"nameEn": "Dahlia",
|
||||
"skillCD": 9,
|
||||
"weapon": "1"
|
||||
}
|
||||
]
|
||||
@@ -21,15 +21,15 @@ public class BigFishType
|
||||
|
||||
// public static readonly BigFishType FormaloRay = new("formalo ray", "fake fly bait", "佛玛洛鳐");
|
||||
// public static readonly BigFishType DivdaRay = new("divda ray", "fake fly bait", "迪芙妲鳐");
|
||||
public static readonly BigFishType Angler = new("angler", "sugardew bait", "角鲀", 8);
|
||||
public static readonly BigFishType AxeMarlin = new("axe marlin", "sugardew bait", "斧枪鱼", 9);
|
||||
public static readonly BigFishType HeartfeatherBass = new("heartfeather bass", "sour bait", "心羽鲈", 10);
|
||||
public static readonly BigFishType MaintenanceMek = new("maintenance mek", "flashing maintenance mek bait", "维护机关", 11);
|
||||
public static readonly BigFishType Unihornfish = new("unihornfish", "spinelgrain bait", "独角鱼", 11);
|
||||
public static readonly BigFishType Sunfish = new("sunfish", "spinelgrain bait", "翻车鲀", 8);
|
||||
public static readonly BigFishType Rapidfish = new("rapidfish", "spinelgrain bait", "斗士急流鱼", 10);
|
||||
public static readonly BigFishType PhonyUnihornfish = new("phony unihornfish", "emberglow bait", "燃素独角鱼", 11);
|
||||
public static readonly BigFishType MagmaRapidfish = new("magma rapidfish", "emberglow bait", "炽岩斗士急流鱼", 10);
|
||||
public static readonly BigFishType Angler = new("angler", "sugardew bait", "角鲀", 7);
|
||||
public static readonly BigFishType AxeMarlin = new("axe marlin", "sugardew bait", "斧枪鱼", 8);
|
||||
public static readonly BigFishType HeartfeatherBass = new("heartfeather bass", "sour bait", "心羽鲈", 9);
|
||||
public static readonly BigFishType MaintenanceMek = new("maintenance mek", "flashing maintenance mek bait", "维护机关", 10);
|
||||
public static readonly BigFishType Unihornfish = new("unihornfish", "spinelgrain bait", "独角鱼", 10);
|
||||
public static readonly BigFishType Sunfish = new("sunfish", "spinelgrain bait", "翻车鲀", 7);
|
||||
public static readonly BigFishType Rapidfish = new("rapidfish", "spinelgrain bait", "斗士急流鱼", 9);
|
||||
public static readonly BigFishType PhonyUnihornfish = new("phony unihornfish", "emberglow bait", "燃素独角鱼", 10);
|
||||
public static readonly BigFishType MagmaRapidfish = new("magma rapidfish", "emberglow bait", "炽岩斗士急流鱼", 9);
|
||||
|
||||
|
||||
public static IEnumerable<BigFishType> Values
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using static TorchSharp.torch;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
|
||||
public record RodInput
|
||||
{
|
||||
|
||||
@@ -37,8 +37,14 @@ namespace BetterGenshinImpact.GameTask.AutoFishing;
|
||||
/// tmd 今天我意识到 XXXX可不就是XXXX
|
||||
///
|
||||
/// 哦 到这一步以后剩下的就很弱智了 远了挪近一点 近了挪远一点 调调参差不多得了
|
||||
///
|
||||
/// *后来又新增了一些访谈内容:
|
||||
///
|
||||
/// 额 总之就是要求不能把不咬钩的识别成咬钩的 但是咬钩的可以识别成不咬钩的
|
||||
///
|
||||
/// 然后就可视化一下onehot在不同距离的结果 加一个offset使得模型输出的结果在保证可以predict距离正好的结果的同时距离范围尽可能小
|
||||
/// </summary>
|
||||
public class RodNet : Module<Tensor, Tensor>
|
||||
public class RodNet : Module<Tensor, Tensor, Tensor, Tensor, Tensor>
|
||||
{
|
||||
const double alpha = 1734.34 / 2.5;
|
||||
// fitted parameters
|
||||
@@ -75,23 +81,21 @@ public class RodNet : Module<Tensor, Tensor>
|
||||
|
||||
static readonly double[] offset = { 0.8, 0.4, 0.35, 0.35, 0.6, 0.3, 0.3, 0.8, 0.8, 0.8, 0.8 };
|
||||
|
||||
private readonly Module<Tensor, Tensor> layers;
|
||||
private Parameter thetaParameter;
|
||||
private Parameter bParameter;
|
||||
private Parameter dzParameter;
|
||||
private Parameter hCoeffParameter;
|
||||
|
||||
public RodNet() : base("RodNet")
|
||||
{
|
||||
var weight = tensor(RodNet.weight, ScalarType.Float64);
|
||||
var bias = tensor(RodNet.bias, ScalarType.Float64);
|
||||
long num_embeddings = RodNet.weight.GetLength(0);
|
||||
long embedding_dim = 3;
|
||||
|
||||
RodLayer1 rodLayer1 = new RodLayer1(num_embeddings: weight.shape[0], embedding_dim: weight.shape[1], input_dim: 3, output_dim: 3);
|
||||
rodLayer1.SetWeightsManually(weight, bias);
|
||||
this.thetaParameter = new Parameter(torch.randn(num_embeddings, embedding_dim, dtype: ScalarType.Float64));
|
||||
this.bParameter = new Parameter(torch.randn(num_embeddings, embedding_dim, dtype: ScalarType.Float64));
|
||||
|
||||
var modules = new List<(string, Module<Tensor, Tensor>)>
|
||||
{
|
||||
($"rodLayer1", rodLayer1),
|
||||
($"softmax", nn.Softmax(1))
|
||||
};
|
||||
|
||||
layers = Sequential(modules);
|
||||
this.dzParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
|
||||
this.hCoeffParameter = new Parameter(torch.zeros(num_embeddings, 1, dtype: ScalarType.Float64));
|
||||
|
||||
RegisterComponents();
|
||||
}
|
||||
@@ -109,58 +113,26 @@ public class RodNet : Module<Tensor, Tensor>
|
||||
dst[i] /= sum;
|
||||
}
|
||||
}
|
||||
public record NetInput(double dist, int fish_label);
|
||||
public static NetInput? GeometryProcessing(RodInput input)
|
||||
|
||||
internal static int GetRodState(RodInput input)
|
||||
{
|
||||
double a, b, v0, u, v, h;
|
||||
double[] pred = ComputeScores(input);
|
||||
|
||||
a = (input.rod_x2 - input.rod_x1) / 2 / alpha;
|
||||
b = (input.rod_y2 - input.rod_y1) / 2 / alpha;
|
||||
h = (input.fish_y2 - input.fish_y1) / 2 / alpha;
|
||||
return Array.IndexOf(pred, pred.Max());
|
||||
}
|
||||
|
||||
if (a < b)
|
||||
{
|
||||
b = Math.Sqrt(a * b);
|
||||
a = b + 1e-6;
|
||||
}
|
||||
public static double[] ComputeScores(RodInput input)
|
||||
{
|
||||
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
|
||||
|
||||
v0 = (288 - (input.rod_y1 + input.rod_y2) / 2) / alpha;
|
||||
|
||||
u = (input.fish_x1 + input.fish_x2 - input.rod_x1 - input.rod_x2) / 2 / alpha;
|
||||
v = (288 - (input.fish_y1 + input.fish_y2) / 2) / alpha;
|
||||
v -= h * h_coeff[input.fish_label];
|
||||
|
||||
double y0, z0, t;
|
||||
double x, y, dist;
|
||||
|
||||
y0 = Math.Sqrt(Math.Pow(a, 4) - b * b + a * a * (1 - b * b + v0 * v0)) / (a * a);
|
||||
z0 = b / (a * a);
|
||||
t = a * a * (y0 * b + v0) / (a * a - b * b);
|
||||
|
||||
x = u * (z0 + dz[input.fish_label]) * Math.Sqrt(1 + t * t) / (t - v);
|
||||
y = (z0 + dz[input.fish_label]) * (1 + t * v) / (t - v);
|
||||
dist = Math.Sqrt(x * x + (y - y0) * (y - y0));
|
||||
|
||||
return new NetInput(dist, input.fish_label);
|
||||
}
|
||||
|
||||
internal static int GetRodState(RodInput input)
|
||||
{
|
||||
NetInput? netInput = GeometryProcessing(input);
|
||||
if (netInput is null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
double[] pred = ComputeScores(netInput);
|
||||
|
||||
return Array.IndexOf(pred, pred.Max());
|
||||
}
|
||||
|
||||
public static double[] ComputeScores(NetInput netInput)
|
||||
{
|
||||
double dist = netInput.dist;
|
||||
int fish_label = netInput.fish_label;
|
||||
int fish_label = input.fish_label;
|
||||
|
||||
double[] logits = new double[3];
|
||||
for (int i = 0; i < 3; i++)
|
||||
@@ -177,73 +149,113 @@ public class RodNet : Module<Tensor, Tensor>
|
||||
|
||||
internal int GetRodState_Torch(RodInput input)
|
||||
{
|
||||
NetInput? netInput = GeometryProcessing(input);
|
||||
if (netInput is null)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
Tensor outputTensor = ComputeScores_Torch(netInput);
|
||||
using var _ = no_grad();
|
||||
Tensor outputTensor = ComputeScores_Torch(input);
|
||||
|
||||
var max = argmax(outputTensor);
|
||||
return (int)max.item<long>();
|
||||
}
|
||||
|
||||
public Tensor ComputeScores_Torch(NetInput netInput)
|
||||
public Tensor ComputeScores_Torch(RodInput input)
|
||||
{
|
||||
double dist = netInput.dist;
|
||||
int fish_label = netInput.fish_label;
|
||||
using var _ = no_grad();
|
||||
this.SetWeightsManually();
|
||||
|
||||
Tensor inputTensor = cat([tensor(new double[,] { { dist } }, dtype: ScalarType.Float64),
|
||||
tensor(new int[,] { {fish_label } }, dtype: ScalarType.Int32)]).T;
|
||||
var outputTensor = forward(inputTensor);
|
||||
var (y0, z0, t, u, v, h) = GetRodStatePreProcess(input);
|
||||
|
||||
outputTensor[0][0] = outputTensor[0][0] - RodNet.offset[fish_label];
|
||||
Tensor fishLabel = tensor(new double[] { input.fish_label }, dtype: ScalarType.Int32);
|
||||
Tensor uv = tensor(new double[,] { { u, v } }, dtype: ScalarType.Float64);
|
||||
Tensor y0z0t = tensor(new double[,] { { y0, z0, t } }, dtype: ScalarType.Float64);
|
||||
Tensor h_ = tensor(new double[,] { { h } }, dtype: ScalarType.Float64);
|
||||
|
||||
return outputTensor;
|
||||
var logits = forward(fishLabel, uv, y0z0t, h_);
|
||||
var output = PostProcess(logits, fishLabel);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
public override Tensor forward(Tensor input)
|
||||
/// <summary>
|
||||
/// 使用时直接赋值已知权重
|
||||
/// </summary>
|
||||
public void SetWeightsManually()
|
||||
{
|
||||
return layers.forward(input);
|
||||
}
|
||||
}
|
||||
|
||||
public class RodLayer1 : Module<Tensor, Tensor>
|
||||
{
|
||||
private readonly Embedding embedding1;
|
||||
private readonly Embedding embedding2;
|
||||
private readonly Linear linear;
|
||||
public RodLayer1(long num_embeddings, long embedding_dim, long input_dim, long output_dim)
|
||||
: base("RodLinear")
|
||||
{
|
||||
embedding1 = torch.nn.Embedding(num_embeddings, embedding_dim);
|
||||
embedding2 = torch.nn.Embedding(num_embeddings, embedding_dim);
|
||||
linear = torch.nn.Linear(input_dim, output_dim);
|
||||
|
||||
RegisterComponents();
|
||||
var weightTensor = tensor(RodNet.weight, ScalarType.Float64);
|
||||
var biasTensor = tensor(RodNet.bias, ScalarType.Float64);
|
||||
var dzTensor = tensor(RodNet.dz, ScalarType.Float64).reshape([RodNet.dz.Length, 1]);
|
||||
var h_coeffTensor = tensor(RodNet.h_coeff, ScalarType.Float64).reshape([RodNet.h_coeff.Length, 1]);
|
||||
this.thetaParameter = new Parameter(weightTensor);
|
||||
this.bParameter = new Parameter(biasTensor);
|
||||
this.dzParameter = new Parameter(dzTensor);
|
||||
this.hCoeffParameter = new Parameter(h_coeffTensor);
|
||||
}
|
||||
|
||||
public void SetWeightsManually(Tensor weight, Tensor bias)
|
||||
public override Tensor forward(Tensor fishLabel, Tensor uv, Tensor y0z0t, Tensor h)
|
||||
{
|
||||
embedding1.weight = new Parameter(weight);
|
||||
embedding2.weight = new Parameter(bias);
|
||||
var uvSplit = uv.split([1, 1], dim: 1);
|
||||
Tensor u = uvSplit[0];
|
||||
Tensor v = uvSplit[1];
|
||||
|
||||
var y0z0tSplit = y0z0t.split([1, 1, 1], dim: 1);
|
||||
Tensor y0 = y0z0tSplit[0];
|
||||
Tensor z0 = y0z0tSplit[1];
|
||||
Tensor t = y0z0tSplit[2];
|
||||
|
||||
v = v - h * hCoeffParameter[fishLabel];
|
||||
|
||||
Tensor x, y, dist;
|
||||
|
||||
var dz = dzParameter[fishLabel];
|
||||
x = u * (z0 + dz) * torch.sqrt(1 + t * t) / (t - v);
|
||||
y = (z0 + dz) * (1 + t * v) / (t - v);
|
||||
dist = torch.sqrt(x * x + (y - y0) * (y - y0));
|
||||
|
||||
Tensor logits = this.thetaParameter[fishLabel] * dist + this.bParameter[fishLabel];
|
||||
|
||||
return logits;
|
||||
}
|
||||
|
||||
public override Tensor forward(Tensor input)
|
||||
public Tensor PostProcess(Tensor logits, Tensor fishLabel)
|
||||
{
|
||||
var splitInput = input.split([1, 1], dim: 1);
|
||||
var dist = splitInput[0];
|
||||
var fish_label = splitInput[1].to(ScalarType.Int32).flatten();
|
||||
var x_softmax = torch.nn.functional.softmax(logits, 1);
|
||||
|
||||
var embed1 = embedding1.forward(fish_label);
|
||||
//Console.WriteLine(String.Join(",", embed1.data<double>()));
|
||||
var embed2 = embedding2.forward(fish_label);
|
||||
//Console.WriteLine(String.Join(",", embed2.data<double>()));
|
||||
Tensor x_offset = tensor(fishLabel.data<int>().Select(l => RodNet.offset[l]).ToArray());
|
||||
|
||||
linear.weight = new Parameter(embed1.T);
|
||||
linear.bias = new Parameter(embed2);
|
||||
x_softmax[torch.arange(x_offset.shape[0]), 0] -= x_offset;
|
||||
return x_softmax;
|
||||
}
|
||||
|
||||
return linear.forward(dist);
|
||||
/// <summary>
|
||||
/// 根据rod和fish的坐标计算y0z0t、uv、h
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns>y0, z0, t, u, v, h</returns>
|
||||
public static (double, double, double, double, double, double) GetRodStatePreProcess(RodInput input)
|
||||
{
|
||||
/*
|
||||
* 以下为hutaofisher代码中关于部分变量的意义的注释
|
||||
# uv: screen coordinate of bbox center of the fish
|
||||
# abv0: rod shape and center coordinate in screen
|
||||
*/
|
||||
double a, b, v0, u, v, h;
|
||||
|
||||
a = (input.rod_x2 - input.rod_x1) / 2 / alpha;
|
||||
b = (input.rod_y2 - input.rod_y1) / 2 / alpha;
|
||||
h = (input.fish_y2 - input.fish_y1) / 2 / alpha;
|
||||
|
||||
if (a < b)
|
||||
{
|
||||
b = Math.Sqrt(a * b);
|
||||
a = b + 1e-6;
|
||||
}
|
||||
v0 = (288 - (input.rod_y1 + input.rod_y2) / 2) / alpha;
|
||||
u = (input.fish_x1 + input.fish_x2 - input.rod_x1 - input.rod_x2) / 2 / alpha;
|
||||
v = (288 - (input.fish_y1 + input.fish_y2) / 2) / alpha;
|
||||
double y0, z0, t;
|
||||
|
||||
y0 = Math.Sqrt(Math.Pow(a, 4) - b * b + a * a * (1 - b * b + v0 * v0)) / (a * a);
|
||||
z0 = b / (a * a);
|
||||
t = a * a * (y0 * b + v0) / (a * a - b * b);
|
||||
|
||||
return (y0, z0, t, u, v, h);
|
||||
}
|
||||
}
|
||||
@@ -919,6 +919,83 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1114,
|
||||
"nameEn": "citlali",
|
||||
"type": "character",
|
||||
"name": "茜特菈莉",
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "冰元素",
|
||||
"weapon": "法器",
|
||||
"skills": [
|
||||
{
|
||||
"nameEn": "shadowstealing_spirit_vessel",
|
||||
"name": "宿灵捕影",
|
||||
"skillTag": [
|
||||
"普通攻击"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1101,
|
||||
"nameEn": "cryo",
|
||||
"type": "冰元素",
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"id": 1109,
|
||||
"nameEn": "unaligned_element",
|
||||
"type": "无色元素",
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "dawnfrost_darkstar",
|
||||
"name": "霜昼黑星",
|
||||
"skillTag": [
|
||||
"元素战技"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1101,
|
||||
"nameEn": "cryo",
|
||||
"type": "冰元素",
|
||||
"count": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "edict_of_entwined_splendor",
|
||||
"name": "诸曜饬令",
|
||||
"skillTag": [
|
||||
"元素爆发"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1101,
|
||||
"nameEn": "cryo",
|
||||
"type": "冰元素",
|
||||
"count": 3
|
||||
},
|
||||
{
|
||||
"id": 1110,
|
||||
"nameEn": "energy",
|
||||
"type": "充能",
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "songs_of_profound_mystery",
|
||||
"name": "奥秘传唱",
|
||||
"skillTag": [
|
||||
"被动技能"
|
||||
],
|
||||
"cost": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1201,
|
||||
"nameEn": "barbara",
|
||||
@@ -1354,7 +1431,7 @@
|
||||
"nameEn": "candace",
|
||||
"type": "character",
|
||||
"name": "坎蒂丝",
|
||||
"hp": 10,
|
||||
"hp": 11,
|
||||
"energy": 2,
|
||||
"element": "水元素",
|
||||
"weapon": "长柄武器",
|
||||
@@ -1569,7 +1646,7 @@
|
||||
"nameEn": "neuvillette",
|
||||
"type": "character",
|
||||
"name": "那维莱特",
|
||||
"hp": 10,
|
||||
"hp": 11,
|
||||
"energy": 2,
|
||||
"element": "水元素",
|
||||
"weapon": "法器",
|
||||
@@ -2853,6 +2930,83 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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
|
||||
},
|
||||
{
|
||||
"id": null,
|
||||
"nameEn": null,
|
||||
"type": null,
|
||||
"count": null
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "fighting_spirit",
|
||||
"name": "战意",
|
||||
"skillTag": [
|
||||
"被动技能"
|
||||
],
|
||||
"cost": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1401,
|
||||
"nameEn": "fischl",
|
||||
@@ -3142,7 +3296,7 @@
|
||||
"nameEn": "beidou",
|
||||
"type": "character",
|
||||
"name": "北斗",
|
||||
"hp": 10,
|
||||
"hp": 11,
|
||||
"energy": 3,
|
||||
"element": "雷元素",
|
||||
"weapon": "双手剑",
|
||||
@@ -3332,7 +3486,7 @@
|
||||
"id": 1104,
|
||||
"nameEn": "electro",
|
||||
"type": "雷元素",
|
||||
"count": 4
|
||||
"count": 3
|
||||
},
|
||||
{
|
||||
"id": 1110,
|
||||
@@ -4464,6 +4618,83 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1511,
|
||||
"nameEn": "chasca",
|
||||
"type": "character",
|
||||
"name": "恰斯卡",
|
||||
"hp": 10,
|
||||
"energy": 2,
|
||||
"element": "风元素",
|
||||
"weapon": "弓",
|
||||
"skills": [
|
||||
{
|
||||
"nameEn": "phantom_feather_flurry",
|
||||
"name": "迷羽流击",
|
||||
"skillTag": [
|
||||
"普通攻击"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1105,
|
||||
"nameEn": "anemo",
|
||||
"type": "风元素",
|
||||
"count": 1
|
||||
},
|
||||
{
|
||||
"id": 1109,
|
||||
"nameEn": "unaligned_element",
|
||||
"type": "无色元素",
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "spirit_reins_shadow_hunt",
|
||||
"name": "灵缰追影",
|
||||
"skillTag": [
|
||||
"元素战技"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1105,
|
||||
"nameEn": "anemo",
|
||||
"type": "风元素",
|
||||
"count": 3
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "soul_reapers_fatal_round",
|
||||
"name": "索魂命袭",
|
||||
"skillTag": [
|
||||
"元素爆发"
|
||||
],
|
||||
"cost": [
|
||||
{
|
||||
"id": 1105,
|
||||
"nameEn": "anemo",
|
||||
"type": "风元素",
|
||||
"count": 3
|
||||
},
|
||||
{
|
||||
"id": 1110,
|
||||
"nameEn": "energy",
|
||||
"type": "充能",
|
||||
"count": 2
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nameEn": "shadowhunt_shell",
|
||||
"name": "追影弹",
|
||||
"skillTag": [
|
||||
"被动技能"
|
||||
],
|
||||
"cost": []
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 1601,
|
||||
"nameEn": "ningguang",
|
||||
@@ -4691,7 +4922,7 @@
|
||||
"nameEn": "albedo",
|
||||
"type": "character",
|
||||
"name": "阿贝多",
|
||||
"hp": 10,
|
||||
"hp": 12,
|
||||
"energy": 2,
|
||||
"element": "岩元素",
|
||||
"weapon": "单手剑",
|
||||
@@ -5550,7 +5781,7 @@
|
||||
"nameEn": "baizhu",
|
||||
"type": "character",
|
||||
"name": "白术",
|
||||
"hp": 10,
|
||||
"hp": 11,
|
||||
"energy": 2,
|
||||
"element": "草元素",
|
||||
"weapon": "法器",
|
||||
@@ -6579,7 +6810,7 @@
|
||||
"nameEn": "hydro_hilichurl_rogue",
|
||||
"type": "character",
|
||||
"name": "丘丘水行游侠",
|
||||
"hp": 10,
|
||||
"hp": 11,
|
||||
"energy": 2,
|
||||
"element": "水元素",
|
||||
"weapon": "其他武器",
|
||||
|
||||
@@ -6,6 +6,7 @@ using BetterGenshinImpact.GameTask.AutoGeniusInvokation.Exception;
|
||||
using BetterGenshinImpact.GameTask.AutoWood.Assets;
|
||||
using BetterGenshinImpact.GameTask.AutoWood.Utils;
|
||||
using BetterGenshinImpact.GameTask.Common.BgiVision;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Vanara.PInvoke;
|
||||
@@ -15,54 +16,46 @@ namespace BetterGenshinImpact.GameTask.Common.Job;
|
||||
|
||||
public class ExitAndReloginJob
|
||||
{
|
||||
private AutoWoodAssets _assets;
|
||||
private AutoWoodAssets _assets = AutoWoodAssets.Instance;
|
||||
private readonly Login3rdParty _login3rdParty = new();
|
||||
|
||||
public async Task Start(CancellationToken ct)
|
||||
{
|
||||
//============== 退出游戏流程 ==============
|
||||
Logger.LogInformation("退出至登录页面");
|
||||
_assets = AutoWoodAssets.Instance;
|
||||
SystemControl.FocusWindow(TaskContext.Instance().GameHandle);
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
|
||||
await Delay(800, ct);
|
||||
|
||||
// 菜单界面验证(带重试机制)
|
||||
try
|
||||
{
|
||||
NewRetry.Do(() =>
|
||||
{
|
||||
using var contentRegion = CaptureToRectArea();
|
||||
using var ra = contentRegion.Find(_assets.MenuBagRo);
|
||||
if (ra.IsEmpty())
|
||||
{
|
||||
// 未检测到菜单时再次发送ESC
|
||||
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
|
||||
throw new RetryException("菜单界面验证失败");
|
||||
}
|
||||
}, TimeSpan.FromSeconds(1.2), 5); // 1.2秒内重试5次
|
||||
}
|
||||
catch
|
||||
{
|
||||
// 即使失败也继续退出流程
|
||||
}
|
||||
|
||||
// 点击退出按钮
|
||||
GameCaptureRegion.GameRegionClick((size, scale) => (50 * scale, size.Height - 50 * scale));
|
||||
await Delay(500, ct);
|
||||
// 等待菜单界面出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.MenuBagRo,
|
||||
() => Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE),
|
||||
ct,
|
||||
5,
|
||||
1200
|
||||
);
|
||||
|
||||
// 点击退出按钮并等待确认弹窗出现
|
||||
await NewRetry.WaitForElementAppear(
|
||||
_assets.ConfirmRo,
|
||||
() => GameCaptureRegion.GameRegionClick((size, scale) => (50 * scale, size.Height - 50 * scale)),
|
||||
ct,
|
||||
5,
|
||||
800
|
||||
);
|
||||
|
||||
// 点击确认退出并等待确认弹窗消失
|
||||
await NewRetry.WaitForElementDisappear(
|
||||
_assets.ConfirmRo,
|
||||
() => {
|
||||
using var cr = CaptureToRectArea();
|
||||
cr.Find(_assets.ConfirmRo, ra => { ra.Click(); ra.Dispose(); });
|
||||
},
|
||||
ct,
|
||||
5,
|
||||
1000
|
||||
);
|
||||
await Delay(1000, ct);
|
||||
|
||||
// 确认退出
|
||||
using var cr = CaptureToRectArea();
|
||||
cr.Find(_assets.ConfirmRo, ra =>
|
||||
{
|
||||
ra.Click();
|
||||
ra.Dispose();
|
||||
});
|
||||
|
||||
await Delay(1000, ct); // 等待退出完成
|
||||
|
||||
//============== 重新登录流程 ==============
|
||||
// 第三方登录(如果启用)
|
||||
Logger.LogInformation("点击登录");
|
||||
_login3rdParty.RefreshAvailabled();
|
||||
if (_login3rdParty is { Type: Login3rdParty.The3rdPartyType.Bilibili, IsAvailabled: true })
|
||||
@@ -72,45 +65,48 @@ public class ExitAndReloginJob
|
||||
Logger.LogInformation("退出重登启用 B 服模式");
|
||||
}
|
||||
|
||||
// 进入游戏检测
|
||||
var clickCnt = 0;
|
||||
for (var i = 0; i < 50; i++)
|
||||
// 等待进入游戏按钮出现并点击
|
||||
var enterGameAppear = await NewRetry.WaitForElementAppear(
|
||||
_assets.EnterGameRo,
|
||||
() => { },
|
||||
ct,
|
||||
50,
|
||||
1000
|
||||
);
|
||||
if (enterGameAppear)
|
||||
{
|
||||
await Delay(1, ct);
|
||||
|
||||
using var contentRegion = CaptureToRectArea();
|
||||
using var ra = contentRegion.Find(_assets.EnterGameRo);
|
||||
if (!ra.IsEmpty())
|
||||
{
|
||||
clickCnt++;
|
||||
GameCaptureRegion.GameRegion1080PPosClick(955, 666);
|
||||
}
|
||||
else
|
||||
{
|
||||
if (clickCnt > 2)
|
||||
{
|
||||
await Delay(5000, ct);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await Delay(1000, ct);
|
||||
// 点击进入游戏按钮直到它消失
|
||||
await NewRetry.WaitForElementDisappear(
|
||||
_assets.EnterGameRo,
|
||||
() => GameCaptureRegion.GameRegion1080PPosClick(955, 666),
|
||||
ct,
|
||||
10,
|
||||
1000
|
||||
);
|
||||
}
|
||||
|
||||
if (clickCnt == 0)
|
||||
else
|
||||
{
|
||||
throw new RetryException("未检测进入游戏界面");
|
||||
}
|
||||
|
||||
for (var i = 0; i < 50; i++)
|
||||
// 等待主界面出现
|
||||
var mainUiFound = await NewRetry.WaitForElementAppear(
|
||||
ElementAssets.Instance.PaimonMenuRo,
|
||||
() => { },
|
||||
ct,
|
||||
50,
|
||||
1000
|
||||
);
|
||||
|
||||
if (mainUiFound)
|
||||
{
|
||||
if (Bv.IsInMainUi(CaptureToRectArea()))
|
||||
{
|
||||
Logger.LogInformation("退出重新登录结束!");
|
||||
break;
|
||||
}
|
||||
await Delay(1000, ct);
|
||||
Logger.LogInformation("退出重新登录结束!");
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.LogWarning("未检测到主界面,登录可能未完成");
|
||||
}
|
||||
await Delay(500, ct);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -82,35 +82,40 @@ internal class GoToSereniteaPotTask
|
||||
// 进入 壶
|
||||
await ChangeCountryForce("尘歌壶", ct);
|
||||
|
||||
|
||||
|
||||
|
||||
// 若未找到 ElementAssets.Instance.SereniteaPotRo 就是已经在尘歌壶了
|
||||
var ra = CaptureToRectArea();
|
||||
//确定洞天名称
|
||||
var list = ra.FindMulti(new RecognitionObject
|
||||
{
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect((int)(ra.Width * 0.86), ra.Height*9/10, (int)(ra.Width * 0.073), (int)(ra.Height*0.04))
|
||||
});
|
||||
if (list.Count > 0)
|
||||
{
|
||||
dongTianName = list[0].Text;
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "洞天名称:" + dongTianName);
|
||||
var ra = CaptureToRectArea();
|
||||
for (int i = 0; i < 5; i++){
|
||||
ra = CaptureToRectArea();
|
||||
//确定洞天名称
|
||||
var list = ra.FindMulti(new RecognitionObject
|
||||
{
|
||||
RecognitionType = RecognitionTypes.Ocr,
|
||||
RegionOfInterest = new Rect((int)(ra.Width * 0.86), ra.Height*9/10, (int)(ra.Width * 0.073), (int)(ra.Height*0.04))
|
||||
});
|
||||
if (list.Count > 0)
|
||||
{
|
||||
dongTianName = list[0].Text;
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "洞天名称:" + dongTianName);
|
||||
await Task.Delay(100, ct);
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
dongTianName = "";
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "未识别到洞天名称");
|
||||
}
|
||||
await Task.Delay(100, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
dongTianName = "";
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "未识别到洞天名称");
|
||||
}
|
||||
|
||||
for (int i = 0; i < 3; i++)
|
||||
|
||||
for (int i = 0; i < 5; i++)
|
||||
{
|
||||
var sereniteaPotHomeIcon = ra.Find(ElementAssets.Instance.SereniteaPotHomeRo);
|
||||
if (!sereniteaPotHomeIcon.IsExist())
|
||||
{
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "住宅图标未找到,调整地图缩放至3.0。");
|
||||
await new Core.Script.Dependence.Genshin().SetBigMapZoomLevel(3.0);
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "住宅图标未找到,调整地图缩放至2。");
|
||||
await Task.Delay(1000, ct);
|
||||
await new Core.Script.Dependence.Genshin().SetBigMapZoomLevel(2.5-i*0.2);//尝试缩放地图
|
||||
await Task.Delay(1000, ct);
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -141,8 +146,6 @@ internal class GoToSereniteaPotTask
|
||||
await NewRetry.WaitForAction(() => Bv.IsInMainUi(CaptureToRectArea()), ct);
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 寻找阿圆并靠近
|
||||
private async Task FindAYuan(CancellationToken ct)
|
||||
{
|
||||
@@ -297,18 +300,18 @@ internal class GoToSereniteaPotTask
|
||||
if (numberBtn.IsExist())
|
||||
{
|
||||
numberBtn.Move();
|
||||
await Delay(300, ct);
|
||||
await Delay(600, ct);//减慢速度,设备差异导致的延迟
|
||||
Simulation.SendInput.Mouse.LeftButtonDown();
|
||||
await Delay(300, ct);
|
||||
await Delay(600, ct);
|
||||
numberBtn.MoveTo(ra.Width/7,0);//moveby会超出边界,改用MoveTo
|
||||
await Delay(300, ct);
|
||||
await Delay(600, ct);
|
||||
Simulation.SendInput.Mouse.LeftButtonUp();
|
||||
}
|
||||
|
||||
await Delay(300, ct);
|
||||
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
|
||||
await Delay(500, ct);
|
||||
await Delay(600, ct);
|
||||
ra.Find(ElementAssets.Instance.BtnWhiteConfirm).Click();
|
||||
await Delay(600, ct);
|
||||
TaskContext.Instance().PostMessageSimulator.SimulateAction(GIActions.OpenPaimonMenu); // ESC
|
||||
}
|
||||
|
||||
private async Task GetReward(CancellationToken ct)
|
||||
@@ -371,7 +374,6 @@ internal class GoToSereniteaPotTask
|
||||
if (shopOption == TalkOptionRes.FoundAndClick)
|
||||
{
|
||||
Logger.LogInformation("领取尘歌壶奖励:{text}", "购买商店物品");
|
||||
|
||||
await Delay(500, ct);
|
||||
// 购买的物品清单
|
||||
var buy = new List<RecognitionObject>();
|
||||
@@ -410,18 +412,39 @@ internal class GoToSereniteaPotTask
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//对比购买成功和buy的数量,如果不等,重试一次
|
||||
var buyCount = 0;
|
||||
var retryBuy= 0;
|
||||
// 直接购买最大数量
|
||||
foreach (var item in buy)
|
||||
while (retryBuy < 2)
|
||||
{
|
||||
var itemRo = CaptureToRectArea().Find(item);
|
||||
if (itemRo.IsExist())
|
||||
foreach (var item in buy)
|
||||
{
|
||||
Logger.LogInformation("领取尘歌壶奖励:购买 {text} ", item.Name);
|
||||
itemRo.Click();
|
||||
await Delay(600, ct);
|
||||
await BuyMaxNumber(ct);
|
||||
await Delay(1200, ct);//等待购买动画结束
|
||||
var itemRo = CaptureToRectArea().Find(item);
|
||||
if (itemRo.IsExist())
|
||||
{
|
||||
buyCount++;
|
||||
Logger.LogInformation("领取尘歌壶奖励:购买 {text} ", item.Name);
|
||||
itemRo.Click();
|
||||
await Delay(600, ct);
|
||||
await BuyMaxNumber(ct);
|
||||
await Delay(1000, ct);//等待购买动画结束
|
||||
}
|
||||
else
|
||||
{
|
||||
await Delay(700, ct);
|
||||
Logger.LogInformation("领取尘歌壶奖励: {text} 未找到", item.Name);
|
||||
}
|
||||
await Delay(700, ct);
|
||||
}
|
||||
if (buyCount < buy.Count)
|
||||
{
|
||||
retryBuy++;
|
||||
await Delay(500, ct);
|
||||
}else
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
await Delay(900, ct);
|
||||
|
||||
@@ -4,6 +4,8 @@ using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using BetterGenshinImpact.Core.Recognition;
|
||||
using static BetterGenshinImpact.GameTask.Common.TaskControl;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common;
|
||||
|
||||
@@ -12,6 +14,12 @@ namespace BetterGenshinImpact.GameTask.Common;
|
||||
/// </summary>
|
||||
public static class NewRetry
|
||||
{
|
||||
/// <summary>
|
||||
/// 重试指定操作,若抛出 RetryException 则在指定间隔后重试,最多尝试 maxAttemptCount 次。
|
||||
/// </summary>
|
||||
/// <param name="action">要执行的操作</param>
|
||||
/// <param name="retryInterval">重试间隔</param>
|
||||
/// <param name="maxAttemptCount">最大尝试次数</param>
|
||||
public static void Do(Action action, TimeSpan retryInterval, int maxAttemptCount = 3)
|
||||
{
|
||||
_ = Do<object?>(() =>
|
||||
@@ -21,6 +29,14 @@ public static class NewRetry
|
||||
}, retryInterval, maxAttemptCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重试指定操作,若抛出 RetryException 则在指定间隔后重试,最多尝试 maxAttemptCount 次,返回操作结果。
|
||||
/// </summary>
|
||||
/// <typeparam name="T">返回值类型</typeparam>
|
||||
/// <param name="action">要执行的操作</param>
|
||||
/// <param name="retryInterval">重试间隔</param>
|
||||
/// <param name="maxAttemptCount">最大尝试次数</param>
|
||||
/// <returns>操作结果</returns>
|
||||
public static T Do<T>(Func<T> action, TimeSpan retryInterval, int maxAttemptCount = 3)
|
||||
{
|
||||
List<System.Exception> exceptions = [];
|
||||
@@ -49,6 +65,14 @@ public static class NewRetry
|
||||
throw new AggregateException(exceptions);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重试执行 action,直到返回 true 或达到最大重试次数。
|
||||
/// </summary>
|
||||
/// <param name="action">判断条件</param>
|
||||
/// <param name="ct">取消令牌</param>
|
||||
/// <param name="retryTimes">最大重试次数</param>
|
||||
/// <param name="delayMs">每次重试间隔(毫秒)</param>
|
||||
/// <returns>是否成功</returns>
|
||||
public static async Task<bool> WaitForAction(Func<bool> action, CancellationToken ct, int retryTimes = 10, int delayMs = 1000)
|
||||
{
|
||||
for (var i = 0; i < retryTimes; i++)
|
||||
@@ -61,4 +85,84 @@ public static class NewRetry
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重试直到某个元素出现,可执行键盘或鼠标操作。
|
||||
/// </summary>
|
||||
/// <param name="recognitionObject">要识别的目标对象</param>
|
||||
/// <param name="retryAction">每次重试时执行的操作</param>
|
||||
/// <param name="ct">取消令牌</param>
|
||||
/// <param name="maxAttemptCount">最大尝试次数</param>
|
||||
/// <param name="retryInterval">重试间隔(毫秒)</param>
|
||||
/// <returns>是否成功找到元素</returns>
|
||||
public static async Task<bool> WaitForElementAppear(
|
||||
RecognitionObject recognitionObject,
|
||||
Action retryAction,
|
||||
CancellationToken ct,
|
||||
int maxAttemptCount = 10,
|
||||
int retryInterval = 1000
|
||||
)
|
||||
{
|
||||
for (int i = 0; i < maxAttemptCount; i++)
|
||||
{
|
||||
if (ct.IsCancellationRequested) return false;
|
||||
|
||||
// 执行重试操作(如按键)
|
||||
retryAction?.Invoke();
|
||||
|
||||
// 等待指定时间
|
||||
await TaskControl.Delay(retryInterval, ct);
|
||||
|
||||
// 截图并查找元素
|
||||
using var screen = CaptureToRectArea();
|
||||
using var result = screen.Find(recognitionObject);
|
||||
|
||||
// 元素已出现
|
||||
if (!result.IsEmpty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重试直到某个元素消失,可执行键盘或鼠标操作。
|
||||
/// </summary>
|
||||
/// <param name="recognitionObject">要识别的目标对象</param>
|
||||
/// <param name="retryAction">每次重试时执行的操作</param>
|
||||
/// <param name="ct">取消令牌</param>
|
||||
/// <param name="maxAttemptCount">最大尝试次数</param>
|
||||
/// <param name="retryInterval">重试间隔(毫秒)</param>
|
||||
/// <returns>是否成功等待元素消失</returns>
|
||||
public static async Task<bool> WaitForElementDisappear(
|
||||
RecognitionObject recognitionObject,
|
||||
Action retryAction,
|
||||
CancellationToken ct,
|
||||
int maxAttemptCount = 10,
|
||||
int retryInterval = 1000)
|
||||
{
|
||||
for (int i = 0; i < maxAttemptCount; i++)
|
||||
{
|
||||
if (ct.IsCancellationRequested) return false;
|
||||
|
||||
// 执行重试操作(如按键)
|
||||
retryAction?.Invoke();
|
||||
|
||||
// 等待指定时间
|
||||
await TaskControl.Delay(retryInterval, ct);
|
||||
|
||||
// 截图并查找元素
|
||||
using var screen = CaptureToRectArea();
|
||||
using var result = screen.Find(recognitionObject);
|
||||
|
||||
// 元素已消失
|
||||
if (result.IsEmpty())
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -88,21 +88,21 @@ public partial class StringUtils
|
||||
return int.TryParse(text, out int result) ? result : defaultValue;
|
||||
}
|
||||
|
||||
public static int TryExtractPositiveInt(string text)
|
||||
public static int TryExtractPositiveInt(string text, int defaultValue = -1)
|
||||
{
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return -1;
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
text = RegexHelper.ExcludeNumberRegex().Replace(text, "");
|
||||
return int.Parse(text);
|
||||
return TryParseInt(text, defaultValue);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return -1;
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ public partial class ScriptRepoWindow
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Toast.Error($"更新失败: {ex.Message}");
|
||||
Toast.Error($"更新失败,可尝试重置仓库后重新更新。失败原因:: {ex.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,12 +8,12 @@
|
||||
{
|
||||
"id": "mirrorc",
|
||||
"name": "Mirror酱",
|
||||
"uri": "mirrorc://BGI"
|
||||
"uri": "mirrorc://BGI?os=win&arch=x64"
|
||||
},
|
||||
{
|
||||
"id": "mirrorc-alpha",
|
||||
"name": "Mirror酱 Alpha",
|
||||
"uri": "mirrorc://BGI?channel=alpha",
|
||||
"uri": "mirrorc://BGI?channel=alpha&os=win&arch=x64",
|
||||
"hidden": true
|
||||
}
|
||||
],
|
||||
|
||||
@@ -130,4 +130,4 @@ BetterGI · 更好的原神, 一个基于计算机视觉技术,意图让原
|
||||
|
||||
## 问题反馈
|
||||
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1036100501](https://qm.qq.com/q/fvRNqEbFyo)
|
||||
提 [Issue](https://github.com/babalae/better-genshin-impact/issues) 或 QQ群[1053273766](https://qm.qq.com/q/qtocsOXnIQ)
|
||||
@@ -16,6 +16,8 @@ public class AvatarClassifyGen
|
||||
private static readonly string BackgroundDir = @"E:\HuiTask\更好的原神\数据源\background";
|
||||
|
||||
private static readonly Random Rd = new Random();
|
||||
|
||||
public static readonly List<string> ImgNames = ["UI_AvatarIcon_Side_Ambor.png","UI_AvatarIcon_Side_AmborCostumeWic.png"];
|
||||
|
||||
public static void GenAll()
|
||||
{
|
||||
@@ -23,9 +25,8 @@ public class AvatarClassifyGen
|
||||
// List<string> sideImageFiles = Directory.GetFiles(Path.Combine(BaseDir, "side_src"), "*.png", SearchOption.TopDirectoryOnly).ToList();
|
||||
// 只用一个图像
|
||||
List<string> sideImageFiles = [];
|
||||
List<string> imgNames = ["UI_AvatarIcon_Side_Escoffier.png","UI_AvatarIcon_Side_Ifa.png",
|
||||
"UI_AvatarIcon_Side_Flamingo.png","UI_AvatarIcon_Side_Hookwalker.png","UI_AvatarIcon_Side_Mosasaurus.png","UI_AvatarIcon_Side_Shamansaurus.png","UI_AvatarIcon_Side_Drillhead.png"];
|
||||
foreach (string imgName in imgNames)
|
||||
|
||||
foreach (string imgName in ImgNames)
|
||||
{
|
||||
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
|
||||
}
|
||||
|
||||
@@ -23,12 +23,7 @@ public class AvatarClassifyTransparentGen
|
||||
public static void GenAll()
|
||||
{
|
||||
List<string> sideImageFiles = [];
|
||||
List<string> imgNames =
|
||||
[
|
||||
"UI_AvatarIcon_Side_Escoffier.png", "UI_AvatarIcon_Side_Ifa.png",
|
||||
"UI_AvatarIcon_Side_Flamingo.png", "UI_AvatarIcon_Side_Hookwalker.png", "UI_AvatarIcon_Side_Mosasaurus.png",
|
||||
"UI_AvatarIcon_Side_Shamansaurus.png", "UI_AvatarIcon_Side_Drillhead.png"
|
||||
];
|
||||
List<string> imgNames = AvatarClassifyGen.ImgNames;
|
||||
foreach (string imgName in imgNames)
|
||||
{
|
||||
sideImageFiles.Add(Path.Combine(BaseDir, imgName));
|
||||
|
||||
+392
@@ -0,0 +1,392 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static TorchSharp.torch.nn;
|
||||
using static TorchSharp.torch;
|
||||
using TorchSharp;
|
||||
using System.Diagnostics;
|
||||
using System.Collections;
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
|
||||
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
{
|
||||
public partial class RodNetTests
|
||||
{
|
||||
/// <summary>
|
||||
/// RodNet验证,应在数据集上达到一定准确率
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData(@"..\..\..\Assets\AutoFishing\data_selected.csv")]
|
||||
public void Training_AccuracyShouldBeOK(string dataLocation)
|
||||
{
|
||||
//
|
||||
using var _ = no_grad();
|
||||
|
||||
var device =
|
||||
torch.cuda.is_available() ? torch.CUDA :
|
||||
torch.mps_is_available() ? torch.MPS :
|
||||
torch.CPU;
|
||||
var loss = CrossEntropyLoss();
|
||||
var sut = new RodNet().to((Device)device);
|
||||
sut.SetWeightsManually();
|
||||
|
||||
using var test_reader = new CSVReader(Enumerable.Repeat(false, 8).Concat(Enumerable.Repeat(true, 2)), Path.GetFullPath(dataLocation), (Device)device);
|
||||
|
||||
//
|
||||
var accuracy = evaluate(test_reader.GetBatches(eval_batch_size), sut, loss);
|
||||
|
||||
//
|
||||
Assert.True(accuracy > 0.8);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// RodNet必须粗略地支持训练
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public void Training_ShouldBeDifferentiable()
|
||||
{
|
||||
//
|
||||
RodInput input = new RodInput();
|
||||
var (y0, z0, t, u, v, h) = RodNet.GetRodStatePreProcess(input);
|
||||
|
||||
Tensor fishLabel = tensor(new double[] { input.fish_label }, dtype: ScalarType.Int32);
|
||||
Tensor uv = tensor(new double[,] { { u, v } }, dtype: ScalarType.Float64);
|
||||
Tensor y0z0t = tensor(new double[,] { { y0, z0, t } }, dtype: ScalarType.Float64);
|
||||
Tensor h_ = tensor(new double[,] { { h } }, dtype: ScalarType.Float64);
|
||||
RodNet sut = new RodNet();
|
||||
|
||||
//
|
||||
Tensor output = sut.forward(fishLabel, uv, y0z0t, h_);
|
||||
output.backward([torch.ones_like(output)]);
|
||||
//
|
||||
}
|
||||
|
||||
#region 训练相关代码
|
||||
// 这部分代码改编自TorchSharpExamples的CSharpExamples.TextClassification
|
||||
private const long batch_size = 32;
|
||||
private const long eval_batch_size = 32;
|
||||
|
||||
internal static RodNet Run(int epochs, int timeout, string dataLocation)
|
||||
{
|
||||
torch.random.manual_seed(1);
|
||||
|
||||
var device =
|
||||
torch.cuda.is_available() ? torch.CUDA :
|
||||
torch.mps_is_available() ? torch.MPS :
|
||||
torch.CPU;
|
||||
|
||||
Console.WriteLine();
|
||||
Console.WriteLine($"\tRunning TextClassification on {device.type.ToString()} for {epochs} epochs, terminating after {TimeSpan.FromSeconds(timeout)}.");
|
||||
Console.WriteLine();
|
||||
|
||||
Console.WriteLine($"\tPreparing training and test data...");
|
||||
|
||||
using (var reader = new CSVReader(Enumerable.Repeat(true, 8).Concat(Enumerable.Repeat(false, 2)), dataLocation, (Device)device))
|
||||
{
|
||||
Console.WriteLine($"\tCreating the model...");
|
||||
Console.WriteLine();
|
||||
|
||||
var model = new RodNet().to((Device)device);
|
||||
|
||||
var loss = CrossEntropyLoss();
|
||||
var lr = 1e-2;
|
||||
var optimizer = torch.optim.SGD(model.parameters(), learningRate: lr);
|
||||
var scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, epochs, eta_min: 0);
|
||||
|
||||
var totalTime = new Stopwatch();
|
||||
totalTime.Start();
|
||||
|
||||
foreach (var epoch in Enumerable.Range(1, epochs))
|
||||
{
|
||||
|
||||
var sw = new Stopwatch();
|
||||
sw.Start();
|
||||
|
||||
train(epoch, reader.GetBatches(batch_size), model, loss, optimizer);
|
||||
|
||||
sw.Stop();
|
||||
|
||||
Console.WriteLine($"\nEnd of epoch: {epoch} | lr: {optimizer.ParamGroups.First().LearningRate:0.0000} | time: {sw.Elapsed.TotalSeconds:0.0}s\n");
|
||||
scheduler.step();
|
||||
|
||||
if (totalTime.Elapsed.TotalSeconds > timeout) break;
|
||||
}
|
||||
|
||||
totalTime.Stop();
|
||||
|
||||
using (var test_reader = new CSVReader(Enumerable.Repeat(false, 8).Concat(Enumerable.Repeat(true, 2)), dataLocation, (Device)device))
|
||||
{
|
||||
|
||||
var sw = new Stopwatch();
|
||||
sw.Start();
|
||||
|
||||
var accuracy = evaluate(test_reader.GetBatches(eval_batch_size), model, loss);
|
||||
|
||||
sw.Stop();
|
||||
|
||||
Console.WriteLine($"\nEnd of training: test accuracy: {accuracy:0.00} | eval time: {sw.Elapsed.TotalSeconds:0.0}s\n");
|
||||
scheduler.step();
|
||||
}
|
||||
|
||||
foreach (var (name, param) in model.named_parameters())
|
||||
{
|
||||
switch (param.dtype)
|
||||
{
|
||||
case ScalarType.Int64:
|
||||
Console.WriteLine($"参数{name}={String.Join(", ", param.data<long>())}");
|
||||
break;
|
||||
case ScalarType.Float32:
|
||||
Console.WriteLine($"参数{name}={String.Join(", ", param.data<float>())}");
|
||||
break;
|
||||
case ScalarType.Float64:
|
||||
Console.WriteLine($"参数{name}={String.Join(", ", param.data<double>())}");
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return model;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
static void train(int epoch, IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> train_data, RodNet model, Loss<Tensor, Tensor, Tensor> criterion, torch.optim.Optimizer optimizer)
|
||||
{
|
||||
model.train();
|
||||
|
||||
double total_acc = 0.0;
|
||||
long total_count = 0;
|
||||
long log_interval = 1;
|
||||
|
||||
var batch = 0;
|
||||
|
||||
var batch_count = train_data.Count();
|
||||
|
||||
using (var d = torch.NewDisposeScope())
|
||||
{
|
||||
foreach (var (y0z0t, uv, h, fish_label, success) in train_data)
|
||||
{
|
||||
|
||||
optimizer.zero_grad();
|
||||
|
||||
using (var predicted_labels = model.forward(fish_label, uv, y0z0t, h))
|
||||
{
|
||||
var loss = criterion.forward(predicted_labels, success.to(ScalarType.Int64));
|
||||
loss.backward();
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), 0.1);
|
||||
optimizer.step();
|
||||
|
||||
total_acc += (predicted_labels.argmax(1) == success).sum().to(torch.CPU).item<long>();
|
||||
total_count += success.size(0);
|
||||
}
|
||||
|
||||
batch += 1;
|
||||
if (batch % log_interval == 0)
|
||||
{
|
||||
var accuracy = total_acc / total_count;
|
||||
Console.WriteLine($"epoch: {epoch} | batch: {batch} / {batch_count} | accuracy: {accuracy:0.00}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static double evaluate(IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> test_data, RodNet model, Loss<Tensor, Tensor, Tensor> criterion)
|
||||
{
|
||||
model.eval();
|
||||
|
||||
double total_acc = 0.0;
|
||||
long total_count = 0;
|
||||
|
||||
using (var d = torch.NewDisposeScope())
|
||||
{
|
||||
foreach (var (y0z0t, uv, h, fish_label, success) in test_data)
|
||||
{
|
||||
using (var predicted_labels = model.forward(fish_label, uv, y0z0t, h))
|
||||
{
|
||||
var loss = criterion.forward(predicted_labels, success.to(ScalarType.Int64));
|
||||
|
||||
total_acc += (predicted_labels.argmax(1) == success).sum().to(torch.CPU).item<long>();
|
||||
total_count += success.size(0);
|
||||
}
|
||||
}
|
||||
|
||||
return total_acc / total_count;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
internal class CSVReader : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="takeMask">按长度分组,布尔值代表每组内此序号元素是否被读取。例如8个true2个false就是将近80%进入训练集</param>
|
||||
/// <param name="path"></param>
|
||||
/// <param name="device"></param>
|
||||
public CSVReader(IEnumerable<bool> takeMask, string path, Device device)
|
||||
{
|
||||
this.takeMask = takeMask.ToArray();
|
||||
_path = path;
|
||||
_device = device;
|
||||
}
|
||||
|
||||
private readonly bool[] takeMask;
|
||||
private readonly string _path;
|
||||
private readonly Device _device;
|
||||
|
||||
|
||||
public IEnumerable<Data> Enumerate()
|
||||
{
|
||||
var all = File.ReadLines(_path).Skip(1); // 跳过首行列名
|
||||
int count = takeMask.Length;
|
||||
int maskCount = all.Count() / count;
|
||||
for (int i = 0; i < maskCount + 1; i++)
|
||||
{
|
||||
int lastGroupCount = (i == maskCount) ? (all.Count() % count) : count;
|
||||
for (int j = 0; j < lastGroupCount; j++)
|
||||
{
|
||||
if (takeMask[j])
|
||||
{
|
||||
yield return ParseLine(all.Skip(i * count + j).First());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<(Tensor, Tensor, Tensor, Tensor, Tensor)> GetBatches(long batch_size)
|
||||
{
|
||||
// This data set fits in memory, so we will simply load it all and cache it between epochs.
|
||||
|
||||
var inputs = new List<Data>();
|
||||
|
||||
if (_data == null)
|
||||
{
|
||||
|
||||
_data = new List<(Tensor, Tensor, Tensor, Tensor, Tensor)>();
|
||||
|
||||
var counter = 0;
|
||||
var lines = Enumerate().ToList();
|
||||
var left = lines.Count;
|
||||
|
||||
foreach (var line in lines)
|
||||
{
|
||||
|
||||
inputs.Add(line);
|
||||
left -= 1;
|
||||
|
||||
if (++counter == batch_size || left == 0)
|
||||
{
|
||||
_data.Add(Batchifier(inputs));
|
||||
inputs.Clear();
|
||||
counter = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _data;
|
||||
}
|
||||
|
||||
private List<(Tensor, Tensor, Tensor, Tensor, Tensor)> _data;
|
||||
private bool disposedValue;
|
||||
|
||||
/// <summary>
|
||||
/// 将csv中的数据进行初步转换
|
||||
/// </summary>
|
||||
/// <param name="input"></param>
|
||||
/// <returns>y0z0t、uv、h、fish_label、success张量</returns>
|
||||
private (Tensor, Tensor, Tensor, Tensor, Tensor) Batchifier(IEnumerable<Data> input)
|
||||
{
|
||||
var y0List = new List<double>();
|
||||
var z0List = new List<double>();
|
||||
var tList = new List<double>();
|
||||
var uList = new List<double>();
|
||||
var vList = new List<double>();
|
||||
var hList = new List<double>();
|
||||
var labelList = new List<int>();
|
||||
var successList = new List<int>();
|
||||
|
||||
foreach (var line in input)
|
||||
{
|
||||
int fish_label = line.fish_label;
|
||||
int success = line.success;
|
||||
RodInput rodInput = new RodInput()
|
||||
{
|
||||
rod_x1 = line.rod_x1,
|
||||
rod_x2 = line.rod_x2,
|
||||
rod_y1 = line.rod_y1,
|
||||
rod_y2 = line.rod_y2,
|
||||
fish_x1 = line.fish_x1,
|
||||
fish_x2 = line.fish_x2,
|
||||
fish_y1 = line.fish_y1,
|
||||
fish_y2 = line.fish_y2
|
||||
};
|
||||
var (y0, z0, t, u, v, h) = RodNet.GetRodStatePreProcess(rodInput);
|
||||
|
||||
y0List.Add(y0);
|
||||
z0List.Add(z0);
|
||||
tList.Add(t);
|
||||
uList.Add(u);
|
||||
vList.Add(v);
|
||||
hList.Add(h);
|
||||
labelList.Add(fish_label);
|
||||
successList.Add(success);
|
||||
}
|
||||
|
||||
Tensor y0Tensor = tensor(y0List, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor z0Tensor = tensor(z0List, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor tTensor = tensor(tList, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor uTensor = tensor(uList, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor vTensor = tensor(vList, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor hTensor = tensor(hList, dtype: ScalarType.Float64).to(_device);
|
||||
Tensor fish_labelTensor = tensor(labelList, dtype: ScalarType.Int32).to(_device);
|
||||
Tensor successTensor = tensor(successList, dtype: ScalarType.Int32).to(_device);
|
||||
|
||||
return (torch.stack([y0Tensor, z0Tensor, tTensor], dim: 1), torch.stack([uTensor, vTensor], dim: 1), hTensor.unsqueeze(1), fish_labelTensor, successTensor);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// csv的列定义默认为time,bite_time,rod_x1,rod_x2,rod_y1,rod_y2,fish_x1,fish_x2,fish_y1,fish_y2,fish_label,success
|
||||
/// </summary>
|
||||
/// <param name="line"></param>
|
||||
/// <returns></returns>
|
||||
public Data ParseLine(string line)
|
||||
{
|
||||
var columns = line.Split(",").ToArray();
|
||||
|
||||
return new Data(float.Parse(columns[2]), float.Parse(columns[3]), float.Parse(columns[4]), float.Parse(columns[5]),
|
||||
float.Parse(columns[6]), float.Parse(columns[7]), float.Parse(columns[8]), float.Parse(columns[9]),
|
||||
int.Parse(columns[10]), int.Parse(columns[11]));
|
||||
}
|
||||
|
||||
protected virtual void Dispose(bool disposing)
|
||||
{
|
||||
if (!disposedValue)
|
||||
{
|
||||
if (disposing && _data != null)
|
||||
{
|
||||
foreach (var (y0z0t, uv, h, label, success) in _data)
|
||||
{
|
||||
y0z0t.Dispose();
|
||||
uv.Dispose();
|
||||
h.Dispose();
|
||||
label.Dispose();
|
||||
success.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
disposedValue = true;
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
|
||||
Dispose(disposing: true);
|
||||
GC.SuppressFinalize(this);
|
||||
}
|
||||
}
|
||||
|
||||
internal record Data(float rod_x1, float rod_x2, float rod_y1, float rod_y2, float fish_x1, float fish_x2, float fish_y1, float fish_y2, int fish_label, int success);
|
||||
}
|
||||
@@ -1,17 +1,16 @@
|
||||
using BetterGenshinImpact.GameTask.AutoFishing;
|
||||
using BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using static BetterGenshinImpact.GameTask.AutoFishing.RodNet;
|
||||
using TorchSharp;
|
||||
using static TorchSharp.torch;
|
||||
|
||||
namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
{
|
||||
[Collection("Init Collection")]
|
||||
public class RodNetTests
|
||||
public partial class RodNetTests
|
||||
{
|
||||
public RodNetTests(TorchFixture torch)
|
||||
{
|
||||
@@ -42,9 +41,8 @@ namespace BetterGenshinImpact.UnitTest.GameTaskTests.AutoFishingTests
|
||||
RodNet sut = new RodNet();
|
||||
|
||||
//
|
||||
NetInput netInput = GeometryProcessing(rodInput) ?? throw new NullReferenceException();
|
||||
Tensor outputTensor = sut.ComputeScores_Torch(netInput);
|
||||
double[] pred = ComputeScores(netInput);
|
||||
Tensor outputTensor = sut.ComputeScores_Torch(rodInput);
|
||||
double[] pred = RodNet.ComputeScores(rodInput);
|
||||
|
||||
//
|
||||
Assert.Equal((float)pred[0], (float)outputTensor.data<double>()[0]); // 对比时降低精度,差不多就行
|
||||
|
||||
Reference in new issue
Block a user