Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
53a43dda3b | ||
|
|
d69bed6797 | ||
|
|
731b82404c |
No files matched your search
@@ -0,0 +1,151 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
|
||||
/// <summary>
|
||||
/// 一次查询图特征提取的可复用结果。
|
||||
/// 实例拥有 <see cref="Descriptors"/> 的生命周期,调用方应使用 <see langword="using"/> 或主动释放。
|
||||
/// </summary>
|
||||
/// <param name="keyPoints">从查询图提取的关键点。</param>
|
||||
/// <param name="descriptors">从查询图提取的描述矩阵,其所有权转交给本实例。</param>
|
||||
/// <param name="imageSize">查询图尺寸,用于透视变换后计算图像中心坐标。</param>
|
||||
internal sealed class FeatureMatchQuery(KeyPoint[] keyPoints, Mat descriptors, Size imageSize) : IDisposable
|
||||
{
|
||||
/// <summary>
|
||||
/// 查询图关键点。
|
||||
/// </summary>
|
||||
public KeyPoint[] KeyPoints { get; } = keyPoints;
|
||||
|
||||
/// <summary>
|
||||
/// 查询图描述矩阵,由当前实例负责释放。
|
||||
/// </summary>
|
||||
public Mat Descriptors { get; } = descriptors;
|
||||
|
||||
/// <summary>
|
||||
/// 查询图原始尺寸。
|
||||
/// </summary>
|
||||
public Size ImageSize { get; } = imageSize;
|
||||
|
||||
/// <summary>
|
||||
/// 释放查询图描述矩阵。
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Descriptors.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 支持复用查询图特征的 <see cref="Feature2D"/> 扩展。
|
||||
/// 将查询图的 DetectAndCompute 与训练数据匹配拆开,使同一帧小地图只提取一次特征,
|
||||
/// 随后可以按顺序与多个普通层或分组分层候选匹配。
|
||||
/// </summary>
|
||||
internal static class Feature2DQueryExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// 复用描述匹配器以避免为每个候选层重复创建原生对象;调用匹配器时需要加锁保证线程安全。
|
||||
/// </summary>
|
||||
private static readonly Dictionary<DescriptorMatcherType, DescriptorMatcher> MatcherFactory = new()
|
||||
{
|
||||
{ DescriptorMatcherType.BruteForce, DescriptorMatcher.Create(DescriptorMatcherType.BruteForce.ToString()) },
|
||||
{ DescriptorMatcherType.FlannBased, DescriptorMatcher.Create(DescriptorMatcherType.FlannBased.ToString()) }
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 提取一次查询图的关键点和描述矩阵,供后续多个训练层共同复用。
|
||||
/// </summary>
|
||||
/// <param name="feature2D">用于提取查询特征的 OpenCV 特征算法。</param>
|
||||
/// <param name="queryMat">待匹配的查询图。</param>
|
||||
/// <param name="queryMatMask">可选的查询图掩码。</param>
|
||||
/// <returns>拥有查询描述矩阵生命周期的可复用查询对象。</returns>
|
||||
internal static FeatureMatchQuery PrepareFeatureMatchQuery(this Feature2D feature2D, Mat queryMat, Mat? queryMatMask = null)
|
||||
{
|
||||
var queryDescriptors = new Mat();
|
||||
try
|
||||
{
|
||||
#pragma warning disable CS8604 // 引用类型参数可能为 null。
|
||||
feature2D.DetectAndCompute(queryMat, queryMatMask, out var queryKeyPoints, queryDescriptors);
|
||||
#pragma warning restore CS8604 // 引用类型参数可能为 null。
|
||||
return new FeatureMatchQuery(queryKeyPoints, queryDescriptors, queryMat.Size());
|
||||
}
|
||||
catch
|
||||
{
|
||||
queryDescriptors.Dispose();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用已经提取的查询特征与一组训练特征执行 KNN 匹配,并返回查询图中心在训练图坐标系中的位置。
|
||||
/// 本方法不会释放查询对象或训练数据,它们可以继续用于后续候选层。
|
||||
/// </summary>
|
||||
/// <param name="feature2D">提供扩展方法入口的特征算法实例。</param>
|
||||
/// <param name="trainKeyPoints">训练层关键点。</param>
|
||||
/// <param name="trainDescriptors">训练层描述矩阵。</param>
|
||||
/// <param name="query">已经提取且可复用的查询图特征。</param>
|
||||
/// <param name="matcherType">描述匹配器类型。</param>
|
||||
/// <returns>匹配成功时返回训练图中的中心坐标,否则返回默认坐标。</returns>
|
||||
internal static Point2f KnnMatch(
|
||||
this Feature2D feature2D,
|
||||
KeyPoint[] trainKeyPoints,
|
||||
Mat trainDescriptors,
|
||||
FeatureMatchQuery query,
|
||||
DescriptorMatcherType matcherType = DescriptorMatcherType.FlannBased)
|
||||
{
|
||||
if (trainKeyPoints.Length == 0 || trainDescriptors.Empty() || query.KeyPoints.Length == 0 || query.Descriptors.Empty())
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
SpeedTimer speedTimer = new();
|
||||
DMatch[][] matches;
|
||||
var matcher = MatcherFactory[matcherType];
|
||||
lock (matcher)
|
||||
{
|
||||
matches = matcher.KnnMatch(query.Descriptors, 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 default;
|
||||
}
|
||||
|
||||
var srcPts = goodMatches.Select(match => query.KeyPoints[match.QueryIdx].Pt).ToArray();
|
||||
var dstPts = goodMatches.Select(match => trainKeyPoints[match.TrainIdx].Pt).ToArray();
|
||||
speedTimer.Record("GetGoodMatchPoints");
|
||||
|
||||
using var mask = new Mat();
|
||||
using var homography = Cv2.FindHomography(
|
||||
srcPts.ToList().ToPoint2d(),
|
||||
dstPts.ToList().ToPoint2d(),
|
||||
HomographyMethods.Ransac,
|
||||
3.0,
|
||||
mask);
|
||||
if (homography.Empty())
|
||||
{
|
||||
return default;
|
||||
}
|
||||
|
||||
speedTimer.Record("FindHomography");
|
||||
var centerPoint = new Point2f(query.ImageSize.Width / 2f, query.ImageSize.Height / 2f);
|
||||
var transformedCenter = Cv2.PerspectiveTransform([centerPoint], homography);
|
||||
speedTimer.Record("PerspectiveTransform");
|
||||
speedTimer.DebugPrint();
|
||||
return transformedCenter[0];
|
||||
}
|
||||
}
|
||||
@@ -1,39 +1,81 @@
|
||||
using System;
|
||||
using BetterGenshinImpact.GameTask.Common;
|
||||
using BetterGenshinImpact.GameTask.Common.Element.Assets;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps;
|
||||
using BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
using BetterGenshinImpact.GameTask.Model.Area;
|
||||
using CommunityToolkit.Mvvm.Messaging;
|
||||
using CommunityToolkit.Mvvm.Messaging.Messages;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.AutoPathing;
|
||||
|
||||
public class NavigationInstance
|
||||
{
|
||||
private float _prevX = -1;
|
||||
private float _prevY = -1;
|
||||
/// <summary>
|
||||
/// 保护最近匹配状态和截图时间,避免并发截图以错误顺序覆盖状态。
|
||||
/// </summary>
|
||||
private readonly object _previousMatchLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 当前导航实例最近一次成功的小地图匹配结果,包含坐标和分组分层来源。
|
||||
/// 状态保存在实例上,避免共享的 SceneBaseMap 在多实例间串用楼层。
|
||||
/// </summary>
|
||||
private MiniMapMatchState? _previousMatch;
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次成功结果保留下来的候选排序依据。
|
||||
/// 即使主动清除上次点位,也继续用它排列已经加载的分组分层地图,但不会用它执行局部范围筛选。
|
||||
/// </summary>
|
||||
private MiniMapMatchState? _lastMatchForOrdering;
|
||||
|
||||
/// <summary>
|
||||
/// 最近一次写入匹配状态的截图时间;较旧截图的结果不能覆盖较新结果。
|
||||
/// </summary>
|
||||
private DateTime _captureTime = DateTime.MinValue;
|
||||
|
||||
/// <summary>
|
||||
/// 清除用于局部匹配的上次点位;最近一次楼层排序依据会继续保留。
|
||||
/// </summary>
|
||||
public void Reset()
|
||||
{
|
||||
(_prevX, _prevY) = (-1, -1);
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
_previousMatch = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置外部提供的初始参考底图坐标。外部坐标没有可用的楼层来源,因此从 floor 0 开始排序。
|
||||
/// </summary>
|
||||
public void SetPrevPosition(float x, float y)
|
||||
{
|
||||
(_prevX, _prevY) = (x, y);
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
var previousMatch = new MiniMapMatchState(
|
||||
new Point2f(x, y),
|
||||
0,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
false);
|
||||
_previousMatch = previousMatch;
|
||||
_lastMatchForOrdering = previousMatch;
|
||||
}
|
||||
}
|
||||
|
||||
public Point2f GetPosition(ImageRegion imageRegion, string mapName, string mapMatchMethod)
|
||||
{
|
||||
using var colorMat = new Mat(imageRegion.SrcMat, MapAssets.Get(imageRegion).MimiMapRect);
|
||||
var captureTime = DateTime.UtcNow;
|
||||
var p = MapManager.GetMap(mapName, mapMatchMethod).GetMiniMapPosition(colorMat, _prevX, _prevY);
|
||||
if (p != default && captureTime > _captureTime)
|
||||
{
|
||||
(_prevX, _prevY) = (p.X, p.Y);
|
||||
_captureTime = captureTime;
|
||||
}
|
||||
var sceneMap = MapManager.GetMap(mapName, mapMatchMethod);
|
||||
var previousMatch = GetPreviousMatch(mapName);
|
||||
var orderingReference = GetLayerOrderingReference(mapName);
|
||||
var matchResult = MatchMiniMap(sceneMap, colorMat, previousMatch, orderingReference, mapName, 2);
|
||||
var p = matchResult?.Position ?? default;
|
||||
UpdatePreviousMatch(matchResult, captureTime, sceneMap is SceneBaseMap and not SceneBaseMapByTemplateMatch);
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(typeof(Navigation),
|
||||
"SendCurrentPosition", new object(), p));
|
||||
return p;
|
||||
@@ -47,27 +89,45 @@ public class NavigationInstance
|
||||
/// <param name="mapMatchMethod">地图匹配方式</param>
|
||||
/// <returns>当前位置坐标</returns>
|
||||
public Point2f GetPositionStable(ImageRegion imageRegion, string mapName, string mapMatchMethod)
|
||||
{
|
||||
return GetPositionStable(imageRegion, mapName, mapMatchMethod, out _);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 稳定获取当前位置坐标,并返回本次最终命中的地图层是否来自分组分层地图。
|
||||
/// 分层来源信息供需要同步游戏地图缩放状态的调用方使用,不改变返回坐标所属的参考底图坐标系。
|
||||
/// </summary>
|
||||
/// <param name="imageRegion">图像区域。</param>
|
||||
/// <param name="mapName">地图名字。</param>
|
||||
/// <param name="mapMatchMethod">地图匹配方式。</param>
|
||||
/// <param name="isGroupLayer">本次最终成功结果是否来自分组分层地图。</param>
|
||||
/// <returns>当前位置坐标。</returns>
|
||||
internal Point2f GetPositionStable(
|
||||
ImageRegion imageRegion,
|
||||
string mapName,
|
||||
string mapMatchMethod,
|
||||
out bool isGroupLayer)
|
||||
{
|
||||
using var colorMat = new Mat(imageRegion.SrcMat, MapAssets.Get(imageRegion).MimiMapRect);
|
||||
var captureTime = DateTime.UtcNow;
|
||||
|
||||
// 先尝试使用局部匹配
|
||||
var sceneMap = MapManager.GetMap(mapName, mapMatchMethod);
|
||||
var previousMatch = GetPreviousMatch(mapName);
|
||||
var orderingReference = GetLayerOrderingReference(mapName);
|
||||
//提高局部匹配的阈值,以解决在沙漠录制点位时,移动过远不会触发全局匹配的情况
|
||||
var p = (sceneMap as SceneBaseMapByTemplateMatch)?.GetMiniMapPosition(colorMat, _prevX, _prevY, 0)
|
||||
?? sceneMap.GetMiniMapPosition(colorMat, _prevX, _prevY);
|
||||
var matchResult = MatchMiniMap(sceneMap, colorMat, previousMatch, orderingReference, mapName, 0);
|
||||
var p = matchResult?.Position ?? default;
|
||||
|
||||
// 如果局部匹配失败或者点位跳跃过大,再尝试全地图匹配
|
||||
if (p == default || (_prevX > 0 && _prevY >0 && p.DistanceTo(new Point2f(_prevX,_prevY)) > 150))
|
||||
if (p == default || previousMatch is { Position.X: > 0, Position.Y: > 0 } && p.DistanceTo(previousMatch.Position) > 150)
|
||||
{
|
||||
Reset();
|
||||
p = MapManager.GetMap(mapName, mapMatchMethod).GetMiniMapPosition(colorMat, _prevX, _prevY);
|
||||
}
|
||||
if (p != default && captureTime > _captureTime)
|
||||
{
|
||||
(_prevX, _prevY) = (p.X, p.Y);
|
||||
_captureTime = captureTime;
|
||||
ResetForFallback(captureTime);
|
||||
matchResult = MatchMiniMap(sceneMap, colorMat, null, orderingReference, mapName, 2);
|
||||
p = matchResult?.Position ?? default;
|
||||
}
|
||||
isGroupLayer = matchResult?.IsGroupLayer == true;
|
||||
UpdatePreviousMatch(matchResult, captureTime, sceneMap is SceneBaseMap and not SceneBaseMapByTemplateMatch);
|
||||
|
||||
WeakReferenceMessenger.Default.Send(new PropertyChangedMessage<object>(typeof(Navigation),
|
||||
"SendCurrentPosition", new object(), p));
|
||||
@@ -77,11 +137,146 @@ public class NavigationInstance
|
||||
public Point2f GetPositionStableByCache(ImageRegion imageRegion, string mapName, string mapMatchingMethod, int cacheTimeMs = 900)
|
||||
{
|
||||
var captureTime = DateTime.UtcNow;
|
||||
if (captureTime - _captureTime < TimeSpan.FromMilliseconds(cacheTimeMs) && _prevX > 0 && _prevY > 0)
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
return new Point2f(_prevX, _prevY);
|
||||
if (_previousMatch is { Position.X: > 0, Position.Y: > 0 } previousMatch &&
|
||||
(string.IsNullOrEmpty(previousMatch.MapName) || previousMatch.MapName.Equals(mapName, StringComparison.OrdinalIgnoreCase)) &&
|
||||
captureTime - _captureTime < TimeSpan.FromMilliseconds(cacheTimeMs))
|
||||
{
|
||||
return previousMatch.Position;
|
||||
}
|
||||
}
|
||||
|
||||
return GetPositionStable(imageRegion, mapName, mapMatchingMethod);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取可供指定地图继续局部匹配的上次状态,跨地图状态不会被复用。
|
||||
/// </summary>
|
||||
private MiniMapMatchState? GetPreviousMatch(string mapName)
|
||||
{
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
if (_previousMatch == null ||
|
||||
(!string.IsNullOrEmpty(_previousMatch.MapName) &&
|
||||
!_previousMatch.MapName.Equals(mapName, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return _previousMatch;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取指定地图最近一次成功匹配留下的排序依据,跨地图的排序状态不会被复用。
|
||||
/// </summary>
|
||||
private MiniMapMatchState? GetLayerOrderingReference(string mapName)
|
||||
{
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
if (_lastMatchForOrdering == null ||
|
||||
(!string.IsNullOrEmpty(_lastMatchForOrdering.MapName) &&
|
||||
!_lastMatchForOrdering.MapName.Equals(mapName, StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return _lastMatchForOrdering;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为当前截图的全局回退清除旧状态。若已有更新截图写入结果,则不允许较旧截图清除它。
|
||||
/// </summary>
|
||||
private void ResetForFallback(DateTime captureTime)
|
||||
{
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
if (captureTime > _captureTime)
|
||||
{
|
||||
_previousMatch = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 按地图实现执行小地图匹配,并把公共坐标结果补充为统一的楼层匹配状态。
|
||||
/// </summary>
|
||||
private static MiniMapMatchState? MatchMiniMap(
|
||||
ISceneMap sceneMap,
|
||||
Mat colorMiniMapMat,
|
||||
MiniMapMatchState? previousMatch,
|
||||
MiniMapMatchState? orderingReference,
|
||||
string mapName,
|
||||
int templateMatchRank)
|
||||
{
|
||||
if (sceneMap is SceneBaseMapByTemplateMatch templateMap)
|
||||
{
|
||||
var p = previousMatch == null
|
||||
? templateMap.GetMiniMapPosition(colorMiniMapMat)
|
||||
: templateMap.GetMiniMapPosition(
|
||||
colorMiniMapMat,
|
||||
previousMatch.Position.X,
|
||||
previousMatch.Position.Y,
|
||||
templateMatchRank);
|
||||
if (p == default)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var layer = templateMap.PrevSuccessResult.Layer;
|
||||
return new MiniMapMatchState(
|
||||
p,
|
||||
layer?.Floor ?? 0,
|
||||
layer?.LayerId ?? string.Empty,
|
||||
layer?.LayerGroupId ?? string.Empty,
|
||||
layer?.Name ?? string.Empty,
|
||||
mapName,
|
||||
false);
|
||||
}
|
||||
|
||||
if (sceneMap is SceneBaseMap sceneBaseMap)
|
||||
{
|
||||
return sceneBaseMap.GetMiniMapMatchResult(colorMiniMapMat, previousMatch, orderingReference);
|
||||
}
|
||||
|
||||
var point = previousMatch == null
|
||||
? sceneMap.GetMiniMapPosition(colorMiniMapMat)
|
||||
: sceneMap.GetMiniMapPosition(colorMiniMapMat, previousMatch.Position.X, previousMatch.Position.Y);
|
||||
return point == default
|
||||
? null
|
||||
: new MiniMapMatchState(point, 0, string.Empty, string.Empty, string.Empty, mapName, false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 仅使用更新截图得到的成功结果推进状态,并在楼层发生变化时记录一次日志。
|
||||
/// </summary>
|
||||
private void UpdatePreviousMatch(MiniMapMatchState? matchResult, DateTime captureTime, bool enableFloorSwitchLog)
|
||||
{
|
||||
if (matchResult == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
lock (_previousMatchLock)
|
||||
{
|
||||
if (captureTime <= _captureTime)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (enableFloorSwitchLog &&
|
||||
_previousMatch != null &&
|
||||
(string.IsNullOrEmpty(_previousMatch.MapName) ||
|
||||
_previousMatch.MapName.Equals(matchResult.MapName, StringComparison.OrdinalIgnoreCase)) &&
|
||||
_previousMatch.Floor != matchResult.Floor)
|
||||
{
|
||||
TaskControl.Logger.LogInformation("[SIFT] 已切换至 {Name}(group={GroupId}, floor={Floor})",
|
||||
matchResult.LayerName, matchResult.LayerGroupId, matchResult.Floor);
|
||||
}
|
||||
|
||||
_previousMatch = matchResult;
|
||||
_lastMatchForOrdering = matchResult;
|
||||
_captureTime = captureTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,31 +7,84 @@ using BetterGenshinImpact.Core.Config;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.Model;
|
||||
using BetterGenshinImpact.Helpers;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Newtonsoft.Json;
|
||||
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 string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 地图层的稳定唯一标识。
|
||||
/// </summary>
|
||||
public string LayerId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 地图层所属分组的稳定标识。
|
||||
/// </summary>
|
||||
public string LayerGroupId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 层级
|
||||
/// </summary>
|
||||
public int Floor { get; set; } = 0;
|
||||
|
||||
/// <summary>
|
||||
/// 分组分层片段在整张参考底图中的裁剪范围
|
||||
/// </summary>
|
||||
public Rect CropRect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前楼层实际高亮图层的范围
|
||||
/// </summary>
|
||||
public Rect HighlightRect { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前特征匹配资源中记录的特征点数量。
|
||||
/// </summary>
|
||||
public int FeatureCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前特征匹配实现使用的关键点资源完整路径。
|
||||
/// </summary>
|
||||
public string KeyPointFilePath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 当前特征匹配实现使用的描述矩阵资源完整路径。
|
||||
/// </summary>
|
||||
public string DescriptorFilePath { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 是否为从分组分层清单创建的地图层。
|
||||
/// 此标记只描述层的组织方式,不限定具体匹配算法。
|
||||
/// </summary>
|
||||
public bool IsGroupLayer { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前层的所有特征
|
||||
/// </summary>
|
||||
public Mat TrainDescriptors { get; set; } = new();
|
||||
|
||||
/// <summary>
|
||||
/// 当前层的所有关键点;分组分层资源加载后会统一转换到参考底图坐标系。
|
||||
/// </summary>
|
||||
public KeyPoint[] TrainKeyPoints { get; set; } = [];
|
||||
|
||||
/// <summary>
|
||||
@@ -44,6 +97,26 @@ public class BaseMapLayer(SceneBaseMap baseMap)
|
||||
/// </summary>
|
||||
private KeyPointFeatureBlock? _lastMergedBlock = null;
|
||||
|
||||
/// <summary>
|
||||
/// 保护分组分层特征资源的首次加载,避免多个导航实例重复读取同一份文件。
|
||||
/// </summary>
|
||||
private readonly object _featureLoadLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 特征资源是否已经成功加载并可供复用。
|
||||
/// </summary>
|
||||
private volatile bool _isFeatureLoaded;
|
||||
|
||||
/// <summary>
|
||||
/// 特征资源是否已经加载失败;失败后本进程内不再反复读取损坏或缺失的文件。
|
||||
/// </summary>
|
||||
private volatile bool _featureLoadFailed;
|
||||
|
||||
/// <summary>
|
||||
/// 获取当前层的特征资源是否已加载。
|
||||
/// </summary>
|
||||
public bool IsFeatureLoaded => _isFeatureLoaded;
|
||||
|
||||
/// <summary>
|
||||
/// 从本地文件加载分层地图信息
|
||||
/// 路径 Assets\Map
|
||||
@@ -84,7 +157,13 @@ public class BaseMapLayer(SceneBaseMap baseMap)
|
||||
foreach (var group in groupedFiles)
|
||||
{
|
||||
var floor = group.Key;
|
||||
var layer = new BaseMapLayer(baseMap) { Floor = floor };
|
||||
var layer = new BaseMapLayer(baseMap)
|
||||
{
|
||||
Floor = floor,
|
||||
Name = floor == 0 ? $"{baseMap.Type} 主地图" : $"{baseMap.Type} floor {floor}",
|
||||
LayerId = $"{baseMap.Type}_{floor}",
|
||||
LayerGroupId = baseMap.Type.ToString()
|
||||
};
|
||||
|
||||
// 查找特征文件路径
|
||||
var kpFilePath = group.First(f => f.EndsWith(".kp.bin"));
|
||||
@@ -94,7 +173,10 @@ public class BaseMapLayer(SceneBaseMap baseMap)
|
||||
// 加载特征数据
|
||||
layer.TrainKeyPoints = FeatureStorageHelper.LoadKeyPointArray(kpFilePath) ?? throw new Exception($"地图数据加载失败,文件: {kpFilePath}");
|
||||
speedTimer.Record("特征点");
|
||||
layer.TrainDescriptors.Dispose();
|
||||
layer.TrainDescriptors = FeatureStorageHelper.LoadDescriptorMat(matFilePath) ?? throw new Exception($"地图数据加载失败,文件: {matFilePath}");
|
||||
layer.FeatureCount = layer.TrainKeyPoints.Length;
|
||||
layer._isFeatureLoaded = true;
|
||||
speedTimer.Record("特征描述");
|
||||
|
||||
// 切割特征数据
|
||||
@@ -121,15 +203,168 @@ public class BaseMapLayer(SceneBaseMap baseMap)
|
||||
});
|
||||
return layers;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从 layers_sift.json 加载分组分层地图元数据,不在此处加载具体匹配资源
|
||||
/// </summary>
|
||||
/// <param name="baseMap">清单所属的场景地图。</param>
|
||||
/// <returns>清单中有效的分组分层地图元数据;清单不存在或不可用时返回空集合。</returns>
|
||||
public static IReadOnlyList<BaseMapLayer> LoadGroupLayers(SceneBaseMap baseMap)
|
||||
{
|
||||
// 目录名称属于当前资源格式;加载后的领域对象使用 GroupLayer 命名,不与 SIFT 算法绑定。
|
||||
var groupLayerDirectory = Path.Combine(Global.Absolute(@"Assets\Map\"), baseMap.Type.ToString(), "layers_sift");
|
||||
var manifestPath = Path.Combine(groupLayerDirectory, "layers_sift.json");
|
||||
if (!File.Exists(manifestPath))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(manifestPath);
|
||||
var manifest = JsonConvert.DeserializeObject<GroupLayerManifest>(json)
|
||||
?? throw new InvalidDataException($"无法解析分层地图清单: {manifestPath}");
|
||||
if (!manifest.MapType.Equals(baseMap.Type.ToString(), StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
throw new InvalidDataException($"分层地图清单 mapType 不匹配,期望 {baseMap.Type},实际 {manifest.MapType}");
|
||||
}
|
||||
if (manifest.ReferenceWidth != baseMap.MapSize.Width || manifest.ReferenceHeight != baseMap.MapSize.Height)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"分层地图清单尺寸不匹配,期望 {baseMap.MapSize.Width}x{baseMap.MapSize.Height},实际 {manifest.ReferenceWidth}x{manifest.ReferenceHeight}");
|
||||
}
|
||||
|
||||
var layers = new List<BaseMapLayer>(manifest.Fragments.Count);
|
||||
var ids = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var fragment in manifest.Fragments)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(fragment.Id) ||
|
||||
string.IsNullOrWhiteSpace(fragment.KeyPointFile) ||
|
||||
string.IsNullOrWhiteSpace(fragment.DescriptorFile) ||
|
||||
fragment.CropWidth <= 0 || fragment.CropHeight <= 0 ||
|
||||
fragment.HighlightWidth <= 0 || fragment.HighlightHeight <= 0 ||
|
||||
fragment.FeatureCount <= 0 || !ids.Add(fragment.Id))
|
||||
{
|
||||
TaskControl.Logger.LogWarning("[SIFT] 跳过无效或重复的分层地图片段:{Name}(id={LayerId}, floor={Floor})",
|
||||
fragment.Name, fragment.Id, fragment.Floor);
|
||||
continue;
|
||||
}
|
||||
|
||||
var cropRect = new Rect(fragment.CropX, fragment.CropY, fragment.CropWidth, fragment.CropHeight);
|
||||
var highlightRect = new Rect(fragment.HighlightX, fragment.HighlightY, fragment.HighlightWidth, fragment.HighlightHeight);
|
||||
var mapRect = new Rect(0, 0, baseMap.MapSize.Width, baseMap.MapSize.Height);
|
||||
if (cropRect.Intersect(mapRect) != cropRect || highlightRect.Intersect(cropRect) != highlightRect)
|
||||
{
|
||||
TaskControl.Logger.LogWarning("[SIFT] 跳过范围无效的分层地图片段:{Name}(id={LayerId}, floor={Floor})",
|
||||
fragment.Name, fragment.Id, fragment.Floor);
|
||||
continue;
|
||||
}
|
||||
|
||||
layers.Add(new BaseMapLayer(baseMap)
|
||||
{
|
||||
Name = string.IsNullOrWhiteSpace(fragment.Name) ? fragment.Id : fragment.Name,
|
||||
LayerId = fragment.Id,
|
||||
LayerGroupId = fragment.GroupId,
|
||||
Floor = fragment.Floor,
|
||||
CropRect = cropRect,
|
||||
HighlightRect = highlightRect,
|
||||
FeatureCount = fragment.FeatureCount,
|
||||
KeyPointFilePath = Path.Combine(groupLayerDirectory, fragment.KeyPointFile),
|
||||
DescriptorFilePath = Path.Combine(groupLayerDirectory, fragment.DescriptorFile),
|
||||
IsGroupLayer = true
|
||||
});
|
||||
}
|
||||
|
||||
TaskControl.Logger.LogInformation("[SIFT] {MapType} 分层地图清单已加载,共 {Count} 个片段", baseMap.Type, layers.Count);
|
||||
return layers;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
TaskControl.Logger.LogWarning(e, "[SIFT] 分层地图清单加载失败:{ManifestPath}", manifestPath);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 首次进入分组分层片段范围时加载当前特征匹配资源,加载成功后在进程生命周期内持续复用
|
||||
/// </summary>
|
||||
/// <returns>资源已经可用时返回 <see langword="true"/>;加载失败时返回 <see langword="false"/>。</returns>
|
||||
public bool EnsureFeatureLoaded()
|
||||
{
|
||||
if (!IsGroupLayer || _isFeatureLoaded)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (_featureLoadFailed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
lock (_featureLoadLock)
|
||||
{
|
||||
if (_isFeatureLoaded)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
if (_featureLoadFailed)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
Mat? descriptors = null;
|
||||
try
|
||||
{
|
||||
var keyPoints = FeatureStorageHelper.LoadKeyPointArray(KeyPointFilePath)
|
||||
?? throw new FileNotFoundException("分层地图关键点文件不存在", KeyPointFilePath);
|
||||
descriptors = FeatureStorageHelper.LoadDescriptorMat(DescriptorFilePath)
|
||||
?? throw new FileNotFoundException("分层地图特征描述文件不存在", DescriptorFilePath);
|
||||
if (descriptors.Empty() || keyPoints.Length != descriptors.Rows || keyPoints.Length != FeatureCount)
|
||||
{
|
||||
throw new InvalidDataException(
|
||||
$"分层地图特征数量不一致,清单 {FeatureCount},关键点 {keyPoints.Length},描述 {descriptors.Rows}");
|
||||
}
|
||||
|
||||
// 文件中的关键点以裁剪图左上角为原点,加载后统一平移到完整参考底图坐标系。
|
||||
for (var i = 0; i < keyPoints.Length; i++)
|
||||
{
|
||||
var keyPoint = keyPoints[i];
|
||||
keyPoint.Pt = new Point2f(keyPoint.Pt.X + CropRect.X, keyPoint.Pt.Y + CropRect.Y);
|
||||
keyPoints[i] = keyPoint;
|
||||
}
|
||||
|
||||
TrainDescriptors.Dispose();
|
||||
TrainKeyPoints = keyPoints;
|
||||
TrainDescriptors = descriptors;
|
||||
descriptors = null;
|
||||
_isFeatureLoaded = true;
|
||||
TaskControl.Logger.LogInformation("[SIFT] 分层地图加载完成:{Name},共 {FeatureCount} 个特征点", Name, FeatureCount);
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
descriptors?.Dispose();
|
||||
_featureLoadFailed = true;
|
||||
TaskControl.Logger.LogWarning(e,
|
||||
"[SIFT] 分层地图加载失败:{Name}(floor={Floor},kp={KeyPointPath},descriptor={DescriptorPath})",
|
||||
Name, Floor, KeyPointFilePath, DescriptorFilePath);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static BaseMapLayer LoadLayer(SceneBaseMap baseMap, string kpFilePath, string matFilePath)
|
||||
{
|
||||
var layer = new BaseMapLayer(baseMap)
|
||||
{
|
||||
Floor = 0,
|
||||
Name = $"{baseMap.Type} 主地图",
|
||||
LayerId = $"{baseMap.Type}_0",
|
||||
LayerGroupId = baseMap.Type.ToString(),
|
||||
TrainKeyPoints = FeatureStorageHelper.LoadKeyPointArray(kpFilePath) ?? throw new Exception($"地图数据加载失败,文件: {kpFilePath}"),
|
||||
TrainDescriptors = FeatureStorageHelper.LoadDescriptorMat(matFilePath) ?? throw new Exception($"地图数据加载失败,文件: {matFilePath}")
|
||||
};
|
||||
layer.FeatureCount = layer.TrainKeyPoints.Length;
|
||||
layer._isFeatureLoaded = true;
|
||||
return layer;
|
||||
}
|
||||
|
||||
@@ -156,4 +391,4 @@ public class BaseMapLayer(SceneBaseMap baseMap)
|
||||
|
||||
return (_lastMergedBlock.KeyPointArray, _lastMergedBlock.Descriptor!);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
using System.Collections.Generic;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
|
||||
/// <summary>
|
||||
/// 分组分层地图清单。
|
||||
/// 当前数据来源是 <c>layers_sift.json</c>,类型名称不与具体匹配算法绑定,便于后续复用到其他匹配方式。
|
||||
/// </summary>
|
||||
internal sealed class GroupLayerManifest
|
||||
{
|
||||
/// <summary>
|
||||
/// 清单所属的地图类型。
|
||||
/// </summary>
|
||||
[JsonProperty("mapType")]
|
||||
public string MapType { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 清单使用的参考底图宽度。
|
||||
/// </summary>
|
||||
[JsonProperty("referenceWidth")]
|
||||
public int ReferenceWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 清单使用的参考底图高度。
|
||||
/// </summary>
|
||||
[JsonProperty("referenceHeight")]
|
||||
public int ReferenceHeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 清单内的所有分组分层片段。
|
||||
/// </summary>
|
||||
[JsonProperty("fragments")]
|
||||
public List<GroupLayerFragmentManifest> Fragments { get; set; } = [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 单个分组分层片段的清单数据。
|
||||
/// </summary>
|
||||
internal sealed class GroupLayerFragmentManifest
|
||||
{
|
||||
/// <summary>
|
||||
/// 片段的稳定唯一标识,也是当前资源文件的名称前缀。
|
||||
/// </summary>
|
||||
[JsonProperty("id")]
|
||||
public string Id { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 片段所属的分层区域标识。
|
||||
/// </summary>
|
||||
[JsonProperty("groupId")]
|
||||
public string GroupId { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 用于日志和诊断的可读名称。
|
||||
/// </summary>
|
||||
[JsonProperty("name")]
|
||||
public string Name { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 片段对应的楼层编号。
|
||||
/// </summary>
|
||||
[JsonProperty("floor")]
|
||||
public int Floor { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 片段裁剪范围的左上角 X 坐标。
|
||||
/// </summary>
|
||||
[JsonProperty("cropX")]
|
||||
public int CropX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 片段裁剪范围的左上角 Y 坐标。
|
||||
/// </summary>
|
||||
[JsonProperty("cropY")]
|
||||
public int CropY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 片段裁剪范围的宽度。
|
||||
/// </summary>
|
||||
[JsonProperty("cropWidth")]
|
||||
public int CropWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 片段裁剪范围的高度。
|
||||
/// </summary>
|
||||
[JsonProperty("cropHeight")]
|
||||
public int CropHeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前楼层实际高亮范围的左上角 X 坐标。
|
||||
/// </summary>
|
||||
[JsonProperty("highlightX")]
|
||||
public int HighlightX { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前楼层实际高亮范围的左上角 Y 坐标。
|
||||
/// </summary>
|
||||
[JsonProperty("highlightY")]
|
||||
public int HighlightY { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前楼层实际高亮范围的宽度。
|
||||
/// </summary>
|
||||
[JsonProperty("highlightWidth")]
|
||||
public int HighlightWidth { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前楼层实际高亮范围的高度。
|
||||
/// </summary>
|
||||
[JsonProperty("highlightHeight")]
|
||||
public int HighlightHeight { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 当前特征资源中记录的特征点数量。
|
||||
/// </summary>
|
||||
[JsonProperty("featureCount")]
|
||||
public int FeatureCount { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// 关键点文件相对于清单目录的路径。
|
||||
/// </summary>
|
||||
[JsonProperty("keyPointFile")]
|
||||
public string KeyPointFile { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// 特征描述文件相对于清单目录的路径。
|
||||
/// </summary>
|
||||
[JsonProperty("descriptorFile")]
|
||||
public string DescriptorFile { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using OpenCvSharp;
|
||||
|
||||
namespace BetterGenshinImpact.GameTask.Common.Map.Maps.Base;
|
||||
|
||||
/// <summary>
|
||||
/// 单个导航实例最近一次成功的小地图匹配状态。
|
||||
/// 除整图图像坐标外,同时保存楼层来源,供下一帧筛选和排序分组分层候选。
|
||||
/// </summary>
|
||||
/// <param name="Position">匹配结果在参考底图中的图像坐标。</param>
|
||||
/// <param name="Floor">匹配结果所在楼层。</param>
|
||||
/// <param name="LayerId">命中层的稳定标识。</param>
|
||||
/// <param name="LayerGroupId">命中层所属分组的标识。</param>
|
||||
/// <param name="LayerName">命中层用于日志显示的名称。</param>
|
||||
/// <param name="MapName">匹配结果所属地图,用于防止跨地图复用状态。</param>
|
||||
/// <param name="IsGroupLayer">是否命中了由分组分层清单创建的层。</param>
|
||||
internal sealed record MiniMapMatchState(
|
||||
Point2f Position,
|
||||
int Floor,
|
||||
string LayerId,
|
||||
string LayerGroupId,
|
||||
string LayerName,
|
||||
string MapName,
|
||||
bool IsGroupLayer);
|
||||
@@ -2,6 +2,7 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv;
|
||||
using BetterGenshinImpact.Core.Recognition.OpenCv.FeatureMatch;
|
||||
using Microsoft.Extensions.Logging;
|
||||
@@ -63,10 +64,26 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
/// <summary>
|
||||
/// 分层地图特征列表
|
||||
/// 0 是主地图
|
||||
/// 此列表保留原有整图/旧楼层资源,继续用于全局匹配和大地图匹配。
|
||||
/// </summary>
|
||||
private List<BaseMapLayer> _layers = [];
|
||||
|
||||
/// <summary>
|
||||
/// 保护原有整图/旧楼层资源的延迟加载。
|
||||
/// </summary>
|
||||
private readonly object _layersLock = new();
|
||||
|
||||
/// <summary>
|
||||
/// 分组分层地图列表。<see langword="null"/> 表示清单尚未读取,空集合表示清单不存在或不可用。
|
||||
/// 列表元素只描述层的组织方式;当前 SIFT 实现按需填充其中的特征资源。
|
||||
/// </summary>
|
||||
private IReadOnlyList<BaseMapLayer>? _groupLayers;
|
||||
|
||||
/// <summary>
|
||||
/// 保护分组分层地图清单的首次读取。
|
||||
/// </summary>
|
||||
private readonly object _groupLayersLock = new();
|
||||
|
||||
public List<BaseMapLayer> Layers
|
||||
{
|
||||
get
|
||||
@@ -88,6 +105,24 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
set => _layers = value ?? [];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有分组分层地图。首次访问时只加载清单元数据,不读取各层的具体匹配资源。
|
||||
/// </summary>
|
||||
internal IReadOnlyList<BaseMapLayer> GroupLayers
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_groupLayers == null)
|
||||
{
|
||||
lock (_groupLayersLock)
|
||||
{
|
||||
_groupLayers ??= BaseMapLayer.LoadGroupLayers(this);
|
||||
}
|
||||
}
|
||||
return _groupLayers;
|
||||
}
|
||||
}
|
||||
|
||||
protected BaseMapLayer MainLayer => Layers[0];
|
||||
|
||||
public readonly Feature2D SiftMatcher = Feature2DFactory.Get(Feature2DType.SIFT);
|
||||
@@ -111,6 +146,8 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
public virtual void WarmUp()
|
||||
{
|
||||
Console.WriteLine("提前加载地图,层数:" + Layers.Count);
|
||||
// 预热阶段只读取分组分层清单,片段的匹配资源仍在进入 HighlightRect 后按需加载。
|
||||
_ = GroupLayers.Count;
|
||||
}
|
||||
|
||||
public virtual Point2f GetBigMapPosition(Mat greyBigMapMat)
|
||||
@@ -160,15 +197,30 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
|
||||
public virtual Point2f GetMiniMapPosition(Mat greyMiniMapMat)
|
||||
{
|
||||
return GetGlobalMiniMapMatchResult(greyMiniMapMat, null)?.Position ?? default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 不使用上次点位执行全局小地图匹配。
|
||||
/// 除原有整图/旧楼层外,也会匹配已经加载的分组分层片段,但不会在此阶段动态加载新片段。
|
||||
/// 如果仍保留上次成功结果,则继续沿用相同的楼层、层、分组和高亮范围排序规则。
|
||||
/// </summary>
|
||||
private MiniMapMatchState? GetGlobalMiniMapMatchResult(Mat greyMiniMapMat, MiniMapMatchState? orderingReference)
|
||||
{
|
||||
var candidates = OrderMiniMapCandidates(
|
||||
Layers.Concat(GetLoadedGroupLayers()),
|
||||
orderingReference);
|
||||
|
||||
using var query = SiftMatcher.PrepareFeatureMatchQuery(greyMiniMapMat);
|
||||
// 从表到里逐层匹配
|
||||
foreach (var layer in Layers)
|
||||
foreach (var layer in candidates)
|
||||
{
|
||||
try
|
||||
{
|
||||
var result = SiftMatcher.KnnMatch(layer.TrainKeyPoints, layer.TrainDescriptors, greyMiniMapMat);
|
||||
var result = SiftMatcher.KnnMatch(layer.TrainKeyPoints, layer.TrainDescriptors, query);
|
||||
if (result != default)
|
||||
{
|
||||
return result;
|
||||
return CreateMiniMapMatchState(result, layer);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -177,7 +229,7 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
}
|
||||
}
|
||||
|
||||
return default;
|
||||
return null;
|
||||
}
|
||||
|
||||
public virtual Point2f GetMiniMapPosition(Mat greyMiniMapMat, float prevX, float prevY)
|
||||
@@ -187,20 +239,77 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
return GetMiniMapPosition(greyMiniMapMat);
|
||||
}
|
||||
|
||||
foreach (var layer in Layers)
|
||||
var previousMatch = new MiniMapMatchState(
|
||||
new Point2f(prevX, prevY),
|
||||
0,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
string.Empty,
|
||||
Type.ToString(),
|
||||
false);
|
||||
return GetMiniMapMatchResult(greyMiniMapMat, previousMatch, previousMatch)?.Position ?? default;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用完整的上次匹配状态执行局部小地图匹配,并返回本次命中的楼层来源。
|
||||
/// </summary>
|
||||
/// <param name="greyMiniMapMat">待匹配的小地图图像。</param>
|
||||
/// <param name="previousMatch">当前导航实例最近一次成功的匹配状态。</param>
|
||||
/// <param name="orderingReference">没有上次点位时,用于延续候选顺序的最近成功匹配状态。</param>
|
||||
/// <returns>成功时返回包含参考底图坐标和楼层来源的状态,否则返回 <see langword="null"/>。</returns>
|
||||
internal MiniMapMatchState? GetMiniMapMatchResult(
|
||||
Mat greyMiniMapMat,
|
||||
MiniMapMatchState? previousMatch,
|
||||
MiniMapMatchState? orderingReference)
|
||||
{
|
||||
if (previousMatch == null ||
|
||||
(previousMatch.Position.X <= 0 && previousMatch.Position.Y <= 0) ||
|
||||
(!string.IsNullOrEmpty(previousMatch.MapName) &&
|
||||
!previousMatch.MapName.Equals(Type.ToString(), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return GetGlobalMiniMapMatchResult(greyMiniMapMat, orderingReference);
|
||||
}
|
||||
|
||||
// Teyvat 使用 2048 级别底图坐标,因此对应 1024 级别的 100 像素范围需要扩张为 200。
|
||||
var rangePadding = Type == MapTypes.Teyvat ? 200 : 100;
|
||||
var groupLayerCandidates = GroupLayers
|
||||
.Where(layer => ContainsExpanded(layer.HighlightRect, previousMatch.Position, rangePadding))
|
||||
.ToList();
|
||||
var loadedGroupLayerCandidates = new List<BaseMapLayer>(groupLayerCandidates.Count);
|
||||
|
||||
// 命中范围的片段全部尝试加载;已加载片段会直接复用,单个片段失败不会阻断其他候选。
|
||||
foreach (var layer in groupLayerCandidates)
|
||||
{
|
||||
if (layer.EnsureFeatureLoaded())
|
||||
{
|
||||
loadedGroupLayerCandidates.Add(layer);
|
||||
}
|
||||
}
|
||||
|
||||
// 临时候选集合不修改原有 Layers 或 GroupLayers 的元素与持久顺序。
|
||||
// 排序依次考虑楼层距离、上次命中层、上次命中分组、HighlightRect 距离和稳定层标识。
|
||||
var candidates = OrderMiniMapCandidates(
|
||||
Layers.Concat(loadedGroupLayerCandidates),
|
||||
previousMatch);
|
||||
|
||||
// 当前小地图只提取一次查询特征,随后在所有候选层之间复用,避免每层重复 DetectAndCompute。
|
||||
using var query = SiftMatcher.PrepareFeatureMatchQuery(greyMiniMapMat);
|
||||
foreach (var layer in candidates)
|
||||
{
|
||||
Debug.WriteLine("尝试匹配" + string.Concat(candidates.Select(c => c.Name), ","));
|
||||
try
|
||||
{
|
||||
var (keyPoints, descriptors) = (layer.TrainKeyPoints, layer.TrainDescriptors);
|
||||
if (SplitRow > 0 || SplitCol > 0)
|
||||
{
|
||||
(keyPoints, descriptors) = layer.ChooseBlocks(prevX, prevY);
|
||||
(keyPoints, descriptors) = layer.ChooseBlocks(previousMatch.Position.X, previousMatch.Position.Y);
|
||||
}
|
||||
|
||||
var result = SiftMatcher.KnnMatch(keyPoints, descriptors, greyMiniMapMat, null, DescriptorMatcherType.BruteForce);
|
||||
var result = SiftMatcher.KnnMatch(keyPoints, descriptors, query, DescriptorMatcherType.BruteForce);
|
||||
if (result != default)
|
||||
{
|
||||
return result;
|
||||
Debug.WriteLine(layer.Name + " - 匹配 -" + result.ToString());
|
||||
return CreateMiniMapMatchState(result, layer);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
@@ -209,7 +318,103 @@ public abstract class SceneBaseMap : ISceneMap
|
||||
}
|
||||
}
|
||||
|
||||
return default;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取已经成功加载特征资源的分组分层地图快照。
|
||||
/// 直接读取内部缓存,确保全局匹配不会仅为枚举候选而触发清单或特征文件加载。
|
||||
/// </summary>
|
||||
private IReadOnlyList<BaseMapLayer> GetLoadedGroupLayers()
|
||||
{
|
||||
lock (_groupLayersLock)
|
||||
{
|
||||
return _groupLayers?.Where(layer => layer.IsFeatureLoaded).ToList() ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 使用统一规则排列普通层和分组分层候选。
|
||||
/// 没有可用排序依据时保留输入顺序,即普通层在前、已加载分组分层片段随后。
|
||||
/// </summary>
|
||||
private List<BaseMapLayer> OrderMiniMapCandidates(
|
||||
IEnumerable<BaseMapLayer> candidates,
|
||||
MiniMapMatchState? orderingReference)
|
||||
{
|
||||
var candidateList = candidates.ToList();
|
||||
if (orderingReference == null ||
|
||||
(!string.IsNullOrEmpty(orderingReference.MapName) &&
|
||||
!orderingReference.MapName.Equals(Type.ToString(), StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
return candidateList;
|
||||
}
|
||||
|
||||
return candidateList
|
||||
.OrderBy(layer => Math.Abs(layer.Floor - orderingReference.Floor))
|
||||
.ThenBy(layer => IsSameLayer(layer, orderingReference) ? 0 : 1)
|
||||
.ThenBy(layer => IsSameGroup(layer, orderingReference) ? 0 : 1)
|
||||
.ThenBy(layer => GetDistanceToHighlightRect(layer, orderingReference.Position))
|
||||
.ThenBy(layer => layer.LayerId, StringComparer.OrdinalIgnoreCase)
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将底层匹配坐标和命中层组合成导航实例可保存的状态。
|
||||
/// </summary>
|
||||
private MiniMapMatchState CreateMiniMapMatchState(Point2f position, BaseMapLayer layer)
|
||||
{
|
||||
return new MiniMapMatchState(
|
||||
position,
|
||||
layer.Floor,
|
||||
layer.LayerId,
|
||||
layer.LayerGroupId,
|
||||
layer.Name,
|
||||
Type.ToString(),
|
||||
layer.IsGroupLayer);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断坐标是否落在向四周扩张后的矩形内,矩形边界也视为命中。
|
||||
/// </summary>
|
||||
private static bool ContainsExpanded(Rect rect, Point2f point, int padding)
|
||||
{
|
||||
return point.X >= rect.X - padding && point.X <= rect.Right + padding &&
|
||||
point.Y >= rect.Y - padding && point.Y <= rect.Bottom + padding;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断候选是否与上次命中的是同一种来源下的同一地图层。
|
||||
/// </summary>
|
||||
private static bool IsSameLayer(BaseMapLayer layer, MiniMapMatchState previousMatch)
|
||||
{
|
||||
return !string.IsNullOrEmpty(previousMatch.LayerId) &&
|
||||
layer.IsGroupLayer == previousMatch.IsGroupLayer &&
|
||||
layer.LayerId.Equals(previousMatch.LayerId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 判断候选是否与上次命中的层属于同一分组。
|
||||
/// </summary>
|
||||
private static bool IsSameGroup(BaseMapLayer layer, MiniMapMatchState previousMatch)
|
||||
{
|
||||
return !string.IsNullOrEmpty(previousMatch.LayerGroupId) &&
|
||||
layer.LayerGroupId.Equals(previousMatch.LayerGroupId, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算上次位置到分组分层实际高亮范围的平方距离;普通层不参与此项排序优先级。
|
||||
/// </summary>
|
||||
private static double GetDistanceToHighlightRect(BaseMapLayer layer, Point2f point)
|
||||
{
|
||||
if (!layer.IsGroupLayer)
|
||||
{
|
||||
return double.MaxValue;
|
||||
}
|
||||
|
||||
var rect = layer.HighlightRect;
|
||||
var deltaX = Math.Max(rect.X - point.X, Math.Max(0, point.X - rect.Right));
|
||||
var deltaY = Math.Max(rect.Y - point.Y, Math.Max(0, point.Y - rect.Bottom));
|
||||
return deltaX * deltaX + deltaY * deltaY;
|
||||
}
|
||||
|
||||
#region 坐标系转换
|
||||
|
||||
@@ -133,6 +133,17 @@ public class MapMaskTrigger : ITaskTrigger
|
||||
|
||||
if (inBigMapUi)
|
||||
{
|
||||
if (Bv.BigMapIsUnderground(region))
|
||||
{
|
||||
_stableCount = 0;
|
||||
QueueUiUpdate(new PendingUiUpdate
|
||||
{
|
||||
IsInBigMapUi = true,
|
||||
BigMapViewport = new Rect(0, 0, 0, 0)
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (_detector.IsStable(region.CacheGreyMat))
|
||||
{
|
||||
_stableCount++;
|
||||
@@ -358,17 +369,27 @@ public class MapMaskTrigger : ITaskTrigger
|
||||
using var imageRegion = new ImageRegion(workItem.Mat, 0, 0);
|
||||
workItem.Mat = null;
|
||||
|
||||
var miniPoint = _navigationInstance.GetPositionStable(imageRegion, nameof(MapTypes.Teyvat), workItem.MapMatchingMethod);
|
||||
var miniPoint = _navigationInstance.GetPositionStable(
|
||||
imageRegion,
|
||||
nameof(MapTypes.Teyvat),
|
||||
workItem.MapMatchingMethod,
|
||||
out var isGroupLayer);
|
||||
if (miniPoint != default)
|
||||
{
|
||||
double viewportSize = MapAssets.MimiMapRect1080P.Width / 3.0 * 10;
|
||||
|
||||
// 原神进入分层地图后会把小地图内容放大 2 倍。
|
||||
// MiniMapPointsCanvas 的实际控件尺寸由 XAML 决定且保持不变;这里只把可见地图坐标范围缩小一半,
|
||||
// 使遮罩点位围绕当前坐标同步放大 2 倍。
|
||||
const double groupLayerMapScale = 2.0;
|
||||
var viewportCoordinateSize = isGroupLayer ? viewportSize / groupLayerMapScale : viewportSize;
|
||||
QueueUiUpdate(new PendingUiUpdate
|
||||
{
|
||||
MiniMapViewport = new Rect(
|
||||
miniPoint.X - viewportSize / 2.0,
|
||||
miniPoint.Y - viewportSize / 2.0,
|
||||
viewportSize,
|
||||
viewportSize)
|
||||
miniPoint.X - viewportCoordinateSize / 2.0,
|
||||
miniPoint.Y - viewportCoordinateSize / 2.0,
|
||||
viewportCoordinateSize,
|
||||
viewportCoordinateSize)
|
||||
});
|
||||
}
|
||||
else
|
||||
|
||||
Reference in new issue
Block a user