Compare commits

...
31 Commits
Author SHA1 Message Date
辉鸭蛋 8f2c186cb9 修复地区切换失败的问题 2025-05-03 21:45:55 +08:00
辉鸭蛋 253eaa7800 录制支持多独立地图 2025-05-03 21:19:49 +08:00
辉鸭蛋 3057ee3723 修改独立地图相关命名,使用 Scene(场景) 命名,和原神内部命名保持一致 2025-05-03 19:02:20 +08:00
辉鸭蛋 4d4a570c3b 更新传送点信息 2025-05-03 18:56:32 +08:00
辉鸭蛋 0f3cc38db3 传送时切换独立地图地区 2025-05-03 17:13:03 +08:00
辉鸭蛋 2f3e6cd24f 路径追踪窗体支持多地图 2025-05-03 16:28:20 +08:00
辉鸭蛋 65cc732e2f 体积较小的地图动态生成特征 2025-05-02 23:29:02 +08:00
辉鸭蛋 d97c956e4b 是用正确的特征匹配 2025-05-02 22:01:20 +08:00
辉鸭蛋 6923fb11c0 修复不正确的坐标转换 2025-05-02 21:50:51 +08:00
辉鸭蛋 4c87dc1a0d 更多坐标方法的迁移 2025-05-02 21:38:28 +08:00
辉鸭蛋 e1273f912e 修复定位问题,迁移部分 MapCoordinate 的代码。MapCoordinate 标记为废弃 2025-05-02 21:09:07 +08:00
辉鸭蛋 30f42968f2 修复类方法覆盖不生效的问题 2025-05-02 20:12:28 +08:00
辉鸭蛋 523d4c59b7 兼容新提交的内容 2025-05-02 19:51:52 +08:00
辉鸭蛋 be869ed23e Merge remote-tracking branch 'origin/main' into more-maps
# Conflicts:
#	BetterGenshinImpact/Core/Script/Dependence/Genshin.cs
2025-05-02 19:50:22 +08:00
辉鸭蛋 5ebe1ebe52 修改tp的入参方式,删除无用类 2025-05-02 19:30:21 +08:00
辉鸭蛋 b34e6c8fef 替换小地图匹配类 EntireMap 2025-05-02 19:15:38 +08:00
辉鸭蛋 6a4cbe4d22 替换大地图匹配类 BigMap.cs 2025-05-02 18:07:42 +08:00
辉鸭蛋 682da243ce 提瓦特大陆地图大地图位置获取使用256级别的地图 2025-05-02 13:38:55 +08:00
辉鸭蛋 40b22a645f 提瓦特大陆的大地图匹配 2025-05-02 13:31:38 +08:00
辉鸭蛋 ee50147e0e 添加远古圣山,修改地图参数 2025-05-02 00:29:06 +08:00
辉鸭蛋 477b404b12 支持不切分特征点匹配 2025-05-01 23:13:00 +08:00
辉鸭蛋 d44a48ef2a 新增独立地图 层岩巨渊,渊下宫,旧日之海 2025-05-01 23:02:18 +08:00
辉鸭蛋 f2a06247c1 加载分层特征数据 2025-05-01 22:45:18 +08:00
辉鸭蛋 a2f7d7913d 迁移坐标计算 2025-05-01 21:39:33 +08:00
辉鸭蛋 f2c736c024 临时提交 2025-05-01 19:48:01 +08:00
辉鸭蛋 3cf71f34d5 新增地图基类实现 2025-05-01 14:18:59 +08:00
辉鸭蛋 e0f5c7c346 抽象出Feature2D相关能力 2025-05-01 12:05:10 +08:00
辉鸭蛋 84f0b3b94d Merge branch 'main' into more-maps 2025-05-01 10:51:48 +08:00
辉鸭蛋 84df1c2fc8 修改定义 2025-04-27 01:26:48 +08:00
辉鸭蛋 432d0305e0 Merge branch 'main' into more-maps 2025-04-27 00:16:05 +08:00
辉鸭蛋 8b334ca8c8 抽象基础类 2025-04-10 21:45:50 +08:00
49 changed files with 14557 additions and 12064 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/UserDictionary/Words/=enkanomiya/@EntryIndexedValue">True</s:Boolean></wpf:ResourceDictionary>
@@ -163,6 +163,11 @@
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
<Page Update="View\Windows\MapPathingDevWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<XamlRuntime>Wpf</XamlRuntime>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
@@ -190,6 +190,12 @@ public partial class AllConfig : ObservableObject
/// 传送相关配置
/// </summary>
public TpConfig TpConfig { get; set; } = new();
/// <summary>
/// 开发者配置
/// </summary>
public DevConfig DevConfig { get; set; } = new();
[JsonIgnore]
public Action? OnAnyChangedAction { get; set; }
@@ -217,6 +223,7 @@ public partial class AllConfig : ObservableObject
TpConfig.PropertyChanged += OnAnyPropertyChanged;
ScriptConfig.PropertyChanged += OnAnyPropertyChanged;
PathingConditionConfig.PropertyChanged += OnAnyPropertyChanged;
DevConfig.PropertyChanged += OnAnyPropertyChanged;
}
public void OnAnyPropertyChanged(object? sender, EventArgs args)
@@ -0,0 +1,16 @@
using CommunityToolkit.Mvvm.ComponentModel;
using System;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.Core.Config;
/// <summary>
/// 脚本配置
/// </summary>
[Serializable]
public partial class DevConfig : ObservableObject
{
// 录制地图名称
[ObservableProperty]
private string _recordMapName = MapTypes.Teyvat.ToString();
}
@@ -0,0 +1,262 @@
using System;
using System.Collections.Generic;
using System.Linq;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public static class Feature2DExtensions
{
private static readonly Dictionary<DescriptorMatcherType, DescriptorMatcher> MatcherFactory = new()
{
{ DescriptorMatcherType.BruteForce, DescriptorMatcher.Create(DescriptorMatcherType.BruteForce.ToString()) },
{ DescriptorMatcherType.FlannBased, DescriptorMatcher.Create(DescriptorMatcherType.FlannBased.ToString()) }
};
private static DescriptorMatcher GetMatcher(DescriptorMatcherType type)
{
return MatcherFactory[type];
}
#region 生成并保存特征
public static void SaveFeatures(this Feature2D feature2D, string trainImagePath, string trainKeyPointsPath, string trainDescriptorsPath)
{
Mat trainDescriptors = new();
var img = Cv2.ImRead(trainImagePath, ImreadModes.Grayscale);
feature2D.DetectAndCompute(img, null, out var trainKeyPoints, trainDescriptors);
FeatureStorageHelper.SaveKeyPointArray(trainKeyPoints, trainKeyPointsPath);
FeatureStorageHelper.SaveDescMat(trainDescriptors, trainDescriptorsPath);
}
#endregion
#region 普通匹配
/// <summary>
/// 用于从训练图像和查询图像中找到匹配的特征点,计算透视变换并确定查询图像的中心点在训练图像中的位置。
/// </summary>
/// <param name="feature2D"></param>
/// <param name="trainKeyPoints">训练图像中的关键点集合。</param>
/// <param name="trainDescriptors">训练图像的特征描述子。</param>
/// <param name="queryMat">查询图像的 Mat 对象。</param>
/// <param name="queryMatMask">查询图像的 Mask,用于限定检测特征的区域。</param>
/// <param name="matcherType">描述符匹配器的类型,默认为 DescriptorMatcherType.FlannBased</param>
/// <returns></returns>
public static Point2f Match(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).Match(queryDescriptors, trainDescriptors);
//Finding the Minimum and Maximum Distance
double minDistance = 1000; //Backward approximation
double maxDistance = 0;
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance > maxDistance)
{
maxDistance = distance;
}
if (distance < minDistance)
{
minDistance = distance;
}
}
// Debug.WriteLine($"max distance : {maxDistance}");
// Debug.WriteLine($"min distance : {minDistance}");
var pointsQuery = new List<Point2f>();
var pointsTrain = new List<Point2f>();
//Screening better matching points
// var goodMatches = new List<DMatch>();
for (int i = 0; i < queryDescriptors.Rows; i++)
{
double distance = matches[i].Distance;
if (distance < Math.Max(minDistance * 2, 0.02))
{
pointsQuery.Add(queryKeyPoints[matches[i].QueryIdx].Pt);
pointsTrain.Add(trainKeyPoints[matches[i].TrainIdx].Pt);
//Compression of new ones with distances less than ranges DMatch
// goodMatches.Add(matches[i]);
}
}
speedTimer.Record("FlannMatch");
// var outMat = new Mat();
// algorithm RANSAC Filter the matched results
var pQuery = pointsQuery.ToPoint2d();
var pTrain = pointsTrain.ToPoint2d();
var outMask = new Mat();
// If the original matching result is null, Skip the filtering step
if (pQuery.Count > 0 && pTrain.Count > 0)
{
var hMat = Cv2.FindHomography(pQuery, pTrain, HomographyMethods.Ransac, mask: outMask);
speedTimer.Record("FindHomography");
// 1. 计算查询图像的中心点
var queryCenterPoint = new Point2f(queryMat.Cols / 2f, queryMat.Rows / 2f);
// 2. 使用单应矩阵进行透视变换
Point2f[] queryCenterPoints = [queryCenterPoint];
Point2f[] transformedCenterPoints = Cv2.PerspectiveTransform(queryCenterPoints, hMat);
// 3. 获取变换后的中心点
var trainCenterPoint = transformedCenterPoints[0];
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return trainCenterPoint;
}
speedTimer.DebugPrint();
return new Point2f();
}
#endregion 普通匹配
#region Knn匹配
/// <summary>
/// https://github.com/tignioj/minimap/blob/main/matchmap/sifttest/sifttest5.py
/// Copilot 生成
/// </summary>
/// <returns></returns>
public static Point2f KnnMatch(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
foreach (var match in matches)
{
if (match.Length == 2 && match[0].Distance < 0.75 * match[1].Distance)
{
goodMatches.Add(match[0]);
}
}
if (goodMatches.Count < 7)
{
return new Point2f();
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
{
return new Point2f();
}
speedTimer.Record("FindHomography");
// 计算小地图的中心点
var h = queryMat.Rows;
var w = queryMat.Cols;
var centerPoint = new Point2f(w / 2f, h / 2f);
Point2f[] centerPoints = [centerPoint];
Point2f[] transformedCenter = Cv2.PerspectiveTransform(centerPoints, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
// 返回小地图在大地图中的中心坐标
return transformedCenter[0];
}
public static Point2f[] KnnMatchCorners(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null,
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
{
SpeedTimer speedTimer = new();
using var queryDescriptors = new Mat();
#pragma warning disable CS8604 // 引用类型参数可能为 null。
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
#pragma warning restore CS8604 // 引用类型参数可能为 null。
speedTimer.Record("模板生成KeyPoint");
var matches = GetMatcher(matcherType).KnnMatch(queryDescriptors, trainDescriptors, k: 2);
speedTimer.Record("FlannMatch");
// 应用比例测试来过滤匹配点
List<DMatch> goodMatches = [];
foreach (var match in matches)
{
if (match.Length == 2 && match[0].Distance < 0.75 * match[1].Distance)
{
goodMatches.Add(match[0]);
}
}
if (goodMatches.Count < 7)
{
return [];
}
// 获取匹配点的坐标
var srcPts = goodMatches.Select(m => queryKeyPoints[m.QueryIdx].Pt).ToArray();
var dstPts = goodMatches.Select(m => trainKeyPoints[m.TrainIdx].Pt).ToArray();
speedTimer.Record("GetGoodMatchPoints");
// 使用RANSAC找到变换矩阵
var mask = new Mat();
var hMat = Cv2.FindHomography(srcPts.ToList().ToPoint2d(), dstPts.ToList().ToPoint2d(), HomographyMethods.Ransac, 3.0, mask);
if (hMat.Empty())
{
return [];
}
speedTimer.Record("FindHomography");
// 返回四个角点
var objCorners = new Point2f[4];
objCorners[0] = new Point2f(0, 0);
objCorners[1] = new Point2f(0, queryMat.Rows);
objCorners[2] = new Point2f(queryMat.Cols, queryMat.Rows);
objCorners[3] = new Point2f(queryMat.Cols, 0);
var sceneCorners = Cv2.PerspectiveTransform(objCorners, hMat);
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return sceneCorners;
}
public static Rect KnnMatchRect(this Feature2D feature2D, KeyPoint[] trainKeyPoints, Mat trainDescriptors, Mat queryMat, Mat? queryMatMask = null)
{
var corners = KnnMatchCorners(feature2D, trainKeyPoints, trainDescriptors, queryMat, queryMatMask);
if (corners.Length == 0)
{
return default;
}
return Cv2.BoundingRect(corners);
}
#endregion Knn匹配
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using OpenCvSharp;
using OpenCvSharp.Features2D;
using OpenCvSharp.XFeatures2D;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public class Feature2DFactory
{
private static readonly Dictionary<Feature2DType, Feature2D> Instances = new();
private static readonly object Lock = new();
public static Feature2D Get(Feature2DType type)
{
lock (Lock)
{
if (Instances.TryGetValue(type, out var instance))
{
return instance;
}
instance = type switch
{
Feature2DType.SIFT => SIFT.Create(),
Feature2DType.SURF => SURF.Create(100, 4, 3, false, true),
_ => throw new ArgumentException($"不支持的特征检测器类型: {type}")
};
Instances[type] = instance;
return instance;
}
}
}
@@ -11,6 +11,7 @@ using System.Linq;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
[Obsolete]
public class FeatureMatcher
{
private readonly double _threshold = 100; // SURF 100
@@ -28,8 +29,8 @@ public class FeatureMatcher
private readonly KeyPoint[] _trainKeyPoints;
private readonly KeyPointFeatureBlock[][] _blocks; // 特征块存储
private readonly int _splitRow = MapCoordinate.GameMapRows * 2; // 特征点拆分行数
private readonly int _splitCol = MapCoordinate.GameMapCols * 2; // 特征点拆分列数
private readonly int _splitRow = TeyvatMapCoordinate.GameMapRows * 2; // 特征点拆分行数
private readonly int _splitCol = TeyvatMapCoordinate.GameMapCols * 2; // 特征点拆分列数
private KeyPointFeatureBlock? _lastMergedBlock; // 上次合并的特征块
/// <summary>
@@ -234,7 +235,6 @@ public class FeatureMatcher
// 3. 获取变换后的中心点
var trainCenterPoint = transformedCenterPoints[0];
speedTimer.Record("PerspectiveTransform");
speedTimer.DebugPrint();
return trainCenterPoint;
}
@@ -0,0 +1,57 @@
using System;
using System.IO;
using System.Runtime.InteropServices;
using OpenCvSharp;
using OpenCvSharp.Internal.Vectors;
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
public class FeatureStorageHelper
{
public static unsafe KeyPoint[]? LoadKeyPointArray(string kpPath)
{
if (File.Exists(kpPath))
{
using var fs = File.Open(kpPath, FileMode.Open);
var sizeOfKeyPoint = Marshal.SizeOf<KeyPoint>();
if (fs.Length % sizeOfKeyPoint != 0)
{
throw new FileFormatException("无法识别的KeyPoint格式");
}
using var kpVector = new VectorOfKeyPoint((nuint)(fs.Length / sizeOfKeyPoint));
using var ms = new UnmanagedMemoryStream((byte*)kpVector.ElemPtr, fs.Length, fs.Length, FileAccess.Write);
fs.CopyTo(ms);
return kpVector.ToArray();
}
return null;
}
public static unsafe void SaveKeyPointArray(KeyPoint[] kpArray, string kpPath)
{
var kpVector = new VectorOfKeyPoint(kpArray);
var sizeOfKeyPoint = Marshal.SizeOf<KeyPoint>();
var kpSpan = new ReadOnlySpan<byte>((byte*)kpVector.ElemPtr, kpArray.Length * sizeOfKeyPoint);
using var fs = new FileStream(kpPath, FileMode.Create);
fs.Write(kpSpan);
}
public static Mat? LoadDescriptorMat(string descriptorPath)
{
if (File.Exists(descriptorPath))
{
using var img = new Mat(descriptorPath, ImreadModes.Grayscale);
var mat = new Mat(img.Size(), MatType.CV_32FC1);
img.ConvertTo(mat, MatType.CV_32FC1);
return mat;
}
return null;
}
public static void SaveDescMat(Mat descMat, string descriptorPath)
{
descMat.SaveImage(descriptorPath);
}
}
@@ -11,7 +11,12 @@ using BetterGenshinImpact.GameTask.Common.BgiVision;
using OpenCvSharp;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.Helpers.Extensions;
namespace BetterGenshinImpact.Core.Script.Dependence;
public class Genshin
@@ -49,9 +54,15 @@ public class Genshin
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y);
}
public async Task Tp(double x, double y, string mapName, bool force)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, mapName, force);
}
public async Task Tp(double x, double y, bool force)
{
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, force);
await new TpTask(CancellationContext.Instance.Cts.Token).Tp(x, y, MapTypes.Teyvat.ToString(), force);
}
/// <summary>
@@ -74,8 +85,9 @@ public class Genshin
await Tp(dx, dy, force);
}
#region 大地图操作
/// <summary>
/// 移动大地图到指定坐标
/// </summary>
@@ -91,7 +103,35 @@ public class Genshin
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
await tpTask.CheckInBigMapUi();
await tpTask.SwitchRecentlyCountryMap(x, y, forceCountry);
await tpTask.MoveMapTo(x, y);
await tpTask.MoveMapTo(x, y, MapTypes.Teyvat.ToString());
}
/// <summary>
/// 移动大地图到指定坐标
/// </summary>
/// <remarks>
/// 与内置传送功能不同,此方法不会多次重试。
/// 为避免初次中心点识别失败,建议先使用 SetBigMapZoomLevel 设置合适的大地图缩放等级。
/// </remarks>
/// <param name="x">目标X坐标</param>
/// <param name="y">目标Y坐标</param>
/// <param name="mapName">指定要移动的大地图</param>
public async Task MoveIndependentMapTo(int x, int y, string mapName, string? forceCountry = null)
{
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
await tpTask.CheckInBigMapUi();
// 切换地区
if (mapName == MapTypes.Teyvat.ToString())
{
// 计算传送点位置离哪张地图切换后的中心点最近,切换到该地图
await tpTask.SwitchRecentlyCountryMap(x, y, forceCountry);
}
else
{
// 直接切换地区
await tpTask.SwitchArea(MapTypesExtensions.ParseFromName(mapName).GetDescription());
}
await tpTask.MoveMapTo(x, y, mapName);
}
/// <summary>
@@ -100,7 +140,7 @@ public class Genshin
/// <returns>当前大地图缩放等级,范围1.0-6.0</returns>
public double GetBigMapZoomLevel()
{
TpTask tpTask = new(CancellationContext.Instance.Cts.Token);
TpTask tpTask = new(CancellationContext.Instance.Cts.Token);
return tpTask.GetBigMapZoomLevel(CaptureToRectArea());
}
@@ -121,7 +161,7 @@ public class Genshin
double currentZoomLevel = GetBigMapZoomLevel();
await tpTask.AdjustMapZoomLevel(currentZoomLevel, zoomLevel);
}
/// <summary>
/// 传送到用户指定的七天神像
/// </summary>
@@ -138,23 +178,47 @@ public class Genshin
public Point2f GetPositionFromBigMap()
{
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
return tpTask.GetPositionFromBigMap();
return tpTask.GetPositionFromBigMap(MapTypes.Teyvat.ToString());
}
/// <summary>
/// 获取当前在大地图上的位置坐标
/// </summary>
/// <param name="mapName">大地图名称</param>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f GetPositionFromBigMap(string mapName)
{
TpTask tpTask = new TpTask(CancellationContext.Instance.Cts.Token);
return tpTask.GetPositionFromBigMap(mapName);
}
/// <summary>
/// 获取当前在小地图上的位置坐标
/// </summary>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f GetPositionFromMap(){
public Point2f GetPositionFromMap()
{
return GetPositionFromMap(MapTypes.Teyvat.ToString());
}
/// <summary>
/// 获取当前在小地图上的位置坐标
/// </summary>
/// <param name="mapName">大地图名称</param>
/// <returns>包含X和Y坐标的Point2f结构体</returns>
public Point2f GetPositionFromMap(string mapName)
{
var imageRegion = CaptureToRectArea();
if (!Bv.IsInMainUi(imageRegion))
{
throw new InvalidOperationException("不在主界面,无法识别小地图坐标");
}
return MapCoordinate.Main2048ToGame(Navigation.GetPositionStable(imageRegion));
return MapManager.GetMap(mapName).ConvertImageCoordinatesToGenshinMapCoordinates(Navigation.GetPositionStable(imageRegion, mapName));
}
#endregion 大地图操作
/// <summary>
/// 切换队伍
/// </summary>
@@ -257,7 +321,7 @@ public class Genshin
param.FishingTimePolicy = (FishingTimePolicy)fishingTimePolicy;
await new AutoFishingTask(param).Start(CancellationContext.Instance.Cts.Token);
}
/// <summary>
/// 重新登录原神
/// </summary>
@@ -1,6 +1,7 @@
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using System;
using System.Text.Json.Serialization;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
@@ -27,6 +28,8 @@ public class PathingTaskInfo
[JsonIgnore]
public string TypeDesc => PathingTaskType.GetMsgByCode(Type);
public string MapName { get; set; } = MapTypes.Teyvat.ToString();
// 任务参数/配置
// 持续操作 切换某个角色 长E or 短E
@@ -2,6 +2,7 @@
using System;
using BetterGenshinImpact.GameTask.AutoFight.Script;
using BetterGenshinImpact.GameTask.AutoPathing.Model.Enum;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
namespace BetterGenshinImpact.GameTask.AutoPathing.Model;
@@ -17,6 +18,8 @@ public class WaypointForTrack : Waypoint
public double MatX { get; set; }
public double MatY { get; set; }
public string MapName { get; set; }
/// <summary>
/// 存在 combat_script 的 action 的话,这个值会存在
@@ -28,7 +31,7 @@ public class WaypointForTrack : Waypoint
/// </summary>
public string? LogInfo { get; set; }
public WaypointForTrack(Waypoint waypoint)
public WaypointForTrack(Waypoint waypoint, string mapName)
{
Type = waypoint.Type;
MoveMode = waypoint.MoveMode;
@@ -36,8 +39,9 @@ public class WaypointForTrack : Waypoint
ActionParams = waypoint.ActionParams;
GameX = waypoint.X;
GameY = waypoint.Y;
MapName = mapName;
// 坐标系转换
(MatX, MatY) = MapCoordinate.GameToMain2048(waypoint.X, waypoint.Y);
(MatX, MatY) = MapManager.GetMap(mapName).ConvertGenshinMapCoordinatesToImageCoordinates((float)waypoint.X, (float)waypoint.Y);
X = MatX;
Y = MatY;
if (waypoint.Action == ActionEnum.CombatScript.Code)
@@ -3,12 +3,15 @@ using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Model.Area;
using OpenCvSharp;
using System;
using System.Diagnostics;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.GameTask.AutoPathing;
@@ -16,28 +19,38 @@ public class Navigation
{
private static bool _isWarmUp = false;
private static float _prevX = -1;
private static float _prevY = -1;
public static void WarmUp()
{
if (!_isWarmUp)
{
TaskControl.Logger.LogInformation("地图特征点加载中,由于体积较大,首次加载速度较慢,请耐心等待...");
EntireMap.Instance.GetFeatureMatcher();
TaskControl.Logger.LogInformation("地图特征点加载完成!");
MapManager.GetMap(MapTypes.Teyvat);
}
_isWarmUp = true;
Reset();
}
public static void Reset()
{
EntireMap.Instance.SetPrevPosition(-1, -1);
(_prevX, _prevY) = (-1, -1);
}
public static void SetPrevPosition(float x, float y)
{
(_prevX, _prevY) = (x, y);
}
public static Point2f GetPosition(ImageRegion imageRegion)
public static Point2f GetPosition(ImageRegion imageRegion, string mapName)
{
var greyMat = new Mat(imageRegion.SrcGreyMat, MapAssets.Instance.MimiMapRect);
var p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
var p = MapManager.GetMap(mapName).GetMiniMapPosition(greyMat, _prevX, _prevY);
if (p != default)
{
(_prevX, _prevY) = (p.X, p.Y);
}
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(typeof(Navigation),
"SendCurrentPosition", new object(), p));
return p;
@@ -47,30 +60,26 @@ public class Navigation
/// 稳定获取当前位置坐标,优先使用全地图匹配,适用于不需要高效率但需要高稳定性的场景
/// </summary>
/// <param name="imageRegion">图像区域</param>
/// <param name="retryCount">匹配失败时的重试次数</param>
/// <param name="mapName"></param>
/// <returns>当前位置坐标</returns>
public static Point2f GetPositionStable(ImageRegion imageRegion, int retryCount = 3)
public static Point2f GetPositionStable(ImageRegion imageRegion, string mapName)
{
var greyMat = new Mat(imageRegion.SrcGreyMat, MapAssets.Instance.MimiMapRect);
// 先尝试使用局部匹配
var p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
// 如果全地图匹配失败,再尝试局部匹配
var p = MapManager.GetMap(mapName).GetMiniMapPosition(greyMat, _prevX, _prevY);
// 如果局部匹配失败,再尝试全地图匹配失败
if (p == new Point2f())
{
p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
// 如果仍然失败,进行多次重试
int attempts = 0;
while (p == new Point2f() && attempts < retryCount)
{
// 重置位置记录,强制使用全地图匹配
Reset();
p = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(greyMat);
attempts++;
}
Reset();
p = MapManager.GetMap(mapName).GetMiniMapPosition(greyMat, _prevX, _prevY);
}
if (p != default)
{
(_prevX, _prevY) = (p.X, p.Y);
}
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(typeof(Navigation),
"SendCurrentPosition", new object(), p));
return p;
@@ -85,6 +94,7 @@ public class Navigation
{
return 0;
}
// 计算向量与x轴之间的夹角(逆时针方向)
double angle = Math.Acos(deltaX / vectorLength);
// 如果向量在x轴下方,角度需要调整
@@ -92,6 +102,7 @@ public class Navigation
{
angle = 2 * Math.PI - angle;
}
return (int)(angle * (180.0 / Math.PI));
}
@@ -103,4 +114,4 @@ public class Navigation
var y2 = position.Y;
return Math.Sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
}
}
@@ -36,6 +36,7 @@ using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
namespace BetterGenshinImpact.GameTask.AutoPathing;
@@ -151,7 +152,7 @@ public class PathExecutor
InitializePathing(task);
// 转换、按传送点分割路径
var waypointsList = ConvertWaypointsForTrack(task.Positions);
var waypointsList = ConvertWaypointsForTrack(task.Positions, task);
await Delay(100, ct);
Navigation.WarmUp(); // 提前加载地图特征点
@@ -473,10 +474,10 @@ public class PathExecutor
}
}
private List<List<WaypointForTrack>> ConvertWaypointsForTrack(List<Waypoint> positions)
private List<List<WaypointForTrack>> ConvertWaypointsForTrack(List<Waypoint> positions, PathingTask task)
{
// 把 X Y 转换为 MatX MatY
var allList = positions.Select(waypoint => new WaypointForTrack(waypoint)).ToList();
var allList = positions.Select(waypoint => new WaypointForTrack(waypoint, task.Info.MapName)).ToList();
// 按照WaypointType.Teleport.Code切割数组
var result = new List<List<WaypointForTrack>>();
@@ -585,11 +586,10 @@ public class PathExecutor
{
// tp 到七天神像回血
var tpTask = new TpTask(ct);
await RunnerContext.Instance.StopAutoPickRunTask(async () =>await tpTask.TpToStatueOfTheSeven(),5);
await RunnerContext.Instance.StopAutoPickRunTask(async () => await tpTask.TpToStatueOfTheSeven(), 5);
Logger.LogInformation("血量恢复完成。【设置】-【七天神像设置】可以修改回血相关配置。");
}
/// <summary>
/// 尝试自动领取派遣奖励,
/// </summary>
@@ -600,15 +600,16 @@ public class PathExecutor
{
tpTask = new TpTask(ct);
}
//打开大地图操作
await tpTask.OpenBigMapUi();
bool changeBigMap = false;
string adventurersGuildCountry =
TaskContext.Instance().Config.OtherConfig.AutoFetchDispatchAdventurersGuildCountry;
if (!RunnerContext.Instance.isAutoFetchDispatch && adventurersGuildCountry!="无")
if (!RunnerContext.Instance.isAutoFetchDispatch && adventurersGuildCountry != "无")
{
var ra1 = CaptureToRectArea();
var textRect = new Rect(60, 20, 160, 260);
var textMat = new Mat(ra1.SrcGreyMat, textRect);
string text = OcrFactory.Paddle.Ocr(textMat);
@@ -618,11 +619,12 @@ public class PathExecutor
Logger.LogInformation("开始自动领取派遣任务!");
try
{
RunnerContext.Instance.isAutoFetchDispatch = true;
await RunnerContext.Instance.StopAutoPickRunTask(async () =>await new GoToAdventurersGuildTask().Start(adventurersGuildCountry,ct,null,true),5);
await RunnerContext.Instance.StopAutoPickRunTask(async () => await new GoToAdventurersGuildTask().Start(adventurersGuildCountry, ct, null, true), 5);
Logger.LogInformation("自动领取派遣结束,回归原任务!");
} catch (Exception e){
}
catch (Exception e)
{
Logger.LogInformation("未知原因,发生异常,尝试继续执行任务!");
}
finally
@@ -630,8 +632,8 @@ public class PathExecutor
RunnerContext.Instance.isAutoFetchDispatch = false;
}
}
}
return changeBigMap;
}
@@ -639,16 +641,17 @@ public class PathExecutor
{
var forceTp = waypoint.Action == ActionEnum.ForceTp.Code;
TpTask tpTask = new TpTask(ct);
var (tpX, tpY) = await tpTask.Tp(waypoint.GameX, waypoint.GameY, forceTp,!await TryAutoFetchDispatch(tpTask));
var (tprX, tprY) = MapCoordinate.GameToMain2048(tpX, tpY);
EntireMap.Instance.SetPrevPosition((float)tprX, (float)tprY); // 通过上一个位置直接进行局部特征匹配
await TryAutoFetchDispatch(tpTask);
var (tpX, tpY) = await tpTask.Tp(waypoint.GameX, waypoint.GameY, waypoint.MapName, forceTp);
var (tprX, tprY) = MapManager.GetMap(waypoint.MapName).ConvertGenshinMapCoordinatesToImageCoordinates((float)tpX, (float)tpY);
Navigation.SetPrevPosition(tprX, tprY); // 通过上一个位置直接进行局部特征匹配
await Delay(500, ct); // 多等一会
}
public async Task FaceTo(WaypointForTrack waypoint)
{
var screen = CaptureToRectArea();
var position = await GetPosition(screen);
var position = await GetPosition(screen, waypoint.MapName);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("朝向点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 2);
@@ -663,7 +666,7 @@ public class PathExecutor
await SwitchAvatar(PartyConfig.MainAvatarIndex);
var screen = CaptureToRectArea();
var position = await GetPosition(screen);
var position = await GetPosition(screen, waypoint.MapName);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
Logger.LogInformation("粗略接近途经点,位置({x2},{y2})", $"{waypoint.GameX:F1}", $"{waypoint.GameY:F1}");
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
@@ -682,7 +685,7 @@ public class PathExecutor
{
Simulation.SendInput.SimulateAction(GIActions.MoveForward, KeyType.KeyDown);
}
num++;
if ((DateTime.UtcNow - moveToStartTime).TotalSeconds > 240)
{
@@ -694,7 +697,7 @@ public class PathExecutor
EndJudgment(screen);
position = await GetPosition(screen);
position = await GetPosition(screen, waypoint.MapName);
var distance = Navigation.GetDistance(waypoint, position);
Debug.WriteLine($"接近目标点中,距离为{distance}");
if (distance < 4)
@@ -868,7 +871,7 @@ public class PathExecutor
// 切人
Logger.LogInformation("切换盾、回血角色,使用元素战技");
var avatar = await SwitchAvatar(PartyConfig.GuardianAvatarIndex,true);
var avatar = await SwitchAvatar(PartyConfig.GuardianAvatarIndex, true);
if (avatar == null)
{
return;
@@ -882,7 +885,7 @@ public class PathExecutor
Simulation.SendInput.SimulateAction(GIActions.MoveBackward);
await Delay(200, ct);
}
avatar.UseSkill(PartyConfig.GuardianElementalSkillLongPress);
// 钟离往身后放柱子 后继续走路
@@ -913,7 +916,7 @@ public class PathExecutor
EndJudgment(screen);
position = await GetPosition(screen);
position = await GetPosition(screen, waypoint.MapName);
if (Navigation.GetDistance(waypoint, position) < 2)
{
Logger.LogInformation("已到达路径点");
@@ -950,7 +953,7 @@ public class PathExecutor
{
Simulation.SendInput.Mouse.MiddleButtonClick();
var screen = CaptureToRectArea();
var position = await GetPosition(screen);
var position = await GetPosition(screen, waypoint.MapName);
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 10);
var handler = ActionFactory.GetBeforeHandler(waypoint.Action);
@@ -984,7 +987,7 @@ public class PathExecutor
}
}
private async Task<Avatar?> SwitchAvatar(string index,bool needSkill = false)
private async Task<Avatar?> SwitchAvatar(string index, bool needSkill = false)
{
if (string.IsNullOrEmpty(index))
{
@@ -998,19 +1001,21 @@ public class PathExecutor
Logger.LogInformation("角色{Name}技能未冷却,跳过。", avatar.Name);
return null;
}
var success = avatar.TrySwitch();
if (success)
{
await Delay(100, ct);
return avatar;
}
Logger.LogInformation("尝试切换角色{Name}失败!", avatar.Name);
return null;
}
private async Task<Point2f> GetPosition(ImageRegion imageRegion)
private async Task<Point2f> GetPosition(ImageRegion imageRegion, string mapName)
{
var position = Navigation.GetPosition(imageRegion);
var position = Navigation.GetPosition(imageRegion, mapName);
if (position == new Point2f())
{
@@ -1046,7 +1051,7 @@ public class PathExecutor
{
return;
}
Logger.LogInformation("检测到其他界面,使用ESC关闭界面");
Simulation.SendInput.Keyboard.KeyPress(User32.VK.VK_ESCAPE);
await Delay(1000, ct); // 等待界面关闭
@@ -11,6 +11,9 @@ using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Windows;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Model;
using Microsoft.Web.WebView2.Core;
@@ -32,15 +35,29 @@ public class PathRecorder : Singleton<PathRecorder>
private PathingTask _pathingTask = new();
public void Start()
private string _mapName = MapTypes.Teyvat.ToString();
public void Start(string mapName)
{
Navigation.WarmUp();
_mapName = mapName;
_pathingTask = new PathingTask();
TaskControl.Logger.LogInformation("开始路径点记录");
if (mapName == MapTypes.Teyvat.ToString())
{
TaskControl.Logger.LogInformation("如果需要切换其他地图,请在 {Msg} 中切换", "地图追踪——开发者工具");
}
var waypoint = new Waypoint();
var screen = TaskControl.CaptureToRectArea();
var position = Navigation.GetPositionStable(screen);
position = MapCoordinate.Main2048ToGame(position);
var position = Navigation.GetPositionStable(screen, mapName);
if (position == default)
{
TaskControl.Logger.LogWarning("未识别到当前位置!");
return;
}
position = MapManager.GetMap(mapName).ConvertImageCoordinatesToGenshinMapCoordinates(position);
waypoint.X = position.X;
waypoint.Y = position.Y;
waypoint.Type = WaypointType.Teleport.Code;
@@ -61,8 +78,14 @@ public class PathRecorder : Singleton<PathRecorder>
{
Waypoint waypoint = new();
var screen = TaskControl.CaptureToRectArea();
var position = Navigation.GetPositionStable(screen);
position = MapCoordinate.Main2048ToGame(position);
var position = Navigation.GetPositionStable(screen, _mapName);
position = MapManager.GetMap(_mapName).ConvertImageCoordinatesToGenshinMapCoordinates(position);
if (position == default)
{
TaskControl.Logger.LogWarning("未识别到当前位置!");
return;
}
waypoint.X = position.X;
waypoint.Y = position.Y;
waypoint.Type = string.IsNullOrEmpty(waypointType) ? WaypointType.Path.Code : waypointType;
@@ -75,6 +98,13 @@ public class PathRecorder : Singleton<PathRecorder>
{
if (_webWindow == null)
{
_pathingTask.Info = new PathingTaskInfo
{
Name = "未命名路线",
Type = PathingTaskType.Collect.Code,
MapName = _mapName,
BgiVersion = Global.Version
};
var name = $@"{DateTime.Now:yyyyMMdd_HHmmss}.json";
_pathingTask.SaveToFile(Path.Combine(MapPathingViewModel.PathJsonPath, name));
TaskControl.Logger.LogInformation("录制编辑器未打开,直接保存路径点记录:{Name}", name);
@@ -87,15 +117,15 @@ public class PathRecorder : Singleton<PathRecorder>
}
}
public void AddPosToEditor(double x, double y)
private void AddPosToEditor(double x, double y)
{
if (_webWindow != null)
{
_webWindow.WebView.ExecuteScriptAsync($"addNewPoint({x},{y})");
UIDispatcherHelper.Invoke(() => { _webWindow.WebView.ExecuteScriptAsync($"addNewPoint({x},{y})"); });
}
}
public void OpenEditorInWebView()
public void OpenEditorInWebView(string mapName = "Teyvat")
{
if (_webWindow is not { IsVisible: true })
{
@@ -109,7 +139,13 @@ public class PathRecorder : Singleton<PathRecorder>
};
_webWindow.Closed += (s, e) => _webWindow = null;
_webWindow.Panel!.DownloadFolderPath = MapPathingViewModel.PathJsonPath;
_webWindow.NavigateToFile(Global.Absolute(@"Assets\Map\Editor\index.html"));
var htmlPath = Global.Absolute(@"Assets\Map\Editor\index.html");
var uri = new UriBuilder(htmlPath);
var query = System.Web.HttpUtility.ParseQueryString(string.Empty);
query["map"] = mapName;
uri.Query = query.ToString();
_webWindow.NavigateToFile(uri.ToString());
_webWindow.Show();
}
else
@@ -117,4 +153,4 @@ public class PathRecorder : Singleton<PathRecorder>
_webWindow.Activate();
}
}
}
}
@@ -35,7 +35,7 @@ public class TrapEscaper(CancellationToken ct)
var startTime = DateTime.UtcNow;
bool left = false;
var screen = CaptureToRectArea();
var position = Navigation.GetPosition(screen);
var position = Navigation.GetPosition(screen, waypoint.MapName);
LastActionTime = DateTime.UtcNow;
var targetOrientation = Navigation.GetTargetOrientation(waypoint, position);
await _rotateTask.WaitUntilRotatedTo(targetOrientation, 5);
@@ -56,7 +56,7 @@ public class TrapEscaper(CancellationToken ct)
}
screen = CaptureToRectArea();
position = Navigation.GetPosition(screen);
position = Navigation.GetPosition(screen, waypoint.MapName);
// 旋转视角
/* 这里的角度增加了一个randomAngle角度,用来在原角度不适用的情况下修改角度以适应复杂环境
File diff suppressed because it is too large. Load diff
@@ -24,6 +24,8 @@ using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using Vanara.PInvoke;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
@@ -208,7 +210,7 @@ public class AutoTrackPathTask
var miniMapMat = GetMiniMapMat(ra) ?? throw new InvalidOperationException("当前不在主界面");
// 注意游戏坐标系的角度是顺时针的
var currMapImageAvatarPos = EntireMap.Instance.GetMiniMapPositionByFeatureMatch(miniMapMat);
var currMapImageAvatarPos = MapManager.GetMap(MapTypes.Teyvat).GetMiniMapPosition(miniMapMat);
if (currMapImageAvatarPos.IsEmpty())
{
Debug.WriteLine("识别小地图位置失败");
@@ -1,6 +1,8 @@
using BetterGenshinImpact.GameTask.Common.Map;
using OpenCvSharp;
using System;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
@@ -23,7 +25,7 @@ public class GiPathPoint
public static GiPathPoint BuildFrom(Point2f point, int index)
{
var pt = MapCoordinate.Main2048ToGame(point);
var pt = MapManager.GetMap(MapTypes.Teyvat).ConvertImageCoordinatesToGenshinMapCoordinates(point);
return new GiPathPoint
{
Pt = pt,
@@ -0,0 +1,27 @@
using System.Collections.Generic;
namespace BetterGenshinImpact.GameTask.AutoTrackPath.Model;
public class GiWorldScene
{
/// <summary>
/// 地图名称
/// MapTypes
/// </summary>
public string MapName { get; set; } = string.Empty;
/// <summary>
/// 场景ID
/// </summary>
public int SceneId { get; set; }
/// <summary>
/// 场景描述
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// 场景内的坐标点集合
/// </summary>
public List<GiTpPosition> Points { get; set; } = new();
}
@@ -16,6 +16,8 @@ using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using static BetterGenshinImpact.GameTask.Common.TaskControl;
namespace BetterGenshinImpact.GameTask.AutoTrackPath;
@@ -23,8 +25,6 @@ namespace BetterGenshinImpact.GameTask.AutoTrackPath;
[Obsolete]
public class PathPointRecorder : Singleton<PathPointRecorder>
{
private readonly EntireMap _bigMap = EntireMap.Instance;
private Task? _recordTask;
private CancellationTokenSource? _recordTaskCts;
@@ -76,7 +76,7 @@ public class PathPointRecorder : Singleton<PathPointRecorder>
continue;
}
var p2 = _bigMap.GetMiniMapPositionByFeatureMatch(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
var p2 = MapManager.GetMap(MapTypes.Teyvat).GetMiniMapPosition(new Mat(ra.SrcGreyMat, new Rect(p.X + 24, p.Y - 15, 210, 210)));
if (!p2.IsEmpty())
{
way.AddPoint(p2);
@@ -21,10 +21,13 @@ using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Exceptions;
using BetterGenshinImpact.GameTask.Common.Job;
using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.Helpers;
using BetterGenshinImpact.Helpers.Extensions;
using Microsoft.ClearScript.JavaScript;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
@@ -47,6 +50,7 @@ public class TpTask(CancellationToken ct)
/// 直接通过缩放比例按钮计算放大按钮的Y坐标
/// </summary>
private readonly int _zoomInButtonY = TaskContext.Instance().Config.TpConfig.ZoomStartY - 24; // y-coordinate for zoom-in button = _zoomStartY - 24
/// <summary>
/// 直接通过缩放比例按钮计算缩小按钮的Y坐标
/// </summary>
@@ -74,6 +78,7 @@ public class TpTask(CancellationToken ct)
await AdjustMapZoomLevel(currentZoomLevel, 3);
}
}
string? country = _tpConfig.ReviveStatueOfTheSevenCountry;
string? area = _tpConfig.ReviveStatueOfTheSevenArea;
double x = _tpConfig.ReviveStatueOfTheSevenPointX;
@@ -81,7 +86,7 @@ public class TpTask(CancellationToken ct)
GiTpPosition revivePoint = _tpConfig.ReviveStatueOfTheSeven ?? GetNearestGoddess(x, y);
if (_tpConfig.IsReviveInNearestStatueOfTheSeven)
{
var center = GetBigMapCenterPoint();
var center = GetBigMapCenterPoint(MapTypes.Teyvat.ToString());
var giTpPoint = GetNearestGoddess(center.X, center.Y);
country = giTpPoint.Country;
area = giTpPoint.Area;
@@ -91,7 +96,7 @@ public class TpTask(CancellationToken ct)
}
Logger.LogInformation("将传送至 {country} {area} 七天神像", country, area);
await Tp(x, y);
await Tp(x, y, MapTypes.Teyvat.ToString(), false);
if (_tpConfig.ShouldMove || _tpConfig.IsReviveInNearestStatueOfTheSeven)
{
(x, y) = GetClosestPoint(revivePoint.TranX, revivePoint.TranY, x, y, 5);
@@ -102,7 +107,7 @@ public class TpTask(CancellationToken ct)
Type = WaypointType.Path.Code,
MoveMode = MoveModeEnum.Walk.Code
};
var waypointForTrack = new WaypointForTrack(waypoint);
var waypointForTrack = new WaypointForTrack(waypoint, MapTypes.Teyvat.ToString());
await new PathExecutor(ct).MoveTo(waypointForTrack);
Simulation.SendInput.SimulateAction(GIActions.Drop);
}
@@ -130,6 +135,7 @@ public class TpTask(CancellationToken ct)
{
return (tranX, tranY);
}
double ratio = d / distance;
double px = (x - dx * ratio);
double py = (y - dy * ratio);
@@ -155,6 +161,7 @@ public class TpTask(CancellationToken ct)
nearestGiTpPosition = goddessPosition;
}
}
// 获取最近的神像位置
return nearestGiTpPosition ?? throw new InvalidOperationException("没找到最近的七天神像");
}
@@ -165,7 +172,6 @@ public class TpTask(CancellationToken ct)
/// <param name="retryCount">重试次数</param>
public async Task OpenBigMapUi(int retryCount = 3)
{
for (var i = 0; i < retryCount; i++)
{
try
@@ -182,20 +188,18 @@ public class TpTask(CancellationToken ct)
}
catch (Exception e)
{
if (retryCount>1)
if (retryCount > 1)
{
Logger.LogError("打开大地图失败,重试 {I} 次", i + 1);
Logger.LogDebug(e, "打开大地图失败,重试 {I} 次", i + 1);
}
if (i+1>=retryCount)
if (i + 1 >= retryCount)
{
throw;
}
}
}
}
/// <summary>
@@ -203,28 +207,33 @@ public class TpTask(CancellationToken ct)
/// </summary>
/// <param name="tpX"></param>
/// <param name="tpY"></param>
/// <param name="mapName">独立地图名称</param>
/// <param name="force">强制以当前的tpX,tpY坐标进行自动传送</param>
/// <param name="skipOpenBigMapUi">跳过打开地图步骤</param>
private async Task<(double, double)> TpOnce(double tpX, double tpY, bool force = false,bool skipOpenBigMapUi = false)
private async Task<(double, double)> TpOnce(double tpX, double tpY, string mapName = "Teyvat", bool force = false)
{
if (!skipOpenBigMapUi)
{
// 1. 确认在地图界面
await OpenBigMapUi(1);
}
// 1. 确认在地图界面
await OpenBigMapUi(1);
// 2. 传送前的计算准备
// 获取离目标传送点最近的两个传送点,按距离排序
var nTpPoints = GetNearestNTpPoints(tpX, tpY, 2);
var nTpPoints = GetNearestNTpPoints(tpX, tpY, mapName, 2);
// 获取最近的传送点与区域
var (x, y, country) = force ? (tpX, tpY, null) : (nTpPoints[0].X, nTpPoints[0].Y, nTpPoints[0].Country);
var disBetweenTpPoints = Math.Sqrt(Math.Pow(nTpPoints[0].X - nTpPoints[1].X, 2) +
Math.Pow(nTpPoints[0].Y - nTpPoints[1].Y, 2));
// 确保不会点错传送点的最小缩放,保证至少为 1.0
var minZoomLevel = Math.Max(disBetweenTpPoints / 20, 1.0);
// 计算传送点位置离哪个地图切换后的中心点最近,切换到该地图
await SwitchRecentlyCountryMap(x, y, country);
// 切换地区
if (mapName == MapTypes.Teyvat.ToString())
{
// 计算传送点位置离哪张地图切换后的中心点最近,切换到该地图
await SwitchRecentlyCountryMap(x, y, country);
}
else
{
// 直接切换地区
await SwitchArea(MapTypesExtensions.ParseFromName(mapName).GetDescription());
}
// 3. 调整初始缩放等级,避免识别中心点失败
var zoomLevel = GetBigMapZoomLevel(CaptureToRectArea());
@@ -253,7 +262,7 @@ public class TpTask(CancellationToken ct)
if (_tpConfig.MapZoomEnabled)
{
Logger.LogInformation("目标传送点有相近传送点,到目标传送点附近将缩放到{zoomLevel:0.00}", minZoomLevel);
await MoveMapTo(x, y, minZoomLevel);
await MoveMapTo(x, y, mapName, minZoomLevel);
await Delay(300, ct); // 等待地图移动完成
}
else
@@ -264,11 +273,11 @@ public class TpTask(CancellationToken ct)
}
// 5. 判断传送点是否在当前界面,若否则移动地图
var bigMapInAllMapRect = GetBigMapRect();
var bigMapInAllMapRect = GetBigMapRect(mapName);
var retryCount = 0;
do
{
if (IsPointInBigMapWindow(bigMapInAllMapRect, x, y)) break;
if (IsPointInBigMapWindow(mapName, bigMapInAllMapRect, x, y)) break;
if (retryCount++ >= 5) // 防止死循环
{
Logger.LogWarning("多次尝试未移动到目标传送点,传送失败");
@@ -276,15 +285,15 @@ public class TpTask(CancellationToken ct)
}
Logger.LogInformation("传送点不在当前大地图范围内,重新调整地图位置");
await MoveMapTo(x, y);
await MoveMapTo(x, y, mapName);
await Delay(300, ct);
bigMapInAllMapRect = GetBigMapRect();
bigMapInAllMapRect = GetBigMapRect(mapName);
} while (true);
// 6. 计算传送点位置并点击
// Debug.WriteLine($"({x},{y}) 在 {bigMapInAllMapRect} 内,计算它在窗体内的位置");
// 注意这个坐标的原点是中心区域某个点,所以要转换一下点击坐标(点击坐标是左上角为原点的坐标系),不能只是缩放
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
var (clickX, clickY) = ConvertToGameRegionPosition(mapName, bigMapInAllMapRect, x, y);
Logger.LogInformation("点击传送点");
CaptureToRectArea().ClickTo((int)clickX, (int)clickY);
@@ -323,11 +332,12 @@ public class TpTask(CancellationToken ct)
/// <summary>
/// 传送点是否在大地图窗口内
/// </summary>
/// <param name="mapName"></param>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private bool IsPointInBigMapWindow(Rect bigMapInAllMapRect, double x, double y)
private bool IsPointInBigMapWindow(string mapName, Rect bigMapInAllMapRect, double x, double y)
{
// 坐标不包含直接返回
if (!bigMapInAllMapRect.Contains(x, y))
@@ -335,7 +345,7 @@ public class TpTask(CancellationToken ct)
return false;
}
var (clickX, clickY) = ConvertToGameRegionPosition(bigMapInAllMapRect, x, y);
var (clickX, clickY) = ConvertToGameRegionPosition(mapName, bigMapInAllMapRect, x, y);
// 屏蔽左上角360x400区域
if (clickX < 360 * _zoomOutMax1080PRatio && clickY < 400 * _zoomOutMax1080PRatio)
{
@@ -357,14 +367,15 @@ public class TpTask(CancellationToken ct)
/// <summary>
/// 转换传送点坐标到窗体内需要点击的坐标
/// </summary>
/// <param name="mapName"></param>
/// <param name="bigMapInAllMapRect">大地图在整个游戏地图中的矩形位置(原神坐标系)</param>
/// <param name="x">传送点x坐标(原神坐标系)</param>
/// <param name="y">传送点y坐标(原神坐标系)</param>
/// <returns></returns>
private (double clickX, double clickY) ConvertToGameRegionPosition(Rect bigMapInAllMapRect, double x, double y)
private (double clickX, double clickY) ConvertToGameRegionPosition(string mapName, Rect bigMapInAllMapRect, double x, double y)
{
var (picX, picY) = MapCoordinate.GameToMain2048(x, y);
var picRect = MapCoordinate.GameToMain2048(bigMapInAllMapRect);
var (picX, picY) = MapManager.GetMap(mapName).ConvertGenshinMapCoordinatesToImageCoordinates((float)x, (float)y);
var picRect = MapManager.GetMap(mapName).ConvertGenshinMapCoordinatesToImageCoordinates(bigMapInAllMapRect);
Debug.WriteLine($"({picX},{picY}) 在 {picRect} 内,计算它在窗体内的位置");
var clickX = (picX - picRect.X) / picRect.Width * _captureRect.Width;
var clickY = (picY - picRect.Y) / picRect.Height * _captureRect.Height;
@@ -418,13 +429,13 @@ public class TpTask(CancellationToken ct)
}
public async Task<(double, double)> Tp(double tpX, double tpY, bool force = false ,bool skipOpenBigMapUi = false)
public async Task<(double, double)> Tp(double tpX, double tpY, string mapName = "Teyvat", bool force = false)
{
for (var i = 0; i < 3; i++)
{
try
{
return await TpOnce(tpX, tpY, force: force,skipOpenBigMapUi);
return await TpOnce(tpX, tpY, mapName, force);
}
catch (TpPointNotActivate e)
{
@@ -442,10 +453,6 @@ public class TpTask(CancellationToken ct)
{
Logger.LogError("传送失败,重试 {I} 次", i + 1);
Logger.LogDebug(e, "传送失败,重试 {I} 次", i + 1);
}finally
{
//只要异常过,后续重试都需要打开大地图操作
skipOpenBigMapUi = false;
}
}
@@ -458,8 +465,9 @@ public class TpTask(CancellationToken ct)
/// </summary>
/// <param name="x">目标x坐标</param>
/// <param name="y">目标y坐标</param>
/// <param name="mapName">地图名称</param>
/// <param name="finalZoomLevel">到达目标点的最小缩放等级,只在 MapZoomEnabled 为 True 生效</param>
public async Task MoveMapTo(double x, double y, double finalZoomLevel = 2)
public async Task MoveMapTo(double x, double y, string mapName, double finalZoomLevel = 2)
{
// 参数初始化
double minZoomLevel = Math.Min(finalZoomLevel, _tpConfig.MinZoomLevel);
@@ -469,12 +477,12 @@ public class TpTask(CancellationToken ct)
Point2f mapCenterPoint;
try
{
mapCenterPoint = GetPositionFromBigMap(); // 初始中心
mapCenterPoint = GetPositionFromBigMap(mapName); // 初始中心
}
catch (Exception e)
{
++exceptionTimes;
mapCenterPoint = new Point2f(0f, 0f); // 其他恰当的初始值?
mapCenterPoint = new Point2f(0f, 0f); // 其他恰当的初始值?
}
var (xOffset, yOffset) = (x - mapCenterPoint.X, y - mapCenterPoint.Y);
@@ -534,7 +542,7 @@ public class TpTask(CancellationToken ct)
try
{
exceptionTimes = 0;
mapCenterPoint = GetPositionFromBigMap(); // 随循环更新的地图中心
mapCenterPoint = GetPositionFromBigMap(mapName); // 随循环更新的地图中心
}
catch (Exception)
{
@@ -542,10 +550,12 @@ public class TpTask(CancellationToken ct)
{
throw new Exception("多次中心点识别失败,重新传送");
}
Logger.LogWarning("中心点识别失败,预测移动的距离");
mapCenterPoint += new Point2f((float)(moveMouseX * currentZoomLevel / _tpConfig.MapScaleFactor),
(float)(moveMouseY * currentZoomLevel / _tpConfig.MapScaleFactor));
}
(xOffset, yOffset) = (x - mapCenterPoint.X, y - mapCenterPoint.Y);
totalMoveMouseX = _tpConfig.MapScaleFactor * Math.Abs(xOffset) / currentZoomLevel;
totalMoveMouseY = _tpConfig.MapScaleFactor * Math.Abs(yOffset) / currentZoomLevel;
@@ -675,30 +685,30 @@ public class TpTask(CancellationToken ct)
for (int i = 0; i < steps; i++)
{
double ratio = factors[i] / sum;
stepsArr[i] = (int)(delta * ratio); // 基础值
stepsArr[i] = (int)(delta * ratio); // 基础值
remaining -= stepsArr[i];
}
int center = steps / 2;
for (int r = 0; r < Math.Abs(remaining); r++)
{
int target = (center + r) % steps; // 从中点开始螺旋分配
int target = (center + r) % steps; // 从中点开始螺旋分配
stepsArr[target] += remaining > 0 ? 1 : -1;
}
return stepsArr;
}
public Point2f GetPositionFromBigMap()
public Point2f GetPositionFromBigMap(string mapName)
{
return GetBigMapCenterPoint();
return GetBigMapCenterPoint(mapName);
}
public Point2f? GetPositionFromBigMapNullable()
public Point2f? GetPositionFromBigMapNullable(string mapName)
{
try
{
return GetBigMapCenterPoint();
return GetBigMapCenterPoint(mapName);
}
catch
{
@@ -706,7 +716,7 @@ public class TpTask(CancellationToken ct)
}
}
public Rect GetBigMapRect()
public Rect GetBigMapRect(string mapName)
{
var rect = new Rect();
NewRetry.Do(() =>
@@ -716,7 +726,7 @@ public class TpTask(CancellationToken ct)
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
rect = BigMap.Instance.GetBigMapRectByFeatureMatch(ra.SrcGreyMat);
rect = MapManager.GetMap(mapName).GetBigMapRect(ra.SrcGreyMat);
if (rect == default)
{
// 滚轮调整后再次识别
@@ -737,25 +747,38 @@ public class TpTask(CancellationToken ct)
}
Debug.WriteLine("识别大地图在全地图位置矩形:" + rect);
const int s = BigMap.ScaleTo2048; // 相对1024做4倍缩放
return MapCoordinate.Main2048ToGame(new Rect(rect.X * s, rect.Y * s, rect.Width * s, rect.Height * s));
// 提瓦特大陆由于用的256的图,需要做特殊逻辑
if (mapName == MapTypes.Teyvat.ToString())
{
const int s = TeyvatMap.BigMap256ScaleTo2048; // 相对2048做8倍缩放
rect = new Rect(rect.X * s, rect.Y * s, rect.Width * s, rect.Height * s);
}
return MapManager.GetMap(mapName).ConvertImageCoordinatesToGenshinMapCoordinates(rect);
}
public Point2f GetBigMapCenterPoint()
public Point2f GetBigMapCenterPoint(string mapName)
{
// 判断是否在地图界面
using var ra = CaptureToRectArea();
using var mapScaleButtonRa = ra.Find(QuickTeleportAssets.Instance.MapScaleButtonRo);
if (mapScaleButtonRa.IsExist())
{
var p = BigMap.Instance.GetBigMapPositionByFeatureMatch(ra.SrcGreyMat);
var p = MapManager.GetMap(mapName).GetBigMapPosition(ra.SrcGreyMat);
if (p.IsEmpty())
{
throw new InvalidOperationException("识别大地图位置失败");
}
Debug.WriteLine("识别大地图在全地图位置:" + p);
return MapCoordinate.Main2048ToGame(new Point2f(BigMap.ScaleTo2048 * p.X, BigMap.ScaleTo2048 * p.Y));
// 提瓦特大陆由于用的256的图,需要做特殊逻辑
var (x, y) = (p.X, p.Y);
if (mapName == MapTypes.Teyvat.ToString())
{
(x, y) = (p.X * TeyvatMap.BigMap256ScaleTo2048, p.Y * TeyvatMap.BigMap256ScaleTo2048);
}
return MapManager.GetMap(mapName).ConvertImageCoordinatesToGenshinMapCoordinates(new Point2f(p.X, p.Y));
}
else
{
@@ -763,34 +786,6 @@ public class TpTask(CancellationToken ct)
}
}
/// <summary>
/// 获取最近的传送点位置和所处区域
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <returns></returns>
[Obsolete]
public (double x, double y, string? country) GetRecentlyTpPoint(double x, double y)
{
double recentX = 0;
double recentY = 0;
string? country = "";
var minDistance = double.MaxValue;
foreach (var tpPosition in MapLazyAssets.Instance.TpPositions)
{
var distance = Math.Sqrt(Math.Pow(tpPosition.X - x, 2) + Math.Pow(tpPosition.Y - y, 2));
if (distance < minDistance)
{
minDistance = distance;
recentX = tpPosition.X;
recentY = tpPosition.Y;
country = tpPosition.Country;
}
}
return (recentX, recentY, country);
}
/// <summary>
/// 获取最接近的N个传送点坐标和所处区域
/// </summary>
@@ -798,7 +793,7 @@ public class TpTask(CancellationToken ct)
/// <param name="y"></param>
/// <param name="n">获取最近的 n 个传送点</param>
/// <returns></returns>
public List<GiTpPosition> GetNearestNTpPoints(double x, double y, int n = 1)
public List<GiTpPosition> GetNearestNTpPoints(double x, double y, string mapName, int n = 1)
{
// 检查 n 的合法性
if (n < 1)
@@ -807,7 +802,7 @@ public class TpTask(CancellationToken ct)
}
// 按距离排序并选择前 n 个点
return MapLazyAssets.Instance.TpPositions
return MapLazyAssets.Instance.ScenesDic[mapName].Points
.OrderBy(tp => Math.Pow(tp.X - x, 2) + Math.Pow(tp.Y - y, 2))
.Take(n)
.ToList();
@@ -825,7 +820,7 @@ public class TpTask(CancellationToken ct)
// 识别当前位置
var minDistance = double.MaxValue;
var bigMapCenterPointNullable = GetPositionFromBigMapNullable();
var bigMapCenterPointNullable = GetPositionFromBigMapNullable(MapTypes.Teyvat.ToString());
if (bigMapCenterPointNullable != null)
{
@@ -858,35 +853,45 @@ public class TpTask(CancellationToken ct)
minCountry = forceCountry;
}
GameCaptureRegion.GameRegionClick((rect, scale) => (rect.Width - 160 * scale, rect.Height - 60 * scale));
await Delay(300, ct);
using var ra = CaptureToRectArea();
var list = ra.FindMulti(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect(ra.Width / 2, 0, ra.Width / 2, ra.Height)
});
IStringLocalizer<MapLazyAssets> stringLocalizer = App.GetService<IStringLocalizer<MapLazyAssets>>() ?? throw new NullReferenceException(nameof(stringLocalizer));
CultureInfo cultureInfo = new CultureInfo(TaskContext.Instance().Config.OtherConfig.GameCultureInfoName);
string minCountryLocalized = stringLocalizer.WithCultureGet(cultureInfo, minCountry);
string commissionLocalized = stringLocalizer.WithCultureGet(cultureInfo, "委托");
Region? matchRect = list.FirstOrDefault(r => r.Text.Length == minCountryLocalized.Length && !r.Text.Contains(commissionLocalized) && r.Text.Contains(minCountryLocalized));
if (matchRect == null)
{
Logger.LogWarning("切换区域失败:{Country}", minCountry);
}
else
{
matchRect.Click();
Logger.LogInformation("切换到区域:{Country}", minCountry);
}
await Delay(500, ct);
await SwitchArea(minCountry);
return true;
}
return false;
}
public async Task SwitchArea(string areaName)
{
GameCaptureRegion.GameRegionClick((rect, scale) => (rect.Width - 160 * scale, rect.Height - 60 * scale));
await Delay(300, ct);
using var ra = CaptureToRectArea();
var list = ra.FindMulti(new RecognitionObject
{
RecognitionType = RecognitionTypes.Ocr,
RegionOfInterest = new Rect(ra.Width / 2, 0, ra.Width / 2, ra.Height)
});
IStringLocalizer<MapLazyAssets> stringLocalizer = App.GetService<IStringLocalizer<MapLazyAssets>>() ?? throw new NullReferenceException(nameof(stringLocalizer));
CultureInfo cultureInfo = new CultureInfo(TaskContext.Instance().Config.OtherConfig.GameCultureInfoName);
string minCountryLocalized = stringLocalizer.WithCultureGet(cultureInfo, areaName);
string commissionLocalized = stringLocalizer.WithCultureGet(cultureInfo, "委托");
Region? matchRect = list.FirstOrDefault(r => !r.Text.Contains(commissionLocalized) && r.Text.Contains(minCountryLocalized));
if (matchRect == null)
{
Logger.LogWarning("切换区域失败:{Country}", areaName);
if (areaName == MapTypes.TheChasm.GetDescription() || areaName == MapTypes.Enkanomiya.GetDescription())
{
throw new Exception($"切换独立地图区域[{areaName}]失败");
}
}
else
{
matchRect.Click();
Logger.LogInformation("切换到区域:{Country}", areaName);
}
await Delay(500, ct);
}
public async Task Tp(string name)
{
@@ -7,17 +7,16 @@ using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.Model;
using Newtonsoft.Json;
namespace BetterGenshinImpact.GameTask.Common.Element.Assets;
public class MapLazyAssets : Singleton<MapLazyAssets>
{
// 2048 区块下,存在传送点的最大面积,识别结果比这个大的话,需要点击放大
// 传送点信息
public readonly List<GiTpPosition> TpPositions;
// 不同场景的传送点信息
public readonly Dictionary<string, GiWorldScene> ScenesDic;
// 每个地区点击后处于的中心位置
public readonly Dictionary<string, double[]> CountryPositions = new()
@@ -29,27 +28,30 @@ public class MapLazyAssets : Singleton<MapLazyAssets>
{ "枫丹", [4515, 3631] },
{ "纳塔", [8973.5, -1879.1] },
};
public readonly Dictionary<string, GiTpPosition> DomainPositionMap = new();
public readonly Dictionary<string, GiTpPosition> GoddessPositions = new();
public readonly List<String> DomainNameList = [];
// 反方向行走的副本
public readonly List<string> DomainBackwardList = ["无妄引咎密宫", "芬德尼尔之顶"];
public MapLazyAssets()
{
var json = File.ReadAllText(Global.Absolute(@"GameTask\AutoTrackPath\Assets\tp.json"));
TpPositions = JsonSerializer.Deserialize<List<GiTpPosition>>(json, ConfigService.JsonOptions) ?? throw new System.Exception("tp.json deserialize failed");
var worldScenes = JsonConvert.DeserializeObject<List<GiWorldScene>>(json) ?? throw new Exception("tp.json deserialize failed");
ScenesDic = worldScenes.ToDictionary(x => x.MapName, x => x);
// 取出秘境 description=Domain
foreach (var tp in TpPositions.Where(tp => (tp.Description == "材料本"|| tp.Description == "圣遗物本")))
var teyvatTpPositions = ScenesDic[MapTypes.Teyvat.ToString()].Points;
foreach (var tp in teyvatTpPositions.Where(tp => (tp.Description == "材料本" || tp.Description == "圣遗物本")))
{
DomainPositionMap[tp.Name] = tp;
DomainNameList.Add(tp.Name);
DomainPositionMap[tp.Name!] = tp;
DomainNameList.Add(tp.Name!);
}
foreach (var tp in TpPositions.Where(tp => (tp.Type == "Goddess")))
foreach (var tp in teyvatTpPositions.Where(tp => (tp.Type == "Goddess")))
{
GoddessPositions[tp.Id] = tp;
}
}
}
}
@@ -1,59 +0,0 @@
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.Model;
using OpenCvSharp;
using System.Diagnostics;
namespace BetterGenshinImpact.GameTask.Common.Map;
/// <summary>
/// 专门用于大地图的识别
/// 图像缩小了8倍
/// </summary>
public class BigMap : Singleton<BigMap>
{
// 直接从图像加载特征点
private readonly FeatureMatcher _featureMatcher = new(new Size(MapCoordinate.Main256Width, MapCoordinate.Main256Height), new FeatureStorage("mainMap256Block"));
// 相对标准1024区块的缩放比例
public const int ScaleTo1024 = 4;
// 相对2048区块的缩放比例
public const int ScaleTo2048 = ScaleTo1024 * 2;
/// <summary>
/// 基于特征匹配获取地图位置 全部匹配
/// </summary>
/// <param name="greyMat">传入的大地图图像会缩小8倍</param>
/// <returns></returns>
public Point2f GetBigMapPositionByFeatureMatch(Mat greyMat)
{
try
{
greyMat = ResizeHelper.Resize(greyMat, 1d / 4);
return _featureMatcher.Match(greyMat);
}
catch
{
Debug.WriteLine("Feature Match Failed");
return new Point2f();
}
}
public Rect GetBigMapRectByFeatureMatch(Mat greyMat)
{
try
{
greyMat = ResizeHelper.Resize(greyMat, 1d / 4);
return _featureMatcher.KnnMatchRect(greyMat);
}
catch
{
Debug.WriteLine("Feature Match Failed");
return default;
}
}
}
@@ -1,107 +0,0 @@
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Model;
using OpenCvSharp;
using System;
using System.Diagnostics;
using Size = OpenCvSharp.Size;
namespace BetterGenshinImpact.GameTask.Common.Map;
public class EntireMap : Singleton<EntireMap>
{
// 这个模板缩放大小的计算方式 https://github.com/babalae/better-genshin-impact/issues/318
public static readonly Size TemplateSize = new(240, 135);
// 对无用部分进行裁剪(左160,上80,下96)
public static readonly Rect TemplateSizeRoi = new(20, 10, TemplateSize.Width - 20, TemplateSize.Height - 22);
private readonly FeatureMatcher _featureMatcher;
private float _prevX = -1;
private float _prevY = -1;
public EntireMap()
{
_featureMatcher = new FeatureMatcher(new Size(MapCoordinate.Main2048Width, MapCoordinate.Main2048Height), new FeatureStorage("mainMap2048Block"));
}
public FeatureMatcher GetFeatureMatcher()
{
return _featureMatcher;
}
private int _failCnt = 0;
public void SetPrevPosition(float x, float y)
{
(_prevX, _prevY) = (x, y);
}
/// <summary>
/// 基于特征匹配获取地图位置
/// 移动匹配
/// </summary>
/// <param name="greyMat">灰度图</param>
/// <param name="mask">遮罩</param>
/// <returns></returns>
public Point2f GetMiniMapPositionByFeatureMatch(Mat greyMat, Mat? mask = null)
{
try
{
Point2f p;
if (_prevX <= 0 && _prevY <= 0)
{
p = _featureMatcher.KnnMatch(greyMat, mask);
}
else
{
p = _featureMatcher.KnnMatch(greyMat, _prevX, _prevY, mask, DescriptorMatcherType.BruteForce);
}
if (p.IsEmpty())
{
throw new InvalidOperationException();
}
_prevX = p.X;
_prevY = p.Y;
_failCnt = 0;
return p;
}
catch
{
Debug.WriteLine("Feature Match Failed");
_failCnt++;
if (_failCnt > 5)
{
Debug.WriteLine("Feature Match Failed Too Many Times, 重新从全地图进行特征匹配");
_failCnt = 0;
(_prevX, _prevY) = (-1, -1);
}
return new Point2f();
}
}
/// <summary>
/// 基于特征匹配获取地图位置 全部匹配
/// </summary>
/// <param name="greyMat"></param>
/// <returns></returns>
public Point2f GetBigMapPositionByFeatureMatch(Mat greyMat)
{
try
{
var p = _featureMatcher.Match(greyMat);
if (p.IsEmpty())
{
throw new InvalidOperationException();
}
return p;
}
catch
{
Debug.WriteLine("Feature Match Failed");
return new Point2f();
}
}
}
@@ -1,8 +0,0 @@
namespace BetterGenshinImpact.GameTask.Common.Map;
public static class EntireMapOperation
{
public static void Tp(this EntireMap entireMap, double x, double y)
{
}
}
@@ -0,0 +1,33 @@
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
/// <summary>
/// 远古圣山
/// 地图大小从4x4改到了2x2
/// </summary>
public class AncientSacredMountainMap : SceneBaseMap
{
#region 地图参数
static readonly int GameMapRows = 2; // 游戏坐标下地图块的行数
static readonly int GameMapCols = 2; // 游戏坐标下地图块的列数
static readonly int GameMapUpRows = 0; // 游戏坐标下 左上角离地图原点的行数(注意原点在块的右下角)
static readonly int GameMapLeftCols = 0; // 游戏坐标下 左上角离地图原点的列数(注意原点在块的右下角)
#endregion 地图参数
static readonly int AncientSacredMountainMapImageBlockWidth = 1024;
public AncientSacredMountainMap() : base(type: MapTypes.AncientSacredMountain,
mapSize: new Size(GameMapCols * AncientSacredMountainMapImageBlockWidth, GameMapRows * AncientSacredMountainMapImageBlockWidth),
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * AncientSacredMountainMapImageBlockWidth, (GameMapUpRows + 1) * AncientSacredMountainMapImageBlockWidth),
mapImageBlockWidth: AncientSacredMountainMapImageBlockWidth,
splitRow: 0,
splitCol: 0)
{
Layers = BaseMapLayer.LoadLayers(this);
}
}
@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
using BetterGenshinImpact.Helpers;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
/// <summary>
/// 每层的特征
/// </summary>
public class BaseMapLayer(SceneBaseMap baseMap)
{
// public string Name { get; set; } = string.Empty;
//
// public string LayerId { get; set; } = string.Empty;
//
// public string LayerGroupId { get; set; } = string.Empty;
/// <summary>
/// 层级
/// </summary>
public int Floor { get; set; } = 0;
/// <summary>
/// 当前层的所有特征
/// </summary>
public Mat TrainDescriptors { get; set; } = new();
public KeyPoint[] TrainKeyPoints { get; set; } = [];
/// <summary>
/// 切割后的特征块
/// </summary>
public KeyPointFeatureBlock[][] SplitBlocks { get; set; } = [];
/// <summary>
/// 最近一次合并的特征块
/// </summary>
private KeyPointFeatureBlock? _lastMergedBlock = null;
/// <summary>
/// 从本地文件加载分层地图信息
/// 路径 Assets\Map
/// - Teyvat
/// - Teyvat_0_2048_SIFT.kp.bin
/// - Teyvat_0_2048_SIFT.mat.png
/// - Teyvat_-1_2048_SIFT.kp.bin
/// - Teyvat_-1_2048_SIFT.mat.png
/// </summary>
/// <param name="baseMap"></param>
/// <returns></returns>
public static List<BaseMapLayer> LoadLayers(SceneBaseMap baseMap)
{
var layers = new List<BaseMapLayer>();
var layerDir = Path.Combine(Global.Absolute(@"Assets\Map\"), baseMap.Type.ToString());
if (!Directory.Exists(layerDir))
{
return layers;
}
var files = Directory.GetFiles(layerDir);
var validFiles = files.Where(f => (f.EndsWith(".kp.bin") || f.EndsWith(".mat.png"))
&& !f.EndsWith("Teyvat_0_256_SIFT.kp.bin")
&& !f.EndsWith("Teyvat_0_256_SIFT.mat.png"));
// 解析后按 floor 分组,然后按 floor 创建BaseMapLayer
var groupedFiles = validFiles.GroupBy(file =>
{
var fileName = Path.GetFileNameWithoutExtension(file);
var parts = fileName.Split('_');
if (parts.Length < 3)
{
throw new Exception($"分层地图数据文件夹中中存在无法解析的文件名: {fileName}");
}
return int.TryParse(parts[1], out var floor) ? floor : throw new Exception($"分层地图数据文件夹中中存在无法解析的文件名: {fileName}");
});
foreach (var group in groupedFiles)
{
var floor = group.Key;
var layer = new BaseMapLayer(baseMap) { Floor = floor };
// 查找特征文件路径
var kpFilePath = group.First(f => f.EndsWith(".kp.bin"));
var matFilePath = group.First(f => f.EndsWith(".mat.png"));
SpeedTimer speedTimer = new($"加载 {Path.GetFileNameWithoutExtension(kpFilePath)} 地图特征");
// 加载特征数据
layer.TrainKeyPoints = FeatureStorageHelper.LoadKeyPointArray(kpFilePath) ?? throw new Exception($"地图数据加载失败,文件: {kpFilePath}");
speedTimer.Record("特征点");
layer.TrainDescriptors = FeatureStorageHelper.LoadDescriptorMat(matFilePath) ?? throw new Exception($"地图数据加载失败,文件: {matFilePath}");
speedTimer.Record("特征描述");
// 切割特征数据
if (baseMap.SplitRow > 0 || baseMap.SplitCol > 0)
{
layer.SplitBlocks = KeyPointFeatureBlockHelper.SplitFeatures(baseMap.MapSize, baseMap.SplitRow, baseMap.SplitCol, layer.TrainKeyPoints, layer.TrainDescriptors);
speedTimer.Record("切割特征点");
}
speedTimer.DebugPrint();
layers.Add(layer);
}
// 从 0, -1, -2 这样的顺序对这个list排序
layers.Sort((a, b) =>
{
if (a.Floor == b.Floor)
{
return 0;
}
return a.Floor > b.Floor ? 1 : -1;
});
return layers;
}
public static BaseMapLayer LoadLayer(SceneBaseMap baseMap, string kpFilePath, string matFilePath)
{
var layer = new BaseMapLayer(baseMap)
{
Floor = 0,
TrainKeyPoints = FeatureStorageHelper.LoadKeyPointArray(kpFilePath) ?? throw new Exception($"地图数据加载失败,文件: {kpFilePath}"),
TrainDescriptors = FeatureStorageHelper.LoadDescriptorMat(matFilePath) ?? throw new Exception($"地图数据加载失败,文件: {matFilePath}")
};
return layer;
}
/// <summary>
/// 选择切分后的特征块合并
/// </summary>
/// <param name="prevX"></param>
/// <param name="prevY"></param>
/// <returns></returns>
public (KeyPoint[], Mat) ChooseBlocks(float prevX, float prevY)
{
if (baseMap.SplitRow <= 0 || baseMap.SplitCol <= 0 || SplitBlocks.Length == 0)
{
return (TrainKeyPoints, TrainDescriptors);
}
var (cellRow, cellCol) = KeyPointFeatureBlockHelper.GetCellIndex(baseMap.MapSize, baseMap.SplitRow, baseMap.SplitCol, prevX, prevY);
Debug.WriteLine($"当前坐标({prevX},{prevY})在特征块({cellRow},{cellCol})中");
if (_lastMergedBlock == null || _lastMergedBlock.MergedCenterCellRow != cellRow || _lastMergedBlock.MergedCenterCellCol != cellCol)
{
Debug.WriteLine($"---------切换到新的特征块({cellRow},{cellCol}),合并特征点--------");
_lastMergedBlock = KeyPointFeatureBlockHelper.MergeNeighboringFeatures(SplitBlocks, TrainDescriptors, cellRow, cellCol);
}
return (_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!);
}
}
@@ -0,0 +1,16 @@
using System;
using System.ComponentModel;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
public enum DisplayMapTypes
{
[Description("提瓦特大陆")]
Teyvat,
[Description("层岩巨渊")]
TheChasm,
[Description("渊下宫")]
Enkanomiya,
}
@@ -0,0 +1,68 @@
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
/// <summary>
/// 独立地图接口
/// 使用 Scene(场景) 命名是和原神内部命名保持一致
/// 每个独立地图都是一个场景
/// </summary>
public interface ISceneMap
{
/// <summary>
/// 获取大地图在整张地图上的位置
/// </summary>
/// <param name="greyBigMapMat"></param>
/// <returns></returns>
Point2f GetBigMapPosition(Mat greyBigMapMat);
/// <summary>
/// 获取大地图在整张地图上的位置(矩形,含缩放信息)
/// </summary>
/// <param name="greyBigMapMat"></param>
/// <returns></returns>
Rect GetBigMapRect(Mat greyBigMapMat);
/// <summary>
/// 获取小地图在整张地图上的位置
/// </summary>
/// <param name="greyMiniMapMat"></param>
/// <returns></returns>
Point2f GetMiniMapPosition(Mat greyMiniMapMat);
/// <summary>
/// 获取小地图在整张地图上的位置
/// 根据上一个位置的坐标缩小匹配范围,加速获取速度
/// </summary>
/// <param name="greyMiniMapMat"></param>
/// <param name="prevX"></param>
/// <param name="prevY"></param>
/// <returns></returns>
Point2f GetMiniMapPosition(Mat greyMiniMapMat, float prevX, float prevY);
#region 坐标系转换
/// <summary>
/// 地图图像坐标系 -> 原神游戏坐标系
/// </summary>
/// <param name="imageCoordinates"></param>
/// <returns></returns>
Point2f ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates);
(float x, float y) ConvertImageCoordinatesToGenshinMapCoordinates(float x, float y);
Rect ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect);
/// <summary>
/// 原神游戏坐标系 -> 地图图像坐标系
/// </summary>
/// <param name="genshinMapCoordinates"></param>
/// <returns></returns>
Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f genshinMapCoordinates);
(float x, float y) ConvertGenshinMapCoordinatesToImageCoordinates(float c, float a);
Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect rect);
#endregion
}
@@ -0,0 +1,48 @@
using System;
using System.ComponentModel;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
public enum MapTypes
{
[Description("提瓦特大陆")]
Teyvat,
[Description("层岩巨渊")]
TheChasm,
[Description("渊下宫")]
Enkanomiya,
[Description("旧日之海")]
SeaOfBygoneEras,
[Description("远古圣山")]
AncientSacredMountain
}
public static class MapTypesExtensions
{
public static MapTypes ParseFromDescription(string description)
{
foreach (var field in typeof(MapTypes).GetFields())
{
if (Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) is DescriptionAttribute attribute)
{
if (attribute.Description == description)
{
return (MapTypes)field.GetValue(null)!;
}
}
}
throw new ArgumentException($"无法找到描述为 '{description}' 的枚举值", nameof(description));
}
public static MapTypes ParseFromName(string name)
{
if (Enum.TryParse<MapTypes>(name, true, out var result))
{
return result;
}
throw new ArgumentException($"无法找到名称为 '{name}' 的枚举值", nameof(name));
}
}
@@ -0,0 +1,198 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
/// <summary>
/// 独立地图
/// </summary>
public abstract class SceneBaseMap : ISceneMap
{
public MapTypes Type { get; set; }
/// <summary>
/// 地图大小
/// 当前只用于切割特征点
/// </summary>
public Size MapSize { get; set; }
/// <summary>
/// 地图原点位置 (在图像坐标系中)
/// </summary>
public Point2f MapOriginInImageCoordinate { get; set; }
/// <summary>
/// 特征地图图像的块大小
/// 2048 或者 1024
/// </summary>
public Point2f MapImageBlockWidth { get; set; }
/// <summary>
/// 特征点拆分行数
/// </summary>
public readonly int SplitRow;
/// <summary>
/// 特征点拆分列数
/// </summary>
public readonly int SplitCol;
/// <summary>
/// 特征地图图像的块大小 / 1024 的值,用于坐标系转换
/// </summary>
private readonly float _mapImageBlockWidthScale = 0;
// ReSharper disable once ConvertToPrimaryConstructor
protected SceneBaseMap(MapTypes type, Size mapSize, Point2f mapOriginInImageCoordinate, int mapImageBlockWidth, int splitRow, int splitCol)
{
Type = type;
MapSize = mapSize;
MapOriginInImageCoordinate = mapOriginInImageCoordinate;
_mapImageBlockWidthScale = mapImageBlockWidth / 1024f;
SplitRow = splitRow;
SplitCol = splitCol;
}
/// <summary>
/// 分层地图特征列表
/// 0 是主地图
/// </summary>
public List<BaseMapLayer> Layers { get; set; } = [];
protected BaseMapLayer MainLayer => Layers[0];
protected readonly Feature2D SiftMatcher = Feature2DFactory.Get(Feature2DType.SIFT);
protected void ExtractAndSaveFeature(string basePath)
{
var fileName = Path.GetFileNameWithoutExtension(basePath);
var folder = Path.GetDirectoryName(basePath)!;
string trainKeyPointsPath = Path.Combine(folder, $"{fileName}_SIFT.kp.bin");
string trainDescriptorsPath = Path.Combine(folder, $"{fileName}_SIFT.mat.png");
if (File.Exists(trainKeyPointsPath) && File.Exists(trainDescriptorsPath))
{
return;
}
SiftMatcher.SaveFeatures(basePath, trainKeyPointsPath, trainDescriptorsPath);
}
public virtual Point2f GetBigMapPosition(Mat greyBigMapMat)
{
return SiftMatcher.Match(MainLayer.TrainKeyPoints, MainLayer.TrainDescriptors, greyBigMapMat);
}
public virtual Rect GetBigMapRect(Mat greyBigMapMat)
{
return SiftMatcher.KnnMatchRect(MainLayer.TrainKeyPoints, MainLayer.TrainDescriptors, greyBigMapMat);
}
public Point2f GetMiniMapPosition(Mat greyMiniMapMat)
{
// 从表到里逐层匹配
foreach (var layer in Layers)
{
try
{
var result = SiftMatcher.KnnMatch(layer.TrainKeyPoints, layer.TrainDescriptors, greyMiniMapMat);
if (result != default)
{
return result;
}
}
catch (Exception e)
{
Debug.WriteLine($"地图{Type}层数{layer.Floor},特征匹配失败:{e.Message}");
}
}
return default;
}
public Point2f GetMiniMapPosition(Mat greyMiniMapMat, float prevX, float prevY)
{
if (prevX <= 0 && prevY <= 0)
{
return GetMiniMapPosition(greyMiniMapMat);
}
foreach (var layer in Layers)
{
try
{
var (keyPoints, descriptors) = (layer.TrainKeyPoints, layer.TrainDescriptors);
if (SplitRow > 0 || SplitCol > 0)
{
(keyPoints, descriptors) = layer.ChooseBlocks(prevX, prevY);
}
var result = SiftMatcher.KnnMatch(keyPoints, descriptors, greyMiniMapMat, null, DescriptorMatcherType.BruteForce);
if (result != default)
{
return result;
}
}
catch (Exception e)
{
Debug.WriteLine($"地图{Type}层数{layer.Floor},特征匹配失败:{e.Message}");
}
}
return default;
}
#region 坐标系转换
public Point2f ConvertImageCoordinatesToGenshinMapCoordinates(Point2f imageCoordinates)
{
// 原神坐标系是 1024 级别的,当图像坐标系不是 1024 级别的时候要做转换
return new Point2f((MapOriginInImageCoordinate.X - imageCoordinates.X) / _mapImageBlockWidthScale,
(MapOriginInImageCoordinate.Y - imageCoordinates.Y) / _mapImageBlockWidthScale);
}
public (float x, float y) ConvertImageCoordinatesToGenshinMapCoordinates(float x, float y)
{
return new((MapOriginInImageCoordinate.X - x) / _mapImageBlockWidthScale,
(MapOriginInImageCoordinate.Y - y) / _mapImageBlockWidthScale);
}
public Rect ConvertImageCoordinatesToGenshinMapCoordinates(Rect rect)
{
var center = rect.GetCenterPoint();
var (x, y) = ConvertImageCoordinatesToGenshinMapCoordinates(center.X, center.Y);
return new Rect((int)(x - rect.Width / 2f / _mapImageBlockWidthScale), (int)(y - rect.Height / 2f / _mapImageBlockWidthScale),
(int)(rect.Width / _mapImageBlockWidthScale), (int)(rect.Height / _mapImageBlockWidthScale));
}
public Point2f ConvertGenshinMapCoordinatesToImageCoordinates(Point2f genshinMapCoordinates)
{
return new Point2f(MapOriginInImageCoordinate.X - genshinMapCoordinates.X * _mapImageBlockWidthScale,
MapOriginInImageCoordinate.Y - genshinMapCoordinates.Y * _mapImageBlockWidthScale);
}
public (float x, float y) ConvertGenshinMapCoordinatesToImageCoordinates(float c, float a)
{
return new(MapOriginInImageCoordinate.X - c * _mapImageBlockWidthScale,
MapOriginInImageCoordinate.Y - a * _mapImageBlockWidthScale);
}
public Rect ConvertGenshinMapCoordinatesToImageCoordinates(Rect rect)
{
var center = rect.GetCenterPoint();
var (x, y) = ConvertGenshinMapCoordinatesToImageCoordinates(center.X, center.Y);
return new Rect((int)Math.Round(x - rect.Width / 2f * _mapImageBlockWidthScale),
(int)Math.Round(y - rect.Height / 2f * _mapImageBlockWidthScale),
(int)Math.Round(rect.Width * _mapImageBlockWidthScale),
(int)Math.Round(rect.Height * _mapImageBlockWidthScale));
}
#endregion
}
@@ -0,0 +1,34 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
/// <summary>
/// 渊下宫
/// </summary>
public class EnkanomiyaMap : SceneBaseMap
{
#region 地图参数
static readonly int GameMapRows = 3; // 游戏坐标下地图块的行数
static readonly int GameMapCols = 3; // 游戏坐标下地图块的列数
static readonly int GameMapUpRows = 1; // 游戏坐标下 左上角离地图原点的行数(注意原点在块的右下角)
static readonly int GameMapLeftCols = 1; // 游戏坐标下 左上角离地图原点的列数(注意原点在块的右下角)
#endregion 地图参数
static readonly int EnkanomiyaMapImageBlockWidth = 1024;
public EnkanomiyaMap() : base(type: MapTypes.Enkanomiya,
mapSize: new Size(GameMapCols * EnkanomiyaMapImageBlockWidth, GameMapRows * EnkanomiyaMapImageBlockWidth),
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * EnkanomiyaMapImageBlockWidth, (GameMapUpRows + 1) * EnkanomiyaMapImageBlockWidth),
mapImageBlockWidth: EnkanomiyaMapImageBlockWidth,
splitRow: 0,
splitCol: 0)
{
ExtractAndSaveFeature(Global.Absolute("Assets/Map/Enkanomiya/Enkanomiya_0_1024.png"));
Layers = BaseMapLayer.LoadLayers(this);
}
}
@@ -0,0 +1,55 @@
using System.Collections.Generic;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
public static class MapManager
{
private static readonly Dictionary<MapTypes, ISceneMap> _maps = new();
private static readonly object LockObject = new();
public static ISceneMap GetMap(string mapName)
{
return GetMap(MapTypesExtensions.ParseFromName(mapName));
}
/// <summary>
/// 获取指定类型的地图实例
/// </summary>
/// <param name="mapType">地图类型</param>
/// <returns>地图实例</returns>
public static ISceneMap GetMap(MapTypes mapType)
{
if (_maps.TryGetValue(mapType, out var map))
{
return map;
}
lock (LockObject)
{
// 双重检查锁定
if (_maps.TryGetValue(mapType, out map))
{
return map;
}
map = CreateMap(mapType);
_maps[mapType] = map;
return map;
}
}
private static ISceneMap CreateMap(MapTypes mapType)
{
return mapType switch
{
MapTypes.Teyvat => new TeyvatMap(),
MapTypes.TheChasm => new TheChasmMap(),
MapTypes.Enkanomiya => new EnkanomiyaMap(),
MapTypes.AncientSacredMountain => new AncientSacredMountainMap(),
MapTypes.SeaOfBygoneEras => new SeaOfBygoneErasMap(),
_ => throw new System.ArgumentException($"未知的地图类型: {mapType}", nameof(mapType))
};
}
}
@@ -0,0 +1,34 @@
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
/// <summary>
/// 旧日之海
/// 从3x4改成了1x2
/// 大地图都是半黑的,传送可能有问题
/// </summary>
public class SeaOfBygoneErasMap : SceneBaseMap
{
#region 地图参数
static readonly int GameMapRows = 1; // 游戏坐标下地图块的行数
static readonly int GameMapCols = 2; // 游戏坐标下地图块的列数
static readonly int GameMapUpRows = 0; // 游戏坐标下 左上角离地图原点的行数(注意原点在块的右下角) TODO 没找到
static readonly int GameMapLeftCols = 0; // 游戏坐标下 左上角离地图原点的列数(注意原点在块的右下角) TODO 没找到
#endregion 地图参数
static readonly int SeaOfBygoneErasMapImageBlockWidth = 1024;
public SeaOfBygoneErasMap() : base(type: MapTypes.SeaOfBygoneEras,
mapSize: new Size(GameMapCols * SeaOfBygoneErasMapImageBlockWidth, GameMapRows * SeaOfBygoneErasMapImageBlockWidth),
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * SeaOfBygoneErasMapImageBlockWidth, (GameMapUpRows + 1) * SeaOfBygoneErasMapImageBlockWidth),
mapImageBlockWidth: SeaOfBygoneErasMapImageBlockWidth,
splitRow: 0,
splitCol: 0)
{
Layers = BaseMapLayer.LoadLayers(this);
}
}
@@ -0,0 +1,63 @@
using System.IO;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using Microsoft.Extensions.Logging;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
/// <summary>
/// 提瓦特大陆
/// </summary>
public class TeyvatMap : SceneBaseMap
{
#region 每次地图扩大都要更新的参数
static readonly int GameMapRows = 13; // 游戏坐标下地图块的行数
static readonly int GameMapCols = 18; // 游戏坐标下地图块的列数
static readonly int GameMapUpRows = 5; // 游戏坐标下 左上角离地图原点的行数(注意原点在块的右下角)
static readonly int GameMapLeftCols = 11; // 游戏坐标下 左上角离地图原点的列数(注意原点在块的右下角)
#endregion 每次地图扩大都要更新的参数
static readonly int TeyvatMapImageBlockWidth = 2048;
private readonly BaseMapLayer _teyvat256MapLayer;
public TeyvatMap() : base(type: MapTypes.Teyvat,
mapSize: new Size(GameMapCols * TeyvatMapImageBlockWidth, GameMapRows * TeyvatMapImageBlockWidth),
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * TeyvatMapImageBlockWidth, (GameMapUpRows + 1) * TeyvatMapImageBlockWidth),
mapImageBlockWidth: TeyvatMapImageBlockWidth,
splitRow: GameMapRows * 2,
splitCol: GameMapCols * 2)
{
TaskControl.Logger.LogInformation("提瓦特大陆地图特征点加载中,由于体积较大,首次加载速度可能较慢,请耐心等待...");
Layers = BaseMapLayer.LoadLayers(this);
var layerDir = Path.Combine(Global.Absolute(@"Assets\Map\"), Type.ToString());
// 256用于大地图匹配
_teyvat256MapLayer = BaseMapLayer.LoadLayer(this, Path.Combine(layerDir, "Teyvat_0_256_SIFT.kp.bin"), Path.Combine(layerDir, "Teyvat_0_256_SIFT.mat.png"));
TaskControl.Logger.LogInformation("地图特征点加载完成!");
}
// 大地图使用256 相对 2048 区块的缩放比例 2048/256=8
public const int BigMap256ScaleTo2048 = 8;
public override Point2f GetBigMapPosition(Mat greyBigMapMat)
{
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
return SiftMatcher.Match(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
}
public override Rect GetBigMapRect(Mat greyBigMapMat)
{
greyBigMapMat = ResizeHelper.Resize(greyBigMapMat, 1d / 4);
return SiftMatcher.KnnMatchRect(_teyvat256MapLayer.TrainKeyPoints, _teyvat256MapLayer.TrainDescriptors, greyBigMapMat);
}
}
@@ -0,0 +1,35 @@
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using OpenCvSharp;
namespace BetterGenshinImpact.GameTask.Common.Map.Maps;
/// <summary>
/// 层岩巨渊
/// 地图大小从3x3改到了2x2
/// </summary>
public class TheChasmMap : SceneBaseMap
{
#region 每次地图扩大都要更新的参数(层岩巨渊无需更新)
static readonly int GameMapRows = 2; // 游戏坐标下地图块的行数
static readonly int GameMapCols = 2; // 游戏坐标下地图块的列数
static readonly int GameMapUpRows = 1; // 游戏坐标下 左上角离地图原点的行数(注意原点在0_0块的右下角)
static readonly int GameMapLeftCols = 1; // 游戏坐标下 左上角离地图原点的列数(注意原点在0_0块的右下角)
#endregion 每次地图扩大都要更新的参数(层岩巨渊无需更新)
static readonly int TheChasmMapImageBlockWidth = 1024;
public TheChasmMap() : base(type: MapTypes.TheChasm,
mapSize: new Size(GameMapCols * TheChasmMapImageBlockWidth, GameMapRows * TheChasmMapImageBlockWidth),
mapOriginInImageCoordinate: new Point2f((GameMapLeftCols + 1) * TheChasmMapImageBlockWidth, (GameMapUpRows + 1) * TheChasmMapImageBlockWidth),
mapImageBlockWidth: TheChasmMapImageBlockWidth,
splitRow: 0,
splitCol: 0)
{
ExtractAndSaveFeature(Global.Absolute("Assets/Map/TheChasm/TheChasm_0_1024.png"));
Layers = BaseMapLayer.LoadLayers(this);
}
}
@@ -8,8 +8,11 @@ namespace BetterGenshinImpact.GameTask.Common.Map;
/// 地图坐标系转换
/// 1. 原神游戏坐标系 Game
/// 2. BetterGI主地图1024区块坐标系 Main1024
///
/// 已过时,请使用 TeyvatMap 替代
/// </summary>
public class MapCoordinate
[Obsolete]
public class TeyvatMapCoordinate
{
#region 每次地图扩大都要更新的参数
+15 -2
View File
@@ -10,6 +10,7 @@ public class SpeedTimer
private readonly Dictionary<string, TimeSpan> _timeRecordDic = [];
private readonly string _name = string.Empty;
public SpeedTimer()
{
@@ -17,6 +18,13 @@ public class SpeedTimer
_stopwatch.Start();
}
public SpeedTimer(string name)
{
_name = name;
_stopwatch = new Stopwatch();
_stopwatch.Start();
}
public void Record(string name)
{
_timeRecordDic[name] = _stopwatch.Elapsed;
@@ -25,20 +33,25 @@ public class SpeedTimer
public void DebugPrint()
{
var msg = string.Empty;
var msg = _name;
if (!string.IsNullOrEmpty(msg))
{
msg += " : ";
}
foreach (var pair in _timeRecordDic)
{
// if (pair.Value.TotalMilliseconds > 0.1)
// {
msg += $"{pair.Key}:{pair.Value.TotalMilliseconds}ms,";
// }
}
if (msg.Length > 0)
{
Debug.WriteLine(msg[..^1]);
}
_stopwatch.Stop();
}
}
@@ -70,11 +70,8 @@
Content="设置"
Icon="{ui:SymbolIcon Settings24}" />
<ui:Button Margin="10,0,0,0"
Command="{Binding OpenMapViewerCommand}"
Content="查看实时追踪地图" />
<ui:Button Margin="10,0,0,0"
Command="{Binding OpenMapEditorCommand}"
Content="录制编辑器" />
Command="{Binding OpenDevToolsCommand}"
Content="开发者工具" />
</StackPanel>
<Separator Grid.Row="3"
@@ -0,0 +1,46 @@
<ui:FluentWindow x:Class="BetterGenshinImpact.View.Windows.MapPathingDevWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ui="http://schemas.lepo.co/wpfui/2022/xaml"
xmlns:windows="clr-namespace:BetterGenshinImpact.ViewModel.Windows"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
d:DataContext="{d:DesignInstance Type=windows:MapPathingDevViewModel}"
ui:Design.Background="{DynamicResource ApplicationBackgroundBrush}"
ui:Design.Foreground="{DynamicResource TextFillColorPrimaryBrush}"
Width="320"
Height="260"
mc:Ignorable="d">
<StackPanel>
<ui:TitleBar Title="地图追踪开发者工具">
<ui:TitleBar.Icon>
<ui:ImageIcon Source="pack://application:,,,/Assets/Images/logo.png" />
</ui:TitleBar.Icon>
</ui:TitleBar>
<StackPanel Margin="12">
<ui:TextBlock Margin="5">(下方地图选择会影响路径录制所在的独立地图)</ui:TextBlock>
<ui:TextBlock Margin="5">请选择地图:</ui:TextBlock>
<ComboBox ItemsSource="{Binding MapTypeItems}"
DisplayMemberPath="DisplayName"
SelectedValuePath="EnumName"
SelectedValue="{Binding SelectedMapType, Mode=TwoWay}"
Margin="5">
<b:Interaction.Triggers>
<b:EventTrigger EventName="SelectionChanged">
<b:InvokeCommandAction Command="{Binding DropDownChangedCommand}"
CommandParameter="GeniusInvocation" />
</b:EventTrigger>
</b:Interaction.Triggers>
</ComboBox>
<ui:Button Margin="5"
Command="{Binding OpenMapViewerCommand}"
Content="查看实时追踪地图" />
<ui:Button Margin="5"
Command="{Binding OpenMapEditorCommand}"
Content="录制编辑器" />
</StackPanel>
</StackPanel>
</ui:FluentWindow>
@@ -0,0 +1,14 @@
using MapPathingDevViewModel = BetterGenshinImpact.ViewModel.Windows.MapPathingDevViewModel;
namespace BetterGenshinImpact.View.Windows;
public partial class MapPathingDevWindow
{
private MapPathingDevViewModel ViewModel { get; }
public MapPathingDevWindow()
{
DataContext = ViewModel = new MapPathingDevViewModel();
InitializeComponent();
}
}
@@ -6,9 +6,9 @@ public partial class MapViewer
{
public MapViewerViewModel ViewModel { get; }
public MapViewer()
public MapViewer(string mapName)
{
DataContext = ViewModel = new();
DataContext = ViewModel = new MapViewerViewModel(mapName);
InitializeComponent();
}
}
@@ -31,6 +31,7 @@ using System.Threading.Tasks;
using BetterGenshinImpact.Core.Recognition.OCR;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.AutoFight.Assets;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.GameTask.Model.Area;
using BetterGenshinImpact.GameTask.QuickTeleport.Assets;
using BetterGenshinImpact.View;
@@ -363,7 +364,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
Config.HotKeyConfig.OnedragonHotkeyType,
(_, _) => { SwitchSoloTask(_taskSettingsPageViewModel.SOneDragonFlowCommand); }
));
soloTaskDirectory.Children.Add(new HotKeySettingModel(
"启动/停止自动七圣召唤",
nameof(Config.HotKeyConfig.AutoGeniusInvokationHotkey),
@@ -492,7 +493,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
Config.HotKeyConfig.RecBigMapPosHotkeyType,
(_, _) =>
{
var p = new TpTask(new CancellationToken()).GetPositionFromBigMap();
var p = new TpTask(CancellationToken.None).GetPositionFromBigMap(MapTypes.Teyvat.ToString());
_logger.LogInformation("大地图位置:{Position}", p);
}
));
@@ -513,7 +514,7 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
}
else
{
pathRecorder.Start();
Task.Run(() => { pathRecorder.Start(TaskContext.Instance().Config.DevConfig.RecordMapName); });
}
pathRecording = !pathRecording;
@@ -529,7 +530,8 @@ public partial class HotKeyPageViewModel : ObservableObject, IViewModel
{
if (pathRecording)
{
pathRecorder.AddWaypoint();
Task.Run(() => { pathRecorder.AddWaypoint(); });
}
}
));
@@ -35,7 +35,7 @@ public partial class MapPathingViewModel : ViewModel
[ObservableProperty]
private FileTreeNode<PathingTask>? _selectNode;
private MapViewer? _mapViewer;
private MapPathingDevWindow? _mapPathingDevWindow;
private readonly IScriptService _scriptService;
public AllConfig Config { get; set; }
@@ -122,28 +122,22 @@ public partial class MapPathingViewModel : ViewModel
var project = ScriptGroupProject.BuildPathingProject(fileInfo.Name, fileInfo.DirectoryName!);
await _scriptService.RunMulti([project]);
}
[RelayCommand]
public void OnOpenMapViewer()
public void OnOpenDevTools()
{
if (_mapViewer == null || !_mapViewer.IsVisible)
if (_mapPathingDevWindow == null || !_mapPathingDevWindow.IsVisible)
{
_mapViewer = new MapViewer();
_mapViewer.Closed += (s, e) => _mapViewer = null;
_mapViewer.Show();
_mapPathingDevWindow = new MapPathingDevWindow();
_mapPathingDevWindow.Closed += (s, e) => _mapPathingDevWindow = null;
_mapPathingDevWindow.Show();
}
else
{
_mapViewer.Activate();
_mapPathingDevWindow.Activate();
}
}
[RelayCommand]
public void OnOpenMapEditor()
{
PathRecorder.Instance.OpenEditorInWebView();
}
[RelayCommand]
public async void OnOpenSettings()
{
@@ -0,0 +1,49 @@
using System.Collections.Generic;
using BetterGenshinImpact.GameTask;
using BetterGenshinImpact.GameTask.AutoPathing;
using BetterGenshinImpact.GameTask.Common;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
using BetterGenshinImpact.Helpers.Extensions;
using BetterGenshinImpact.Model;
using BetterGenshinImpact.View.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace BetterGenshinImpact.ViewModel.Windows;
public partial class MapPathingDevViewModel: ObservableObject
{
public IEnumerable<EnumItem<DisplayMapTypes>> MapTypeItems { get; } = EnumExtensions.ToEnumItems<DisplayMapTypes>();
private MapViewer? _mapViewer;
[ObservableProperty]
private string _selectedMapType = TaskContext.Instance().Config.DevConfig.RecordMapName;
[RelayCommand]
private void DropDownChanged()
{
TaskContext.Instance().Config.DevConfig.RecordMapName = SelectedMapType;
}
[RelayCommand]
private void OpenMapViewer()
{
if (_mapViewer == null || !_mapViewer.IsVisible)
{
_mapViewer = new MapViewer(SelectedMapType);
_mapViewer.Closed += (s, e) => _mapViewer = null;
_mapViewer.Show();
}
else
{
_mapViewer.Activate();
}
}
[RelayCommand]
private void OpenMapEditor()
{
PathRecorder.Instance.OpenEditorInWebView(SelectedMapType);
}
}
@@ -14,24 +14,42 @@ using BetterGenshinImpact.GameTask.Common.Map;
using BetterGenshinImpact.Helpers;
using System.Linq;
using BetterGenshinImpact.Core.Recognition.OpenCv;
using BetterGenshinImpact.GameTask.Common.Map.Maps;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.ViewModel.Windows;
/// <summary>
/// TODO 需要支持更多地图
/// </summary>
public partial class MapViewerViewModel : ObservableObject
{
[ObservableProperty]
private WriteableBitmap _mapBitmap;
private readonly Mat _all256Map = new(Global.Absolute(@"Assets/Map/mainMap256Block.png"));
// private readonly Mat _all256Map = new(Global.Absolute(@"Assets/Map/mainMap256Block.png"));
private Mat _currentPathingMap = new(); // 2048级别
private Mat _currentPathingMap = new(); // 2048级别
private Rect _currentPathingRect = new(); // 2048级别
public MapViewerViewModel()
private readonly string _mapName;
private Mat _mapImage;
private int _scale = 1;
public MapViewerViewModel(string mapName)
{
var center = MapCoordinate.GameToMain2048(0, 0);
_mapBitmap = ClipMat(new Point2f((float)center.x, (float)center.y)).ToWriteableBitmap();
if (string.IsNullOrEmpty(mapName))
{
mapName = MapTypes.Teyvat.ToString();
}
_mapName = mapName;
Init(mapName);
var center = MapManager.GetMap(_mapName).ConvertGenshinMapCoordinatesToImageCoordinates(512, 512);
_mapBitmap = ClipMat(new Point2f(center.x, center.y)).ToWriteableBitmap();
WeakReferenceMessenger.Default.Register<PropertyChangedMessage<object>>(this, (sender, msg) =>
{
if (msg.PropertyName == "SendCurrentPosition")
@@ -62,6 +80,28 @@ public partial class MapViewerViewModel : ObservableObject
});
}
private void Init(string mapName)
{
if (mapName == MapTypes.Teyvat.ToString())
{
_mapImage = new Mat(Global.Absolute(@"Assets/Map/Teyvat/Teyvat_0_256.png"));
// 最特殊,图像坐标是 2048 级别的,路径展示窗口是 256 级别的
_scale = 2048 / 256;
}
else if (mapName == MapTypes.TheChasm.ToString())
{
_mapImage = new Mat(Global.Absolute(@"Assets/Map/TheChasm/TheChasm_0_1024.png"));
}
else if (mapName == MapTypes.Enkanomiya.ToString())
{
_mapImage = new Mat(Global.Absolute(@"Assets/Map/Enkanomiya/Enkanomiya_0_1024.png"));
}
else
{
throw new Exception("暂时不支持展示路径的地图类型:" + mapName);
}
}
public Mat ClipMat(Point2f pos)
{
var len = 256;
@@ -71,7 +111,7 @@ public partial class MapViewerViewModel : ObservableObject
if (_currentPathingMap.Empty())
{
Debug.WriteLine("_currentPathingMap 未初始化");
return new Mat(_all256Map, new Rect(rect.X / 8, rect.Y / 8, rect.Width, rect.Height));
return new Mat(_mapImage, new Rect(rect.X / _scale, rect.Y / _scale, rect.Width, rect.Height));
}
else
{
@@ -94,11 +134,11 @@ public partial class MapViewerViewModel : ObservableObject
var points = pathingTask.Positions;
var mapPoints = points.Select(ConvertToMapPoint).ToList();
var offsetRect = CalcRect(mapPoints);
var offsetRect256 = new Rect(offsetRect.X / 8, offsetRect.Y / 8, offsetRect.Width / 8, offsetRect.Height / 8);
var offsetRectZoom = new Rect(offsetRect.X / _scale, offsetRect.Y / _scale, offsetRect.Width / _scale, offsetRect.Height / _scale);
// 把 _all256Map 的局部转化为 2048 级别
Mat taskMat = new Mat(_all256Map, offsetRect256);
taskMat = ResizeHelper.Resize(taskMat, 2048d / 256d);
// 把 map 的局部转化为 实际展示图(提瓦特是256,其他的1024) 级别
Mat taskMat = new Mat(_mapImage, offsetRectZoom);
taskMat = ResizeHelper.Resize(taskMat, _scale);
// 设置线条粗细
int thickness = 2;
@@ -141,7 +181,7 @@ public partial class MapViewerViewModel : ObservableObject
private Point ConvertToMapPoint(Waypoint point)
{
var (x, y) = MapCoordinate.GameToMain2048(point.X, point.Y);
var (x, y) = MapManager.GetMap(_mapName).ConvertGenshinMapCoordinatesToImageCoordinates((float)point.X, (float)point.Y);
return new Point(x, y);
}
@@ -182,4 +222,4 @@ public partial class MapViewerViewModel : ObservableObject
{
Cv2.Line(mat, startPoint, endPoint, color, thickness);
}
}
}
@@ -8,7 +8,6 @@ namespace BetterGenshinImpact.Test.Simple.AllMap;
public class MapPuzzleOther
{
public static List<string> PicWhiteHashList = new List<string>
{
};
@@ -19,16 +18,17 @@ public class MapPuzzleOther
{
// 保存1024
var img1024 = Put(1024);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\DeepSea_1024.png", img1024);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\DeepSea_1024_1x2.png", img1024);
}
public static Mat Put(int block = 1024)
{
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map_5.2"; // 图片文件夹路径
string folderPath = @"E:\HuiTask\更好的原神\地图匹配\UI_Map_最新"; // 图片文件夹路径
// 层岩巨渊 UI_MapBack_TheChasm_
// 渊下宫 UI_MapBack_AbyssalPalace_
// UI_MapBack_DeepSea_
// UI_Map_Volcano_
string pattern = @"UI_MapBack_DeepSea_([-+]?\d+)_([-+]?\d+)(.*)";
var images = Directory.GetFiles(folderPath, "*.png", SearchOption.TopDirectoryOnly); // 获取所有图片文件路径
@@ -36,6 +36,35 @@ public class MapPuzzleOther
var imageLocations = new Dictionary<(int row, int col), ImgInfo>();
foreach (var imagePath in images)
{
// 远古圣山 特殊逻辑
// if (imagePath.Contains("UI_Map_Volcano_800_01.png") || imagePath.Contains("UI_Map_Volcano_01.png"))
// {
// continue;
// }
// if (!imagePath.Contains("UI_Map_Volcano_0_0.png")
// &&!imagePath.Contains("UI_Map_Volcano_0_-1.png")
// &&!imagePath.Contains("UI_Map_Volcano_-1_0.png")
// &&!imagePath.Contains("UI_Map_Volcano_-1_-1.png"))
// {
// continue;
// }
// 层岩巨渊 特殊逻辑
// if (!imagePath.Contains("UI_MapBack_TheChasm_0_0.png")
// &&!imagePath.Contains("UI_MapBack_TheChasm_0_1.png")
// &&!imagePath.Contains("UI_MapBack_TheChasm_1_0.png")
// &&!imagePath.Contains("UI_MapBack_TheChasm_1_1.png"))
// {
// continue;
// }
// 旧日之海
if (!imagePath.Contains("UI_MapBack_DeepSea_1_4.png")
&&!imagePath.Contains("UI_MapBack_DeepSea_1_3.png"))
{
continue;
}
// 获取文件大小
var fileInfo = new FileInfo(imagePath);
@@ -107,7 +136,7 @@ public class MapPuzzleOther
// 计算大图的总宽度和高度
var lenCol = maxCol - minCol;
var lenRow = maxRow - minRow;
Debug.WriteLine($"列数X: {lenCol+1}, 行数Y: {lenRow+1}");
Debug.WriteLine($"列数X: {lenCol + 1}, 行数Y: {lenRow + 1}");
int totalWidth = (lenCol + 1) * block;
int totalHeight = (lenRow + 1) * block;
@@ -182,6 +211,7 @@ public class MapPuzzleOther
{
img = imgInfo.Img.Resize(new Size(1024, 1024), 0, 0, InterpolationFlags.Nearest);
}
var outputPath = Path.Combine(outputFolder, $"{row}_{col}.png");
Cv2.ImWrite(outputPath, img);
img.Dispose();
@@ -212,4 +242,4 @@ public class MapPuzzleOther
Locked = locked;
}
}
}
}
@@ -6,6 +6,7 @@ using System.Diagnostics;
using System.IO;
using System.Text.Json;
using BetterGenshinImpact.GameTask.Common.Element.Assets;
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
namespace BetterGenshinImpact.Test.Simple.AllMap;
@@ -16,7 +17,7 @@ public class MapTeleportPointDraw
// var pList = LoadTeleportPoint(@"E:\HuiTask\更好的原神\地图匹配\地图点位\5.0");
// pList.AddRange(MapAssets.Instance.TpPositions);
var map = new Mat(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\mainMap1024BlockColor.png");
DrawTeleportPoint(map, MapLazyAssets.Instance.TpPositions);
DrawTeleportPoint(map, MapLazyAssets.Instance.ScenesDic[MapTypes.Teyvat.ToString()].Points);
Cv2.ImWrite(@"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.0\传送点_1024_0.34.3.png", map);
}
@@ -24,7 +25,7 @@ public class MapTeleportPointDraw
{
foreach (var point in points)
{
var p = MapCoordinate.GameToMain1024(point.Position);
var p = TeyvatMapCoordinate.GameToMain1024(point.Position);
Cv2.Circle(map, p, 4, Scalar.Red, 2);
// 写文字
Cv2.PutText(map, $"[{point.X:F2},{point.Y:F2}]", new Point(p.X + 10, p.Y + 5), HersheyFonts.HersheySimplex, 1, Scalar.Red, 2);
@@ -0,0 +1,41 @@
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using BetterGenshinImpact.Core.Config;
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
using OpenCvSharp;
using OpenCvSharp.Features2D;
using OpenCvSharp.Internal.Vectors;
namespace BetterGenshinImpact.Test.Simple.AllMap;
/// <summary>
/// 运行完毕MapPuzzle就来运行这个
/// 每次地图更新都需要
/// </summary>
public class NormalSiftExtractor
{
private static readonly Feature2D Sift = SIFT.Create();
public static void GenNormalSift()
{
var imagePath = @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\TheChasm_1024_2x2.png";
var outputPath = @"E:\HuiTask\更好的原神\地图匹配\有用的素材\5.2\";
Mat trainDescriptors = new();
var img = Cv2.ImRead(imagePath, ImreadModes.Grayscale);
Sift.DetectAndCompute(img, null, out var trainKeyPoints,trainDescriptors);
SaveFeatures(trainKeyPoints, trainDescriptors, outputPath);
}
private static void SaveFeatures(KeyPoint[] keyPoints, Mat descriptors, string outputPath)
{
Debug.WriteLine($"保存 {keyPoints.Length} 个关键点和描述符到 {outputPath}");
FeatureStorageHelper.SaveKeyPointArray(keyPoints, Path.Combine(outputPath, "TheChasm_0_1024_SIFT.kp.bin"));
FeatureStorageHelper.SaveDescMat(descriptors, Path.Combine(outputPath, "TheChasm_0_1024_SIFT.mat.png"));
Debug.WriteLine("特征保存成功。");
}
}